diff --git a/crates/draw/src/ui/gradient/palette/mod.rs b/crates/draw/src/ui/gradient/palette/mod.rs index d9659a062..82b60fba8 100644 --- a/crates/draw/src/ui/gradient/palette/mod.rs +++ b/crates/draw/src/ui/gradient/palette/mod.rs @@ -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), } } diff --git a/crates/draw/src/ui/gradient/palette/stories.rs b/crates/draw/src/ui/gradient/palette/stories.rs index 14d6302cc..a5660ac6a 100644 --- a/crates/draw/src/ui/gradient/palette/stories.rs +++ b/crates/draw/src/ui/gradient/palette/stories.rs @@ -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 = 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::::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) diff --git a/crates/draw/src/ui/gradient/swatch.rs b/crates/draw/src/ui/gradient/swatch.rs index 2b2a36639..f982221ea 100644 --- a/crates/draw/src/ui/gradient/swatch.rs +++ b/crates/draw/src/ui/gradient/swatch.rs @@ -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); } diff --git a/crates/draw/src/ui/gradient/swatch/stories.rs b/crates/draw/src/ui/gradient/swatch/stories.rs index d7c207c66..d19ba8502 100644 --- a/crates/draw/src/ui/gradient/swatch/stories.rs +++ b/crates/draw/src/ui/gradient/swatch/stories.rs @@ -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 { diff --git a/crates/draw/src/ui/gradient/tile.rs b/crates/draw/src/ui/gradient/tile.rs index 0f0205962..7110d6b94 100644 --- a/crates/draw/src/ui/gradient/tile.rs +++ b/crates/draw/src/ui/gradient/tile.rs @@ -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)); } } diff --git a/crates/draw/src/ui/mod.rs b/crates/draw/src/ui/mod.rs index d5146a9bc..65dcc21bb 100644 --- a/crates/draw/src/ui/mod.rs +++ b/crates/draw/src/ui/mod.rs @@ -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, diff --git a/crates/draw/tests/it/gradient_fill.rs b/crates/draw/tests/it/gradient_fill.rs index 0c15f8a5c..ae28c566e 100644 --- a/crates/draw/tests/it/gradient_fill.rs +++ b/crates/draw/tests/it/gradient_fill.rs @@ -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"); +} diff --git a/crates/theme/src/variant.rs b/crates/theme/src/variant.rs index 345b51761..fb9d58b0d 100644 --- a/crates/theme/src/variant.rs +++ b/crates/theme/src/variant.rs @@ -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 diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index d2d16758c..ce7f01bfe 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -174,6 +174,7 @@ impl ShapeHooks 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); diff --git a/crates/ui-contract/src/primitives/kit.rs b/crates/ui-contract/src/primitives/kit.rs index 6baf217c3..e5cd58ead 100644 --- a/crates/ui-contract/src/primitives/kit.rs +++ b/crates/ui-contract/src/primitives/kit.rs @@ -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 { + 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); diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 8257570d5..be02e9f0a 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -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 diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index 3c54c03df..7b87f6fd5 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -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(&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(&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 diff --git a/crates/ui-contract/src/style/span.rs b/crates/ui-contract/src/style/span.rs index 7c1151069..11a75bd36 100644 --- a/crates/ui-contract/src/style/span.rs +++ b/crates/ui-contract/src/style/span.rs @@ -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. diff --git a/crates/ui-widgets/src/display/text.rs b/crates/ui-widgets/src/display/text.rs index fbbb943e1..6552a63a9 100644 --- a/crates/ui-widgets/src/display/text.rs +++ b/crates/ui-widgets/src/display/text.rs @@ -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>, - /// 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>, + /// 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