fu-chrome: app batch 1 rulings (S-L267, S-L271, S-L330)

ListRow label_spans: the label drawn from styled spans, the match in the
highlight look, with a story and a trial. AccessBuilder::image: a placed
picture's image node with screen bounds; link sub-nodes carry their URL.
AccessTree::level_of and url_of. WindowHost::monitor_of, with scale_of
rewritten over it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Martin Ball
2026-11-18 22:39:41 +00:00
co-authored by Claude Opus 5.5
parent 395718f8ce
commit 05f2de14a6
15 changed files with 268 additions and 16 deletions
+15 -4
View File
@@ -1,8 +1,8 @@
//! The accessibility bridge: a page view draws pages as pictures, so on its own it is one opaque node to a screen
//! reader. The bridge describes the text under it, the way a browser describes a page: each paragraph a Paragraph,
//! Heading (with its level) or ListItem (grouped in Lists, with its ListMarker), holding one TextRun per laid-out line
//! with its characters' screen positions; tables are Table > Row > Cell, pictures Images named by their alt text,
//! hyperlinks Links around their runs. The page view's own node is the Document; the nodes below it are its
//! with its characters' screen positions; tables are Table > Row > Cell, pictures Images named by their alt text (at
//! their place on screen when they have one), hyperlinks Links to their URL around their runs. The page view's own node is the Document; the nodes below it are its
//! sub-nodes, and the document's text selection is the Document's text selection.
//!
//! The app describes the pages it was asked for through [`AccessDescriber`]. The bridge builds nothing unless a
@@ -51,7 +51,8 @@ pub enum BlockRole {
Row,
/// A table cell.
Cell,
/// A picture or chart named by its alt text.
/// A picture or chart named by its alt text, with no place on screen of its own; a placed one is
/// [`AccessBuilder::image`].
Image(String),
/// A hyperlink to `url`.
Link(String),
@@ -205,6 +206,16 @@ impl AccessBuilder {
Some(at)
}
/// A placed picture or chart under `parent`, named by its alt text, at `bounds` on screen: a floating picture's
/// placed rectangle or the box of the text it is anchored in. A picture with no place on screen is a
/// [`BlockRole::Image`] block. Bounds that are not finite are left out.
// wordcraft: crates/ui-egui/src/a11y.rs:180-185, :398-406.
pub fn image(&mut self, parent: Option<AccessNode>, alt: impl Into<String>, bounds: Rect) -> Option<AccessNode> {
let at = self.block(parent, BlockRole::Image(alt.into()))?;
self.built(at)?.bounds = bounds.is_finite().then_some(bounds);
Some(at)
}
/// One laid-out line's text under `parent`, with each character's screen x and width and the line's screen
/// rectangle; word starts are worked out from the text.
// wordcraft: crates/ui-egui/src/a11y.rs:431 `Builder::flush`, :501 `push_char`, :515 `word_starts`.
@@ -344,7 +355,7 @@ fn emit(access: &mut Access, built: &AccessBuilder, at: AccessNode) {
let label = built.text_below(at);
let sub = access.node(part, Role::LINK);
sub.name = Name::Text(if label.is_empty() { url.clone() } else { label });
sub
sub.url(url.clone())
}
},
};
+57
View File
@@ -0,0 +1,57 @@
//! The accessibility bridge: what a describer adds reaches the page view's tree.
use craft_pages::layout::LayoutOptions;
use craft_pages::ui::fixtures::{DemoPages, PAPER};
use craft_pages::ui::view::PlacedPage;
use craft_pages::ui::{AccessBuilder, AccessDescriber, AccessPosition, BlockRole, PageView, PageViewState};
use craft_ui::contract::Role;
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, vec2};
use std::cell::Cell;
use std::rc::Rc;
const ALT: &str = "The harbour at dusk";
/// Places one picture on the first page and records where.
struct OnePicture(Rc<Cell<Option<Rect>>>);
impl AccessDescriber for OnePicture {
fn describe(&self, placed: &[PlacedPage], out: &mut AccessBuilder) {
let Some(page) = placed.iter().find(|page| page.page == 0) else { return };
let picture = Rect::from_min_size(page.rect.min + vec2(40.0, 60.0), vec2(120.0, 80.0));
let paragraph = out.block(None, BlockRole::Paragraph);
if out.image(paragraph, ALT, picture).is_some() {
self.0.set(Some(picture));
}
}
fn selection(&self) -> Option<(AccessPosition, AccessPosition)> {
None
}
}
/// A placed picture is an image node named by its alt text at its own screen rectangle, inside the paragraph that
/// holds it: a screen reader's cursor and a magnifier land on the picture, not on the page.
#[trial]
fn a_placed_picture_is_an_image_at_its_screen_rect_inside_its_paragraph() {
let placed = Rc::new(Cell::new(None));
let seen = Rc::clone(&placed);
let pages = DemoPages::new(2);
let mut state = PageViewState::default();
let mut fixture = Fixture::new(move |ui| {
let describer = OnePicture(Rc::clone(&seen));
PageView::new("Pages", &pages, &mut state, PAPER).options(LayoutOptions::ACROBAT).access(&describer).show(ui, |_, _| ());
});
fixture.room(vec2(900.0, 600.0));
fixture.settle();
let picture = placed.get().expect("the describer placed the picture");
let image = fixture.by_label(ALT).expect("a node is named by the alt text");
assert_eq!(fixture.tree().role_of(image.node), Some(Role::IMAGE), "the alt text names an image");
assert!(
image.rect.min.distance(picture.min) < 1.0 && image.rect.max.distance(picture.max) < 1.0,
"the image lies at the picture's rect: {:?} {picture:?}",
image.rect
);
let paragraph = fixture.by_role(Role::PARAGRAPH);
assert!(paragraph.iter().any(|paragraph| paragraph.rect.contains_rect(image.rect)), "the paragraph holds the picture: {paragraph:?}");
}
+1
View File
@@ -1,5 +1,6 @@
//! The screen tests of craft-pages, folded into the lib's test target.
mod access;
mod range;
mod rulers;
mod setup;
+9
View File
@@ -518,6 +518,7 @@ pub struct SubNode {
pub(crate) column: Option<craft_behavior::ColumnKey>,
pub(crate) access_key: Option<char>,
pub(crate) shortcut: Option<String>,
pub(crate) url: Option<String>,
pub(crate) has_popup: Option<PopupKind>,
pub(crate) current: bool,
pub(crate) part: PartRef,
@@ -550,6 +551,7 @@ impl SubNode {
column: None,
access_key: None,
shortcut: None,
url: None,
has_popup: None,
current: false,
part,
@@ -629,6 +631,13 @@ impl SubNode {
self
}
/// The address a link sub-node goes to (`Access::url` for the component's own node): a hyperlink a content
/// painter describes.
pub fn url(&mut self, url: impl Into<String>) -> &mut Self {
self.url = Some(url.into());
self
}
/// What kind of popup the sub-node opens.
pub fn has_popup(&mut self, kind: PopupKind) -> &mut Self {
self.has_popup = Some(kind);
@@ -376,6 +376,7 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
spec.expanded = expanded;
spec.access_key = node.access_key;
spec.shortcut = node.shortcut.clone();
spec.url = node.url.clone();
spec.has_popup = node.has_popup;
spec.current = node.current || flags.contains(Flags::CURRENT);
if let Some(expanded) = expanded {
@@ -345,6 +345,16 @@ impl AccessTree {
self.lookup(NodeId(key.0)).and_then(Node::aria_current).is_some_and(|current| current != accesskit::AriaCurrent::False)
}
/// The level a node by key states: a heading's outline level, a list item's list level, a tree item's depth.
pub fn level_of(&self, key: NodeKey) -> Option<usize> {
self.lookup(NodeId(key.0))?.level()
}
/// The address a link node by key goes to.
pub fn url_of(&self, key: NodeKey) -> Option<&str> {
self.lookup(NodeId(key.0))?.url()
}
/// The nearest ancestor of `id` that screen readers see: AccessKit's consumer drops generic containers.
pub fn parent_of(&self, id: Id) -> Option<NodeKey> {
self.parent_of_key(NodeKey::of(id))
+17 -6
View File
@@ -310,6 +310,14 @@ impl WindowHost {
monitors(&self.ctx)
}
/// The monitor `viewport`'s window lies on: the one its top-left corner is on, the rule its scale
/// ([`WindowFacts::scale`]) falls back to. `None` before the window has reported its rect, or where the platform
/// lists no monitor under the corner.
pub fn monitor_of(&self, viewport: ViewportId) -> Option<Monitor> {
let facts = PerViewport::<Record>::with(&self.ctx, viewport, |record| record.facts)?;
monitor_of(&self.ctx, &facts)
}
/// Places `viewport`'s outer rect at `outer`: its position, and the inner size that leaves the window's
/// decoration as it is. A minimized window is restored first, and a placement below the window's smallest inner
/// size lowers that size to the placed one, so the window takes the place it is given. False when a command could
@@ -405,13 +413,16 @@ pub(super) fn monitors(ctx: &Context) -> Vec<Monitor> {
system.map(|system| system.monitors()).unwrap_or_default()
}
/// The scale of a window with `facts`: the platform's report, else the scale of the monitor the window's top-left
/// corner lies on. A corner is on a monitor when its pixel position at that monitor's scale is inside the monitor.
/// The monitor the top-left corner of a window with `facts` lies on. A corner is on a monitor when its pixel position
/// at that monitor's scale is inside the monitor.
fn monitor_of(ctx: &Context, facts: &viewports::Facts) -> Option<Monitor> {
let corner = facts.outer.or(facts.inner)?.min;
monitors(ctx).into_iter().find(|monitor| monitor.rect_px().contains(corner * monitor.scale))
}
/// The scale of a window with `facts`: the platform's report, else the scale of its monitor ([`monitor_of`]).
pub(super) fn scale_of(ctx: &Context, facts: &viewports::Facts) -> Option<f32> {
facts.native_scale.or_else(|| {
let corner = facts.outer.or(facts.inner)?.min;
monitors(ctx).iter().find(|monitor| monitor.rect_px().contains(corner * monitor.scale)).map(|monitor| monitor.scale)
})
facts.native_scale.or_else(|| monitor_of(ctx, facts).map(|monitor| monitor.scale))
}
/// Records the pointer of the viewport a drag runs in, `local` in that viewport's coordinates, as a desktop
@@ -0,0 +1,68 @@
//! The levels and link addresses that sub-nodes state reach the tree, where the kit's readers find them.
use craft_behavior::PartKey;
use craft_ui::contract::{Access, Common, Component, Cx, MeasureCx, Name, PaintUi, Props as _, Role, Show as _};
use craft_ui::style::StyleCx;
use craft_ui::testing::{Fixture, trial};
use craft_ui_test_kit::contract::PlainStyle;
use egui::{Pos2, Rect, Response, Vec2};
const HEADING: PartKey = PartKey::new("heading");
const ITEM: PartKey = PartKey::new("item");
const LINK: PartKey = PartKey::new("link");
const URL: &str = "https://example.org/harbour";
/// A content painter's page: a heading at level 2, a list item at level 3 and a link, each a sub-node with bounds.
#[derive(craft_ui::contract::Component)]
struct Page {
#[common]
common: Common,
}
impl Component for Page {
const ROLE: Role = Role::GROUP;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: PageStyleKey) -> PlainStyle {
PlainStyle::default()
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::new(300.0, 90.0)
}
fn paint(&mut self, _: &mut PaintUi<'_>, _: &Cx<'_, Self>) {}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let line = |at: f32| Rect::from_min_size(Pos2::new(cx.rect.min.x, cx.rect.min.y + 30.0 * at), Vec2::new(cx.rect.width(), 30.0));
let heading = access.node(HEADING, Role::HEADING).level(2).bounds(line(0.0));
heading.name = Name::Text("The harbour".to_owned());
let item = access.node(ITEM, Role::LIST_ITEM).level(3).bounds(line(1.0));
item.name = Name::Text("Boats".to_owned());
let link = access.node(LINK, Role::LINK).url(URL).bounds(line(2.0));
link.name = Name::Text("Charts".to_owned());
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
/// A heading's and a list item's level and a link's address, as a sub-node states them, read back by key. A reader
/// that looked at another property, or an emitter that dropped a sub-node's address, would read none.
#[trial]
fn a_sub_nodes_level_and_link_address_read_back_from_the_tree() {
let mut fixture = Fixture::new(|ui| {
let _ = Page { common: Common::new() }.label("Page").show(ui);
});
fixture.settle();
let tree = fixture.tree();
let one = |role: Role| *tree.with_role(role).first().unwrap_or_else(|| panic!("a {role:?} node"));
let (heading, item, link) = (one(Role::HEADING), one(Role::LIST_ITEM), one(Role::LINK));
assert_eq!(tree.level_of(heading), Some(2), "the heading's level");
assert_eq!(tree.level_of(item), Some(3), "the list item's level");
assert_eq!(tree.level_of(link), None, "a link states no level");
assert_eq!(tree.url_of(link), Some(URL), "the link's address");
assert_eq!(tree.url_of(heading), None, "a heading has no address");
}
@@ -4,6 +4,7 @@ mod bounds;
mod face_record;
mod face_state;
mod focus;
mod levels;
mod nodes;
mod scope;
mod static_text;
@@ -418,6 +418,32 @@ fn placing_a_minimized_window_below_its_minimum_restores_it_at_the_placed_size()
assert!(lowered.x <= PLACED.width() && lowered.y <= PLACED.height(), "the minimum fits the placed size: {lowered:?}");
}
/// On a desktop of two monitors at different scales, a window whose corner lies on the second reports the second as
/// its monitor, and, with no scale of its own from the platform, takes that monitor's scale: one rule finds both.
#[trial]
fn a_window_on_the_second_of_two_monitors_reports_that_monitor_and_its_scale() {
use craft_behavior::{Monitor, MonitorKey};
let system = Arc::new(FakeSystem::new());
let first = Monitor::new(MonitorKey::new("first", [1920, 1080]), [0, 0], [1920, 1080], 1.0);
let second = Monitor::new(MonitorKey::new("second", [2880, 1800]), [1920, 0], [2880, 1800], 2.0);
system.set_monitors(vec![first, second.clone()]);
let windows = Windows::with(InstallSpec::new(ShellInfo::default(), system));
let frame = || {
windows.frame(vec![], vec![], |ui| {
Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {});
})
};
let (id, _) = builder_titled(&frame(), "tool");
// 2000 points is past the first monitor at its scale of 1 and, at 4000 pixels, inside the second at its scale of 2.
let placed = Rect::from_min_size(Pos2::new(2000.0, 100.0), Vec2::new(400.0, 300.0));
windows.child_info(ViewportInfo { inner_rect: Some(placed), outer_rect: Some(placed), ..ViewportInfo::default() });
frame();
frame();
let host = WindowHost::of(&windows.ctx);
assert_eq!(host.monitor_of(id).map(|monitor| monitor.key), Some(second.key), "the window is on the second monitor");
assert_eq!(host.facts(id).and_then(|facts| facts.scale), Some(second.scale), "the window takes the second monitor's scale");
}
/// The OS windows the runtime opens carry the app id the app installed, as its main window does: docks and Wayland
/// compositors find the app's icon and rules by it.
#[trial]
+7 -1
View File
@@ -10,7 +10,7 @@
use super::toggle::ToggleCell;
use super::words::ListWords;
use crate::contract::{Common, OpenChange, RowHeight, RowPressed, RowState, Show};
use crate::primitives::{ContentPainterCx, HAlign, IconSpec};
use crate::primitives::{ContentPainterCx, HAlign, IconSpec, Span};
use crate::runtime::env::Label;
use craft_behavior::{ColumnKey, Cursor};
use craft_theme::variant::Tone;
@@ -166,6 +166,11 @@ pub struct ListRow<'a> {
/// The label in italics.
#[prop]
pub(super) italic: bool,
/// The label drawn from styled spans, as `Text::styled` draws them: a search result's match in the theme's
/// highlight look (`Span::highlight`). The label given to `new` is their joined text, which is also what a screen
/// reader reads. Empty for a plain label.
#[prop]
pub(super) label_spans: Vec<Span<'static>>,
/// The hover look without the pointer (the canvas hovers the layer).
#[prop]
pub(super) highlight: bool,
@@ -301,6 +306,7 @@ impl<'a> ListRow<'a> {
sub_steps: 0,
divider_below: true,
italic: false,
label_spans: Vec::new(),
highlight: false,
clipped: false,
rule: false,
+11 -3
View File
@@ -179,9 +179,7 @@ impl ListRow<'_> {
if !self.renaming && !self.label_has_field() {
let muted = self.label_column(&self.cells).is_some_and(|column| self.muted.contains(column));
let look = if muted { &style.cell_muted } else { &style.text };
let mut span = Span::new(cx.resolved.label);
span.italic = self.italic;
let run = TextRun::spans(vec![span]).role(look.role).color(cx.resolve(&look.color)).elide();
let run = self.label_run(cx.resolved.label).role(look.role).color(cx.resolve(&look.color)).elide();
draw.text(Rect::from_min_size(Pos2::new(label.left(), top), Vec2::new((label.width() - beside).max(0.0), sizes.label_line)), &run);
}
top += sizes.label_line;
@@ -199,6 +197,16 @@ impl ListRow<'_> {
}
impl ListRow<'_> {
/// The label as a run without its role and colour: its styled spans (`label_spans`) when it has them, else `label`
/// as one span, every span italic under `italic`.
pub(super) fn label_run<'s>(&'s self, label: &'s str) -> TextRun<'s> {
let mut spans: Vec<Span<'s>> = if self.label_spans.is_empty() { vec![Span::new(label)] } else { self.label_spans.clone() };
if self.italic {
spans.iter_mut().for_each(|span| span.italic = true);
}
TextRun::spans(spans)
}
/// The text cells, inset and centred on the row's height, each aligned as its column says.
/// The text cell `at` as a run in its column's look, without its colour.
pub(super) fn cell_run(&self, style: &ListRowStyle, at: usize) -> TextRun<'_> {
+1 -1
View File
@@ -154,7 +154,7 @@ impl Component for ListRow<'_> {
if cx.proposal == Proposal::Min {
return Vec2::new(probe_min, height);
}
let label = cx.layout(&TextRun::new(cx.resolved.label).role(cx.style.text.role)).size().x;
let label = cx.layout(&self.label_run(cx.resolved.label).role(cx.style.text.role)).size().x;
// The label band holds the detail line under the label, so it is as wide as the wider of the two.
let label = match self.detail.as_ref().filter(|_| self.detail_line()) {
Some(detail) => label.max(cx.layout(&TextRun::new(detail.as_str()).role(cx.style.detail.role)).size().x),
+9 -1
View File
@@ -2,7 +2,7 @@
use super::{ListRow, RowInk, TrailingFace, TrailingPart};
use crate::contract::Show as _;
use crate::primitives::IconSpec;
use crate::primitives::{IconSpec, Span};
use crate::testing::{Drive, StoryData, StoryOutput, show_as_only_item, story};
use craft_behavior::{ColumnKey, IconId};
use egui::{Pos2, Rect, Ui};
@@ -41,6 +41,14 @@ fn list_row_text_cell(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
show_as_only_item(ui, ListRow::new("report.pdf").cells(&cells).cell(SIZE, "2.4 MB")).into()
}
/// A search result: the match in the label reads in the highlight look.
#[story(ListRow<'static>, covers = [], drive = Drive::Never)]
fn list_row_match_highlight(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let spans = vec![Span::new("…the light over the "), Span::new("harbour").highlight(), Span::new(" turned grey…")];
let joined: String = spans.iter().map(|span| span.text.as_ref()).collect();
show_as_only_item(ui, ListRow::new(joined).label_spans(spans).detail("Page 4")).into()
}
fn trailing_row() -> ListRow<'static> {
ListRow::new("Background copy")
.trailing("100%")
+35
View File
@@ -968,6 +968,41 @@ fn a_thumbnails_frame_is_square_and_lies_outside_its_picture() {
assert!(row.contains_rect(frame.rect), "the row holds the frame: {row:?} {frame:?}");
}
/// A row whose label comes from styled spans draws its match, and nothing else of the label, on the highlight, and the
/// joined text names the row. A row that dropped the spans would draw the label as one plain span.
#[trial]
fn a_row_labelled_from_spans_highlights_only_its_match_and_is_named_by_the_joined_text() {
use craft_ui::primitives::Span;
const JOINED: &str = "over the harbour at dusk";
let mut fixture = Fixture::new(|ui| {
let keys = [0_usize];
let source = keyed(&keys, |key: &usize| *key).with_text(|_| std::borrow::Cow::Borrowed(JOINED));
let _ = List::new("Results").show_items(ui, &source, &mut |_, _| {
let spans = vec![Span::new("over the "), Span::new("harbour").highlight(), Span::new(" at dusk")];
ListRow::new(JOINED).label_spans(spans)
});
});
fixture.room(Vec2::new(300.0, 200.0));
fixture.settle();
assert!(fixture.by_label(JOINED).is_some(), "the joined text names the row");
let shapes = fixture.frame_shapes();
let galley = shapes
.iter()
.find_map(|shape| match shape {
egui::Shape::Text(shown) if shown.galley.text() == JOINED => Some(shown.galley.clone()),
_ => None,
})
.expect("the row draws its label whole");
let marked: Vec<&str> = galley
.job
.sections
.iter()
.filter(|section| section.format.background != egui::Color32::TRANSPARENT)
.filter_map(|section| galley.job.text.get(section.byte_range.clone()))
.collect();
assert_eq!(marked, ["harbour"], "only the match is drawn on the highlight");
}
/// What a double click on the second row of a list with `select` and `allow_empty`, nothing selected, reports, and the
/// selection it leaves with a host that keeps every selection the list reports.
fn double_clicked(