chrome-w5: net change of 3 commits

- chrome-w5: written by an agent
- chrome-w5: review fixes (review-1)
- chrome-w5: review fixes (review-1b)
This commit is contained in:
Martin Ball
2026-11-18 16:01:11 +00:00
parent b912c077f0
commit 1bbb502203
17 changed files with 398 additions and 40 deletions
+25 -4
View File
@@ -211,17 +211,30 @@ impl<'a> GradientPalette<'a> {
let default = default_sampler(self.rows);
let sampler: &Sampler = self.sampler.unwrap_or(&default);
let (groups, recent) = (self.groups, self.recent);
let (wide, high) = GradientRamp::CHIP_ASPECT;
// The browser has one cell shape for the grid and the list, so any tile makes every cell square.
let square = groups.iter().flat_map(|g| &g.items).any(|item| item.tile != GradientTile::Ramp);
let thumb =
move |cx: &craft_ui::primitives::ContentPainterCx, rect: egui::Rect, info: craft_ui::patterns::presets::ThumbInfo<'_, GradientRef>| {
if let Some(stops) = stops_of(groups, recent, *info.key) {
let (radius, edge) = GradientRamp::chip_look(&cx.style_cx());
GradientRamp::paint_chip(cx, rect, radius, &GradientRamp::colors(stops, sampler), edge);
let tile = item_of(groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile);
if tile != GradientTile::Ramp {
tile.paint(cx, rect, radius, stops, sampler, edge);
return;
}
let chip = if square {
egui::Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide)))
} else {
rect
};
GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge);
}
};
let (wide, high) = GradientRamp::CHIP_ASPECT;
let most = Env::of(ui).tokens.size.control.sm * MAX_ROWS;
let shape = if square { CellShape::Square } else { CellShape::ratio(wide, high) };
let mut browser = PresetBrowser::new(self.label, self.state, &rows)
.cell_shape(CellShape::ratio(wide, high))
.cell_shape(shape)
.tiles(PresetTiles::Chips)
.room_height(most)
.thumb(thumb);
@@ -245,6 +258,14 @@ impl<'a> GradientPalette<'a> {
pub(super) fn stops_of<'a>(groups: &'a [GradientGroup], recent: &'a [GradientStops], key: GradientRef) -> Option<&'a GradientStops> {
match key {
GradientRef::Recent(i) => recent.get(i),
GradientRef::Item { group, item } => groups.get(group)?.items.get(item).map(|preset| &preset.stops),
GradientRef::Item { .. } => item_of(groups, key).map(|preset| &preset.stops),
}
}
/// The group item `key` names; none for a recent gradient (which has stops only) or a group header.
pub(super) fn item_of(groups: &[GradientGroup], key: GradientRef) -> Option<&GradientItem> {
match key {
GradientRef::Recent(_) => None,
GradientRef::Item { group, item } => groups.get(group)?.items.get(item),
}
}
@@ -7,6 +7,7 @@ use craft_ui::testing::{StoryData, StoryOutput, story};
use egui::Ui;
use super::{GradientGroup, GradientItem, GradientPalette, GradientRef};
use crate::ui::gradient::{FocusOutline, GradientStyle, GradientTile};
use craft_color_ui::ui::gradient::{ColorStop, GradientStops};
fn pair(a: [f32; 3], b: [f32; 3]) -> GradientStops {
@@ -48,6 +49,24 @@ fn gradient_palette(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
palette(ui, data, PresetView::Grid)
}
/// Presets drawn as square tiles: a style at an angle, a focus tile, and a plain ramp among them.
#[story(GradientPalette<'static>, covers = [], title = "Tiles")]
fn gradient_palette_tiles(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let stops = pair([0.95, 0.6, 0.1], [0.5, 0.1, 0.5]);
let focus = egui::Rect::from_min_max(egui::pos2(0.25, 0.25), egui::pos2(0.75, 0.75));
let mut items: Vec<GradientItem> = GradientStyle::ALL
.into_iter()
.map(|style| GradientItem::new(format!("{style:?}"), stops.clone()).tile(GradientTile::Style { style, angle: -45.0 }))
.collect();
items.push(GradientItem::new("Focus, circle", stops.clone()).tile(GradientTile::Focus { outline: FocusOutline::Circle, focus }));
items.push(GradientItem::new("Focus, rectangle", stops.clone()).tile(GradientTile::Focus { outline: FocusOutline::Rect, focus }));
items.push(GradientItem::new("Ramp", stops));
let groups = [GradientGroup::new("Tiles", items)];
let state = data.value("state", PresetState::<GradientRef>::new());
let shown = GradientPalette::new("Gradient tiles", &groups, Bind::bound(&mut *state)).show(ui);
StoryOutput::from(shown)
}
#[story(GradientPalette<'static>, covers = [Default])]
fn gradient_palette_list(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
palette(ui, data, PresetView::List)
+7 -1
View File
@@ -76,7 +76,6 @@ pub struct GradientSwatch<'a> {
has_popup: bool,
/// How the gradient is drawn: the ramp chip, or a square two-dimensional tile.
#[prop]
#[allow(dead_code)] // P3(chrome-w5): ch.C15
tile: GradientTile,
clicked: bool,
}
@@ -119,6 +118,9 @@ impl Component for GradientSwatch<'_> {
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let height = cx.style.side;
if self.tile != GradientTile::Ramp {
return Vec2::splat(height);
}
let (wide, high) = GradientRamp::CHIP_ASPECT;
let chip = height * f32::from(wide) / f32::from(high);
let width = if cx.resolved.sizing() == Some(Sizing::FillWidth) {
@@ -152,6 +154,10 @@ impl Component for GradientSwatch<'_> {
let style = cx.style;
let default = default_sampler(self.rows);
let sampler: &Sampler = self.sampler.unwrap_or(&default);
if self.tile != GradientTile::Ramp {
self.tile.paint(&ui.content_painter(cx), cx.rect, style.radius, self.stops, sampler, style.edge);
return;
}
let colors = GradientRamp::colors(self.stops, sampler);
GradientRamp::paint_chip(&ui.content_painter(cx), cx.rect, style.radius, &colors, style.edge);
}
@@ -1,6 +1,7 @@
//! Stories of `GradientSwatch`.
use super::GradientSwatch;
use crate::ui::gradient::{FocusOutline, GradientStyle, GradientTile};
use craft_color_ui::ui::gradient::{ColorStop, GradientStops, OpacityStop, StopRows};
use craft_theme::Srgba;
use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, Sizing};
@@ -59,6 +60,28 @@ fn gradient_swatch(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
StoryOutput { clicked, ..StoryOutput::default() }.readout(craft_i18n::fmt(words.clicked.as_str(), &[("count", clicks.to_string().as_str())]))
}
/// One square tile per gradient style at an angle, and a focus tile in each outline, each with its name.
#[story(GradientSwatch, covers = [], drive = Drive::Never, title = "Tiles")]
fn gradient_swatch_tiles(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let stops = GradientStops::new(vec![stop(0.0, [0.96, 0.65, 0.14]), stop(1.0, [0.24, 0.39, 0.87])]);
let focus = egui::Rect::from_min_max(egui::pos2(0.25, 0.25), egui::pos2(0.5, 0.5));
let mut tiles: Vec<(String, GradientTile)> = GradientStyle::ALL
.into_iter()
.map(|style| (format!("{style:?}"), GradientTile::Style { style, angle: -45.0 }))
.collect();
tiles.push(("Focus, circle".to_owned(), GradientTile::Focus { outline: FocusOutline::Circle, focus }));
tiles.push(("Focus, rectangle".to_owned(), GradientTile::Focus { outline: FocusOutline::Rect, focus }));
Stack::new().show(ui, |ui, _| {
for (name, tile) in &tiles {
Row::new().show(ui, |ui, _| {
GradientSwatch::new(name.as_str(), &stops).tile(*tile).show(ui);
Text::new(name.as_str()).shade(Shade::Muted).show(ui);
});
}
});
StoryOutput::default()
}
/// A gradient fading in, enabled and disabled, each with its name.
#[story(GradientSwatch, covers = [], drive = Drive::Never, title = "Disabled")]
fn gradient_swatch_disabled(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+87 -5
View File
@@ -1,11 +1,23 @@
//! [`GradientTile`]: a square two-dimensional gradient in a swatch or the palette grid.
use std::cell::Cell;
use std::f32::consts::TAU;
use craft_color_ui::ui::gradient::{GradientStops, Sampler};
use craft_color_ui::ui::smooth_mesh;
use craft_ui::primitives::{Checker, ContentPainterCx, PaintShape, StrokeWidth};
use craft_ui::style::StyleColor;
use egui::{CornerRadius, Mesh, Rect, Vec2, vec2};
use super::GradientStyle;
/// Vertices along a side of a tile's mesh.
const TILE_STEPS: usize = 17;
/// How a gradient swatch or palette cell draws its gradient.
///
/// A tile other than [`Ramp`](GradientTile::Ramp) is one `craft_color_ui::ui::smooth_mesh` sampled through
/// [`t_at`](GradientTile::t_at).
/// [`t_at`](GradientTile::t_at). `p` below is a point in the tile's unit square (0 to 1, y down) and `c` its centre.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub enum GradientTile {
@@ -16,7 +28,8 @@ pub enum GradientTile {
Style {
/// How the gradient runs.
style: GradientStyle,
/// The angle of the gradient line, in degrees.
/// The angle of the gradient line, in degrees, in the convention of `GradientFill::angle`: 0 points right and
/// 90 points up.
angle: f32,
},
/// A square tile whose gradient runs out from `focus`.
@@ -39,8 +52,77 @@ pub enum FocusOutline {
impl GradientTile {
/// The gradient position, 0 to 1, at `p` in the tile's unit square.
pub fn t_at(&self, p: egui::Vec2) -> f32 {
let _ = p;
todo!("ch.C15")
///
/// - `Linear`: the line runs through the centre from edge to edge, 0 on the start side and 1 on the far side.
/// - `Radial`, `Reflected`, `Diamond`: 0 at the centre, 1 at the edge along the angle's direction, in circles,
/// mirrored about the centre, or in diamonds.
/// - `Angle`: the counter-clockwise sweep from the angle's direction, over a full turn.
/// - `Focus`: 0 at the focus rectangle's centre, 1 at the farthest corner, in circles or in rectangles.
///
/// `Ramp` has no second dimension: its position is `p.x`.
pub fn t_at(&self, p: Vec2) -> f32 {
let c = vec2(0.5, 0.5);
let t = match *self {
GradientTile::Ramp => p.x,
GradientTile::Style { style, angle } => {
let rad = angle.to_radians();
let d = vec2(rad.cos(), -rad.sin());
let v = p - c;
let h = (d.x.abs() + d.y.abs()) / 2.0;
let along = v.dot(d);
match style {
GradientStyle::Linear => 0.5 + along / (2.0 * h),
GradientStyle::Radial => v.length() / h,
GradientStyle::Reflected => along.abs() / h,
GradientStyle::Diamond => (along.abs() + v.dot(vec2(-d.y, d.x)).abs()) / h,
GradientStyle::Angle => {
let at = (-v.y).atan2(v.x);
(at - rad).rem_euclid(TAU) / TAU
}
}
}
GradientTile::Focus { outline, focus } => {
let f = focus.center().to_vec2();
let corners = [vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0)];
let distance = |v: Vec2| match outline {
FocusOutline::Circle => v.length(),
FocusOutline::Rect => v.x.abs().max(v.y.abs()),
};
let far = corners.iter().map(|&corner| distance(corner - f)).fold(0.0, f32::max);
if far > 0.0 { distance(p - f) / far } else { 0.0 }
}
};
if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }
}
/// Paints the tile over `rect`: the checkerboard where a colour is translucent, the gradient of `stops` through
/// `sampler`, then a thin `edge` ring. A `Ramp` tile paints nothing here; the ramp chip is the caller's.
pub(crate) fn paint(
&self,
cx: &ContentPainterCx<'_>,
rect: Rect,
radius: CornerRadius,
stops: &GradientStops,
sampler: &Sampler,
edge: StyleColor,
) {
if matches!(self, GradientTile::Ramp) || rect.width() <= 0.0 || rect.height() <= 0.0 {
return;
}
let translucent = Cell::new(false);
let at = |fx: f32, fy: f32| {
let color = sampler(stops, self.t_at(vec2(fx, fy)));
if color.a < 1.0 {
translucent.set(true);
}
color
};
let mut mesh = Mesh::default();
smooth_mesh(&mut mesh, rect, TILE_STEPS, &at);
if translucent.get() {
cx.checker_with(&Checker::new(), rect, radius);
}
cx.mesh_in(rect, radius, mesh);
cx.with_draw(|draw| draw.stroke(&PaintShape::Rect(rect, radius), StrokeWidth::Thin, edge));
}
}
+2 -2
View File
@@ -79,8 +79,8 @@ pub use crop::{
pub use crop::{PerspectiveCropQuad, PerspectiveQuad};
pub use gradient::{GradientFill, GradientFillEditor, GradientFillEditorOutput, GradientFillWords, GradientStyle};
pub use gradient::{
GradientGroup, GradientItem, GradientLine, GradientMap, GradientMapEditor, GradientMapOutput, GradientOverlay, GradientPalette, GradientRef,
GradientSwatch, LineGradient, LinePart,
FocusOutline, GradientGroup, GradientItem, GradientLine, GradientMap, GradientMapEditor, GradientMapOutput, GradientOverlay, GradientPalette,
GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart,
};
pub use measure::{
MIN_LINE, RulerBar, RulerBarOutput, RulerLine, RulerOverlay, RulerPass, RulerTool, RulerWords, box_distances, ruler_line_form, show_ruler,
+53 -1
View File
@@ -5,7 +5,7 @@ use std::rc::Rc;
use craft_behavior::EditEvent;
use craft_color_ui::ui::gradient::{ColorStop, GradientStops};
use craft_draw::ui::gradient::{GradientFill, GradientFillEditor, GradientGroup, GradientItem, GradientRef, GradientStyle};
use craft_draw::ui::gradient::{FocusOutline, GradientFill, GradientFillEditor, GradientGroup, GradientItem, GradientRef, GradientStyle, GradientTile};
use craft_theme::Srgba;
use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::presets::PresetState;
@@ -110,3 +110,55 @@ fn each_row_reports_one_gesture_of_the_whole_fill() {
assert_eq!(value, &expected, "the preset replaces the stops with centred midpoints and keeps the rest");
}
}
#[trial]
fn a_style_tile_samples_its_parameter_from_the_start_point_outward() {
let tile = |style, angle| GradientTile::Style { style, angle };
let t = |tile: GradientTile, x: f32, y: f32| tile.t_at(vec2(x, y));
// Linear at -90 runs down: 0 at the top, 1 at the bottom, equal along a row.
let down = tile(GradientStyle::Linear, -90.0);
assert!(t(down, 0.5, 0.0) < 0.01 && t(down, 0.5, 1.0) > 0.99);
assert!(t(down, 0.5, 0.25) < t(down, 0.5, 0.75));
assert!((t(down, 0.1, 0.4) - t(down, 0.9, 0.4)).abs() < 1e-4);
// At -45 the start is the top-left corner and the end the bottom-right.
let diagonal = tile(GradientStyle::Linear, -45.0);
assert!(t(diagonal, 0.0, 0.0) < 0.01 && t(diagonal, 1.0, 1.0) > 0.99);
// Radial is 0 at the centre and equal on a circle round it.
let radial = tile(GradientStyle::Radial, 0.0);
assert!(t(radial, 0.5, 0.5) < 0.01);
assert!(t(radial, 0.5, 0.5) < t(radial, 0.6, 0.5) && t(radial, 0.6, 0.5) < t(radial, 0.8, 0.5));
assert!((t(radial, 0.7, 0.5) - t(radial, 0.5, 0.3)).abs() < 1e-4);
// Reflected is mirrored about the centre.
let mirrored = tile(GradientStyle::Reflected, 0.0);
assert!(t(mirrored, 0.5, 0.5) < 0.01);
assert!((t(mirrored, 0.8, 0.3) - t(mirrored, 0.2, 0.7)).abs() < 1e-4);
assert!(t(mirrored, 0.6, 0.5) < t(mirrored, 0.9, 0.5));
// Diamond isolines run through the points of equal |dx| + |dy|, which a circle does not.
let diamond = tile(GradientStyle::Diamond, 0.0);
assert!((t(diamond, 0.7, 0.5) - t(diamond, 0.6, 0.6)).abs() < 1e-4);
assert!(t(diamond, 0.5, 0.5) < 0.01);
// Angle sweeps counter-clockwise from the start direction, rising round the centre.
let sweep = tile(GradientStyle::Angle, 0.0);
assert!(t(sweep, 0.9, 0.5) < 0.01);
assert!(t(sweep, 0.9, 0.5) < t(sweep, 0.5, 0.1), "up is a quarter turn counter-clockwise");
assert!(t(sweep, 0.5, 0.1) < t(sweep, 0.1, 0.5));
assert!(t(sweep, 0.1, 0.5) < t(sweep, 0.5, 0.9));
// Focus: 0 at the focus centre, rising outward; circles round, rectangles square.
let focus = egui::Rect::from_min_max(egui::pos2(0.25, 0.25), egui::pos2(0.75, 0.75));
let circle = GradientTile::Focus { outline: FocusOutline::Circle, focus };
let rect = GradientTile::Focus { outline: FocusOutline::Rect, focus };
for tile in [circle, rect] {
assert!(t(tile, 0.5, 0.5) < 0.01);
assert!(t(tile, 0.5, 0.5) < t(tile, 0.6, 0.5) && t(tile, 0.6, 0.5) < t(tile, 0.9, 0.5));
assert!((t(tile, 0.7, 0.5) - t(tile, 0.5, 0.3)).abs() < 1e-4);
}
// A corner-ward step along the diagonal is farther in a circle than in a rectangle.
assert!(t(circle, 0.7, 0.7) > t(rect, 0.7, 0.7) + 0.05);
assert!((t(rect, 0.7, 0.7) - t(rect, 0.7, 0.5)).abs() < 1e-4, "a rectangle's isoline is square");
}
+1 -2
View File
@@ -70,8 +70,7 @@ impl Tone {
/// The ink text and icons of the tone read in: `accent.text`, the status foreground, and the normal text for no status.
pub fn ink(self, tokens: &Tokens) -> Rgba {
let _ = tokens;
todo!("ch.C14a")
tokens.color.get(ToneTokens::of(self).fg)
}
/// The ink text and icons read in on the tone's [`soft_fill`](Self::soft_fill): `accent.on_soft`, the status
@@ -174,6 +174,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
ShowAt::Rect(rect) => rect.size(),
ShowAt::Flow => crate::layout::flow_room(ui),
};
let scx = &scx.measured_by(ui);
self.room = room;
self.indent_step = scx.control().icon;
let env = Env::of(ui);
+32
View File
@@ -291,6 +291,32 @@ pub fn ramp(rect: Rect, radius: CornerRadius, stops: &[(f32, DataColor)], axis:
vec![Shape::mesh(mesh)]
}
/// `mesh` with every vertex that lies outside a rounded corner of `rect` moved onto the arc, towards the corner's
/// centre, keeping its colour. A square corner moves nothing.
fn rounded_mesh(mut mesh: Mesh, rect: Rect, radius: CornerRadius) -> Vec<Shape> {
let most = rect.width().min(rect.height()) / 2.0;
let r = |corner: u8| f32::from(corner).min(most);
let corners = [
(r(radius.nw), rect.left_top(), egui::vec2(1.0, 1.0)),
(r(radius.ne), rect.right_top(), egui::vec2(-1.0, 1.0)),
(r(radius.sw), rect.left_bottom(), egui::vec2(1.0, -1.0)),
(r(radius.se), rect.right_bottom(), egui::vec2(-1.0, -1.0)),
];
for vertex in &mut mesh.vertices {
for &(r, corner, toward) in &corners {
if r <= 0.0 {
continue;
}
let centre = corner + toward * r;
let d = vertex.pos - centre;
if d.x * toward.x < 0.0 && d.y * toward.y < 0.0 && d.length() > r {
vertex.pos = centre + d * (r / d.length());
}
}
}
vec![Shape::mesh(mesh)]
}
/// The columns of a rounded ramp: the places of `marks` (sorted) and of samples along each corner of `corners` (its
/// radius, and whether it is at the start of the strip), each with its colour.
fn rounded_columns(marks: &[(f32, Color32)], corners: &[(f32, bool)], length: f32) -> Vec<(f32, Color32)> {
@@ -840,6 +866,12 @@ impl ContentPainterCx<'_> {
self.data_shapes(ramp(rect, radius, stops, axis));
}
/// Paints a colour `mesh` laid over `rect`, as data, with its vertices pulled inside the outline of corners of
/// `radius`, so a gradient keeps inside the rounded ring of the well it fills.
pub fn mesh_in(&self, rect: Rect, radius: CornerRadius, mesh: Mesh) {
self.data_shapes(rounded_mesh(mesh, rect, radius));
}
/// Paints the well of a plot over `rect` and returns the rect inside its edge, where the plot draws.
pub fn plot_frame(&self, rect: Rect) -> Rect {
let style = surface_style(self.tokens, SurfaceKind::Well);
@@ -299,6 +299,9 @@ impl TextRun<'_> {
if span.underline {
format.underline = egui::Stroke::new(env.tokens.stroke.thin, color);
}
if let Some(tone) = span.flag {
format.underline = egui::Stroke::new(env.tokens.stroke.thin, to_color(tone.ink(env.tokens)));
}
job.append(text_part, 0.0, format);
}
job
+17 -13
View File
@@ -68,6 +68,8 @@ pub struct StyleCx<'a> {
line_ratio: f32,
ctx: &'a Context,
values: &'a AppValues,
/// The `Ui` a collection's layout hook measures faces in; none elsewhere.
measuring: Option<&'a egui::Ui>,
}
/// A variant's look as style parts.
@@ -160,6 +162,7 @@ impl<'a> StyleCx<'a> {
line_ratio,
ctx,
values,
measuring: None,
}
}
@@ -189,10 +192,19 @@ impl<'a> StyleCx<'a> {
}
/// The size `face` has, measured from the `Ui` the collection hook fills this context from, so a collection's
/// `item_layout` measures a button's label and icon in the pass it lays out in.
pub fn face<S: crate::contract::Show>(&self, face: S) -> egui::Vec2 {
let _ = face;
todo!("rb.R25")
/// `item_layout` measures a button's label and icon in the pass it lays out in. Zero in a context no collection
/// filled, which has nothing to measure in.
pub fn face<S: crate::contract::Show>(&self, mut face: S) -> egui::Vec2 {
let Some(ui) = self.measuring else { return egui::Vec2::ZERO };
crate::contract::measure_under(&mut face, ui, None, craft_behavior::Proposal::Ideal, None)
}
/// The same context measuring faces in `ui`; the collection hook calls it before it asks for a layout.
pub(crate) fn measured_by<'b>(&self, ui: &'b egui::Ui) -> StyleCx<'b>
where
'a: 'b,
{
StyleCx { measuring: Some(ui), ..*self }
}
/// The same context with another variant.
@@ -249,15 +261,7 @@ impl<'a> StyleCx<'a> {
/// The colour text and icons of `tone` read in.
pub fn tone(&self, tone: Tone) -> StyleColor {
let c = &self.tokens.color;
self.color(match tone {
Tone::Accent => c.accent.text,
Tone::Info => c.status.info.fg,
Tone::Good => c.status.good.fg,
Tone::Warn => c.status.warn.fg,
Tone::Bad => c.status.bad.fg,
_ => c.text.normal,
})
self.color(tone.ink(self.tokens))
}
/// The tinted background text and icons of `tone` sit on: the status or accent background, and the sunken surface
+3 -3
View File
@@ -47,9 +47,9 @@ impl<'a> Span<'a> {
}
/// Underlines the span in the ink of `tone` (spelling `Bad`, grammar `Info`).
pub fn flag(self, tone: Tone) -> Self {
let _ = tone;
todo!("ch.C14a")
pub fn flag(mut self, tone: Tone) -> Self {
self.flag = Some(tone);
self
}
/// Italic.
+43 -9
View File
@@ -3,6 +3,8 @@
use crate::contract::{Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Styled as _};
use crate::primitives::{DocRun, DocText, Span, TextRun, Wrap};
use crate::runtime::env::Label;
use std::borrow::Cow;
use crate::style::{ComponentStyle, StyleCx, TextLook, TypeRole};
use craft_behavior::{Metrics, Proposal, Sense};
use craft_theme::{Stateful, States, variant::Tone};
@@ -76,14 +78,16 @@ pub struct Text {
elide: Elide,
/// The styled spans that replace the label's text; empty for plain text.
spans: Vec<DocRun<'static>>,
/// The label's text is set in italics.
/// The interface spans that replace the label's text, in the type role, shade and tone of the text; empty for plain text.
styled: Vec<Span<'static>>,
/// Whether every span is italic, a value set apart from the words around it.
italic: bool,
}
impl Text {
/// `text`, which is also its accessible name, in body type and the normal shade.
pub fn new(text: impl Into<Label>) -> Self {
Text { common: Common::new(), shade: Shade::Normal, tone: None, role: TypeRole::Body, elide: Elide::Off, spans: Vec::new(), italic: false }
Text { common: Common::new(), shade: Shade::Normal, tone: None, role: TypeRole::Body, elide: Elide::Off, spans: Vec::new(), styled: Vec::new(), italic: false }
.label(text)
}
@@ -97,13 +101,17 @@ impl Text {
text
}
/// Interface text from styled `spans`; the joined text is its accessible name.
/// Interface text from styled `spans`; the joined text is its accessible name. The spans take the type role, shade
/// and tone of the text, as plain text does; each span adds its own emphasis (italic, strong, a flag underline).
pub fn styled(spans: Vec<Span<'static>>) -> Self {
let _ = spans;
todo!("ch.C14b")
let label: String = spans.iter().map(|span| span.text.as_ref()).collect();
let mut text = Text::new(label);
text.styled = spans;
text
}
/// Sets the text in italics: a value set apart from the words around it.
/// Sets the text in italics: a value set apart from the words around it. The resolved label is what is set, so a
/// catalogue word shows in its own language.
pub fn italic(mut self) -> Self {
self.italic = true;
self
@@ -114,7 +122,35 @@ impl Text {
if self.elide == Elide::Off { doc } else { doc.elide() }
}
/// The spans of the text: its styled spans when it has them, else `label` as one, each italic under `italic`.
fn spans_of<'a>(&self, label: &'a str) -> Vec<Span<'a>> {
let mut spans: Vec<Span<'a>> = if self.styled.is_empty() { vec![Span::new(label)] } else { self.styled.clone() };
if self.italic {
spans.iter_mut().for_each(|span| span.italic = true);
}
spans
}
/// The run of the whole text.
fn run<'a>(&self, role: TypeRole, label: &'a str) -> TextRun<'a> {
let run = if self.styled.is_empty() && !self.italic { TextRun::new(label) } else { TextRun::spans(self.spans_of(label)) };
self.shaped(run, role)
}
/// One run per word of the text, each in the style of the span it is in, to find the narrowest the text can wrap to.
fn word_runs<'a>(&self, role: TypeRole, label: &'a str) -> Vec<TextRun<'a>> {
let mut runs = Vec::new();
for span in self.spans_of(label) {
for word in span.text.split_whitespace() {
let mut one = span.clone();
one.text = Cow::Owned(word.to_owned());
runs.push(self.shaped(TextRun::spans(vec![one]), role));
}
}
runs
}
fn shaped<'a>(&self, run: TextRun<'a>, role: TypeRole) -> TextRun<'a> {
let wrap = match self.elide {
Elide::Off => Wrap::Wrap,
Elide::End => Wrap::Elide,
@@ -122,7 +158,6 @@ impl Text {
Elide::Start => Wrap::ElideStart,
Elide::Path => Wrap::ElidePath,
};
let run = if self.italic { TextRun::spans(vec![Span::new(label).italic()]) } else { TextRun::new(label) };
run.role(role).wrap(wrap)
}
}
@@ -161,8 +196,7 @@ impl Component for Text {
}
let role = cx.style.text.role;
// A line breaks between words, never inside one: a wrapped text is never narrower than its widest word.
let widest =
|| cx.resolved.label.split_whitespace().map(|word| cx.layout_at(&self.run(role, word), f32::INFINITY).size().x).fold(0.0, f32::max);
let widest = || self.word_runs(role, cx.resolved.label).iter().map(|word| cx.layout_at(word, f32::INFINITY).size().x).fold(0.0, f32::max);
if cx.proposal == Proposal::Min && self.elide == Elide::Off {
let widest = widest();
return Vec2::new(widest, cx.layout_at(&self.run(role, cx.resolved.label), widest).size().y);
@@ -3,6 +3,7 @@
use super::{Elide, Shade, Text};
use crate::contract::{Props as _, Show as _, ShowContainer as _};
use crate::layout_components::{Grid, Row};
use crate::primitives::Span;
use crate::style::TypeRole;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_behavior::ColumnWidth;
@@ -60,6 +61,26 @@ fn text_toned(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Text::new("Enter a value between 0 and 100").role(TypeRole::Caption).tone(Tone::Bad).show(ui).into()
}
/// Interface text of several spans: a match highlight, a strong word, an italic value, and words flagged by tone.
#[story(Text, covers = [], drive = Drive::Never)]
fn text_styled(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Text::styled(vec![
Span::new("Find "),
Span::new("layer").highlight(),
Span::new(" in "),
Span::new("Background").strong(),
Span::new(" = "),
Span::new("0.5").italic().tabular(),
Span::new(", a "),
Span::new("mispelled").flag(Tone::Bad),
Span::new(" and a "),
Span::new("clumsy").flag(Tone::Info),
Span::new(" word."),
])
.show(ui)
.into()
}
/// One line each, cut at the end, the middle and the start, a path that drops leading folders, and a right-to-left
/// name that keeps its logical start.
#[story(Text, covers = [], drive = Drive::Never)]
@@ -0,0 +1,60 @@
//! `AltTextField`: the box and the check are named, typing commits the description, and the check marks every
//! target decorative, which disables the box without clearing its text.
use craft_behavior::Mixed;
use craft_ui::contract::{Bind, Role, Show as _};
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::{AltText, AltTextField};
use egui::{Key, Modifiers};
use std::cell::RefCell;
use std::rc::Rc;
const PROMPT: &str = "Describe this object";
fn rig(start: AltText) -> (Fixture, Rc<RefCell<AltText>>) {
let value = Rc::new(RefCell::new(start));
let shown = value.clone();
let mut fixture = Fixture::new(move |ui| {
let _ = AltTextField::new(PROMPT, Bind::bound(&mut *shown.borrow_mut())).show(ui);
});
fixture.settle();
(fixture, value)
}
/// Whether the description box is disabled in the access tree.
fn box_disabled(fixture: &Fixture) -> bool {
let boxes = fixture.by_role(Role::MULTILINE_TEXT_INPUT);
let node = boxes.first().expect("the description box is a multi-line text input").node;
fixture.tree().is_disabled_key(node)
}
#[trial]
fn marking_decorative_disables_the_description_and_keeps_its_text() {
let (mut fixture, value) = rig(AltText::new(""));
assert!(fixture.by_label(PROMPT).is_some(), "the field is named by its prompt");
let check = fixture.by_role(Role::CHECK_BOX).remove(0);
assert!(!box_disabled(&fixture), "the box edits while the object is not decorative");
let description = fixture.by_role(Role::MULTILINE_TEXT_INPUT).remove(0);
fixture.click(&description);
fixture.type_text("A green circle");
fixture.key(Key::Tab, Modifiers::NONE);
fixture.idle(2);
assert_eq!(value.borrow().text, Mixed::Same("A green circle".to_owned()), "typing commits the description");
fixture.click(&check);
fixture.idle(2);
assert_eq!(value.borrow().decorative, Mixed::Same(true), "the check marks the object decorative");
assert_eq!(value.borrow().text, Mixed::Same("A green circle".to_owned()), "the description keeps its text");
assert!(box_disabled(&fixture), "the box is disabled while every target is decorative");
let (mut fixture, value) = rig(AltText::parts(Mixed::Same("Kept".to_owned()), Mixed::Mixed));
assert!(!box_disabled(&fixture), "the box edits while only some targets are decorative");
let check = fixture.by_role(Role::CHECK_BOX).remove(0);
fixture.click(&check);
fixture.idle(2);
assert_eq!(value.borrow().decorative, Mixed::Same(true), "a mixed check sets every target decorative");
assert_eq!(value.borrow().text, Mixed::Same("Kept".to_owned()));
assert!(box_disabled(&fixture));
}
+1
View File
@@ -1,4 +1,5 @@
mod access;
mod alt_text;
mod chips;
mod edit_menu;
mod fields;