mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 16:59:56 +01:00
pages: screen readers get the direction and bounds of right-to-left and vertical runs (#7823)
AccessBuilder::line hardcoded left-to-right and derived the run's rectangle from its characters, so right-to-left runs had backwards positions and vertical runs no extent. It now takes the run's bounds and RunDirection, and turns each character's screen span into AccessKit's offset from the leading edge. craft-ui-contract gains RunDirection, SubNode::text_run_in and AccessTree::run_of. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
This commit is contained in:
1 parent
ea14416aaf
commit
9eee62fd81
8 files changed
+152
-25
No files matched your search
@@ -13,7 +13,7 @@ use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
|
||||
use craft_behavior::{PartKey, PartRef};
|
||||
use craft_ui::contract::{Access, GridPlace, Name, Role};
|
||||
use craft_ui::contract::{Access, GridPlace, Name, Role, RunDirection};
|
||||
use egui::{Pos2, Rect};
|
||||
|
||||
use super::view::PlacedPage;
|
||||
@@ -92,7 +92,7 @@ enum Kind {
|
||||
Block(BlockRole),
|
||||
List,
|
||||
Marker(String),
|
||||
Run { text: String, positions: Vec<f32>, widths: Vec<f32> },
|
||||
Run { text: String, positions: Vec<f32>, widths: Vec<f32>, direction: RunDirection },
|
||||
}
|
||||
|
||||
/// A node being built.
|
||||
@@ -216,28 +216,47 @@ impl AccessBuilder {
|
||||
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.
|
||||
/// One laid-out line's text under `parent`, in the run's `direction`, with each character's span along that
|
||||
/// direction in screen coordinates (`chars`: its low edge and its advance, so x and width for horizontal text, y
|
||||
/// and height for vertical) and the run's screen rectangle `bounds`; word starts are worked out from the text.
|
||||
/// AccessKit measures positions from the leading edge (the right for right-to-left, the bottom for bottom to
|
||||
/// top), so they are turned around here; a line over [`MAX_RUN`] characters is split into runs, each with the
|
||||
/// part of `bounds` its characters cover.
|
||||
// wordcraft: crates/ui-egui/src/a11y.rs:431 `Builder::flush`, :501 `push_char`, :515 `word_starts`.
|
||||
pub fn line(&mut self, parent: AccessNode, text: &str, chars: &[(f32, f32)], line: Rect) -> Option<AccessNode> {
|
||||
pub fn line(&mut self, parent: AccessNode, text: &str, chars: &[(f32, f32)], bounds: Rect, direction: RunDirection) -> Option<AccessNode> {
|
||||
let tables = self.built(parent)?.tables;
|
||||
let bounds = if bounds.is_finite() { bounds } else { Rect::from_min_max(Pos2::ZERO, Pos2::ZERO) };
|
||||
let vertical = matches!(direction, RunDirection::TopToBottom | RunDirection::BottomToTop);
|
||||
let reversed = matches!(direction, RunDirection::RightToLeft | RunDirection::BottomToTop);
|
||||
let (low, high) = if vertical { (bounds.top(), bounds.bottom()) } else { (bounds.left(), bounds.right()) };
|
||||
// A character's distance from the leading edge, and its advance.
|
||||
let from_edge = |&(start, size): &(f32, f32)| {
|
||||
let (start, size) = (finite(start), finite(size));
|
||||
if reversed { (high - (start + size), size) } else { (start - low, size) }
|
||||
};
|
||||
let text: Vec<char> = text.chars().collect();
|
||||
let mut first = None;
|
||||
let mut start = 0;
|
||||
loop {
|
||||
let end = (start + MAX_RUN).min(text.len());
|
||||
let spans: Vec<(f32, f32)> =
|
||||
(start..end).map(|i| chars.get(i).or_else(|| chars.last()).map_or((line.left(), 0.0), |&(x, w)| (finite(x), finite(w)))).collect();
|
||||
let left = spans.iter().map(|c| c.0).fold(f32::INFINITY, f32::min);
|
||||
let right = spans.iter().map(|c| c.0 + c.1).fold(f32::NEG_INFINITY, f32::max);
|
||||
let (left, right) = if left.is_finite() && right.is_finite() { (left, right) } else { (line.left(), line.left()) };
|
||||
let bounds = Rect::from_min_max(Pos2::new(left, line.top()), Pos2::new(right.max(left), line.bottom()));
|
||||
let spans: Vec<(f32, f32)> = (start..end).map(|i| chars.get(i).or_else(|| chars.last()).map_or((0.0, 0.0), from_edge)).collect();
|
||||
let near = spans.iter().map(|c| c.0).fold(f32::INFINITY, f32::min);
|
||||
let far = spans.iter().map(|c| c.0 + c.1).fold(f32::NEG_INFINITY, f32::max);
|
||||
let (near, far) = if near.is_finite() && far.is_finite() { (near, far.max(near)) } else { (0.0, 0.0) };
|
||||
// The part of the run's extent these characters cover, in screen coordinates.
|
||||
let (lo, hi) = if reversed { (high - far, high - near) } else { (low + near, low + far) };
|
||||
let covered = if vertical {
|
||||
Rect::from_min_max(Pos2::new(bounds.left(), lo), Pos2::new(bounds.right(), hi))
|
||||
} else {
|
||||
Rect::from_min_max(Pos2::new(lo, bounds.top()), Pos2::new(hi, bounds.bottom()))
|
||||
};
|
||||
let run = Kind::Run {
|
||||
text: text[start..end].iter().collect(),
|
||||
positions: spans.iter().map(|c| c.0 - left).collect(),
|
||||
positions: spans.iter().map(|c| c.0 - near).collect(),
|
||||
widths: spans.iter().map(|c| c.1).collect(),
|
||||
direction,
|
||||
};
|
||||
let at = self.push(Some(parent), run, tables, Some(bounds))?;
|
||||
let at = self.push(Some(parent), run, tables, Some(covered))?;
|
||||
first.get_or_insert(at);
|
||||
if end >= text.len() {
|
||||
return first;
|
||||
@@ -314,8 +333,8 @@ fn emit(access: &mut Access, built: &AccessBuilder, at: AccessNode) {
|
||||
let sub = match &node.kind {
|
||||
Kind::List => access.node(part, Role::LIST),
|
||||
Kind::Marker(text) => access.node(part, Role::LIST_MARKER).value(text.clone()),
|
||||
Kind::Run { text, positions, widths } => {
|
||||
let sub = access.node(part, Role::TEXT_RUN).text_run(text.clone(), positions.clone(), widths.clone(), false);
|
||||
Kind::Run { text, positions, widths, direction } => {
|
||||
let sub = access.node(part, Role::TEXT_RUN).text_run_in(text.clone(), positions.clone(), widths.clone(), *direction);
|
||||
if let Some(bounds) = node.bounds {
|
||||
sub.bounds(bounds);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ 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::contract::{Role, RunDirection};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Rect, vec2};
|
||||
use std::cell::Cell;
|
||||
@@ -90,3 +90,54 @@ fn headings_and_list_items_take_accesskit_zero_based_levels() {
|
||||
assert_eq!(levels(Role::HEADING), [Some(0), Some(1)], "Heading 1 and Heading 2");
|
||||
assert_eq!(levels(Role::LIST_ITEM), [Some(0)], "a first-level list item");
|
||||
}
|
||||
|
||||
/// One right-to-left and one top-to-bottom line, on the first page.
|
||||
struct TwoLines;
|
||||
|
||||
impl AccessDescriber for TwoLines {
|
||||
fn describe(&self, placed: &[PlacedPage], out: &mut AccessBuilder) {
|
||||
if !placed.iter().any(|page| page.page == 0) {
|
||||
return;
|
||||
}
|
||||
let Some(paragraph) = out.block(None, BlockRole::Paragraph) else { return };
|
||||
// Three characters, the first (logical) one rightmost: each is 10 wide, from x 150 down to 130.
|
||||
let rtl = Rect::from_min_max(egui::pos2(130.0, 20.0), egui::pos2(160.0, 34.0));
|
||||
out.line(paragraph, "אבג", &[(150.0, 10.0), (140.0, 10.0), (130.0, 10.0)], rtl, RunDirection::RightToLeft);
|
||||
// Three characters stacked, the first at the top: each is 20 tall, from y 50 down.
|
||||
let tall = Rect::from_min_max(egui::pos2(300.0, 50.0), egui::pos2(316.0, 110.0));
|
||||
out.line(paragraph, "日本語", &[(50.0, 20.0), (70.0, 20.0), (90.0, 20.0)], tall, RunDirection::TopToBottom);
|
||||
}
|
||||
|
||||
fn selection(&self) -> Option<(AccessPosition, AccessPosition)> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A screen reader's character positions follow the run's reading direction inside the run's own rectangle: a
|
||||
/// right-to-left run says so and counts from its right edge, a vertical run says so, has a box with size and counts
|
||||
/// from its top (WordCraft #7823). Before, both read as left-to-right with positions that ran backwards or zero
|
||||
/// widths.
|
||||
#[trial]
|
||||
fn right_to_left_and_vertical_runs_keep_their_direction_and_bounds() {
|
||||
let pages = DemoPages::new(1);
|
||||
let mut state = PageViewState::default();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
PageView::new("Pages", &pages, &mut state, PAPER).options(LayoutOptions::ACROBAT).access(&TwoLines).show(ui, |_, _| ());
|
||||
});
|
||||
fixture.room(vec2(900.0, 600.0));
|
||||
fixture.settle();
|
||||
let tree = fixture.tree();
|
||||
let runs: Vec<_> = tree.with_role(Role::TEXT_RUN).into_iter().filter_map(|key| Some((tree.run_of(key)?, tree.bounds_of(key)?))).collect();
|
||||
let find = |direction| runs.iter().find(|((d, ..), _)| *d == direction).unwrap_or_else(|| panic!("no run reads {direction:?}: {runs:?}"));
|
||||
let ((_, positions, widths), bounds) = find(RunDirection::RightToLeft);
|
||||
assert!(positions.windows(2).all(|pair| pair[0] < pair[1]), "positions grow from the right edge: {positions:?}");
|
||||
assert!(widths.iter().all(|width| *width > 0.0), "every character has a width: {widths:?}");
|
||||
assert!(bounds.width() > 0.0, "the run has width: {bounds:?}");
|
||||
let reach = positions[2] + widths[2];
|
||||
assert!(reach <= bounds.width() + 0.5, "the characters stay inside the run: {reach} in {bounds:?}");
|
||||
let ((_, positions, widths), bounds) = find(RunDirection::TopToBottom);
|
||||
assert!(positions.windows(2).all(|pair| pair[0] < pair[1]), "positions go down the run: {positions:?}");
|
||||
assert!(widths.iter().all(|width| *width > 0.0), "every character has a height: {widths:?}");
|
||||
assert!(bounds.width() > 0.0 && bounds.height() > 0.0, "the run has size: {bounds:?}");
|
||||
assert!(positions[2] + widths[2] <= bounds.height() + 0.5, "the characters stay inside the run: {bounds:?}");
|
||||
}
|
||||
@@ -44,7 +44,9 @@ mod values;
|
||||
pub use crate::bind_tracked;
|
||||
pub use crate::layout::{BodyLayout, RowAlign};
|
||||
pub use crate::primitives::FacesCx;
|
||||
pub use crate::runtime::access::{Access, FieldLabel, GridPlace, Name, Numeric, Politeness, PopupKind, Role, SetPosition, SubNode, announce};
|
||||
pub use crate::runtime::access::{
|
||||
Access, FieldLabel, GridPlace, Name, Numeric, Politeness, PopupKind, Role, RunDirection, SetPosition, SubNode, announce,
|
||||
};
|
||||
pub use crate::runtime::commands::{CommandSet, Commands};
|
||||
pub use crate::runtime::keys::MenuKey;
|
||||
pub use crate::runtime::memory::{Remember, Savable, SaveKey, Slot};
|
||||
|
||||
@@ -505,7 +505,29 @@ pub(crate) struct RunFacts {
|
||||
/// Each character's start offset from the run's left edge, and its advance.
|
||||
pub(crate) positions: Vec<f32>,
|
||||
pub(crate) widths: Vec<f32>,
|
||||
pub(crate) rtl: bool,
|
||||
pub(crate) direction: RunDirection,
|
||||
}
|
||||
|
||||
/// The way a text run reads: the edge its character positions are measured from is the run's leading edge (left,
|
||||
/// right, top or bottom).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RunDirection {
|
||||
/// Left to right: positions run from the left edge.
|
||||
LeftToRight,
|
||||
/// Right to left: positions run from the right edge.
|
||||
RightToLeft,
|
||||
/// Top to bottom (vertical text): positions run from the top edge.
|
||||
TopToBottom,
|
||||
/// Bottom to top (vertical text): positions run from the bottom edge.
|
||||
BottomToTop,
|
||||
}
|
||||
|
||||
impl RunDirection {
|
||||
/// The direction of horizontal text.
|
||||
pub fn horizontal(rtl: bool) -> Self {
|
||||
if rtl { Self::RightToLeft } else { Self::LeftToRight }
|
||||
}
|
||||
}
|
||||
|
||||
/// A node below a component's node, for a part, a cell or a line of a content painter.
|
||||
@@ -598,7 +620,13 @@ impl SubNode {
|
||||
/// is a `TextRun` whatever role it was given, takes its [`bounds`](Self::bounds) as the line's rectangle, and is
|
||||
/// a valid end of [`Access::text_selection`].
|
||||
pub fn text_run(&mut self, text: impl Into<String>, positions: Vec<f32>, widths: Vec<f32>, rtl: bool) -> &mut Self {
|
||||
self.run = Some(RunFacts { text: text.into(), positions, widths, rtl });
|
||||
self.text_run_in(text, positions, widths, RunDirection::horizontal(rtl))
|
||||
}
|
||||
|
||||
/// [`text_run`](Self::text_run) for any direction, vertical included: `positions` are each character's start
|
||||
/// offset from the run's leading edge (see [`RunDirection`]) and `widths` its advance along the direction.
|
||||
pub fn text_run_in(&mut self, text: impl Into<String>, positions: Vec<f32>, widths: Vec<f32>, direction: RunDirection) -> &mut Self {
|
||||
self.run = Some(RunFacts { text: text.into(), positions, widths, direction });
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -365,7 +365,7 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
|
||||
parent: decl.parent,
|
||||
rect: node.bounds.unwrap_or(decl.rect),
|
||||
text: &run.text,
|
||||
rtl: run.rtl,
|
||||
direction: run.direction,
|
||||
positions: &run.positions,
|
||||
widths: &run.widths,
|
||||
},
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! component's layout; the policy (what is exposed, what a password hides, how a request maps back to a position)
|
||||
//! is here, and `runtime::egui::access` writes the nodes.
|
||||
|
||||
use crate::runtime::access::RunDirection;
|
||||
use crate::runtime::egui::access::{self as adapter, NodeEnd, RunNode, TextNode};
|
||||
use crate::runtime::egui::memory::Service;
|
||||
use crate::runtime::keys;
|
||||
@@ -110,7 +111,15 @@ pub(crate) fn report_text(ctx: &Context, owner: Id, facts: &TextFacts, unit: Opt
|
||||
let text = line.text.get(run.bytes.clone()).unwrap_or_default();
|
||||
adapter::write_run(
|
||||
ctx,
|
||||
&RunNode { id, parent: owner, rect: line.rect, text, rtl: run.rtl, positions: &run.positions, widths: &run.widths },
|
||||
&RunNode {
|
||||
id,
|
||||
parent: owner,
|
||||
rect: line.rect,
|
||||
text,
|
||||
direction: RunDirection::horizontal(run.rtl),
|
||||
positions: &run.positions,
|
||||
widths: &run.widths,
|
||||
},
|
||||
);
|
||||
let index = u64::try_from(entries.len()).ok();
|
||||
keys::register_node(ctx, id, owner, Some(PartRef { key: RUN, index }), false);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The text nodes of AccessKit: a text component's value, actions and selection, and the `TextRun` nodes below it.
|
||||
|
||||
use crate::runtime::access::RunDirection;
|
||||
use egui::{Context, Id, Rect};
|
||||
|
||||
/// A selection end as AccessKit names it: a run node's key and a character index in the run.
|
||||
@@ -15,8 +16,8 @@ pub(crate) struct RunNode<'a> {
|
||||
pub parent: Id,
|
||||
pub rect: Rect,
|
||||
pub text: &'a str,
|
||||
pub rtl: bool,
|
||||
/// Each character's start offset from the run's left edge, and its advance.
|
||||
pub direction: RunDirection,
|
||||
/// Each character's start offset from the run's leading edge, and its advance.
|
||||
pub positions: &'a [f32],
|
||||
pub widths: &'a [f32],
|
||||
}
|
||||
@@ -66,7 +67,12 @@ pub(crate) fn write_run(ctx: &Context, run: &RunNode<'_>) {
|
||||
node.set_character_positions(run.positions.to_vec());
|
||||
node.set_character_widths(run.widths.to_vec());
|
||||
node.set_word_starts(word_starts(run.text));
|
||||
node.set_text_direction(if run.rtl { accesskit::TextDirection::RightToLeft } else { accesskit::TextDirection::LeftToRight });
|
||||
node.set_text_direction(match run.direction {
|
||||
RunDirection::LeftToRight => accesskit::TextDirection::LeftToRight,
|
||||
RunDirection::RightToLeft => accesskit::TextDirection::RightToLeft,
|
||||
RunDirection::TopToBottom => accesskit::TextDirection::TopToBottom,
|
||||
RunDirection::BottomToTop => accesskit::TextDirection::BottomToTop,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! A finished AccessKit tree update, read by trials without naming AccessKit.
|
||||
|
||||
use super::{NodeRole, node_key};
|
||||
use crate::runtime::access::{GridPlace, Numeric, Politeness, PopupKind, Role};
|
||||
use crate::runtime::access::{GridPlace, Numeric, Politeness, PopupKind, Role, RunDirection};
|
||||
use accesskit::{Action, Node, NodeId, TreeUpdate};
|
||||
use egui::Id;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -321,6 +321,18 @@ impl AccessTree {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A text run's direction, character positions and widths, as AccessKit has them.
|
||||
pub fn run_of(&self, key: NodeKey) -> Option<(RunDirection, Vec<f32>, Vec<f32>)> {
|
||||
let node = self.lookup(NodeId(key.0)).filter(|node| node.role() == accesskit::Role::TextRun)?;
|
||||
let direction = match node.text_direction()? {
|
||||
accesskit::TextDirection::LeftToRight => RunDirection::LeftToRight,
|
||||
accesskit::TextDirection::RightToLeft => RunDirection::RightToLeft,
|
||||
accesskit::TextDirection::TopToBottom => RunDirection::TopToBottom,
|
||||
accesskit::TextDirection::BottomToTop => RunDirection::BottomToTop,
|
||||
};
|
||||
Some((direction, node.character_positions()?.to_vec(), node.character_widths()?.to_vec()))
|
||||
}
|
||||
|
||||
/// The selection of the text node `id` as the run node and character index of its anchor and focus.
|
||||
pub fn text_selection(&self, id: Id) -> Option<((NodeKey, usize), (NodeKey, usize))> {
|
||||
let selection = self.node(id)?.text_selection()?;
|
||||
|
||||
Reference in new issue
Block a user