ui-widgets: a link in a sentence is one Link node: the paragraph is its own node, and the link's words on each row are their part's Link node below the row's run, which takes focus and the click; SubNode::run_link is gone

This commit is contained in:
bflatastic
2026-11-23 10:19:57 +07:00
parent fb939c5c7f
commit d6d8e4c859
7 changed files with 56 additions and 87 deletions
+1 -11
View File
@@ -11,7 +11,7 @@ pub(crate) mod live;
pub(crate) mod scope;
pub(crate) mod text;
use crate::runtime::egui::access::{self as adapter, NodeRole, RunLink};
use crate::runtime::egui::access::{self as adapter, NodeRole};
use crate::runtime::env::Label;
use craft_behavior::PartRef;
use craft_theme::{Flags, Srgba, variant::Tone};
@@ -551,7 +551,6 @@ pub struct SubNode {
pub(crate) steps: bool,
pub(crate) bounds: Option<egui::Rect>,
pub(crate) run: Option<RunFacts>,
pub(crate) run_links: Vec<RunLink>,
}
impl SubNode {
@@ -583,7 +582,6 @@ impl SubNode {
steps: false,
bounds: None,
run: None,
run_links: Vec::new(),
}
}
@@ -603,14 +601,6 @@ impl SubNode {
self
}
/// Marks characters `chars` of a [text run](Self::text_run) as a link to `target`: the run node gets a `Link`
/// child named by those characters, bounded by their extent on the line. Indices count characters, as
/// `positions` and `widths` do. A link on a node that is not a run is not emitted.
pub fn run_link(&mut self, chars: std::ops::Range<usize>, target: impl Into<String>) -> &mut Self {
self.run_links.push(RunLink { chars, target: target.into() });
self
}
/// Declares Increment and Decrement on a node that steps something with no number (a canvas tool's arrows
/// nudging what it holds); a part with no focus stop gets them as `take_access` requests that name the part.
#[doc(hidden)]
@@ -360,7 +360,6 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
rtl: run.rtl,
positions: &run.positions,
widths: &run.widths,
links: &node.run_links,
},
);
keys::register_node(ctx, id, decl.owner, Some(node.part), false);
@@ -109,7 +109,7 @@ 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, links: &[] },
&RunNode { id, parent: owner, rect: line.rect, text, rtl: 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);
@@ -18,7 +18,7 @@ pub use accesskit::TreeUpdate;
pub(crate) use node::{NodeAction, NodeSpec, Toggle, write_node};
pub(crate) use patch::{write_label_patch, write_merge_patch, write_set_position, write_status};
pub(crate) use text::{
NodeEnd, RunLink, RunNode, TextNode, fold_widget, is_text_request, requested_selection, requested_value, write_run, write_selection, write_text,
NodeEnd, RunNode, TextNode, fold_widget, is_text_request, requested_selection, requested_value, write_run, write_selection, write_text,
};
pub use tree::{AccessTree, Declared, NodeKey, is_interactive, name};
@@ -1,7 +1,6 @@
//! The text nodes of AccessKit: a text component's value, actions and selection, and the `TextRun` nodes below it.
use egui::{Context, Id, Rect};
use std::ops::Range;
/// A selection end as AccessKit names it: a run node's key and a character index in the run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -10,13 +9,6 @@ pub(crate) struct NodeEnd {
pub character: usize,
}
/// A link inside a run: the characters it covers and where it leads.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RunLink {
pub chars: Range<usize>,
pub target: String,
}
/// One `TextRun` node.
pub(crate) struct RunNode<'a> {
pub id: Id,
@@ -27,8 +19,6 @@ pub(crate) struct RunNode<'a> {
/// Each character's start offset from the run's left edge, and its advance.
pub positions: &'a [f32],
pub widths: &'a [f32],
/// The links in the run, each written as a `Link` child of the run node.
pub links: &'a [RunLink],
}
/// What a text component's own node says beyond the common facts.
@@ -78,34 +68,6 @@ pub(crate) fn write_run(ctx: &Context, run: &RunNode<'_>) {
node.set_word_starts(word_starts(run.text));
node.set_text_direction(if run.rtl { accesskit::TextDirection::RightToLeft } else { accesskit::TextDirection::LeftToRight });
});
for (at, link) in run.links.iter().enumerate() {
write_link(ctx, run, at, link);
}
}
/// The `Link` child of a run for `link`: named by the characters it covers, bounded by their extent in the run.
fn write_link(ctx: &Context, run: &RunNode<'_>, at: usize, link: &RunLink) {
let end = link.chars.end.min(run.positions.len()).min(run.widths.len());
let start = link.chars.start.min(end);
if start == end {
return;
}
let name: String = run.text.chars().skip(start).take(end - start).collect();
let (from, to) = (run.positions[start], run.positions[end - 1] + run.widths[end - 1]);
let id = run.id.with(("link", at));
super::register_parent(ctx, id, run.id);
crate::runtime::egui::widgets::note_node(ctx, id);
ctx.accesskit_node_builder(id, |node| {
node.set_role(accesskit::Role::Link);
node.set_bounds(accesskit::Rect {
x0: f64::from(run.rect.min.x + from.min(to)),
y0: f64::from(run.rect.min.y),
x1: f64::from(run.rect.min.x + from.max(to)),
y1: f64::from(run.rect.max.y),
});
node.set_label(name);
node.set_url(link.target.clone());
});
}
/// Adds the text value, the text actions and the selection to the node of `id`.
+30 -29
View File
@@ -1,7 +1,7 @@
//! `Link`: text in the accent colour, always underlined, that reports a click.
use super::ButtonOutput;
use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, PartsCx, Pointer as _, Role, Styled as _};
use crate::contract::{Access, Common, Component, Cx, MeasureCx, Name, PaintUi, PartsCx, Pointer as _, Role, Styled as _};
use crate::primitives::{Span, TextLayout, TextRun, Wrap};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, FocusLook, Stateful, StyleCx, TextLook, TypeRole};
@@ -11,7 +11,8 @@ use craft_theme::variant::Tone;
use egui::{Pos2, Rect, Vec2};
use std::ops::Range;
/// The part a link in a sentence takes the pointer on, one per row the link's characters cover.
/// The part a link in a sentence takes the pointer on, one per row the link's characters cover, and its `Link` node
/// below the row's run.
const LINK: PartKey = PartKey::new("link");
/// The access node of one row of a link's sentence.
@@ -48,13 +49,13 @@ struct LaidLine {
positions: Vec<f32>,
widths: Vec<f32>,
bounds: Rect,
/// The link's characters in this row, when it covers some.
link: Option<Range<usize>>,
/// The link's characters in this row and their rect, when it covers some.
link: Option<(Range<usize>, Rect)>,
}
/// A link: drawn in the accent colour in a type role (body by default) and underlined, so colour is not its only cue.
/// A click, Enter or Space opens the URL in the same tab; a middle click, or a click with a modifier held, opens it in a new tab. The caller can also act on `clicked()`. AccessKit reports the role `Link`, with the URL when
/// it has one.
/// it has one; in a sentence the node is the paragraph, and the link is a `Link` node below each run it covers.
#[derive(crate::contract::Component, crate::contract::Props)]
pub struct Link {
#[common]
@@ -127,6 +128,7 @@ fn origin(content: Rect, flow: &Flow, layout: &TextLayout) -> Pos2 {
impl Component for Link {
const ROLE: Role = Role::LINK;
const ALT_ROLES: &'static [Role] = &[Role::PARAGRAPH];
const PARTS: bool = true;
const OVERLAYS: bool = false;
type Style = LinkStyle;
@@ -176,7 +178,6 @@ impl Component for Link {
let from = before.chars().count();
let chars = from..from + label.chars().count();
let origin = origin(cx.content_rect, &cx.flow, &layout).to_vec2();
let mut rects = Vec::new();
let mut lines = Vec::new();
let mut first = 0;
for (text, row, runs) in layout.row_lines() {
@@ -186,23 +187,17 @@ impl Component for Link {
let (start, end) = (chars.start.max(first), chars.end.min(first + count));
let covered = positions.iter().zip(&widths).skip(start.saturating_sub(first)).take(end.saturating_sub(start));
let (left, right) = covered.fold((f32::INFINITY, f32::NEG_INFINITY), |(left, right), (at, width)| (left.min(*at), right.max(at + width)));
let covers = left < right;
if covers {
let link = (left < right).then(|| {
let (min, max) = (Pos2::new(row.min.x + left, row.min.y), Pos2::new(row.min.x + right, row.max.y));
rects.push(Rect::from_min_max(min, max).translate(origin));
}
lines.push(LaidLine {
text,
positions,
widths,
bounds: row.translate(origin),
link: covers.then(|| start.saturating_sub(first)..end - first),
(start - first..end - first, Rect::from_min_max(min, max).translate(origin))
});
lines.push(LaidLine { text, positions, widths, bounds: row.translate(origin), link });
first += count;
}
self.laid.rows = rects.len() as u64;
self.laid.rtl = cx.flow.is_rtl();
self.laid.lines = lines;
let rects: Vec<Rect> = self.laid.lines.iter().filter_map(|line| line.link.as_ref().map(|(_, rect)| *rect)).collect();
self.laid.rows = rects.len() as u64;
// PLAN: a middle click on a part has no reader in `Cx`, so a link in a sentence opens in a new tab only with a modifier.
for (row, rect) in rects.into_iter().enumerate() {
let part = cx.part(LINK.at(row as u64), rect).cursor(CursorIcon::PointingHand);
@@ -229,22 +224,28 @@ impl Component for Link {
}
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
let url = self.url.as_deref();
if let Some(url) = url {
if self.sentence.is_some() {
// The paragraph is named by its text, so the link's name is its own `Link` node's alone.
access.role(Role::PARAGRAPH).name(Name::Text(self.laid.lines.iter().map(|line| line.text.as_str()).collect()));
} else if let Some(url) = &self.url {
access.url(url);
}
// A run node holds one line, so each row has its own, its offsets from its own left edge.
// A run node holds one line, so each row has its own, its offsets from its own left edge. The link's characters
// on it are the `Link` node of their part, which takes focus and the click.
let mut piece = 0;
for (row, line) in self.laid.lines.iter().enumerate() {
let node = access.node(LINE.at(row as u64), Role::TEXT_RUN).text_run(
line.text.clone(),
line.positions.clone(),
line.widths.clone(),
self.laid.rtl,
);
node.bounds(line.bounds);
if let Some(chars) = &line.link {
node.run_link(chars.clone(), url.unwrap_or_default());
let run = LINE.at(row as u64);
access
.node(run, Role::TEXT_RUN)
.text_run(line.text.clone(), line.positions.clone(), line.widths.clone(), self.laid.rtl)
.bounds(line.bounds);
let Some((chars, rect)) = &line.link else { continue };
let node = access.node(LINK.at(piece), Role::LINK).under(run).bounds(*rect);
node.name = Name::Text(line.text.chars().skip(chars.start).take(chars.len()).collect());
if let Some(url) = &self.url {
node.url(url.clone());
}
piece += 1;
}
}
+23 -6
View File
@@ -2,7 +2,7 @@
//! middle click does.
use craft_ui::buttons::Link;
use craft_ui::contract::Show as _;
use craft_ui::contract::{Role, Show as _};
use craft_ui::testing::focus::{egui_focused, key_release};
use craft_ui::testing::layout::in_region;
use craft_ui::testing::{Frames, input, pointer, trial};
@@ -30,12 +30,12 @@ const BEFORE: &str = "Open the panel and press ";
const LABEL: &str = "Show where this tool is now";
const AFTER: &str = " to find it again later on.";
/// A paragraph with the link in it, narrow enough that the sentence and the link wrap.
fn sentence(frames: &mut Frames) -> (Rect, impl FnMut(&mut egui::Ui) + use<>) {
/// A paragraph with the link in it, `width` wide: 100 is narrow enough that the sentence and the link wrap.
fn sentence(frames: &mut Frames, width: f32) -> (Rect, impl FnMut(&mut egui::Ui) + use<>) {
let shown = std::rc::Rc::new(Cell::new(Rect::NOTHING));
let seen = shown.clone();
let mut show = move |ui: &mut egui::Ui| {
let region = Rect::from_min_size(pos2(0.0, 0.0), vec2(100.0, 300.0));
let region = Rect::from_min_size(pos2(0.0, 0.0), vec2(width, 300.0));
seen.set(in_region(ui, region, |ui| Link::new(LABEL).in_sentence(BEFORE, AFTER).url("https://example.com").show(ui).rect));
};
frames.idle(2, &mut show);
@@ -47,7 +47,7 @@ fn sentence(frames: &mut Frames) -> (Rect, impl FnMut(&mut egui::Ui) + use<>) {
#[trial]
fn a_link_in_a_sentence_takes_the_press_only_on_its_words() {
let mut frames = Frames::new();
let (paragraph, mut show) = sentence(&mut frames);
let (paragraph, mut show) = sentence(&mut frames, 100.0);
pointer::click(&mut frames, paragraph.min + vec2(2.0, 2.0), &mut show);
assert!(frames.opened().is_empty(), "a press on the words before the link does nothing");
assert_eq!(egui_focused(&frames.ctx), None, "and moves no focus");
@@ -73,7 +73,7 @@ fn a_link_in_a_sentence_takes_the_press_only_on_its_words() {
assert!(hits.len() < area / 2, "the sentence's other words take none: {} of {area} points", hits.len());
let mut frames = Frames::new();
let (_, mut show) = sentence(&mut frames);
let (_, mut show) = sentence(&mut frames, 100.0);
for key in [Key::Tab, Key::Enter, Key::Space] {
frames.frame(vec![input::key_press(key, Modifiers::NONE)], &mut show);
frames.frame(vec![key_release(key, Modifiers::NONE)], &mut show);
@@ -81,3 +81,20 @@ fn a_link_in_a_sentence_takes_the_press_only_on_its_words() {
assert!(egui_focused(&frames.ctx).is_some(), "Tab stops on the link");
assert_eq!(frames.opened().len(), 2, "Enter and Space each activate it once");
}
/// A link in a sentence is one `Link` node, named and bounded by its own words inside the paragraph, and Tab gives that
/// node the focus: a screen reader meets the link once, as a link.
#[trial]
fn a_link_in_a_sentence_is_one_link_node_that_takes_the_focus() {
let mut frames = Frames::new();
let (paragraph, mut show) = sentence(&mut frames, 1000.0);
frames.frame(vec![input::key_press(Key::Tab, Modifiers::NONE)], &mut show);
frames.frame(vec![key_release(Key::Tab, Modifiers::NONE)], &mut show);
let tree = frames.tree();
let links = tree.with_role(Role::LINK);
let [link] = links[..] else { panic!("one Link node, not {}", links.len()) };
assert_eq!(tree.name_of(link), Some(LABEL), "named by the link's words");
let bounds = tree.bounds_of(link).expect("the link's bounds");
assert!(paragraph.contains_rect(bounds) && bounds.width() < paragraph.width() / 2.0, "the link's words, not the paragraph: {bounds:?}");
assert_eq!(tree.focused_key(), link, "Tab focuses the link's node");
}