document-panels-w4: net change of 1 commits

- document-panels-w4: written from its sheet
This commit is contained in:
bflatastic
2026-11-21 21:27:41 +07:00
parent 8be8078c03
commit a795af69d1
5 changed files with 313 additions and 50 deletions
+8 -5
View File
@@ -121,9 +121,9 @@ impl<'a> TextRun<'a> {
}
/// Sets the colour of the run's link spans.
pub fn link_color(self, color: Color32) -> Self {
let _ = color;
todo!("dp.R2")
pub fn link_color(mut self, color: Color32) -> Self {
self.link_color = Some(color);
self
}
/// Sets the colour.
@@ -299,6 +299,8 @@ impl TextRun<'_> {
to_color(text.muted)
} else if span.shortcut {
to_color(text.faint)
} else if span.link {
self.link_color.unwrap_or(base)
} else {
base
};
@@ -496,8 +498,9 @@ impl TextLayout {
runs
}
/// Every row as its text, its rect from the galley's origin and its bidi runs, for the AccessKit run nodes.
pub(crate) fn row_lines(&self) -> Vec<(String, egui::Rect, Vec<LayoutRun>)> {
/// Every row as its text, its rect from the galley's origin and its bidi runs: the one per-row geometry, read by
/// the AccessKit run nodes and by a component that hits parts of a wrapped run, such as a link in a sentence.
pub fn row_lines(&self) -> Vec<(String, egui::Rect, Vec<LayoutRun>)> {
(0..self.galley.rows.len())
.map(|at| {
let placed = &self.galley.rows[at];
+3 -2
View File
@@ -46,8 +46,9 @@ impl<'a> Span<'a> {
}
/// Makes the span a link: it takes the run's link colour and the pointer.
pub fn link(self) -> Self {
todo!("dp.R2")
pub fn link(mut self) -> Self {
self.link = true;
self
}
/// Italic.
+109 -5
View File
@@ -3,9 +3,10 @@
use super::kit::{Count, Dismissed, List, ROW_H, RowOut, Words};
use craft_behavior::{
CellAt, CellRange, CellSelection, ColumnKey, EditEvent, EditEvents, ItemSource, PartKey, ScrollPos, Selection, SelectionModel as _, Sense,
SheetLayout, SpanLayout, keyed,
CellAt, CellRange, CellSelection, ColumnKey, EditEvent, EditEvents, GestureId, ItemSource, Mixed, PartKey, ScrollPos, Selection, SelectionModel as _,
Sense, SheetLayout, SpanLayout, keyed,
};
use craft_keymap::Mods;
use craft_ui::contract::{
Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, EditResponse, Focus as _,
MeasureCx, PartsCx, Props as _, Role, SelectMode, ShowCollection as _, request_rename,
@@ -122,6 +123,28 @@ impl Component for ProbeRow {
}
}
/// What the stub rename editor reports for a typed Enter: the key, the text typed, the modifiers held with it, and how
/// often the editor was shown.
struct Typing {
enter: Cell<bool>,
text: Cell<Option<String>>,
mods: Cell<Mods>,
shown: Cell<usize>,
}
impl Typing {
fn new() -> Self {
Typing { enter: Cell::new(false), text: Cell::new(None), mods: Cell::new(Mods::NONE), shown: Cell::new(0) }
}
/// The next pass sees one Enter with `text` typed (none: the proposed draft), with Shift held when `shift`.
fn press(&self, text: Option<&str>, shift: bool) {
self.text.set(text.map(str::to_owned));
self.mods.set(if shift { Mods::SHIFT } else { Mods::NONE });
self.enter.set(true);
}
}
/// A list of `ProbeRow`s over `SpanLayout`, rows of the control height or of the heights they measure.
#[derive(craft_ui::contract::Component)]
#[component(collection)]
@@ -136,6 +159,8 @@ struct Probe<'a> {
auto: bool,
/// The rename draft every row proposes, and whether the rename field reports Enter.
rename: Option<(&'a str, &'a Cell<bool>)>,
/// The typed Enter the rename field reports, one per `Typing::press`.
typing: Option<&'a Typing>,
}
impl<'a> Probe<'a> {
@@ -148,6 +173,7 @@ impl<'a> Probe<'a> {
scroll: None,
auto: false,
rename: None,
typing: None,
}
}
@@ -158,6 +184,13 @@ impl<'a> Probe<'a> {
self
}
/// Rows rename with `draft` proposed; the field reports the Enters `typing` is given, each once.
fn typing(mut self, draft: &'a str, typing: &'a Typing) -> Self {
self = self.renaming(draft, &typing.enter);
self.typing = Some(typing);
self
}
fn auto(mut self) -> Self {
self.auto = true;
self
@@ -211,9 +244,22 @@ impl Collection for Probe<'_> {
}
fn rename_editor(&mut self, ui: &mut Ui, _: Bind<'_, String>, label: Rect, _: &str) -> Option<EditResponse<String>> {
let (_, enter) = self.rename?;
let mut editor = EditResponse::lifted(ui.allocate_rect(label, egui::Sense::hover()), EditEvents::new(), None);
editor.submitted = enter.get();
let (draft, enter) = self.rename?;
let mut events = EditEvents::new();
let (submitted, mods) = match self.typing {
Some(typing) => {
typing.shown.set(typing.shown.get() + 1);
let pressed = enter.replace(false);
if pressed && let Some(text) = typing.text.take() {
events.push(EditEvent::commit(GestureId::new(0), Mixed::Same(draft.to_owned()), text));
}
(pressed, typing.mods.get())
}
None => (enter.get(), Mods::NONE),
};
let mut editor = EditResponse::lifted(ui.allocate_rect(label, egui::Sense::hover()), events, None);
editor.submitted = submitted;
editor.submit_mods = mods;
Some(editor)
}
}
@@ -542,3 +588,61 @@ fn enter_on_an_untyped_rename_commits_only_a_proposed_draft() {
assert_eq!(renamed("proposed"), ["proposed"], "Enter accepts the proposed draft");
assert!(renamed("b").is_empty(), "a draft equal to the row's text reports no commit");
}
/// Shift+Enter in a rename field applies the name as a commit and the rename goes on, each Shift+Enter its own gesture;
/// plain Enter commits and ends it. The proposed draft does the same with Shift.
#[trial]
fn shift_enter_applies_a_rename_and_keeps_the_field_open() {
let (log, typing, words) = (Log::new(), Typing::new(), Words::flat(&["a", "b", "c"]));
let mut frames = Frames::new();
let mut show = |ui: &mut Ui| {
in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| {
let list = Probe::new(SelectMode::Single).id_salt("list").typing("proposed", &typing);
log.take(list.show_items(ui, &words, &mut |key, _| ProbeRow::new(*key, log)));
});
};
let commits = || -> Vec<(GestureId, String)> {
log.events
.borrow()
.iter()
.filter_map(|event| match event {
CollectionEvent::Rename(EditEvent::Commit { id, after, .. }) => Some((*id, after.name.clone())),
_ => None,
})
.collect()
};
frames.idle(3, &mut show);
request_rename(&frames.ctx, log.id(), &1_usize);
frames.idle(3, &mut show);
assert!(typing.shown.get() > 0, "the rename shows its editor");
typing.press(Some("one"), true);
frames.frame(vec![], &mut show);
assert_eq!(commits().iter().map(|(_, name)| name.as_str()).collect::<Vec<_>>(), ["one"], "Shift+Enter reports the typed name once");
let shown = typing.shown.get();
frames.idle(2, &mut show);
assert!(typing.shown.get() > shown, "the rename goes on: the editor shows in the next passes");
assert_eq!(commits().len(), 1, "an idle pass reports nothing more");
typing.press(Some("two"), true);
frames.frame(vec![], &mut show);
let applied = commits();
assert_eq!(applied.len(), 2, "a second Shift+Enter is a second commit");
assert_ne!(applied[0].0, applied[1].0, "each is its own gesture, so its own undo step");
typing.press(Some("three"), false);
frames.frame(vec![], &mut show);
assert_eq!(commits().len(), 3, "plain Enter commits");
let shown = typing.shown.get();
frames.idle(2, &mut show);
assert_eq!(typing.shown.get(), shown, "and ends the rename");
request_rename(&frames.ctx, log.id(), &1_usize);
frames.idle(3, &mut show);
typing.press(None, true);
frames.frame(vec![], &mut show);
assert_eq!(commits().last().map(|(_, name)| name.as_str()), Some("proposed"), "Shift+Enter on a proposed draft commits it");
let shown = typing.shown.get();
frames.idle(2, &mut show);
assert!(typing.shown.get() > shown, "and keeps the rename going");
}
+134 -36
View File
@@ -1,13 +1,18 @@
//! `Link`: text in the accent colour, always underlined, that reports a click.
use super::ButtonOutput;
use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Pointer as _, Role, Styled as _};
use crate::contract::{Access, Common, Component, Cx, MeasureCx, 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};
use craft_behavior::{Flow, Metrics, PointerButton, PressPhase, Proposal, Sense};
use craft_behavior::{CursorIcon, Flow, Metrics, PartKey, PointerButton, PressPhase, Proposal, Sense};
use craft_theme::States;
use craft_theme::variant::Tone;
use craft_theme::{Contrast, States};
use egui::{Pos2, Vec2};
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.
const LINK: PartKey = PartKey::new("link");
/// The style of a link.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
@@ -17,11 +22,25 @@ pub struct LinkStyle {
metrics: Metrics,
#[style(focus)]
focus: FocusLook,
/// The text and underline colour: `accent.solid`, as PhotoCraft's links; `accent.text` at high contrast, which meets the text contrast `accent.solid` does not.
/// The link look (`StyleCx::link_look`), or the tone's colour in its place.
#[style(text)]
text: TextLook,
}
/// What `parts` found of a link in a sentence, for `update` and `access`.
#[derive(Clone, Debug, Default)]
struct Laid {
/// The rows the link's characters cover: the parts `LINK.at(0)..LINK.at(rows)`.
rows: u64,
/// The paragraph's text and each character's start offset and advance in its row, rows in order.
text: String,
positions: Vec<f32>,
widths: Vec<f32>,
rtl: bool,
/// The link's characters in the paragraph.
chars: Range<usize>,
}
/// 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.
@@ -43,49 +62,80 @@ pub struct Link {
#[style_key]
#[prop]
tone: Option<Tone>,
/// The text before and after the link when it sits in a sentence.
sentence: Option<(Label, Label)>,
laid: Laid,
}
impl Link {
/// A link labelled `label`, in body type.
pub fn new(label: impl Into<crate::runtime::env::Label>) -> Self {
pub fn new(label: impl Into<Label>) -> Self {
use crate::contract::Props as _;
Link { common: Common::new(), url: None, role: TypeRole::Body, wrap: Wrap::Line, tone: None }.label(label)
Link { common: Common::new(), url: None, role: TypeRole::Body, wrap: Wrap::Line, tone: None, sentence: None, laid: Laid::default() }
.label(label)
}
/// Sets the link in a wrapped paragraph `before` + the label + `after`, in the body ink. Only the link's characters
/// take the pointer. It is one Tab stop, and click, Enter and Space activate it.
#[must_use]
pub fn in_sentence(self, before: impl Into<crate::runtime::env::Label>, after: impl Into<crate::runtime::env::Label>) -> Self {
let _ = (before, after);
todo!("dp.R2")
pub fn in_sentence(mut self, before: impl Into<Label>, after: impl Into<Label>) -> Self {
self.sentence = Some((before.into(), after.into()));
self.wrap = Wrap::Wrap;
self
}
fn run<'a>(&self, label: &'a str) -> TextRun<'a> {
TextRun::spans(vec![Span::new(label).underline()]).role(self.role).wrap(self.wrap)
/// The sentence's text before and after the link in the env's words.
fn around(&self, resolve: impl Fn(&Label) -> Label) -> Option<(Label, Label)> {
self.sentence.as_ref().map(|(before, after)| (resolve(before), resolve(after)))
}
/// The run: the link span alone, or the paragraph `before` + link + `after` (empty stretches left out).
fn run<'a>(&self, label: &'a str, (before, after): (&'a str, &'a str)) -> TextRun<'a> {
let spans = [Span::new(before), Span::new(label).link().underline(), Span::new(after)];
TextRun::spans(spans.into_iter().filter(|span| span.link || !span.text.is_empty()).collect()).role(self.role).wrap(self.wrap)
}
/// Whether the link was activated this pass: on the node, or on one of its parts in a sentence.
fn activated(&self, cx: &Cx<'_, Self>) -> bool {
cx.activation().is_some() || (0..self.laid.rows).any(|row| cx.part_activated(LINK.at(row)).is_some())
}
}
/// The text of the stretches around a link, as `Link::run` takes them.
fn stretches(around: &Option<(Label, Label)>) -> (&str, &str) {
around.as_ref().map_or(("", ""), |(before, after)| (before.as_str(), after.as_str()))
}
/// Where the layout is painted in the content rect: a single line is centred with its underline in a taller rect, so
/// the underline follows the text.
fn origin(content: Rect, flow: &Flow, layout: &TextLayout) -> Pos2 {
let spare = if layout.galley.rows.len() <= 1 { (content.height() - painted_height(layout)).max(0.0) } else { 0.0 };
let line = Flow::new(content, flow.is_rtl()).take_start(layout.size().x).0;
Pos2::new(line.left(), content.top() + spare / 2.0)
}
impl Component for Link {
const ROLE: Role = Role::LINK;
const PARTS: bool = false;
const PARTS: bool = true;
const OVERLAYS: bool = false;
type Style = LinkStyle;
type Output = ButtonOutput;
fn style(cx: &StyleCx<'_>, key: LinkStyleKey) -> LinkStyle {
let colors = &cx.tokens.color;
let accent = if cx.contrast() == Contrast::High { colors.accent.text } else { colors.accent.solid };
let color = key.tone.map_or_else(|| cx.color(accent), |tone| cx.tone(tone));
LinkStyle {
metrics: Metrics::new(),
focus: cx.focus_look(),
text: TextLook::new(TypeRole::Body, Stateful::new(color).off(States::new(color, color, color, cx.color(colors.text.disabled)))),
}
let text = match key.tone {
Some(tone) => {
let color = cx.tone(tone);
TextLook::new(TypeRole::Body, Stateful::new(color).off(States::new(color, color, color, cx.color(cx.tokens.color.text.disabled))))
}
// PLAN: `link_look` takes the enabled state while the style is per key, so the off state is the look's own.
None => cx.link_look(true),
};
LinkStyle { metrics: Metrics::new(), focus: cx.focus_look(), text }
}
/// A middle click opens the link in a new tab.
/// A middle click opens the link in a new tab. In a sentence the node only hovers: its parts take the click.
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS | Sense::MIDDLE_CLICK
if self.sentence.is_some() { Sense::HOVER } else { Sense::CLICK | Sense::FOCUS | Sense::MIDDLE_CLICK }
}
fn cut_first(&self) -> bool {
@@ -93,7 +143,8 @@ impl Component for Link {
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let run = self.run(cx.resolved.label);
let around = self.around(|label| cx.env.resolve(label));
let run = self.run(cx.resolved.label, stretches(&around));
// At its least a link that elides is at its readable least.
if cx.proposal == Proposal::Min && self.cut_first() {
return Vec2::new(cx.least_width(&run), painted_height(&cx.layout_at(&run, f32::INFINITY)));
@@ -102,40 +153,87 @@ impl Component for Link {
Vec2::new(layout.size().x, painted_height(&layout))
}
/// In a sentence, one part per row the link's characters cover, each as wide as those characters on the row;
/// only the first is a Tab stop.
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
self.laid = Laid::default();
let around = self.around(|label| cx.env.resolve(label));
let Some((before, label)) = around.as_ref().map(|(before, _)| (before.as_str(), cx.resolved.label)) else { return };
let run = self.run(label, stretches(&around));
let layout = cx.layout_at(&run, cx.content_rect.width());
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 first = 0;
for (text, row, runs) in layout.row_lines() {
let count = text.chars().count();
let positions: Vec<f32> = runs.iter().flat_map(|run| run.positions.iter().copied()).collect();
let widths: Vec<f32> = runs.iter().flat_map(|run| run.widths.iter().copied()).collect();
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)));
if left < right {
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));
}
self.laid.text.push_str(&text);
self.laid.positions.extend(positions);
self.laid.widths.extend(widths);
first += count;
}
self.laid.rows = rects.len() as u64;
self.laid.rtl = cx.flow.is_rtl();
self.laid.chars = chars;
// 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);
if row == 0 {
part.sense(Sense::CLICK | Sense::FOCUS).focusable();
} else {
part.sense(Sense::CLICK);
}
}
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let middle_click = match cx.press().phase {
PressPhase::Release { start, click: true, .. } => start.button == PointerButton::Middle,
_ => false,
};
let activation = cx.activation();
let activated = self.activated(cx);
if let Some(url) = &self.url
&& (activation.is_some() || middle_click)
&& (activated || middle_click)
{
let modified = activation.is_some_and(|activation| !activation.mods.is_none());
let modified = cx.activation().is_some_and(|activation| !activation.mods.is_none());
cx.open_url(url, middle_click || modified);
}
}
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
if let Some(url) = &self.url {
access.url(url.as_str());
let url = self.url.as_deref();
if let Some(url) = url {
access.url(url);
}
if self.sentence.is_some() {
// A run node holds one line, so the rows' offsets are each from their own row's left edge.
let laid = &self.laid;
access.text_run(laid.text.clone(), laid.positions.clone(), laid.widths.clone(), laid.rtl);
access.run_link(laid.chars.clone(), url.unwrap_or_default());
}
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let color = cx.resolve(&cx.style.text.color);
let draw = ui.draw();
let run = self.run(cx.resolved.label).color(color);
let around = self.around(|label| cx.env.resolve(label));
let run = self.run(cx.resolved.label, stretches(&around)).link_color(color);
let layout = draw.layout(&run, cx.content_rect.width());
// A single line is centred with its underline in a taller rect, so the underline follows the text.
let spare = if layout.galley.rows.len() <= 1 { (cx.content_rect.height() - painted_height(&layout)).max(0.0) } else { 0.0 };
let top = cx.content_rect.top() + spare / 2.0;
let line = Flow::new(cx.content_rect, cx.flow.is_rtl()).take_start(layout.size().x).0;
draw.galley(Pos2::new(line.left(), top), &layout);
draw.galley(origin(cx.content_rect, &cx.flow, &layout), &layout);
}
fn finish(self, cx: Cx<'_, Self>) -> ButtonOutput {
ButtonOutput::of(&cx, cx.activation().is_some())
ButtonOutput::of(&cx, self.activated(&cx))
}
}
+59 -2
View File
@@ -4,8 +4,9 @@
use craft_ui::buttons::Link;
use craft_ui::contract::Show as _;
use craft_ui::testing::layout::in_region;
use craft_ui::testing::{Frames, pointer, trial};
use egui::{Modifiers, Rect, pos2, vec2};
use craft_ui::testing::focus::{egui_focused, key_release};
use craft_ui::testing::{Frames, input, pointer, trial};
use egui::{Key, Modifiers, Rect, pos2, vec2};
use std::cell::Cell;
#[trial]
@@ -24,3 +25,59 @@ fn a_modified_click_opens_the_link_in_a_new_tab() {
let tabs: Vec<bool> = frames.opened().iter().map(|(_, new_tab)| *new_tab).collect();
assert_eq!(tabs, [false, true], "a plain click opens in the same tab, a Cmd/Ctrl click in a new one");
}
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)) {
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));
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);
(shown.get(), show)
}
/// Drives the link in a sentence by the pointer over the whole paragraph and by the keyboard: only its own words take a
/// press, on every row they wrap onto, and it is one Tab stop that Enter and Space activate.
#[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);
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");
let mut hits = Vec::new();
let mut y = paragraph.min.y + 2.0;
while y < paragraph.max.y {
let mut x = paragraph.min.x + 2.0;
while x < paragraph.max.x {
let before = frames.opened().len();
pointer::click(&mut frames, pos2(x, y), &mut show);
if frames.opened().len() > before {
hits.push(pos2(x, y));
}
x += 6.0;
}
y += 6.0;
}
let (top, bottom) = hits.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(top, bottom), at| (top.min(at.y), bottom.max(at.y)));
assert!(!hits.is_empty(), "the link's characters take the press");
assert!(bottom - top > 14.0, "the link takes the press on each row it wraps onto: {top}..{bottom}");
let area = ((paragraph.height() / 6.0) * (paragraph.width() / 6.0)) as usize;
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);
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);
}
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");
}