pdf-comments-w5: net change of 3 commits

- pdf-comments-w5: written by an agent
- pdf-comments-w5: finished by an agent
- pdf-comments-w5: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor committed 2026-11-18 06:54:15 -05:00
1 parent 1221a396dd
commit 49628dbfc5
16 files changed
+565 -140

No files matched your search

+9 -20
View File
@@ -19,11 +19,10 @@ use craft_ui::contract::{
Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, Pages,
PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _,
};
use craft_ui::display::{Shade, Text};
use craft_ui::layout_components::Row;
use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState, ThumbInfo};
use craft_ui::primitives::textures::CachedTexture;
use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth};
use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth, WellFill};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx};
@@ -43,8 +42,6 @@ pub use paint_list::{PaintLink, PaintLinkKind, PaintList, PaintListEvent, PaintL
const CHIP_WIDTH_IN_HEIGHTS: f32 = 1.5;
/// The most tiles a pattern chip draws; a tile so small that more would fit is drawn as one stretched image.
const MAX_TILES: f32 = 4096.0;
/// The No Color diagonal stops this many control heights short of the chip's edges.
const DIAGONAL_INSET_IN_HEIGHTS: f32 = 0.15;
/// The chip's face: a mixed paint shows the colour well's mixed look.
const WELL: PartKey = PartKey::new("well");
/// The swatch list takes its content height up to this many small control heights, then scrolls, as the gradient
@@ -206,10 +203,8 @@ pub struct PaintChipStyle {
radius: egui::CornerRadius,
/// The ring on the chip's outline.
edge: StyleColor,
/// The fill of an empty chip: the field's.
/// The fill of a picture chip with no texture yet: the field's.
none_fill: StyleColor,
/// The No Color diagonal.
none_mark: StyleColor,
}
/// The last solid colour the chip held: a switch back to Solid starts from it.
@@ -429,7 +424,6 @@ impl Component for PaintChip<'_> {
radius: metrics.radius,
edge: cx.color(colors.line.control_edge),
none_fill: cx.color(colors.surface.sunken),
none_mark: cx.color(colors.status.bad.solid),
}
}
@@ -476,7 +470,7 @@ impl Component for PaintChip<'_> {
let current = FillKind::of(&paint);
let sampled = self.sampled;
let swatch_words = cx.words::<SwatchesWords>();
let recent_cells: Vec<(Label, Srgba)> = self.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
let recent = self.recent;
let full_picker = self.full_picker;
let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated());
let solid_now = if let Paint::Solid(color) = &paint { Some(*color) } else { None };
@@ -506,11 +500,12 @@ impl Component for PaintChip<'_> {
compact_picker(name.clone(), Bind::given(PickedColor::rgb(*color)), sampled).alpha(true).eyedropper(true).show(ui);
shown.edit = picked.events;
shown.screen_pick = picked.screen_pick;
if !recent_cells.is_empty() {
Text::new(words.recent.clone()).shade(Shade::Faint).show(ui);
if !recent.is_empty() {
// A palette of no swatches: the recent row alone, under its caption.
let mut chosen = *color;
let recent = SwatchPalette::new(words.recent.clone(), Bind::bound(&mut chosen), &recent_cells).show(ui);
shown.picked = recent.edit.as_ref().and_then(|edit| edit.value()).copied();
let row =
SwatchPalette::new(words.recent.clone(), Bind::bound(&mut chosen), &[]).recent(words.recent.clone(), recent).show(ui);
shown.picked = row.picked;
}
if let Some((groups, state)) = swatches.as_mut() {
let groups: &[SwatchGroup] = groups;
@@ -602,13 +597,7 @@ impl Component for PaintChip<'_> {
}
ui.draw().data_fill(&shape, DataColor::new(Color32::from(*color)));
}
Paint::None => {
let draw = ui.draw();
draw.fill(&shape, style.none_fill);
let inner = well.shrink(style.height * DIAGONAL_INSET_IN_HEIGHTS);
let (from, to) = if cx.flow.is_rtl() { (inner.right_bottom(), inner.left_top()) } else { (inner.left_bottom(), inner.right_top()) };
draw.stroke(&PaintShape::Path(vec![from, to]), StrokeWidth::Medium, style.none_mark);
}
Paint::None => ui.draw().swatch_well(well, style.radius, WellFill::None),
Paint::Gradient(preview) => {
painter.checker(well);
if !preview.stops.is_empty() {
+2 -7
View File
@@ -8,7 +8,7 @@ use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Meta as _, Outcome, Overlay, OverlayUi,
Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
};
use craft_ui::primitives::{DataWidth, Draw, Glyph, IconSpec, PaintShape, StrokeWidth};
use craft_ui::primitives::{DataWidth, Draw, Glyph, IconSpec, PaintShape, StrokeWidth, WellFill};
use craft_ui::runtime::commands::FireSource;
use craft_ui::runtime::env::Label;
use craft_ui::style::{ComponentStyle, DataColor, Flags, FocusLook, GlyphRole, StyleColor, StyleCx, SurfaceEdge, SurfaceStyle, UiTokens};
@@ -496,12 +496,7 @@ impl Component for SwatchPair<'_> {
match shown.color.same() {
Some(color) if shown.ring => paint_ring(&draw, at, *color, style),
color => {
// P3(pdf-comments-w5): CM-C25 (`swatch_well` takes a `WellFill`)
draw.swatch_well(
at,
style.radius,
color.copied().map_or(craft_ui::primitives::WellFill::Mixed, craft_ui::primitives::WellFill::Color),
);
draw.swatch_well(at, style.radius, color.copied().map_or(WellFill::Mixed, WellFill::Color));
draw.stroke(&PaintShape::Rect(at, style.radius), StrokeWidth::Thin, style.mark);
draw.stroke(&outline(at, style), StrokeWidth::Thin, style.edge);
}
+137 -48
View File
@@ -1,13 +1,16 @@
//! `SwatchPalette`: a wrapping grid of colour cells that chooses one colour. Its table of cells is
//! `craft_ui::choice::SwatchTable`.
use craft_behavior::{EditEvent, Mixed, Selection};
use craft_behavior::{EditEvent, IconId, Mixed, Selection};
use craft_theme::Srgba;
use craft_ui::choice::SwatchTable;
use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _};
use craft_ui::contract::{ActivateOn, Bind, Held, NoValue, Outcome, Pattern, Show as _, ShowContainer as _};
use craft_ui::display::{Shade, Text};
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::memory::StageAccess;
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::style::TypeRole;
use egui::{Response, Ui};
use std::sync::Arc;
@@ -21,10 +24,11 @@ mod stories;
pub struct SwatchPaletteOutput {
/// The palette's response.
pub response: Response,
/// The pick of this pass as one `Set` of the swatch's colour; `None` when nothing was picked. The palette has
/// already written it to its binding.
/// The pick of this pass as one `Set` of the swatch's colour; `None` when nothing was picked or the pick was the
/// colour already bound. The palette has already written it to its binding.
pub edit: Option<EditEvent<Srgba>>,
/// The request of the Other… row for the host's colour picker, when it was pressed this pass.
/// The request of the Other… cell for the host's colour picker, at the bound colour and keyed by the key given to
/// [`SwatchPalette::other`], when it was activated this pass.
pub pick_color: Option<ColorRequest>,
/// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`.
pub picked: Option<Srgba>,
@@ -41,11 +45,15 @@ impl Outcome for SwatchPaletteOutput {
/// A wrapping grid of colour cells from the host's list of named colours that chooses one colour.
///
/// - The swatch equal to the colour (compared in 8 bits, the first when several are) is selected; the name is its
/// tooltip.
/// - A click, Space or Enter on a swatch, or a screen reader's click, sets its colour as one `Set`.
/// tooltip. An [`optional`](Self::optional) palette bound to no colour, or to a mixed one, selects none.
/// - A click, Space or Enter on a swatch, or a screen reader's click, sets its colour as one `Set`; a click on the
/// colour already bound sets nothing and still reports `picked`.
/// - The palette is one Tab stop: Tab enters on the selected swatch (the first when none is) and the next Tab leaves.
/// Arrows move the focus through the cells as the rows lie, Up and Down to the cell above or below; they choose
/// nothing.
/// - [`other`](Self::other) adds an Other… cell after the swatches, in the same Tab stop and arrow walk: activating it
/// files `pick_color` and sets nothing. [`recent`](Self::recent) adds a captioned row of recent colours under the
/// grid, its own Tab stop, whose pick sets the colour as a swatch's does.
/// - AccessKit: a list box named by the label; each cell a list box option named by its name, with the hex colour as
/// its value.
#[must_use = "show the palette with `show`"]
@@ -54,75 +62,156 @@ pub struct SwatchPalette<'a> {
label: Label,
color: PaletteColor<'a>,
swatches: &'a [(Label, Srgba)],
/// The Other… cell: the key of its colour request and its name.
other: Option<(String, Label)>,
/// The recent row: its caption and colours.
recent: Option<(Label, &'a [Srgba])>,
}
/// What a palette binds: a colour, or a colour that may be none.
enum PaletteColor<'a> {
Color(Bind<'a, Srgba>),
Color(Held<'a, Srgba>),
Optional(Bind<'a, Option<Srgba>>),
}
impl PaletteColor<'_> {
/// The bound colour as the palette shows it: `Same(None)` for no colour (or an optional binding that holds
/// nothing), `Mixed` for several. `None` while a plain colour's binding holds no single colour, and the palette
/// shows nothing.
fn read(&mut self, cx: &mut impl StageAccess) -> Option<Mixed<Option<Srgba>>> {
match self {
PaletteColor::Color(held) => held.read(cx).map(|color| Mixed::Same(Some(color))),
PaletteColor::Optional(bind) => Some(bind.reborrow().read(cx).unwrap_or(Mixed::Same(None))),
}
}
/// Writes `after` over `before` as one `Set` named `name`.
fn write(&mut self, cx: &mut impl StageAccess, before: Mixed<Option<Srgba>>, after: Srgba, name: &str) {
match self {
PaletteColor::Color(held) => {
if let Mixed::Same(Some(before)) = before {
held.write(cx, &before, after, name);
}
}
PaletteColor::Optional(bind) => {
let _ = bind.reborrow().write(cx, &EditEvent::set(before, Some(after), Arc::from(name), None));
}
}
}
}
/// What the body picked in its pass.
#[derive(Clone, Copy)]
enum Pick {
/// A swatch or a recent colour.
Color(Srgba),
/// The Other… cell.
Other,
}
/// The cell of `swatches` whose colour is `color`, compared in 8 bits: the first when several are.
fn cell_of(swatches: &[(Label, Srgba)], color: Option<Srgba>) -> Selection<usize> {
color
.and_then(|color| swatches.iter().position(|(_, c)| c.to_rgba() == color.to_rgba()))
.map_or_else(Selection::default, Selection::single)
}
impl<'a> SwatchPalette<'a> {
/// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`.
pub fn new(label: impl Into<Label>, color: Bind<'a, Srgba>, swatches: &'a [(Label, Srgba)]) -> Self {
SwatchPalette { label: label.into(), color: PaletteColor::Color(color), swatches }
SwatchPalette { label: label.into(), color: PaletteColor::Color(Held::new(color)), swatches, other: None, recent: None }
}
/// A palette over a colour that may be none, bound as `Mixed::Same(None)`: no swatch is selected for `Same(None)`
/// or `Mixed`, and a pick writes `Mixed::Same(Some(colour))`.
/// A palette over a colour that may be none: a host binds its `Mixed<Option<Srgba>>` with `Bind::bound_mixed`.
/// No swatch is selected for `Same(None)` or `Mixed`, and a pick writes `Mixed::Same(Some(colour))` and reports
/// the same `edit` as [`new`](Self::new), its `before` the colour or `Mixed` when there was none.
pub fn optional(label: impl Into<Label>, color: Bind<'a, Option<Srgba>>, swatches: &'a [(Label, Srgba)]) -> Self {
SwatchPalette { label: label.into(), color: PaletteColor::Optional(color), swatches }
SwatchPalette { label: label.into(), color: PaletteColor::Optional(color), swatches, other: None, recent: None }
}
/// An Other… row, keyed `key` and named `label`, that asks the host's colour picker.
/// An Other… cell after the swatches, named `label`: activating it files a `ColorRequest` keyed `key` at the bound
/// colour as `pick_color`, for the host's own picker, and sets nothing.
#[must_use]
#[allow(dead_code)] // P3(pdf-comments-w5): CM-C26
pub fn other(self, key: impl Into<String>, label: impl Into<Label>) -> Self {
let _ = (key.into(), label.into());
todo!("CM-C26")
pub fn other(mut self, key: impl Into<String>, label: impl Into<Label>) -> Self {
self.other = Some((key.into(), label.into()));
self
}
/// A row of recent `colors` under `caption`.
/// A row of recent `colors` under `caption`, below the grid, each named by its hex; an empty slice shows no row.
#[must_use]
#[allow(dead_code)] // P3(pdf-comments-w5): CM-C26
pub fn recent(self, caption: impl Into<Label>, colors: &'a [Srgba]) -> Self {
let _ = (caption.into(), colors);
todo!("CM-C26")
pub fn recent(mut self, caption: impl Into<Label>, colors: &'a [Srgba]) -> Self {
self.recent = Some((caption.into(), colors));
self
}
/// Shows the palette.
pub fn show(self, ui: &mut Ui) -> SwatchPaletteOutput {
let SwatchPalette { label, color, swatches } = self;
// P3(pdf-comments-w5): CM-C26 (the optional binding)
let color = match color {
PaletteColor::Color(color) => color,
PaletteColor::Optional(optional) => {
let _ = optional;
todo!("CM-C26")
}
};
let mut held = Held::new(color);
let SwatchPalette { label, mut color, swatches, other, recent } = self;
let recent = recent.filter(|(_, colors)| !colors.is_empty());
let recent_cells: Vec<(Label, Srgba)> =
recent.iter().flat_map(|(_, colors)| colors.iter()).map(|color| (Label::from(color.to_hex()), *color)).collect();
let name = label.clone();
let mut shown = Stack::new().show(ui, |ui, cx| {
let before = held.read(cx)?;
let selected = swatches.iter().position(|(_, c)| c.to_rgba() == before.to_rgba());
let mut current = selected.map_or_else(Selection::default, Selection::single);
let table = SwatchTable::new(label.clone(), swatches).tips(true).wells(true).selection(Bind::bound(&mut current)).show_all(ui);
let picked = table.selected.or(table.open)?;
let after = swatches.get(picked)?.1;
if after.to_rgba() == before.to_rgba() {
return None;
let before = color.read(cx)?;
let bound = before.same().copied().flatten();
let mut current = cell_of(swatches, bound);
// A palette of recent colours alone has no grid: an empty table would be an empty list box in the tree.
let mut pick = None;
if !swatches.is_empty() || other.is_some() {
// Every click activates, so a click on the swatch already selected, which changes no selection, still picks.
let mut table = SwatchTable::new(label.clone(), swatches)
.tips(true)
.wells(true)
.activate(ActivateOn::Click)
.selection(Bind::bound(&mut current));
if let Some((_, other_label)) = &other {
table = table.trailing(other_label.clone(), IconId::new("plus"));
}
let table = table.show_all(ui);
// The Other… cell is keyed `swatches.len()`, past the swatches.
pick = table.selected.or(table.open).and_then(|at| match swatches.get(at) {
Some((_, picked)) => Some(Pick::Color(*picked)),
None => (other.is_some() && at == swatches.len()).then_some(Pick::Other),
});
}
Some((before, after))
if let Some((caption, _)) = &recent {
Text::new(caption.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
let mut current = cell_of(&recent_cells, bound);
let row = SwatchTable::new(caption.clone(), &recent_cells)
.tips(true)
.wells(true)
.activate(ActivateOn::Click)
.selection(Bind::bound(&mut current))
.show_all(ui);
if let Some((_, picked)) = row.selected.or(row.open).and_then(|at| recent_cells.get(at)) {
pick = Some(Pick::Color(*picked));
}
}
Some((before, pick))
});
// Once per pass, after the real run: the picked colour is stored and reported.
let edit = shown
.settle(|cx, picked| {
let (before, after) = picked.take()?;
held.write(cx, &before, after, name.as_str());
Some(EditEvent::set(Mixed::Same(before), after, Arc::from(name.as_str()), None))
// Once per pass, after the real run: a changed colour is stored and reported, every pick is reported.
let settled = shown
.settle(|cx, result| {
let (before, pick) = result.take()?;
let bound = before.same().copied().flatten();
match pick? {
Pick::Other => {
let key = other.as_ref().map(|(key, _)| key.clone())?;
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone()))))
}
Pick::Color(after) => {
let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba());
let edit = (!unchanged).then(|| {
color.write(cx, before, after, name.as_str());
let reported = bound.map_or(Mixed::Mixed, Mixed::Same);
EditEvent::set(reported, after, Arc::from(name.as_str()), None)
});
Some((Some(after), edit, None))
}
}
})
.flatten();
SwatchPaletteOutput { response: shown.output, edit, pick_color: None, picked: None }
let (picked, edit, pick_color) = settled.unwrap_or((None, None, None));
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked }
}
}
+35
View File
@@ -1,6 +1,7 @@
//! Stories of `SwatchPalette`.
use super::SwatchPalette;
use craft_behavior::Mixed;
use craft_theme::Srgba;
use craft_ui::contract::Bind;
use craft_ui::runtime::env::Label;
@@ -23,10 +24,44 @@ const PALETTE: [(&str, Srgba); 12] = [
("Grey", Srgba::rgb(0.53, 0.55, 0.57)),
];
/// The recent colours of the Other… story.
const RECENT: [Srgba; 3] = [Srgba::rgb(0.10, 0.20, 0.30), Srgba::rgb(0.98, 0.80, 0.70), Srgba::rgb(0.40, 0.10, 0.50)];
fn named(entries: impl IntoIterator<Item = (String, Srgba)>) -> Vec<(Label, Srgba)> {
entries.into_iter().map(|(name, color)| (Label::from(name), color)).collect()
}
/// The twelve colours, the Other… cell after them and a row of recent colours; the readout shows the last request
/// for the host's picker.
#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)]
fn swatch_palette_other_and_recent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let swatches = named(PALETTE.iter().map(|(name, color)| ((*name).to_owned(), *color)));
let shown = SwatchPalette::new("Swatches", Bind::bound(data.value("color", PALETTE[8].1)), &swatches)
.other("custom", "Other colour…")
.recent("Recent colours", &RECENT)
.show(ui);
let last = data.note("request", String::new());
if let Some(request) = &shown.pick_color {
*last = format!("{} at {}", request.key, request.color.map_or_else(|| String::from("none"), Srgba::to_hex));
}
let readout = format!("Last request: {last}");
StoryOutput::from(shown).readout(readout)
}
/// A palette over no colour: no swatch is selected until a pick sets one; the readout shows the bound value.
#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)]
fn no_colour(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let swatches = named(PALETTE.iter().map(|(name, color)| ((*name).to_owned(), *color)));
let shown = SwatchPalette::optional("Swatches", Bind::bound_mixed(data.value("color", Mixed::<Option<Srgba>>::Same(None))), &swatches).show(ui);
let bound = *data.value("color", Mixed::<Option<Srgba>>::Same(None));
let readout = match bound {
Mixed::Same(Some(color)) => format!("Colour: {}", color.to_hex()),
Mixed::Same(None) => String::from("Colour: none"),
Mixed::Mixed => String::from("Colour: mixed"),
};
StoryOutput::from(shown).readout(readout)
}
#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)]
fn swatch_palette(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let swatches = named(PALETTE.iter().map(|(name, color)| ((*name).to_owned(), *color)));
+126 -1
View File
@@ -4,7 +4,7 @@
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_behavior::{EditEvent, Selection};
use craft_behavior::{EditEvent, Mixed, Selection};
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
use craft_color_ui::ui::{
ColorPanel, ColorPanelMode, ColorPanelState, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand,
@@ -242,6 +242,131 @@ fn the_palette_arrows_walk_the_wrapped_grid() {
assert_eq!(rig.events.get(), 0);
}
/// What a palette reported over the passes since the last `take`.
#[derive(Default)]
struct PaletteReports {
edits: Vec<EditEvent<Srgba>>,
requests: Vec<ColorRequest>,
picked: Vec<Srgba>,
}
type Reports = Rc<RefCell<PaletteReports>>;
/// Collects what one pass of a palette reported.
fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) {
let mut reports = reports.borrow_mut();
reports.edits.extend(shown.edit);
reports.requests.extend(shown.pick_color);
reports.picked.extend(shown.picked);
}
fn palette_swatches() -> Vec<(Label, Srgba)> {
SWATCHES.iter().map(|(name, [r, g, b])| (Label::from(*name), Srgba::rgb(*r, *g, *b))).collect()
}
/// The colour of `SWATCHES` named `name`.
fn swatch(name: &str) -> Srgba {
SWATCHES.iter().find(|(n, _)| *n == name).map(|(_, [r, g, b])| Srgba::rgb(*r, *g, *b)).unwrap_or_else(|| panic!("no swatch {name}"))
}
const RECENT: [Srgba; 1] = [Srgba::rgb(0.40, 0.10, 0.50)];
/// Activating the Other… cell files a request keyed by the host's key at the bound colour and sets nothing; a pick in
/// the recent row is one `Set` of its colour; a click on the swatch of the bound colour reports `picked` and no edit.
#[trial]
fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
let swatches = palette_swatches();
let green = swatch("Green");
let bound = Rc::new(Cell::new(green));
let reports = Reports::default();
let (c, r) = (bound.clone(), reports.clone());
let mut fixture = Fixture::new(move |ui| {
let mut current = c.get();
let shown = SwatchPalette::new("Swatches", Bind::bound(&mut current), &swatches)
.other("custom", "Other colour…")
.recent("Recent colours", &RECENT)
.show(ui);
c.set(current);
collect(&r, shown);
});
fixture.room(PALETTE_WIDE).settle();
let other = fixture.by_label("Other colour…").expect("the Other… cell is named by its label");
let palette = fixture.by_label("Swatches").expect("the palette's list box");
assert!(palette.rect.contains_rect(other.rect), "the Other… cell is a cell of the palette's table: {other:?} in {palette:?}");
fixture.click(&other).settle();
let taken = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(taken.requests.len(), 1, "one request for one activation");
assert_eq!(taken.requests[0].key, "custom", "the request carries the host's key");
assert_eq!(taken.requests[0].color.map(Srgba::to_rgba), Some(green.to_rgba()), "the picker opens at the bound colour");
assert!(taken.edits.is_empty() && taken.picked.is_empty(), "the Other… cell sets nothing");
assert_eq!(bound.get().to_rgba(), green.to_rgba(), "the bound colour stays");
let recent = fixture.by_label(&RECENT[0].to_hex()).expect("a recent colour is named by its hex");
fixture.click(&recent).settle();
let taken = std::mem::take(&mut *reports.borrow_mut());
assert!(taken.requests.is_empty(), "a recent pick files no request");
assert_eq!(taken.edits.len(), 1, "one edit for one recent pick");
assert!(
matches!(&taken.edits[0], EditEvent::Set { before: Mixed::Same(before), after, .. }
if before.to_rgba() == green.to_rgba() && after.to_rgba() == RECENT[0].to_rgba()),
"a Set from the bound colour to the recent one: {:?}",
taken.edits[0]
);
assert_eq!(bound.get().to_rgba(), RECENT[0].to_rgba(), "the recent pick is written");
let violet = fixture.by_label("Violet").expect("violet");
fixture.click(&violet).settle();
let _ = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(bound.get().to_rgba(), swatch("Violet").to_rgba());
// Past the double-click time, so the repeat is a single click of its own.
fixture.advance(1.0);
let violet = fixture.by_label("Violet").expect("violet");
fixture.click(&violet).settle();
let taken = std::mem::take(&mut *reports.borrow_mut());
assert!(taken.edits.is_empty(), "a click on the bound colour changes nothing: {:?}", taken.edits);
assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::<Vec<_>>(), [swatch("Violet").to_rgba()], "and still reports the pick");
}
/// A palette over a colour that may be none, bound to no colour: no swatch is selected and Tab enters on the first;
/// a click writes `Same(Some(colour))` and reports one `Set` from `Mixed`.
#[trial]
fn an_optional_palette_bound_to_no_colour_selects_nothing_and_a_pick_writes_a_colour() {
let swatches = palette_swatches();
let bound = Rc::new(Cell::new(Mixed::<Option<Srgba>>::Same(None)));
let reports = Reports::default();
let (c, r) = (bound.clone(), reports.clone());
let mut fixture = Fixture::new(move |ui| {
let mut current = c.get();
let shown = SwatchPalette::optional("Swatches", Bind::bound_mixed(&mut current), &swatches).show(ui);
let _ = craft_ui::buttons::Button::new("After").show(ui);
c.set(current);
collect(&r, shown);
});
fixture.room(PALETTE_WIDE).settle();
for (name, _) in SWATCHES {
let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the {name} cell"));
assert_ne!(fixture.tree().selected_of(cell.node), Some(true), "no colour selects no swatch, {name} is selected");
}
fixture.key(Key::Tab, Modifiers::NONE);
let tree = fixture.tree();
assert_eq!(tree.name_of(craft_ui::testing::access::focused_key(tree)), Some("Red"), "Tab enters on the first swatch");
let blue = fixture.by_label("Blue").expect("blue");
fixture.click(&blue).settle();
let written = bound.get();
assert!(matches!(written, Mixed::Same(Some(color)) if color.to_rgba() == swatch("Blue").to_rgba()), "the pick is written: {written:?}");
let taken = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(taken.edits.len(), 1, "one edit for one pick");
assert!(
matches!(&taken.edits[0], EditEvent::Set { before: Mixed::Mixed, after, .. } if after.to_rgba() == swatch("Blue").to_rgba()),
"a Set from no colour, reported as from Mixed: {:?}",
taken.edits[0]
);
let blue = fixture.by_label("Blue").expect("blue");
assert_eq!(fixture.tree().selected_of(blue.node), Some(true), "the written colour's swatch is selected");
}
/// The Swatches panel over two groups, collecting the edits it reports and never applying them.
fn swatches_rig(groups: Vec<SwatchGroup>) -> (Fixture, Rc<RefCell<Vec<SwatchEdit>>>) {
let edits = Rc::new(RefCell::new(Vec::new()));
+1 -2
View File
@@ -452,8 +452,7 @@ impl<M: Value> Pass<'_, M> {
fn mixer_load(&mut self, ui: &mut Ui, words: &PaintBarWords) {
let color = self.values.mixer.load_color;
let solid = self.values.mixer.solid_colors_only;
// `Swatch` has no empty face, so a brush with no load shows the mixed face.
let swatch = Swatch::new(words.load_swatch.clone(), color.map_or(Mixed::Mixed, Mixed::Same)).show(ui).response;
let swatch = Swatch::optional(words.load_swatch.clone(), color).show(ui).response;
let (mut load, mut clean, mut next_solid) = (false, false, None);
let _ = Menu::new(words.load_swatch.clone()).opened_by(&swatch, Trigger::Click).show(ui, |ui, _| {
load = MenuItem::new(words.load_brush.clone()).show(ui).ran;
+35 -15
View File
@@ -13,6 +13,9 @@ use egui::epaint::{CircleShape, RectShape};
use egui::{Color32, CornerRadius, Painter, Pos2, Rect, Shape, Stroke, StrokeKind, TextureId, Vec2};
use std::cell::RefCell;
/// The "no colour" diagonal of a well stops this share of the well's height short of its edges.
const NONE_DIAGONAL_INSET: f32 = 0.15;
/// What a swatch well shows.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WellFill {
@@ -375,7 +378,8 @@ impl<'a> Draw<'a> {
let square = Rect::from_center_size(rect.center(), Vec2::splat(side));
match icon.source {
super::IconSource::Swatch(swatch) => {
self.swatch_well(square, CornerRadius::ZERO, swatch.map_or(WellFill::Mixed, WellFill::Color)); // P3(pdf-comments-w5): CM-C25a
// The icon's `None` is its own empty swatch (a mixed or theme-decided colour), so it keeps the dash.
self.swatch_well(square, CornerRadius::ZERO, swatch.map_or(WellFill::Mixed, WellFill::Color));
self.paint(&PaintShape::Rect(square, CornerRadius::ZERO), None, Some(Stroke::new(self.width(StrokeWidth::Thin), color)));
return;
}
@@ -397,6 +401,12 @@ impl<'a> Draw<'a> {
}
}
/// Paints `icon` as `icon` does, in the data colour `color` in place of the icon's own colour or ink: an icon drawn in
/// document content. The colour paints as `data_fill` paints one (dimmed or inactive with the component).
pub fn data_icon(&self, rect: Rect, icon: &super::IconSpec<'_>, color: DataColor) {
self.icon(rect, &icon.clone().data_color(DataColor::new(self.data_color(color))));
}
/// `letter` in caption text centred in an outlined box that fills the square of `rect`'s shorter side.
fn initial(&self, rect: Rect, letter: char, color: StyleColor) {
let side = rect.width().min(rect.height());
@@ -517,27 +527,37 @@ impl<'a> Draw<'a> {
}
/// Paints the well of a colour swatch over `well` with corners `radius`: the colour, over a checkerboard where it is
/// translucent, or for `None` (no colour of its own, or a mixed one) the empty well, `surface.sunken` with a
/// `text.muted` dash. `Swatch` and swatch icons paint their wells with it and add their own edges.
/// translucent; else the empty well in `surface.sunken`, with a `text.muted` dash for `Mixed`, a `status.bad`
/// diagonal from the bottom start to the top end for `None`, and nothing for `Empty`. `Swatch`, swatch icons and
/// the paint chip paint their wells with it and add their own edges.
pub fn swatch_well(&self, well: Rect, radius: CornerRadius, fill: WellFill) {
let color = match fill {
WellFill::Color(color) => Some(color),
WellFill::Mixed | WellFill::None | WellFill::Empty => None, // P3(pdf-comments-w5): CM-C25a
};
let shape = PaintShape::Rect(well, radius);
match color {
None => {
let colors = &self.env.tokens.color;
self.paint(&shape, Some(crate::style::rgba_color(colors.surface.sunken)), None);
let dash = Stroke::new(self.width(StrokeWidth::Medium), crate::style::rgba_color(colors.text.muted));
self.paint(&super::glyph::dash(well), None, Some(dash));
}
Some(color) => {
let colors = &self.env.tokens.color;
let sunken = Some(crate::style::rgba_color(colors.surface.sunken));
match fill {
WellFill::Color(color) => {
if color.a < 1.0 {
self.checker(&super::Checker::new(), well, radius);
}
self.data_fill(&shape, DataColor::new(Color32::from(color)));
}
WellFill::Mixed => {
self.paint(&shape, sunken, None);
let dash = Stroke::new(self.width(StrokeWidth::Medium), crate::style::rgba_color(colors.text.muted));
self.paint(&super::glyph::dash(well), None, Some(dash));
}
WellFill::None => {
self.paint(&shape, sunken, None);
let inner = well.shrink(well.height() * NONE_DIAGONAL_INSET);
let (from, to) = if self.env.direction == Direction::Rtl {
(inner.right_bottom(), inner.left_top())
} else {
(inner.left_bottom(), inner.right_top())
};
let mark = Stroke::new(self.width(StrokeWidth::Medium), crate::style::rgba_color(colors.status.bad.solid));
self.paint(&PaintShape::Path(vec![from, to]), None, Some(mark));
}
WellFill::Empty => self.paint(&shape, sunken, None),
}
}
@@ -3,7 +3,7 @@
mod completion;
use crate::primitives::{TextLayout, TextOptions};
use crate::primitives::{SubmitKey, TextLayout, TextOptions};
use crate::runtime::access::text::{Line, Run};
use crate::runtime::egui::{clipboard, focus as egui_focus, input as egui_input, text_edit};
use crate::runtime::focus::{EditSet, KeepKeys, KeyUse};
@@ -18,7 +18,7 @@ use std::sync::Arc;
/// How a typing run ended, as the adapter saw it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum End {
/// Enter, or Cmd/Ctrl+Enter in a multi-line field that submits.
/// Enter, or the `TextOptions::submit_key` chord in a multi-line field that submits.
Submit,
/// A commit-on character was typed.
Separator,
@@ -425,6 +425,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
underline: input.underline,
galley: None,
baseline,
submit_key: input.options.submit_key,
};
// A secondary press inside the selection keeps the selection for the edit menu it opens, as native fields do;
// egui's widget moves the caret to any press, so the selection from before the press is put back.
@@ -464,8 +465,17 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
&& state.preedit.is_none()
&& state.draft.is_some()
&& egui_input::step_key_pressed(ctx);
let submitted =
(shown.entered && shown.focused).then(|| held_mods(ctx)).filter(|mods| !input.options.multiline() || (input.options.submits && mods.cmd));
// `entered` is any Enter; which chord submits a multi-line text is decided here, from the held modifiers. Under
// `Enter` the widget broke no line on a submitting chord (`text_edit::show` gives it Shift+Enter alone).
let submit_key = input.options.submit_key;
let submitted = (shown.entered && shown.focused).then(|| held_mods(ctx)).filter(|mods| {
!input.options.multiline()
|| (input.options.submits
&& match submit_key {
SubmitKey::CommandEnter => mods.cmd,
SubmitKey::Enter => !mods.shift,
})
});
if let Some(mods) = submitted {
state.end = Some(End::Submit);
state.submit_mods = mods;
@@ -540,6 +550,7 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) {
underline: 0.0,
galley: Some(layout.galley.clone()),
baseline: None,
submit_key: SubmitKey::default(),
},
);
crate::runtime::pointer::record_text_widget(&ctx, widget, owner);
@@ -1,5 +1,6 @@
//! Building `TextEdit` and its state: the one caller of egui's text editing.
use crate::primitives::SubmitKey;
use craft_theme::TypeRole;
use egui::text::{CCursor, CCursorRange, LayoutJob, TextFormat};
use egui::text_edit::TextEditState;
@@ -43,6 +44,8 @@ pub(crate) struct Edit<'a> {
/// The screen y of the baseline a single line without a laid-out galley sits on: its control's line's, which a
/// text in another face (mono digits) shares. `None` centres the line's row on the rect's centre line.
pub baseline: Option<f32>,
/// The Enter chord that submits a multi-line text; the line break takes the other one.
pub submit_key: SubmitKey,
}
/// What the widget did in one pass.
@@ -85,7 +88,14 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown {
underline,
galley,
baseline,
submit_key,
} = edit;
// egui inserts the line break itself before the adapter sees the Enter, so the chord that submits must not be the
// one egui breaks the line on: under `Enter` the line break is Shift+Enter and plain Enter reaches `entered` untaken.
let line_break = match submit_key {
SubmitKey::Enter => egui::Modifiers::SHIFT,
SubmitKey::CommandEnter => egui::Modifiers::NONE,
};
// The same font and optical size as a label of the same role: one text path.
let env = crate::runtime::env::Env::of(ui);
let tokens = &env.tokens;
@@ -186,7 +196,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown {
.desired_rows(1)
.password(password)
.event_filter(filter)
.return_key(if multiline { Some(egui::KeyboardShortcut::new(egui::Modifiers::NONE, egui::Key::Enter)) } else { None })
.return_key(if multiline { Some(egui::KeyboardShortcut::new(line_break, egui::Key::Enter)) } else { None })
.layouter(&mut layouter)
// A laid-out galley sits at the rect's corner, as a painted run does.
.align(match (centred, rtl) {
+40 -23
View File
@@ -7,10 +7,10 @@ use crate::contract::{
Access, Activation, Common, Component, Cx, DisabledLook, GroupHandle, MeasureCx, Meta as _, Outcome, PaintUi, Pointer as _, Props as _, Role,
Sizing, Styled as _, WordSetCx as _,
};
use crate::primitives::{ContentPainterCx, Draw, PaintShape, StrokeWidth, WellFill};
use crate::primitives::{ContentPainterCx, Draw, IconSpec, PaintShape, StrokeWidth, WellFill};
use crate::runtime::requests::ColorRequest;
use crate::style::{ComponentStyle, DataColor, Flags, FocusLook, State, StateMix, StateSet, StyleColor, StyleCx, UiTokens, resolve_style};
use craft_behavior::{Metrics, Mixed, Sense, Value};
use craft_behavior::{IconId, Metrics, Mixed, Sense, Value};
use craft_theme::{Rgba, Srgba, Stateful, States, over};
use egui::{Color32, CornerRadius, Rect, Response, Vec2};
@@ -56,8 +56,10 @@ pub struct SwatchStyle {
edge: Stateful<StyleColor>,
/// The ring inside the outline of a selected or checked well; clear while it is off.
ring: Stateful<StyleColor>,
/// The thin edge just inside the outline of a marked well.
/// The thin edge just inside the outline of a marked well, and the glyph of an icon cell.
mark: StyleColor,
/// The side of an icon cell's glyph: `size.icon.sm`, cut to the well.
glyph: f32,
/// The checkerboard behind a translucent colour: the colours of its corners and its other cells.
checker: [Rgba; 2],
/// The mixed well's colour, which `inner_edge` contrasts with.
@@ -112,7 +114,9 @@ impl<E> crate::contract::ItemOutput<E> for SwatchOutput {
/// A colour well that shows a colour from data and reports its activation; it edits nothing.
///
/// The colour fills the well over a checkerboard where it has alpha, inside a thin ring that separates it from the
/// panel. A `Mixed` colour shows a neutral well with a dash and has no colour value. A click reports `clicked` and the
/// panel. A `Mixed` colour shows a neutral well with a dash and has no colour value; an [`optional`](Swatch::optional)
/// swatch of no colour shows the sunken well with a diagonal and reads "None". An [`icon`](Swatch::icon) swatch shows
/// its glyph on the empty well, as a palette's Other… cell does. A click reports `clicked` and the
/// `activation`. A swatch with a `picker` key also files a `ColorRequest` for that key, opened at the swatch's colour
/// and titled with its label, as `pick_color`; the host opens its colour picker and answers with the picked colour. A
/// `Mixed` swatch files a request with no colour: the host's picker opens empty and the first pick sets the colour.
@@ -146,6 +150,8 @@ pub struct Swatch<T: Value + 'static = ()> {
/// The key of the `ColorRequest` a click files.
#[prop(into)]
picker: Option<String>,
/// The glyph an icon cell paints over its empty well, in place of a colour.
icon: Option<IconId>,
checked: bool,
activation: Option<Activation>,
}
@@ -161,6 +167,7 @@ impl Swatch<()> {
well: false,
marked: false,
picker: None,
icon: None,
checked: false,
activation: None,
}
@@ -169,14 +176,12 @@ impl Swatch<()> {
/// A swatch that can be "no colour": `None` paints the empty well and reads as "None".
pub fn optional(label: impl Into<crate::runtime::env::Label>, color: impl Into<Mixed<Option<Srgba>>>) -> Swatch<()> {
let _ = (label, color);
todo!("CM-C25b")
Swatch { color: color.into(), ..Swatch::new(label, Mixed::<Srgba>::Mixed) }
}
/// A well with the catalogue glyph `icon` on top; its access node is an option named `label` with no colour value.
pub fn icon(label: impl Into<crate::runtime::env::Label>, icon: craft_behavior::IconId) -> Swatch<()> {
let _ = (label, icon);
todo!("CM-C25b")
pub fn icon(label: impl Into<crate::runtime::env::Label>, icon: IconId) -> Swatch<()> {
Swatch { icon: Some(icon), ..Swatch::new(label, Mixed::<Srgba>::Mixed) }
}
}
@@ -199,6 +204,7 @@ impl<T: Value + 'static> Swatch<T> {
well: self.well,
marked: self.marked,
picker: self.picker,
icon: self.icon,
checked: false,
activation: None,
}
@@ -228,6 +234,7 @@ impl<T: Value + 'static> Component for Swatch<T> {
edge: Stateful::new(rest),
ring: Stateful::new(clear).on(States::new(accent, accent, accent, accent)),
mark: cx.color(colors.text.normal),
glyph: cx.tokens.size.icon.sm,
checker: [colors.overlay.checker_light, colors.overlay.checker_dark],
mixed_rgba: colors.surface.sunken,
}
@@ -267,9 +274,12 @@ impl<T: Value + 'static> Component for Swatch<T> {
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
if self.member.is_some() {
access.role(Role::RADIO_BUTTON);
} else if self.cell {
} else if self.cell || self.icon.is_some() {
access.role(Role::LIST_BOX_OPTION);
}
if self.icon.is_some() {
return;
}
match self.color.same().copied() {
Some(Some(color)) => {
access.value(color.to_hex());
@@ -285,7 +295,8 @@ impl<T: Value + 'static> Component for Swatch<T> {
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
paint_face(&ui.draw(), cx.rect, cx.style, cx.state(), self.color, self.marked);
let fill = if self.icon.is_some() { WellFill::Empty } else { well_fill(self.color) };
paint_face(&ui.draw(), cx.rect, cx.style, cx.state(), fill, self.icon.as_ref(), self.marked);
}
fn finish(self, cx: Cx<'_, Self>) -> SwatchOutput {
@@ -297,17 +308,25 @@ impl<T: Value + 'static> Component for Swatch<T> {
}
}
/// The one swatch face painter: the well of `color` in `well` (a checkerboard behind a translucent colour, the dash
/// of a mixed one), then the outline ring, the mark when `marked`, and the selection ring, in `state`.
fn paint_face(draw: &Draw<'_>, well: Rect, style: &SwatchStyle, state: &StateSet, color: Mixed<Option<Srgba>>, marked: bool) {
let shape = PaintShape::Rect(well, style.radius);
// P3(pdf-comments-w5): CM-C25a
let fill = match color {
/// What the well of a swatch of `color` shows: the colour, the "no colour" diagonal, or the mixed dash.
fn well_fill(color: Mixed<Option<Srgba>>) -> WellFill {
match color {
Mixed::Same(Some(color)) => WellFill::Color(color),
Mixed::Same(None) => WellFill::None,
Mixed::Mixed => WellFill::Mixed,
};
}
}
/// The one swatch face painter: the well `fill` in `well` (a checkerboard behind a translucent colour, the dash of a
/// mixed one, the diagonal of none), the `glyph` of an icon cell in the text colour, then the outline ring, the mark
/// when `marked`, and the selection ring, in `state`.
fn paint_face(draw: &Draw<'_>, well: Rect, style: &SwatchStyle, state: &StateSet, fill: WellFill, glyph: Option<&IconId>, marked: bool) {
let shape = PaintShape::Rect(well, style.radius);
draw.swatch_well(well, style.radius, fill);
if let Some(glyph) = glyph {
let side = style.glyph.min(well.width()).min(well.height());
draw.icon(Rect::from_center_size(well.center(), Vec2::splat(side)), &IconSpec::svg(glyph.clone()).color(style.mark));
}
draw.stroke(&shape, StrokeWidth::Thin, state.resolve(&style.edge));
if marked {
let inside = PaintShape::Rect(well.shrink(draw.width(StrokeWidth::Thin)), style.radius);
@@ -333,8 +352,7 @@ impl SwatchFace {
/// The face of a colour that can be "no colour": `None` paints the empty well.
pub fn optional(color: impl Into<Mixed<Option<Srgba>>>) -> SwatchFace {
let _ = color;
todo!("CM-C25b")
SwatchFace { color: color.into(), selected: false }
}
/// Whether the selected ring shows.
@@ -346,12 +364,11 @@ impl SwatchFace {
/// Paints the face filling `rect`.
pub fn paint(&self, cx: &ContentPainterCx<'_>, rect: Rect) {
// P3(pdf-comments-w5): CM-C25b: the key does not read the colour.
let key = Swatch::new("", Mixed::<Srgba>::Mixed).style_key();
let key = Swatch::optional("", self.color).style_key();
let scope = cx.style_cx();
let style = resolve_style(&scope, key, cx.painter.ctx(), Swatch::<()>::style);
let (flags, on) = if self.selected { (Flags::SELECTED, 1.0) } else { (Flags::empty(), 0.0) };
let state = StateSet::new(State::Rest, flags, StateMix::new(0.0, 0.0, on));
cx.with_draw(|draw| paint_face(draw, rect, &style, &state, self.color, false));
cx.with_draw(|draw| paint_face(draw, rect, &style, &state, well_fill(self.color), None, false));
}
}
@@ -47,6 +47,19 @@ fn swatch_states(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
StoryOutput::default().readout(format!("Clicked {clicks} times"))
}
/// Optional swatches: one of no colour (the sunken well with the diagonal, read as "None"), one with a colour, one
/// mixed.
#[story(Swatch<u8>, covers = [], drive = Drive::Never)]
fn swatch_none(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let clicks = data.note("clicks", 0u32);
Row::new().show(ui, |ui, _| {
*clicks += u32::from(Swatch::optional("No colour", Mixed::<Option<Srgba>>::Same(None)).show(ui).clicked);
*clicks += u32::from(Swatch::optional("Colour", Mixed::Same(Some(BLUE))).show(ui).clicked);
*clicks += u32::from(Swatch::optional("Mixed", Mixed::<Option<Srgba>>::Mixed).show(ui).clicked);
});
StoryOutput::default().readout(format!("Clicked {clicks} times"))
}
/// Twelve swatches in a `RadioGroup`: one Tab stop, arrows move, Space picks.
#[story(Swatch<u8>, covers = [], drive = Drive::Never)]
fn swatch_palette(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+50 -14
View File
@@ -8,7 +8,7 @@ use crate::contract::{
use crate::list::RowTest;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleCx};
use craft_behavior::{DisplayOrder, ItemSource, Metrics, Selection, TileLayout};
use craft_behavior::{DisplayOrder, IconId, ItemSource, Metrics, Selection, TileLayout};
use craft_theme::Srgba;
use egui::{Response, Ui, Vec2};
@@ -17,18 +17,29 @@ mod stories;
/// The entries of a colour table as an item source: keyed by index, named for type-ahead.
#[derive(Clone, Copy, Debug)]
pub struct SwatchRows<'a>(&'a [(Label, Srgba)]);
pub struct SwatchRows<'a> {
swatches: &'a [(Label, Srgba)],
/// The name of the one cell after the entries, keyed `swatches.len()`.
trailing: Option<&'a Label>,
}
impl<'a> SwatchRows<'a> {
/// The entries of `swatches`.
pub const fn new(swatches: &'a [(Label, Srgba)]) -> Self {
SwatchRows(swatches)
SwatchRows { swatches, trailing: None }
}
/// The entries with one more cell named `label` after them, keyed `swatches.len()`.
#[must_use]
pub const fn trailing(mut self, label: &'a Label) -> Self {
self.trailing = Some(label);
self
}
}
impl DisplayOrder<usize> for SwatchRows<'_> {
fn len(&self) -> usize {
self.0.len()
self.swatches.len() + usize::from(self.trailing.is_some())
}
fn key(&self, at: usize) -> usize {
@@ -36,11 +47,14 @@ impl DisplayOrder<usize> for SwatchRows<'_> {
}
fn index_of(&self, key: &usize) -> Option<usize> {
(*key < self.0.len()).then_some(*key)
(*key < self.len()).then_some(*key)
}
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
self.0.get(at).map(|(name, _)| std::borrow::Cow::Borrowed(name.as_str()))
match self.swatches.get(at) {
Some((name, _)) => Some(std::borrow::Cow::Borrowed(name.as_str())),
None => self.trailing.filter(|_| at == self.swatches.len()).map(|name| std::borrow::Cow::Borrowed(name.as_str())),
}
}
}
@@ -78,6 +92,8 @@ impl Outcome for SwatchTableOutput {
/// - The table is one Tab stop; the arrows move through the cells as a grid.
/// - AccessKit: a list box named by the label; each cell a list box option named by its entry, with the hex colour as
/// its value.
/// - A [`trailing`](Self::trailing) cell follows the entries at key `swatches.len()`: a well with a glyph, selected
/// and opened by that key as an entry is, with no colour value.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(collection)]
pub struct SwatchTable<'a> {
@@ -106,6 +122,8 @@ pub struct SwatchTable<'a> {
/// Whether the cells are wells at the control height, as a palette's swatches are, instead of small touching cells.
#[prop]
wells: bool,
/// The icon cell after the entries: its name and glyph.
trailing: Option<(Label, IconId)>,
}
impl<'a> SwatchTable<'a> {
@@ -128,6 +146,7 @@ impl<'a> SwatchTable<'a> {
marked: None,
tips: false,
wells: false,
trailing: None,
}
.label(label)
}
@@ -135,9 +154,14 @@ impl<'a> SwatchTable<'a> {
/// One icon cell after the entries, at key `swatches.len()`, in the same Tab stop and arrow walk: the Other… cell
/// of a palette.
#[must_use]
pub fn trailing(self, label: impl Into<Label>, icon: craft_behavior::IconId) -> Self {
let _ = (label.into(), icon);
todo!("CM-C26")
pub fn trailing(mut self, label: impl Into<Label>, icon: IconId) -> Self {
self.trailing = Some((label.into(), icon));
self
}
/// The number of cells: the entries and the trailing cell.
fn cells(&self) -> usize {
self.swatches.len() + usize::from(self.trailing.is_some())
}
/// Whether Shift or Cmd adds cells to the selection.
@@ -151,12 +175,23 @@ impl<'a> SwatchTable<'a> {
pub fn show_all(mut self, ui: &mut Ui) -> SwatchTableOutput {
let (swatches, tips, wells) = (self.swatches, self.tips, self.wells);
let marked = self.marked.take();
self.show_items(ui, &SwatchRows::new(swatches), &mut |key, _| {
let (name, color) = &swatches[*key];
let cell = Swatch::new(name.clone(), *color).cell();
// A clone, not a take: `ideal_width` reads the trailing cell while the table shows.
let trailing = self.trailing.clone();
let rows = match &trailing {
Some((name, _)) => SwatchRows::new(swatches).trailing(name),
None => SwatchRows::new(swatches),
};
self.show_items(ui, &rows, &mut |key, _| {
let (name, cell) = match (swatches.get(*key), &trailing) {
(Some((name, color)), _) => (name.clone(), Swatch::new(name.clone(), *color)),
(None, Some((name, icon))) => (name.clone(), Swatch::icon(name.clone(), icon.clone())),
// The rows name no key past the trailing cell; a mixed well keeps the closure total without a panic.
(None, None) => (Label::Empty, Swatch::new(Label::Empty, craft_behavior::Mixed::<Srgba>::Mixed)),
};
let cell = cell.cell();
let cell = if wells { cell.well() } else { cell };
let cell = if marked.as_ref().is_some_and(|test| test.passes(key)) { cell.marked() } else { cell };
if tips { cell.tooltip(name.clone()) } else { cell }
if tips { cell.tooltip(name) } else { cell }
})
}
}
@@ -211,7 +246,8 @@ impl Collection for SwatchTable<'_> {
/// Where the table takes its width from its content it asks for every cell in one row, or its count per row: the
/// room it is offered then wraps the cells, as it does where it is given the width.
fn ideal_width(&self, _item: Option<Vec2>, cx: &StyleCx<'_>) -> f32 {
let columns = self.per_row.map_or(self.swatches.len(), |columns| columns.max(1).min(self.swatches.len()));
let cells = self.cells();
let columns = self.per_row.map_or(cells, |columns| columns.max(1).min(cells));
// Half a point over, so the division that counts the columns back never rounds below `columns`.
columns as f32 * self.cell(cx) + 0.5
}
@@ -4,7 +4,7 @@ use super::{SwatchTable, SwatchTableOutput};
use crate::contract::Bind;
use crate::runtime::env::Label;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_behavior::Selection;
use craft_behavior::{IconId, Selection};
use craft_theme::Srgba;
use egui::Ui;
@@ -55,6 +55,19 @@ fn swatch_table_empty(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
SwatchTable::new("Color Table", &[]).empty("No colors").show_all(ui).into()
}
/// Twelve wells and the Other… cell after them, at key 12: selecting or opening it reports that key.
#[story(SwatchTable<'static>, covers = [], drive = Drive::Never)]
fn swatch_table_trailing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let entries = table_entries().into_iter().step_by(21).take(12).collect::<Vec<_>>();
let shown = SwatchTable::new("Colors", &entries)
.selection(Bind::bound(data.value("selected", Selection::single(0usize))))
.wells(true)
.tips(true)
.trailing("Other colour…", IconId::new("plus"))
.show_all(ui);
with_readout(data, shown)
}
#[story(SwatchTable<'static>, covers = [One], drive = Drive::Never)]
fn swatch_table_one(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let entries = table_entries().into_iter().take(1).collect::<Vec<_>>();
+3 -3
View File
@@ -217,9 +217,9 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
/// The key that submits a multi-line field (`TextOptions::submit_key`).
#[must_use]
pub fn submit_key(self, key: SubmitKey) -> Self {
let _ = key;
todo!("CM-C24b")
pub fn submit_key(mut self, key: SubmitKey) -> Self {
self.options.submit_key = key;
self
}
/// Completion candidates for the text before the caret. The text adapter owns the list and the keys it takes.
@@ -4,7 +4,7 @@ use super::TextField;
use crate::contract::LabelScheme;
use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _, Validity};
use crate::form::{Field, FieldGroup};
use crate::primitives::{Completer, Completion, IconSpec};
use crate::primitives::{Completer, Completion, IconSpec, SubmitKey};
use crate::runtime::env::Message;
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use craft_behavior::{IconId, Mixed, PlainText};
@@ -84,6 +84,20 @@ fn text_field_read_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
TextField::new("Name", Bind::bound(data.value("name", "Locked".to_owned()))).read_only(true).show(ui).into()
}
/// A reply box: Enter submits and Shift+Enter breaks the line; the readout counts the submits.
#[story(TextField<'static, PlainText>, covers = [], drive = Drive::Never)]
fn text_field_submits_on_enter(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let shown = TextField::new("Reply", Bind::bound(data.value("reply", String::from("Looks good"))))
.lines(3)
.submits()
.submit_key(SubmitKey::Enter)
.show(ui);
let submits = data.note("submits", 0u32);
*submits += u32::from(shown.submitted);
let readout = format!("Submitted {submits} times");
StoryOutput::from(shown).readout(readout)
}
#[story(TextField<'static, PlainText>, covers = [], drive = Drive::Never)]
fn text_field_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
TextField::new("Name", Bind::bound(data.value("name", "Off".to_owned()))).enabled(false).show(ui).into()
@@ -0,0 +1,59 @@
//! `TextOptions::submit_key`: which Enter chord submits a multi-line field and which one breaks the line.
use craft_ui::contract::{Bind, Show as _};
use craft_ui::primitives::SubmitKey;
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::TextField;
use egui::{Key, Modifiers};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// Types "Hi" into a three-line field that submits on `submit_key`, then presses Enter with `modifiers`, rerunning
/// the pass of the press inside its frame. Gives the bound text and how many passes reported `submitted`.
fn press_enter(submit_key: SubmitKey, modifiers: Modifiers) -> (String, u32) {
let text = Rc::new(RefCell::new(String::new()));
let submits = Rc::new(Cell::new(0u32));
let rerun = Rc::new(Cell::new(false));
let (shown, counted, discard) = (text.clone(), submits.clone(), rerun.clone());
let mut fixture = Fixture::new(move |ui| {
if discard.take() {
ui.ctx().request_discard("the trial reruns the pass of the Enter");
}
let out = TextField::new("Reply", Bind::bound(&mut *shown.borrow_mut())).lines(3).submits().submit_key(submit_key).show(ui);
counted.set(counted.get() + u32::from(out.submitted));
});
fixture.settle();
fixture.key(Key::Tab, Modifiers::NONE);
fixture.type_text("Hi");
fixture.idle(2);
assert_eq!(*text.borrow(), "Hi", "the field takes the typing");
submits.set(0);
rerun.set(true);
fixture.key(Key::Enter, modifiers);
fixture.idle(2);
let typed = text.borrow().clone();
(typed, submits.get())
}
/// Under `SubmitKey::Enter` plain, Cmd and Ctrl+Enter submit and leave the text as it was, and Shift+Enter breaks the
/// line once without submitting; under the default `CommandEnter` plain Enter breaks the line and Cmd+Enter submits.
/// The pass of each Enter runs twice in its frame: the second applies none of the first's input, so nothing submits
/// or breaks twice.
#[trial]
fn enter_submits_and_shift_enter_breaks_a_line_under_the_enter_key() {
for (chord, modifiers) in [("Enter", Modifiers::NONE), ("Cmd+Enter", Modifiers::COMMAND), ("Ctrl+Enter", Modifiers::CTRL)] {
let (text, submits) = press_enter(SubmitKey::Enter, modifiers);
assert_eq!(submits, 1, "{chord} submits once under the Enter key");
assert_eq!(text, "Hi", "{chord} under the Enter key leaves the text unchanged");
}
let (text, submits) = press_enter(SubmitKey::Enter, Modifiers::SHIFT);
assert_eq!(submits, 0, "Shift+Enter does not submit under the Enter key");
assert_eq!(text, "Hi\n", "Shift+Enter breaks the line once under the Enter key");
let (text, submits) = press_enter(SubmitKey::CommandEnter, Modifiers::NONE);
assert_eq!(submits, 0, "plain Enter does not submit under the default key");
assert_eq!(text, "Hi\n", "plain Enter breaks the line once under the default key");
let (text, submits) = press_enter(SubmitKey::default(), Modifiers::COMMAND);
assert_eq!(submits, 1, "Cmd+Enter submits once under the default key");
assert_eq!(text, "Hi", "Cmd+Enter under the default key leaves the text unchanged");
}