Merge main into fix/ui-perf-2-component-cost

This commit is contained in:
FredApps committed 2026-11-28 23:21:48 +01:00
commit 2ed136bd55
70 files changed
+1480 -123

No files matched your search

+2 -2
View File
@@ -6,7 +6,7 @@ use crate::AreaMode;
use craft_behavior::{EditEvent, EditEvents, Metrics, PartKey, Sense};
use craft_theme::Srgba;
use craft_ui::contract::{
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPUP_PAD, PaintUi, PartsCx,
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPOVER_PAD, PaintUi, PartsCx,
Pattern, Props as _, Role, Show as _, ShowContainer as _, pad_of,
};
use craft_ui::popover::Popover;
@@ -77,7 +77,7 @@ fn start_point(geometry: Geometry, start: Option<Srgba>) -> Pos2 {
/// The popover's top left, so that the start colour's point in the area sits at `at`.
fn origin(tokens: &UiTokens, at: Pos2, start: Option<Srgba>) -> Pos2 {
let point = start_point(Geometry::of(tokens), start);
let pad = pad_of(tokens, POPUP_PAD);
let pad = pad_of(tokens, POPOVER_PAD);
pos2(at.x - pad - point.x, at.y - pad - point.y)
}
+38 -18
View File
@@ -24,7 +24,7 @@ use craft_ui::dialog::{
ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field,
};
use craft_ui::layout::{CellAlign, GridFit};
use craft_ui::layout_components::{Grid, Stack};
use craft_ui::layout_components::{Grid, Row, Stack};
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::patterns::form_dialogs::{HostRequests, ResetFooter};
use craft_ui::pickers::Select;
@@ -41,7 +41,7 @@ use std::borrow::Cow;
use std::sync::Arc;
use super::picker::TWO_COLUMNS;
use super::{ColorPicker, ColorPickerLayout, ColorWarning, Gamut, PickedColor, ScreenPickGesture, SwatchPalette};
use super::{ColorPicker, ColorPickerLayout, ColorPickerWords, ColorWarning, CompareSwatch, Gamut, PickedColor, ScreenPickGesture, SwatchPalette};
use crate::{AreaMode, CmykModel, not_web_safe, web_safe};
type StandardColors = (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>);
@@ -318,27 +318,47 @@ impl TabbedBody<'_> {
let (cells, greys) = self.standard.map_or((&[][..], &[][..]), |(cells, greys)| (cells.as_slice(), greys.as_slice()));
let current = held.same().map(|picked| picked.color);
let mut pick = None;
Stack::new().show(ui, |ui, _| {
let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells)
.arrangement(SwatchArrangement::Honeycomb)
.tips(true)
.selection(Bind::given(chosen(cells, current)))
.show_all(ui);
if let Some(at) = honeycomb.selected {
pick = cells.get(at).map(|(_, color)| *color);
}
let row = SwatchTable::new(self.words.greys.clone(), greys)
.per_row(greys.len().max(1))
.tips(true)
.selection(Bind::given(chosen(greys, current)))
.show_all(ui);
if let Some(at) = row.selected {
pick = greys.get(at).map(|(_, color)| *color);
let mut restore = None;
// The compare block stands beside the honeycomb, as it does beside the Custom page's area.
Row::new().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells)
.arrangement(SwatchArrangement::Honeycomb)
.tips(true)
.selection(Bind::given(chosen(cells, current)))
.show_all(ui);
if let Some(at) = honeycomb.selected {
pick = cells.get(at).map(|(_, color)| *color);
}
let row = SwatchTable::new(self.words.greys.clone(), greys)
.per_row(greys.len().max(1))
.tips(true)
.selection(Bind::given(chosen(greys, current)))
.show_all(ui);
if let Some(at) = row.selected {
pick = greys.get(at).map(|(_, color)| *color);
}
});
if let Some(compare) = self.compare {
let new = held.same().map_or(Mixed::Mixed, |picked| Mixed::Same(picked.color));
let current = match compare {
Mixed::Same(current) => Mixed::Same(current.color),
Mixed::Mixed => Mixed::Mixed,
};
let label = Env::of(ui).words::<ColorPickerWords>().new_color.clone();
if CompareSwatch::new(label, new, current).show(ui).restore
&& let Mixed::Same(current) = compare
{
restore = Some(current);
}
}
});
if let Some(color) = pick {
*held = Mixed::Same(PickedColor::rgb(color));
}
if let Some(current) = restore {
*held = Mixed::Same(current);
}
}
/// The compact picker over the colour, the compare swatch beside its area; the model switch is the memory's.
+9
View File
@@ -597,6 +597,15 @@ fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() {
fixture.click(&cell);
fixture.idle(4);
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#0000ff"), "a honeycomb pick is the colour");
// #7984: the Standard page shows the compare block too, and its current half restores the opening colour.
assert!(fixture.by_label("New color").is_some(), "the Standard page shows the compare block");
let restore = fixture.by_label("Restore current color").expect("the compare block's current half");
fixture.click(&restore);
fixture.idle(4);
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#123456"), "the current half restores the opening colour");
let cell = fixture.by_label("Standard 2").expect("the honeycomb shows its cells");
fixture.click(&cell);
fixture.idle(4);
assert!(dialogs.borrow_mut().confirm::<ColorPickerDialog>(&ctx), "OK answers");
let answered = dialogs.borrow_mut().take::<ColorPickerDialog>().and_then(DialogResult::ok).map(|result| result.picked.color.to_hex());
+16 -2
View File
@@ -226,6 +226,8 @@ pub enum GalleryFace<'a> {
thumbnails: &'a Thumbnails<u64>,
/// What renders the thumbnail.
source: &'a dyn ThumbSource<u64>,
/// Whether the transparency grid shows behind transparent pixels.
checker: bool,
},
/// A tile painted directly.
Paint(&'a dyn Fn(&ContentPainterCx, Rect)),
@@ -250,7 +252,17 @@ impl<'a> GalleryFace<'a> {
/// A thumbnail under `key`, rendered by `source` into `thumbnails`.
pub fn rendered(key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64>) -> Self {
GalleryFace::Rendered { key, thumbnails, source }
GalleryFace::Rendered { key, thumbnails, source, checker: true }
}
/// Whether a rendered thumbnail shows the transparency grid behind its transparent pixels (default on). Off for a
/// thumbnail that is a mask on the surface it sits on, such as an equation symbol. Other faces ignore it.
#[must_use]
pub fn checker(mut self, on: bool) -> Self {
if let GalleryFace::Rendered { checker, .. } = &mut self {
*checker = on;
}
self
}
/// The picture this face shows, `size` high and `aspect` times as wide. It is decoration: the tile that holds it
@@ -258,7 +270,9 @@ impl<'a> GalleryFace<'a> {
fn picture(&self, aspect: ThumbAspect, size: ThumbSize) -> Picture<'a> {
let picture = match self {
GalleryFace::Image { key, revision, image } => Picture::new(Label::default(), *key, *image).revision(*revision),
GalleryFace::Rendered { key, thumbnails, source } => Picture::rendered(Label::default(), *key, thumbnails, *source),
GalleryFace::Rendered { key, thumbnails, source, checker } => {
Picture::rendered(Label::default(), *key, thumbnails, *source).checker(*checker)
}
GalleryFace::Paint(paint) => {
let paint = *paint;
Picture::painter(Label::default(), aspect, move |cx: &ContentPainterCx<'_>, rect: Rect| paint(cx, rect))
+2 -3
View File
@@ -172,8 +172,7 @@ fn gallery_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let options = ThumbnailOptions::new();
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "craft_menu.gallery.story", options);
let source = FakeThumbSource::<u64>::new().later(true);
let items: Vec<GalleryItem<'_, usize>> = (0..COUNT)
.map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::Rendered { key: at as u64, thumbnails: &thumbnails, source: &source } })
.collect();
let items: Vec<GalleryItem<'_, usize>> =
(0..COUNT).map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::rendered(at as u64, &thumbnails, &source) }).collect();
show(ui, &items)
}
+4
View File
@@ -24,6 +24,8 @@ use crate::shortcuts::state::{DialogState, Env};
const LISTS_SHARE: f32 = 0.5;
/// The detail column's share of the width beside the lists.
const DETAIL_SHARE: f32 = 0.5;
/// The most Categories rows shown before the list scrolls.
const CATEGORY_ROWS: u16 = 6;
const PANES: [ColumnWidth; 2] = [ColumnWidth::fill(LISTS_SHARE), ColumnWidth::fill(DETAIL_SHARE)];
/// One frame of the command-lists body: a search field, the Categories list beside the Commands
@@ -62,6 +64,8 @@ fn categories(ui: &mut Ui, env: &Env<'_>, state: &mut DialogState) {
let mut selection = Selection::new(at.into_iter().collect(), at, at);
let out = List::<usize>::new(words.categories.clone())
.id_salt("categories")
// A short list, so the Commands list under it keeps room in a dialog of ordinary height.
.max_rows(CATEGORY_ROWS)
.select(SelectMode::Single)
.selection(Bind::bound(&mut selection))
.show_items(ui, &Titles(&labels), &mut |key, _| ListRow::new(labels[*key].clone()));
+23
View File
@@ -263,3 +263,26 @@ fn the_current_tile_paints_an_accent_fill_and_edge_even_when_focused() {
assert!(shapes.iter().any(|p| p.fill == fill && near(p, current)), "{who}: the focused current tile keeps its fill");
}
}
/// How many shapes a gallery of one rendered tile of a transparent image paints, as built or with `checker(false)`.
fn shapes_of_rendered(opt_out: bool) -> usize {
use craft_ui::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails};
let mut fixture = Fixture::new(move |ui| {
let options = ThumbnailOptions::new().jobs(std::sync::Arc::new(craft_host::InlineJobs));
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "gallery_checker_test", options);
let source = FakeThumbSource::<u64>::new();
// The default case sets nothing, so a default that turned the grid off fails here.
let face = GalleryFace::rendered(1, &thumbnails, &source);
let face = if opt_out { face.checker(false) } else { face };
let items = [GalleryItem { key: 0_usize, label: Label::from("Mask"), face }];
Gallery::new("Symbols", &items, None).tiles(1, 1).show(ui);
});
fixture.settle();
fixture.frame_shapes().len()
}
#[trial]
fn a_rendered_gallery_tile_paints_a_checker_unless_it_opts_out() {
let (with, without) = (shapes_of_rendered(false), shapes_of_rendered(true));
assert!(with > without, "the default paints {with} shapes, the opt-out {without}: the grid is the difference");
}
+27 -1
View File
@@ -1,7 +1,7 @@
//! The Customize Keyboard layout: each change is applied at once and Escape closes without rolling back.
use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Scope, Scopes, Trigger};
use craft_menu::shortcuts::{Layout, Outcome};
use craft_menu::shortcuts::{Area, Layout, Outcome};
use craft_ui::contract::Role;
use craft_ui::testing::trial;
use egui::{Key, Modifiers};
@@ -79,3 +79,29 @@ fn command_lists_assign_remove_and_close_apply_each_change_at_once() {
assert_eq!(keys(&rig), left, "the keymap keeps the edits");
assert!(rig.bindings("file.export").is_empty(), "the taken chord is not given back");
}
/// A long Categories list must not take the room the Commands list needs: in a dialog of ordinary height a command row
/// still shows above the footer.
#[trial]
fn commands_keep_room_beside_a_long_categories_list() {
let rig = Rig::tuned(Platform::Mac, |options| {
options.layout = Layout::CommandLists;
options.own_areas = true;
options.size = Some(egui::vec2(640.0, 460.0));
options.areas = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"].map(|name| Area::new(name, name, |_| true)).to_vec();
});
let row = rig.find("Bring to Front").center();
let footer = rig.find("Reset All…").center();
assert!(row.y < footer.y, "the command row ({row:?}) sits above the footer ({footer:?})");
// The capped list scrolls: the arrow keys still reach its last entry.
let mut rig = rig;
rig.click("A");
for _ in 0..11 {
rig.press(Modifiers::NONE, Key::ArrowDown);
}
let area = {
let shared = rig.shared.borrow();
shared.state.snapshot(&shared.km).expect("the dialog has shown").area
};
assert_eq!(area, "L", "the last Categories entry is reachable");
}
+2 -2
View File
@@ -52,8 +52,8 @@ pub use reading::{ReadingNav, ReadingNavOutput, ReadingState, ReadingView, Readi
pub use setup::{PageLayoutChoice, PageLayoutMenus, PageSetupDialog};
pub use sync_views::{Lead, SyncedViews, SyncedViewsOutput, SyncedViewsState};
pub use table::{
BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, RowHeight, SampleArea, TableChange, TableGeometry,
TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection,
BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, EdgeSize, RowHeight, SampleArea, TableChange,
TableGeometry, TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection,
};
pub use text_selection::{
MarkArea, MarkKind, PageTextSource, PageTexts, TextMark, TextMarks, TextSelectState, TextSelectTool, TextSelection, TextSpan,
+22 -2
View File
@@ -163,6 +163,8 @@ pub struct EdgePickerStyle {
focus: FocusLook,
/// The side of the square.
side: f32,
/// The side of the square at [`EdgeSize::Sample`].
sample_side: f32,
/// How far the outer lines sit inside the square, and how near a line the pointer picks it.
inset: f32,
/// The area inside the lines.
@@ -198,6 +200,20 @@ pub struct EdgePicker<'a> {
/// How the picture is drawn: the proxy diagram, or a sample of the borders on text, a paragraph or a page.
#[prop]
look: EdgeLook,
/// The extent of the square: a thumbnail, or a sample-sized preview.
#[prop]
preview: EdgeSize,
}
/// How large the picker's square is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum EdgeSize {
/// A thumbnail (`size.thumb.lg`).
#[default]
Thumb,
/// A preview at sample size (`size.thumb.sample.lg`), for a Borders or Shading dialog's page-like preview.
Sample,
}
/// How the borders preview is drawn.
@@ -246,7 +262,7 @@ struct ClickRun {
impl<'a> EdgePicker<'a> {
/// A picker named `label` editing `edges`.
pub fn new(label: impl Into<Label>, edges: Bind<'a, BorderEdges>) -> Self {
EdgePicker { common: Common::new(), edges, paragraph: false, look: EdgeLook::default() }.label(label).ltr_axis()
EdgePicker { common: Common::new(), edges, paragraph: false, look: EdgeLook::default(), preview: EdgeSize::default() }.label(label).ltr_axis()
}
/// The name of `edge`.
@@ -353,6 +369,7 @@ impl Component for EdgePicker<'_> {
.border(edge, cx.tokens.stroke.thin),
focus: cx.focus_look(),
side: cx.tokens.size.thumb.lg,
sample_side: cx.tokens.size.thumb.sample.lg,
inset: cx.tokens.space.pad.regular,
fill: cx.color(colors.surface.sunken),
on: Stateful::new(cx.color(colors.accent.solid)),
@@ -361,7 +378,10 @@ impl Component for EdgePicker<'_> {
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::splat(cx.style.side)
Vec2::splat(match self.preview {
EdgeSize::Thumb => cx.style.side,
EdgeSize::Sample => cx.style.sample_side,
})
}
fn sense(&self) -> Sense {
+1 -1
View File
@@ -9,7 +9,7 @@ pub mod size_picker;
#[cfg(feature = "suite")]
pub(crate) mod stories;
pub use edges::{BorderEdges, BorderPreset, EdgeKey, EdgeLook, EdgePicker, EdgePickerStyle, EdgePickerWords, SampleArea};
pub use edges::{BorderEdges, BorderPreset, EdgeKey, EdgeLook, EdgePicker, EdgePickerStyle, EdgePickerWords, EdgeSize, SampleArea};
pub use properties::{CellAlign, RowHeight, TableChange, TableProperties, TablePropertiesOutput, TablePropertiesWords, TableValues, TextDirection};
pub use selection::{CellSelectionOverlay, CellSelectionStyle, TableGeometry};
pub use size_picker::{TableSizePicker, TableSizePickerOutput, TableSizePickerStyle, TableSizePickerWords};
+19
View File
@@ -25,3 +25,22 @@ fn right_at_a_row_end_goes_on_to_the_next_row() {
fixture.key(Key::ArrowRight, Modifiers::NONE).idle(2);
assert_eq!(hovered.get(), Some((2, 1)), "Right wraps to the next row");
}
/// A picker asked for sample size draws a larger square than the default thumbnail.
#[trial]
fn edge_picker_sample_size_is_larger_than_the_thumbnail() {
use craft_pages::ui::table::{BorderEdges, EdgePicker, EdgeSize};
use craft_ui::contract::Bind;
let sides = Rc::new(Cell::new((0.0, 0.0)));
let seen = sides.clone();
let mut edges = BorderEdges::default();
let mut fixture = Fixture::new(move |ui| {
let thumb = EdgePicker::new("Thumb", Bind::bound(&mut edges)).show(ui).response.rect.width();
let mut other = BorderEdges::default();
let sample = EdgePicker::new("Sample", Bind::bound(&mut other)).preview(EdgeSize::Sample).show(ui).response.rect.width();
seen.set((thumb, sample));
});
fixture.settle();
let (thumb, sample) = sides.get();
assert!(thumb > 0.0 && sample > thumb, "thumb {thumb}, sample {sample}");
}
+162 -42
View File
@@ -4,11 +4,10 @@
use super::length::{DocUnit, length_field, shown};
use craft_behavior::{EditEvent, EditEvents, Metrics, Mixed, NumberCodec};
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{
Bind, Common, Component, Cx, Entry, FieldLayout, MeasureCx, PaintUi, Props as _, Role, Show as _, ShowContainer as _, SideLabel, Sizing,
Validity, clicked,
Bind, Common, Component, Cx, Entry, FieldLayout, MeasureCx, PaintUi, Pointer as _, Props as _, Role, Show as _, ShowContainer as _, SideLabel,
Sizing, Validity,
};
use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft_ui::form::{Field, FieldGroup};
@@ -18,7 +17,7 @@ use craft_ui::primitives::{PaintShape, StrokeWidth};
use craft_ui::runtime::env::{Env, Label, Message, Units};
use craft_ui::runtime::words::CommonWords;
use craft_ui::sections::{DialogRole, FooterButton, GroupBox};
use craft_ui::style::{ComponentStyle, StyleColor, StyleCx, SurfaceKind, TypeRole};
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, SurfaceKind, TypeRole};
use craft_ui::text::{NumberField, NumberOutput};
use egui::{Pos2, Rect, Ui, Vec2, pos2, vec2};
use std::cell::Cell;
@@ -129,6 +128,19 @@ pub enum ColumnsPreset {
Right,
}
impl ColumnsPreset {
/// The number of columns, and for Left and Right whether the narrow one is first.
fn shape(self) -> (u32, Option<bool>) {
match self {
ColumnsPreset::One => (1, None),
ColumnsPreset::Two => (2, None),
ColumnsPreset::Three => (3, None),
ColumnsPreset::Left => (2, Some(true)),
ColumnsPreset::Right => (2, Some(false)),
}
}
}
/// The Columns dialog: only what changed comes back.
///
/// - [`word`](Self::word) off (PowerPoint): Number (1 to [`MAX_COLUMNS`]) and Spacing (0 to [`MAX_SPACING`] points);
@@ -287,13 +299,7 @@ impl TextColumnsDialog {
let Some(width) = self.word else { return };
let spacing = DEFAULT_SPACING;
self.edited.spacing = Some(spacing);
let (count, narrow_first) = match preset {
ColumnsPreset::One => (1, None),
ColumnsPreset::Two => (2, None),
ColumnsPreset::Three => (3, None),
ColumnsPreset::Left => (2, Some(true)),
ColumnsPreset::Right => (2, Some(false)),
};
let (count, narrow_first) = preset.shape();
self.edited.count = Some(count);
match narrow_first {
None => {
@@ -533,7 +539,11 @@ impl TextColumnsDialog {
let mut chosen = None;
Row::new().show(ui, |ui, _| {
for (preset, label) in every {
if clicked(&Button::new(label.clone()).show(ui)) {
let tile = Field::new(label.clone())
.layout(FieldLayout::Above)
.sizing(Sizing::Content)
.show(ui, |ui, _| ColumnsPresetTile::new(label.clone(), Self::preset_rows(preset)).show(ui).clicked);
if tile.inner == Some(true) {
chosen = Some(preset);
}
}
@@ -543,6 +553,25 @@ impl TextColumnsDialog {
}
}
/// The columns a preset draws as, over a text width of 1 and a spacing of a twelfth.
pub(crate) fn preset_rows(preset: ColumnsPreset) -> Vec<(f32, f32)> {
let (count, narrow_first) = preset.shape();
let spacing = 1.0 / 12.0;
match narrow_first {
// Not `even_rows`: its minimum column width is in points and would close the gaps over a width of 1.
None => {
let each = (1.0 - spacing * (count - 1) as f32) / count as f32;
(0..count).map(|i| (each, if i + 1 < count { spacing } else { 0.0 })).collect()
}
Some(left) => {
let narrow = (1.0 - spacing) * NARROW_SHARE;
let wide = 1.0 - spacing - narrow;
let (first, second) = if left { (narrow, wide) } else { (wide, narrow) };
vec![(first, spacing), (second, 0.0)]
}
}
}
/// One row per column: its number, then its width and the spacing after it, each behind its caption.
fn grid(&mut self, ui: &mut Ui, words: &TextColumnsWords, units: &Units) {
let rows = self.rows();
@@ -723,6 +752,25 @@ pub struct ColumnsPreviewStyle {
pane: f32,
/// The distance between text lines.
pitch: f32,
#[style(focus)]
focus: FocusLook,
}
impl ColumnsPreviewStyle {
/// The preview's look; a preset thumbnail takes the same with a smaller pane.
fn at(cx: &StyleCx<'_>) -> Self {
let colors = &cx.tokens.color;
ColumnsPreviewStyle {
metrics: Metrics::new(),
page: cx.color(colors.surface.raised),
edge: cx.color(colors.line.border),
line: cx.color(colors.text.faint),
separator: cx.color(colors.text.normal),
pane: cx.tokens.size.thumb.sample.lg,
pitch: cx.tokens.typography.get(TypeRole::Body).line_height * LINE_PITCH,
focus: cx.focus_look(),
}
}
}
/// The page preview: the columns and the line between them on a page, as Word's dialog draws it.
@@ -750,16 +798,7 @@ impl Component for ColumnsPreview {
type Output = egui::Response;
fn style(cx: &StyleCx<'_>, _: ColumnsPreviewStyleKey) -> ColumnsPreviewStyle {
let colors = &cx.tokens.color;
ColumnsPreviewStyle {
metrics: Metrics::new(),
page: cx.color(colors.surface.raised),
edge: cx.color(colors.line.border),
line: cx.color(colors.text.faint),
separator: cx.color(colors.text.normal),
pane: cx.tokens.size.thumb.md,
pitch: cx.tokens.typography.get(TypeRole::Body).line_height * LINE_PITCH,
}
ColumnsPreviewStyle::at(cx)
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
@@ -767,26 +806,15 @@ impl Component for ColumnsPreview {
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let style = cx.style;
let pane = cx.rect;
let height = pane.height().min(pane.width() / PAGE_ASPECT);
let page = Rect::from_center_size(pane.center(), vec2(height * PAGE_ASPECT, height));
let draw = ui.draw();
draw.surface(pane, SurfaceKind::Sunken, craft_ui::style::Corners::None);
draw.fill(&PaintShape::Rect(page, egui::CornerRadius::ZERO), style.page);
draw.stroke(&PaintShape::Rect(page, egui::CornerRadius::ZERO), StrokeWidth::Thin, style.edge);
let plan = preview_plan(&self.rows, self.text_width, self.line_between, page);
let line = |a: Pos2, b: Pos2, color: StyleColor| draw.stroke(&PaintShape::Path(vec![a, b]), StrokeWidth::Thin, color);
for &(left, right) in &plan.columns {
let mut y = plan.text.top();
while y + style.pitch / 2.0 <= plan.text.bottom() {
line(pos2(left, y), pos2(right, y), style.line);
y += style.pitch;
}
}
for &x in &plan.separators {
line(pos2(x, plan.text.top()), pos2(x, plan.text.bottom()), style.separator);
}
paint_columns(
ui,
[cx.style.page, cx.style.edge, cx.style.line, cx.style.separator],
cx.style.pitch,
cx.rect,
&self.rows,
self.text_width,
self.line_between,
);
}
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
@@ -794,6 +822,98 @@ impl Component for ColumnsPreview {
}
}
/// Draws the page of `rows` over `text_width` in `pane`.
fn paint_columns(ui: &mut PaintUi<'_>, inks: [StyleColor; 4], pitch: f32, pane: Rect, rows: &[(f32, f32)], text_width: f32, line_between: bool) {
let height = pane.height().min(pane.width() / PAGE_ASPECT);
let page = Rect::from_center_size(pane.center(), vec2(height * PAGE_ASPECT, height));
let draw = ui.draw();
draw.surface(pane, SurfaceKind::Sunken, craft_ui::style::Corners::None);
let [page_ink, edge, text, separator] = inks;
draw.fill(&PaintShape::Rect(page, egui::CornerRadius::ZERO), page_ink);
draw.stroke(&PaintShape::Rect(page, egui::CornerRadius::ZERO), StrokeWidth::Thin, edge);
let plan = preview_plan(rows, text_width, line_between, page);
let line = |a: Pos2, b: Pos2, color: StyleColor| draw.stroke(&PaintShape::Path(vec![a, b]), StrokeWidth::Thin, color);
for &(left, right) in &plan.columns {
let mut y = plan.text.top();
while y + pitch / 2.0 <= plan.text.bottom() {
line(pos2(left, y), pos2(right, y), text);
y += pitch;
}
}
for &x in &plan.separators {
line(pos2(x, plan.text.top()), pos2(x, plan.text.bottom()), separator);
}
}
/// A preset's thumbnail: a small page with the preset's columns, a button named by the label.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
pub struct ColumnsPresetTile {
#[common]
common: Common,
rows: Vec<(f32, f32)>,
clicked: bool,
}
/// What a preset tile reports.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ColumnsPresetTileOutput {
/// The tile's response.
pub response: egui::Response,
/// A click, Space or Enter reached the enabled tile.
pub clicked: bool,
}
impl craft_ui::contract::Outcome for ColumnsPresetTileOutput {
type Value = craft_ui::contract::NoValue;
fn response(&self) -> &egui::Response {
&self.response
}
}
impl ColumnsPresetTile {
/// A tile named `label` drawing `rows` (each column's width and the spacing after it).
pub fn new(label: impl Into<Label>, rows: Vec<(f32, f32)>) -> Self {
ColumnsPresetTile { common: Common::new(), rows, clicked: false }.label(label)
}
}
impl Component for ColumnsPresetTile {
const ROLE: Role = Role::BUTTON;
const PARTS: bool = false;
const OVERLAYS: bool = false;
type Style = ColumnsPreviewStyle;
type Output = ColumnsPresetTileOutput;
fn style(cx: &StyleCx<'_>, _: ColumnsPresetTileStyleKey) -> ColumnsPreviewStyle {
let mut style = ColumnsPreviewStyle::at(cx);
style.pane = cx.tokens.size.thumb.lg;
style.pitch /= 2.0;
style
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::splat(cx.style.pane)
}
fn sense(&self) -> craft_behavior::Sense {
craft_behavior::Sense::CLICK | craft_behavior::Sense::FOCUS
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
self.clicked = cx.activation().is_some() && cx.resolved.enabled;
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
paint_columns(ui, [cx.style.page, cx.style.edge, cx.style.line, cx.style.separator], cx.style.pitch, cx.rect, &self.rows, 1.0, false);
}
fn finish(self, cx: Cx<'_, Self>) -> ColumnsPresetTileOutput {
ColumnsPresetTileOutput { response: cx.response.clone(), clicked: self.clicked }
}
}
/// A choice from the Columns menu.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
+6 -1
View File
@@ -1,6 +1,6 @@
//! Stories of the Columns dialog and the page preview.
use super::{ColumnsApply, ColumnsPreview, TextColumns, TextColumnsDialog};
use super::{ColumnsApply, ColumnsPresetTile, ColumnsPreview, TextColumns, TextColumnsDialog};
use craft_ui::contract::Show as _;
use craft_ui::dialog::{DialogStack, StackDialog as _};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
@@ -24,3 +24,8 @@ fn preview(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let rows = vec![(140.0, 24.0), (140.0, 24.0), (140.0, 0.0)];
ColumnsPreview::new("Preview", rows, TEXT_WIDTH, true).show(ui).into()
}
#[story(ColumnsPresetTile, covers = [Default], drive = Drive::Activate)]
fn preset_tile(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
ColumnsPresetTile::new("Left", vec![(0.3, 1.0 / 12.0), (0.62, 0.0)]).show(ui).into()
}
+60
View File
@@ -0,0 +1,60 @@
//! The Columns dialog's preset thumbnails and page preview.
use craft_text::ui::columns::{ColumnsApply, TextColumns, TextColumnsDialog};
use craft_ui::dialog::{DialogStack, StackDialog as _};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
use std::cell::RefCell;
use std::rc::Rc;
fn opened() -> (Fixture, Rc<RefCell<TextColumnsDialog>>) {
let columns = TextColumns { count: Some(1), spacing: Some(36.0), equal_width: Some(true), line_between: Some(false), ..TextColumns::default() };
let dialog = Rc::new(RefCell::new(TextColumnsDialog::new(columns).word(468.0).apply_to(&[ColumnsApply::Document], ColumnsApply::Document)));
let shown = dialog.clone();
let mut fixture = Fixture::new(move |ui| {
let _ = shown.borrow_mut().show(ui, &DialogStack::default());
});
fixture.idle(2);
(fixture, dialog)
}
/// A preset is a drawn thumbnail that a click applies, and the preview is larger than the thumbnail.
#[trial]
fn a_preset_thumbnail_applies_its_preset_and_the_preview_is_larger() {
let (mut fixture, dialog) = opened();
let tile = fixture.by_label("Two").expect("the Two preset");
let preview = fixture.by_label("Preview").expect("the preview");
let field = fixture.by_label("Line between").expect("a text control");
assert!(tile.rect.height() > field.rect.height() * 1.5, "a drawn thumbnail, not a text button: {:?} against {:?}", tile.rect, field.rect);
assert!(preview.rect.width() > tile.rect.width(), "preview {:?} over tile {:?}", preview.rect, tile.rect);
fixture.click(&tile).idle(4);
assert_eq!(dialog.borrow().edited().count, Some(2));
}
/// Tab reaches a preset thumbnail and draws a focus ring on it.
#[trial]
fn a_focused_preset_thumbnail_draws_a_focus_ring() {
use craft_text::ui::columns::ColumnsPresetTile;
use craft_ui::contract::Show as _;
let mut fixture = Fixture::new(|ui| {
let _ = ColumnsPresetTile::new("Left", vec![(1.0, 0.0)]).show(ui);
});
fixture.idle(2);
let before = fixture.frame_shapes().len();
fixture.key(Key::Tab, Modifiers::NONE).idle(2);
assert!(fixture.focused().is_some(), "Tab reaches the thumbnail");
let after = fixture.frame_shapes().len();
assert!(after > before, "focus adds a ring: {before} shapes before, {after} after");
}
/// Every preset thumbnail draws its columns apart, over a text width of 1: gaps between them, nothing past the page.
#[trial]
fn preset_thumbnails_draw_their_columns_apart() {
use craft_text::ui::columns::ColumnsPreset::{Left, One, Right, Three, Two};
for preset in [One, Two, Three, Left, Right] {
let rows = TextColumnsDialog::preset_rows(preset);
let total: f32 = rows.iter().map(|(width, gap)| width + gap).sum();
assert!((total - 1.0).abs() < 1e-4, "{preset:?} fills the text width: {rows:?}");
assert!(rows[..rows.len() - 1].iter().all(|(_, gap)| *gap > 0.0), "{preset:?} has a gap between columns: {rows:?}");
}
}
+1
View File
@@ -2,6 +2,7 @@
// Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
pub(crate) mod columns;
pub(crate) mod editor;
#[cfg(feature = "find")]
pub(crate) mod find;
+29 -2
View File
@@ -227,8 +227,30 @@ impl VariantLook {
// A disabled solid button keeps its shape: its solid colour dimmed towards the disabled fill, which alone
// would match the panel and leave only the label.
Emphasis::Solid => {
let dimmed = crate::derive::mix(solid, c.state.disabled_fill, DISABLED_SOLID_DIM);
VariantLook::new(States::new(solid, solid_hover, solid_pressed, dimmed), text(on_solid)).radius(button)
// Dimmed towards the disabled fill until it differs from the enabled fill by
// `DISABLED_SOLID_SEPARATION`, so a dark theme's disabled button is not taken for an enabled one. A theme
// whose disabled fill is itself close to the solid colour dims towards black, then white, instead.
let dim = |to: Rgba| {
let mut at = DISABLED_SOLID_DIM;
let mut fill = crate::derive::mix(solid, to, at);
while at < DISABLED_SOLID_DIM_MAX && crate::contrast::contrast_ratio(fill, solid) < DISABLED_SOLID_SEPARATION {
at += 0.05;
fill = crate::derive::mix(solid, to, at);
}
fill
};
let apart = |fill: Rgba| crate::contrast::contrast_ratio(fill, solid) >= DISABLED_SOLID_SEPARATION;
let dimmed = [c.state.disabled_fill, Rgba::BLACK, Rgba::WHITE]
.into_iter()
.map(dim)
.find(|fill| apart(*fill))
.unwrap_or_else(|| dim(c.state.disabled_fill));
// Its label is the disabled ink moved off the dimmed fill until it reads (4.5:1): the disabled grey alone
// is pale on a pale blue block and says nothing.
let label =
crate::contrast::ensure_contrast(c.text.disabled, dimmed, crate::contrast::text_contrast_min(crate::theme::Contrast::Standard));
let text = States::new(on_solid, on_solid, on_solid, label);
VariantLook::new(States::new(solid, solid_hover, solid_pressed, dimmed), text).radius(button)
}
Emphasis::Soft => VariantLook::new(States::new(soft_fill, soft_fill, soft_fill, c.state.disabled_fill), text(fg))
.edge(States::new(edge, edge, edge, c.line.divider))
@@ -256,6 +278,11 @@ impl VariantLook {
/// How far a disabled solid fill moves from its solid colour to the disabled fill.
const DISABLED_SOLID_DIM: f64 = 0.5;
/// The least contrast ratio between a disabled solid fill and the enabled one, and how far the fill may be dimmed to
/// get it.
const DISABLED_SOLID_SEPARATION: f64 = 1.5;
const DISABLED_SOLID_DIM_MAX: f64 = 0.95;
/// A look for one component's style key, built in a `const`. It describes itself; nothing registers it.
#[derive(Clone, Copy)]
pub struct CustomVariant {
+37
View File
@@ -0,0 +1,37 @@
//! A disabled solid button (primary, danger) keeps a readable label and stays clearly unlike the enabled one in every
//! built-in theme and contrast setting (wordcraft#7978).
use craft_theme::contrast::contrast_ratio;
use craft_theme::{Appearance, Contrast, Mode, Size, TextSize, Variant, Variants, builtins, resolve};
/// Least contrast ratio between the disabled fill and the enabled one.
const FILL_SEPARATION: f64 = 1.5;
#[test]
fn disabled_solid_label_reads_and_the_button_is_not_the_enabled_one() {
for theme in builtins() {
// Classic draws a disabled button with its bevel; its pinned greys are not this look.
if theme.name == "Classic" {
continue;
}
let modes = match theme.variants {
Variants::Both => vec![Mode::Light, Mode::Dark],
Variants::LightOnly => vec![Mode::Light],
Variants::DarkOnly => vec![Mode::Dark],
};
for mode in modes {
for contrast in [Contrast::Standard, Contrast::High] {
let appearance = Appearance { mode, contrast, size: Size::Comfortable, text_size: TextSize::Small, reduced_motion: false };
let tokens = resolve(theme, appearance, None).tokens;
for variant in [Variant::PRIMARY, Variant::DANGER] {
let look = variant.resolve(&tokens);
let who = format!("{} {mode:?} {contrast:?} {variant:?}", theme.name);
let label = contrast_ratio(look.text.disabled, look.fill.disabled);
assert!(label >= 4.5, "{who}: disabled label is {label:.2}:1");
let apart = contrast_ratio(look.fill.disabled, look.fill.rest);
assert!(apart >= FILL_SEPARATION, "{who}: disabled fill is {apart:.2}:1 from the enabled one");
}
}
}
}
}
+1
View File
@@ -1,5 +1,6 @@
//! Integration tests, built into the library's own test executable.
mod disabled_solid;
mod dumps;
mod selection;
mod strong_hover;
@@ -9,8 +9,8 @@ pub(crate) mod stories;
use super::space::canvas_space;
use crate::contract::overlay::{Dismiss, LayerRole, Outside};
use crate::contract::{
Access, Bind, Common, Component, Cx, MeasureCx, Name, NoValue, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _,
Props as _, Rename, Role, Show as _,
Access, Bind, Common, Component, Cx, MeasureCx, Name, NoValue, Outcome, Overlay, OverlayUi, Overlays as _, POPUP_PAD, PaintUi, PartsCx,
Pointer as _, Props as _, Rename, Role, Show as _,
};
use crate::primitives::{Checker, CheckerArea, PaintShape, PaintSlot, Rule, StrokeColor, StrokeWidth, TextRun, paint_surround};
use crate::runtime::env::Label;
@@ -590,7 +590,8 @@ impl Component for Pasteboard<'_> {
let layer = Overlay::popover()
.dismiss(Dismiss::new().outside(Outside::Keep))
.focus(FocusPolicy::POPUP.initial(Initial::First))
.role(LayerRole::InPlaceEditor);
.role(LayerRole::InPlaceEditor)
.pad(POPUP_PAD);
let layer = match field.or(state.shown) {
Some(rect) => layer.placed(rect),
None => layer,
+6 -1
View File
@@ -1,6 +1,6 @@
# Icon sources
Each folder holds only the files `icons.toml` lists, unchanged from the pinned source (exception: the drawings named below the table), and the set's licence as `LICENSE`. To add an icon, copy its file from the same commit.
Each folder holds only the files `icons.toml` lists, unchanged from the pinned source (exception: the drawings named below the table), and the set's licence as `LICENSE`. To add an icon, copy its file from the npm package of the version in the table.
| Folder | Set | Licence | Source (tag, commit) | Files taken from |
|---|---|---|---|---|
@@ -13,6 +13,8 @@ Carbon's licence file is the repository's root `LICENSE` (the icons package has
Every set folder's files come from the npm package of the version in the table (`@phosphor-icons/core` 2.0.8, `lucide-static` 1.63.0, `@carbon/icons` 11.91.0, `@tabler/icons` 3.50.0), the same releases as the tags above. Phosphor files are `regular` weight, except `star-filled.svg`, `circle-filled.svg` and `warning-filled.svg`, which are Phosphor's `fill` weight (`star-fill.svg`, `circle-fill.svg`, `warning-fill.svg`). `panel-left.svg` is Phosphor's `sidebar-simple` unchanged, and `panel-right.svg` is the same glyph mirrored.
The transform and layout files added for the flip, scale, skew, padding and gap glyphs are these packages' copies, byte for byte, comments and classes included: Lucide's `flip-horizontal`, `flip-vertical`, `gap-horizontal` and `gap-vertical`; Tabler's `flip-horizontal`, `flip-vertical`, `skew-x`, `skew-y`, `arrow-autofit-width`, `arrow-autofit-height`, `spacing-horizontal` and `spacing-vertical`; and Phosphor's `arrows-out-line-horizontal` and `arrows-out-line-vertical`.
`phosphor/` also holds drawings made for the suite, for glyphs the pinned Phosphor release lacks. They follow Phosphor's regular style (256 view box, 16-unit round-capped strokes, some converted to filled outlines), take their shapes from PhotoCraft's glyphs, and carry the suite's own licence:
- `bandage-sparkle`, `brush-replace`, `clip-below`, `clip-release`, `convert-point`, `direct-select`, `eraser-background`, `eraser-magic`, `font-similar`
@@ -24,5 +26,8 @@ Every set folder's files come from the npm package of the version in the table (
- `sync-lock`, `mark-in`, `mark-out`, `insert-clip`, `overwrite-clip`, `lift-clip`, `extract-clip` (the timeline's lock and edit glyphs, after Premiere Pro's), `keyframe-linear`, `keyframe-bezier`, `keyframe-auto-bezier`, `keyframe-hold`, `keyframe-ease-in`, `keyframe-ease-out` (keyframe nodes after After Effects' shapes: diamond, square for Bezier, circle for Auto Bezier)
- `key-linear`, `key-linear-filled`, `key-hold`, `key-bezier`, `key-auto-bezier`, `key-continuous-bezier`, `key-ease-in`, `key-ease-out`, `keyframe-easy-ease` (the timeline's single keyframe marks and the graph editor's Easy Ease button, after FilmCraft's diamond, square and circle and After Effects' keys; solid shapes except the outline diamond and the rings)
- `font-variable`, `scaling`, `slice-select`, `square-dashed-mouse-pointer`, `text-warp`, `triangle-right`, `type-mask`, `type-mask-vertical`
- `flip-horizontal`, `flip-vertical`, `skew-horizontal`, `skew-vertical`, `padding-top`, `padding-right`, `padding-bottom`, `padding-left`, `gap-horizontal`, `gap-vertical` (the transform and layout panels' glyphs, drawn after the marks those panels make: a dashed axis between two triangles for a flip, a slanted rectangle for the skew along x and the same rectangle transposed for the skew along y, a frame with the space drawn solid on one side for a padding, and two items with a double arrow in the space between them for a gap)
- `crop-overlay-*` (the crop overlay menu's glyphs), `text-align-top`, `text-align-middle`, `text-align-bottom` (the vertical type options), `dash-align-exact`, `dash-align-corners` (the dash alignment options)
- `eye-outline` (Phosphor's `eye` without the pupil: the Outline view), `layer-template` (a dashed layer: the Template view)
Where a pinned set already draws one of these meanings, that set uses its own file rather than the base set's: Lucide's `flip-horizontal`, `flip-vertical`, `gap-horizontal` and `gap-vertical`; Tabler's `flip-horizontal`, `flip-vertical`, `skew-x`, `skew-y`, `arrow-autofit-width`, `arrow-autofit-height`, `spacing-horizontal` and `spacing-vertical`; and Phosphor's own `arrows-out-line-horizontal` and `arrows-out-line-vertical` for the axis of scale. A set without one falls back to the base set's drawing, as it does for every other icon, so Lucide and Carbon draw Phosphor's two `arrows-out-line` marks for the axes of scale. The four paddings keep the base set's drawing in every set: the nearest marks the other packs have, Tabler's `box-padding` and `box-margin`, draw a uniform inset around the content, and that names no side.
+95 -3
View File
@@ -35,14 +35,17 @@ stroke_drawings = [
"crop-overlay-thirds", "crop-overlay-triangle", "dash-align-corners", "dash-align-exact",
"direct-select", "distribute-bottom", "distribute-hcenter", "distribute-horizontal", "distribute-left",
"distribute-right", "distribute-top", "distribute-vcenter", "distribute-vertical", "eraser-background",
"eraser-magic", "extract-clip", "eye-outline", "font-similar", "fx", "gradient-angle", "gradient-diamond", "gradient-linear",
"eraser-magic", "extract-clip", "eye-outline", "flip-horizontal", "flip-vertical", "font-similar", "fx",
"gap-horizontal", "gap-vertical", "gradient-angle", "gradient-diamond", "gradient-linear",
"gradient-radial", "gradient-reflected", "gradient-swatch", "insert-clip", "key-auto-bezier", "key-bezier", "key-continuous-bezier",
"key-ease-in", "key-ease-out", "key-hold", "key-linear", "key-linear-filled", "keyframe-auto-bezier",
"keyframe-bezier", "keyframe-ease-in", "keyframe-ease-out", "keyframe-easy-ease", "keyframe-hold",
"keyframe-linear", "lasso", "lasso-magnetic", "lasso-select", "layer-mask", "layer-template", "lift-clip", "lollipop", "mark-in",
"mark-out", "marquee-column", "marquee-row", "overwrite-clip", "painting-symmetry", "pen-add-anchor",
"mark-out", "marquee-column", "marquee-row", "overwrite-clip", "padding-bottom", "padding-left", "padding-right",
"padding-top", "painting-symmetry", "pen-add-anchor",
"pen-curvature", "pen-delete-anchor", "pen-freeform", "protractor", "quick-selection", "route-curved", "route-elbow",
"route-straight", "stroke-align-center", "stroke-align-inside", "stroke-align-outside", "stroke-cap-butt",
"route-straight", "skew-horizontal", "skew-vertical", "stroke-align-center",
"stroke-align-inside", "stroke-align-outside", "stroke-cap-butt",
"stroke-cap-round", "stroke-cap-square", "stroke-join-bevel", "stroke-join-miter", "stroke-join-round",
"symmetry-diagonal", "symmetry-dual", "symmetry-horizontal", "symmetry-vertical", "sync-lock",
"text-align-bottom", "text-align-middle", "text-align-top"
@@ -594,6 +597,55 @@ phosphor = "arrows-down-up"
carbon = "arrows--vertical"
tabler = "arrows-down-up"
# The transform panels' flip, scale and skew glyphs. Each name is the axis the change runs along:
# `flip_horizontal` mirrors left and right, so the axis it mirrors about is the vertical one the drawing shows.
# The `symmetry_*` names read the other way round: they name the axis line the drawing shows, so `symmetry_vertical`
# mirrors left and right. `skew_horizontal` and `skew_vertical` are the skew along x and along y. None of these is directional: a side or an axis of the
# screen stays where it is under right-to-left. Lucide and Tabler draw the flips, Tabler draws the skew pair and
# the two axes of scale (its `arrow-autofit-width` and `-height`: a box whose width or height is spanned by
# outward arrows), and Phosphor's `arrows-out-line-horizontal` and `-vertical` are the base set's marks for the
# axis of scale; Phosphor draws no flip and no skew, so the base set draws those (ATTRIBUTION.md). Tabler's file
# names read the other way round: its `skew-y` leans the sides and so draws the horizontal skew, and its `skew-x`
# leans the top and bottom and draws the vertical one.
[[icon]]
name = "flip_horizontal"
directional = false
lucide = "flip-horizontal"
phosphor = "flip-horizontal"
tabler = "flip-horizontal"
[[icon]]
name = "flip_vertical"
directional = false
lucide = "flip-vertical"
phosphor = "flip-vertical"
tabler = "flip-vertical"
[[icon]]
name = "scale_horizontal"
directional = false
phosphor = "arrows-out-line-horizontal"
tabler = "arrow-autofit-width"
[[icon]]
name = "scale_vertical"
directional = false
phosphor = "arrows-out-line-vertical"
tabler = "arrow-autofit-height"
[[icon]]
name = "skew_horizontal"
directional = false
phosphor = "skew-horizontal"
tabler = "skew-y"
[[icon]]
name = "skew_vertical"
directional = false
phosphor = "skew-vertical"
tabler = "skew-x"
[[icon]]
name = "ban"
directional = false
@@ -768,6 +820,46 @@ name = "distribute_vertical"
directional = false
phosphor = "distribute-vertical"
# The layout panels' spacing glyphs: a frame with the space on one side, and the gap between two items. Each gap
# name is the axis the gap runs along, as the flip, scale and skew names are, and none of them mirrors under
# right-to-left: a side of the screen stays that side. Phosphor 2.0.8 draws neither a padding nor a gap, so the
# base set draws its own (ATTRIBUTION.md); Lucide's `gap-horizontal` and `gap-vertical` and Tabler's
# `spacing-horizontal` and `spacing-vertical` are the same meanings.
[[icon]]
name = "gap_horizontal"
directional = false
lucide = "gap-horizontal"
phosphor = "gap-horizontal"
tabler = "spacing-horizontal"
[[icon]]
name = "gap_vertical"
directional = false
lucide = "gap-vertical"
phosphor = "gap-vertical"
tabler = "spacing-vertical"
[[icon]]
name = "padding_bottom"
directional = false
phosphor = "padding-bottom"
[[icon]]
name = "padding_left"
directional = false
phosphor = "padding-left"
[[icon]]
name = "padding_right"
directional = false
phosphor = "padding-right"
[[icon]]
name = "padding_top"
directional = false
phosphor = "padding-top"
[[icon]]
name = "droplet"
directional = false
@@ -0,0 +1,20 @@
<!-- @license lucide-static v1.63.0 - ISC -->
<svg
class="lucide lucide-flip-horizontal"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M8 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h3" />
<path d="M16 3h3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-3" />
<path d="M12 20v2" />
<path d="M12 14v2" />
<path d="M12 8v2" />
<path d="M12 2v2" />
</svg>

After

Width:  |  Height:  |  Size: 500 B

@@ -0,0 +1,20 @@
<!-- @license lucide-static v1.63.0 - ISC -->
<svg
class="lucide lucide-flip-vertical"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v3" />
<path d="M21 16v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3" />
<path d="M4 12H2" />
<path d="M10 12H8" />
<path d="M16 12h-2" />
<path d="M22 12h-2" />
</svg>

After

Width:  |  Height:  |  Size: 501 B

@@ -0,0 +1,20 @@
<!-- @license lucide-static v1.63.0 - ISC -->
<svg
class="lucide lucide-gap-horizontal"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 2v2" />
<path d="M12 8v2" />
<path d="M12 14v2" />
<path d="M12 20v2" />
<path d="M21 3h-3a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3" />
<path d="M3 3h3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H3" />
</svg>

After

Width:  |  Height:  |  Size: 499 B

@@ -0,0 +1,20 @@
<!-- @license lucide-static v1.63.0 - ISC -->
<svg
class="lucide lucide-gap-vertical"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M2 12h2" />
<path d="M8 12h2" />
<path d="M14 12h2" />
<path d="M20 12h2" />
<path d="M3 21v-3a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3" />
<path d="M3 3v3a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V3" />
</svg>

After

Width:  |  Height:  |  Size: 497 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M136,40V216a8,8,0,0,1-16,0V40a8,8,0,0,1,16,0ZM96,120H35.31l18.35-18.34A8,8,0,0,0,42.34,90.34l-32,32a8,8,0,0,0,0,11.32l32,32a8,8,0,0,0,11.32-11.32L35.31,136H96a8,8,0,0,0,0-16Zm149.66,2.34-32-32a8,8,0,0,0-11.32,11.32L220.69,120H160a8,8,0,0,0,0,16h60.69l-18.35,18.34a8,8,0,0,0,11.32,11.32l32-32A8,8,0,0,0,245.66,122.34Z"/></svg>

After

Width:  |  Height:  |  Size: 416 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M224,128a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16H216A8,8,0,0,1,224,128ZM101.66,53.66,120,35.31V96a8,8,0,0,0,16,0V35.31l18.34,18.35a8,8,0,0,0,11.32-11.32l-32-32a8,8,0,0,0-11.32,0l-32,32a8,8,0,0,0,11.32,11.32Zm52.68,148.68L136,220.69V160a8,8,0,0,0-16,0v60.69l-18.34-18.35a8,8,0,0,0-11.32,11.32l32,32a8,8,0,0,0,11.32,0l32-32a8,8,0,0,0-11.32-11.32Z"/></svg>

After

Width:  |  Height:  |  Size: 436 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><path d="M128 36V76M128 96V156M128 176V220"/><path d="M52 68V188L100 128Z" fill="currentColor" stroke="none"/><path d="M204 68V188L156 128Z" fill="currentColor" stroke="none"/></svg>

After

Width:  |  Height:  |  Size: 344 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><path d="M36 128H76M96 128H160M180 128H220"/><path d="M68 52H188L128 100Z" fill="currentColor" stroke="none"/><path d="M68 204H188L128 156Z" fill="currentColor" stroke="none"/></svg>

After

Width:  |  Height:  |  Size: 344 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><rect x="36" y="44" width="44" height="168" rx="14"/><rect x="176" y="44" width="44" height="168" rx="14"/><path d="M96 128H160M112 112L96 128L112 144M144 112L160 128L144 144"/></svg>

After

Width:  |  Height:  |  Size: 345 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><rect x="44" y="36" width="168" height="44" rx="14"/><rect x="44" y="176" width="168" height="44" rx="14"/><path d="M128 96V160M112 112L128 96L144 112M112 144L128 160L144 144"/></svg>

After

Width:  |  Height:  |  Size: 345 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><rect x="40" y="40" width="176" height="176" rx="28"/><rect x="64" y="148" width="128" height="44" rx="14" fill="currentColor" stroke="none"/></svg>

After

Width:  |  Height:  |  Size: 310 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><rect x="40" y="40" width="176" height="176" rx="28"/><rect x="64" y="64" width="44" height="128" rx="14" fill="currentColor" stroke="none"/></svg>

After

Width:  |  Height:  |  Size: 309 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><rect x="40" y="40" width="176" height="176" rx="28"/><rect x="148" y="64" width="44" height="128" rx="14" fill="currentColor" stroke="none"/></svg>

After

Width:  |  Height:  |  Size: 310 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><rect x="40" y="40" width="176" height="176" rx="28"/><rect x="64" y="64" width="128" height="44" rx="14" fill="currentColor" stroke="none"/></svg>

After

Width:  |  Height:  |  Size: 309 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><path d="M104 56H216L152 200H40Z"/></svg>

After

Width:  |  Height:  |  Size: 203 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" stroke="currentColor" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><path d="M56 104V216L200 152V40Z"/></svg>

After

Width:  |  Height:  |  Size: 203 B

@@ -0,0 +1,19 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="icon icon-tabler icons-tabler-outline icon-tabler-arrow-autofit-height"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M12 20h-6a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h6" />
<path d="M18 14v7" />
<path d="M18 3v7" />
<path d="M15 18l3 3l3 -3" />
<path d="M15 6l3 -3l3 3" />
</svg>

After

Width:  |  Height:  |  Size: 513 B

@@ -0,0 +1,19 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="icon icon-tabler icons-tabler-outline icon-tabler-arrow-autofit-width"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M4 12v-6a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v6" />
<path d="M10 18h-7" />
<path d="M21 18h-7" />
<path d="M6 15l-3 3l3 3" />
<path d="M18 15l3 3l-3 3" />
</svg>

After

Width:  |  Height:  |  Size: 511 B

@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="icon icon-tabler icons-tabler-outline icon-tabler-flip-horizontal"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M12 3l0 18" />
<path d="M16 7l0 10l5 0l-5 -10" />
<path d="M8 7l0 10l-5 0l5 -10" />
</svg>

After

Width:  |  Height:  |  Size: 437 B

@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="icon icon-tabler icons-tabler-outline icon-tabler-flip-vertical"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M3 12l18 0" />
<path d="M7 16l10 0l-10 5l0 -5" />
<path d="M7 8l10 0l-10 -5l0 5" />
</svg>

After

Width:  |  Height:  |  Size: 435 B

@@ -0,0 +1,15 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="icon icon-tabler icons-tabler-outline icon-tabler-skew-x"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M4 5.205v13.59a1 1 0 0 0 1.184 .983l14 -2.625a1 1 0 0 0 .816 -.983v-8.34a1 1 0 0 0 -.816 -.983l-14 -2.625a1 1 0 0 0 -1.184 .983" />
</svg>

After

Width:  |  Height:  |  Size: 472 B

@@ -0,0 +1,15 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="icon icon-tabler icons-tabler-outline icon-tabler-skew-y"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M4.326 19h15.348a1 1 0 0 0 .962 -1.275l-3.429 -12a1 1 0 0 0 -.961 -.725h-8.492a1 1 0 0 0 -.961 .725l-3.429 12a1 1 0 0 0 .962 1.275" />
</svg>

After

Width:  |  Height:  |  Size: 475 B

@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="icon icon-tabler icons-tabler-outline icon-tabler-spacing-horizontal"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M20 20h-2a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h2" />
<path d="M4 20h2a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2" />
<path d="M12 8v8" />
</svg>

After

Width:  |  Height:  |  Size: 487 B

@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="icon icon-tabler icons-tabler-outline icon-tabler-spacing-vertical"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M4 20v-2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v2" />
<path d="M4 4v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2" />
<path d="M16 12h-8" />
</svg>

After

Width:  |  Height:  |  Size: 479 B

+5 -1
View File
@@ -162,9 +162,13 @@ pub enum PadEdges {
Inline,
}
/// The padding of every popup surface around its content.
/// The padding of a menu's or a list's popup surface around its rows, which carry their own inset.
pub const POPUP_PAD: Pad = Pad::Control;
/// The padding of a popover's surface around its content: `space.pad.regular`, as a panel's, so controls stand clear of
/// its edge.
pub const POPOVER_PAD: Pad = Pad::Regular;
/// How a container's size follows its content.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
+2 -2
View File
@@ -70,8 +70,8 @@ pub use container::InBar;
pub use container::InMenu;
pub use container::{
BandFill, Bracket, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion,
LeastWidth, Mount, MoveBandCursor, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, QuietHeader, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator,
SectionRhythm, ShellPane, Sizing, ThemeScope, WrapWidth,
LeastWidth, Mount, MoveBandCursor, Notch, POPOVER_PAD, POPUP_PAD, Pad, PadEdges, PaneEdge, QuietHeader, Scroll, ScrollAnchor, ScrollAxes,
ScrollIndicator, SectionRhythm, ShellPane, Sizing, ThemeScope, WrapWidth,
};
pub use craft_tracked::{PlainData, Revision, Tracked};
pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract};
@@ -2,6 +2,7 @@
use super::opener::{Opener, Trigger};
use super::place::{Anchor, DragBounds, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare};
use crate::contract::{POPOVER_PAD, POPUP_PAD, Pad};
use crate::runtime::access::PopupKind;
use crate::runtime::focus::{FocusPolicy, Initial};
use crate::runtime::motion::{MotionSpec, spec};
@@ -146,6 +147,10 @@ pub struct Overlay {
/// Whether a container mounted as this layer scrolls its body vertically. Off for a layer whose body fills it and
/// manages its own scrolling (a dock tree); a body that is one collection uses `collection_body` instead.
pub body_scroll: bool,
/// The padding [`OverlayUi::show`](super::OverlayUi::show) puts around a popup's body closure: `POPUP_PAD` for the
/// rows of a menu or a list, which carry their own inset, and `POPOVER_PAD` for a popover's content. A container
/// mounted as the layer takes its own padding from its props.
pub pad: Pad,
/// Whether the layer's move band moves the OS window the layer is shown in, in place of the layer: the chrome a
/// modal puts over the part of a title bar it covers. The layer stays where it is placed.
pub moves_window: bool,
@@ -203,6 +208,7 @@ impl Overlay {
bounds: None,
opacity: 1.0,
body_scroll: true,
pad: POPUP_PAD,
moves_window: false,
moved_by_app: false,
continue_move: None,
@@ -240,11 +246,12 @@ impl Overlay {
}
/// A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window,
/// taking focus in. It closes when the focus moves out of it.
/// taking focus in. It closes when the focus moves out of it. Its content stands `POPOVER_PAD` in from the edges.
pub fn popover() -> Overlay {
let mut overlay = Overlay::base(Rank::Popup, Overlay::below(), OverlayFit::Content, OwnerClass::Popup, FocusPolicy::POPUP);
overlay.dismiss = Dismiss::new().focus_left(true);
overlay.min_width = MinWidth::Anchor;
overlay.pad = POPOVER_PAD;
overlay
}
@@ -442,6 +449,12 @@ impl Overlay {
self
}
/// Sets the padding [`OverlayUi::show`](super::OverlayUi::show) puts around a popup's body closure.
pub fn pad(mut self, pad: Pad) -> Overlay {
self.pad = pad;
self
}
/// Sets the layer's opacity, from 0 (invisible) to 1.
pub fn opacity(mut self, opacity: f32) -> Overlay {
self.opacity = opacity;
@@ -6,8 +6,7 @@ use super::placement::PopupRegion;
use super::popups::{PopupHandle, PopupLayer, with_popups};
use super::props::Overlay;
use crate::contract::{
BodyCx, Common, Component, Container, ContainerProps, Cx, Inner, Internal, Mount, NoValue, Outcome, POPUP_PAD, Props as _, Resolved, Role,
ShowContainer,
BodyCx, Common, Component, Container, ContainerProps, Cx, Inner, Internal, Mount, NoValue, Outcome, Props as _, Resolved, Role, ShowContainer,
};
use crate::runtime::access::PopupShown;
use crate::runtime::egui::areas::{self};
@@ -89,8 +88,8 @@ impl<'a> OverlayUi<'a> {
});
}
/// Shows the popup while its handle is open, on a popup surface, inside `POPUP_PAD`; the content is a body closure.
/// `None` while closed.
/// Shows the popup while its handle is open, on a popup surface, inside the overlay's `pad` (`POPUP_PAD` for a menu
/// or a list, `POPOVER_PAD` for a popover); the content is a body closure. `None` while closed.
///
/// The popup is a layer container sized from its content: its body is measured in this pass before the layer is
/// placed, so a popup whose content changes is placed by its new size in the pass that shows it. A child that fills
@@ -122,7 +121,7 @@ impl<'a> OverlayUi<'a> {
}
.body_scroll(false);
let label = self.resolved.label_value.clone();
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(POPUP_PAD).mount(Mount::Layer(overlay));
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(overlay.pad).mount(Mount::Layer(overlay));
let container = PopupBody { common: Common::new(), props: ContainerProps { owner: Some(owner), ..props } }.label(label);
self.show_container_with(popup, container, body).and_then(|shown| shown.inner)
}
@@ -227,7 +226,7 @@ impl Outcome for PopupBodyOutput {
}
/// The layer container [`OverlayUi::show`] shows a popup's body closure in: content-sized, on a popup surface inside
/// `POPUP_PAD`, its memory owned by the component that shows the popup. It adds no node of its own: the layer's node
/// the overlay's `pad`, its memory owned by the component that shows the popup. It adds no node of its own: the layer's node
/// is the popup's.
#[derive(crate::contract::Component)]
#[component(container, unregistered)]
+1 -1
View File
@@ -26,7 +26,7 @@ pub(crate) mod sensing;
mod state_layer;
mod surface;
mod surround;
mod svg_set;
pub(crate) mod svg_set;
#[doc(hidden)]
pub mod svg_tree;
pub(crate) mod text;
@@ -8,6 +8,12 @@ use super::svg_tree;
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
// The trials of the catalogue's drawings: beside the generated `svg`, `stroke_width` and `DIRECTIONAL`, whose routing
// they read without a public accessor. The module is `pub(crate)` so the crate's `registry!()` reaches its trials by
// path.
#[cfg(all(feature = "testing", any(test, feature = "suite")))]
pub(crate) mod inspector_trials;
/// An app's own icon set: SVG documents drawn beside the built-in catalog in every `IconSet`.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
@@ -0,0 +1,302 @@
//! The drawings the catalogue gained for the transform and layout panels, read from the generated catalogue itself:
//! each parses, its ink stays inside its view box, it draws along the axis or on the side its name gives in the
//! coordinates it renders in, it does not mirror, and no two of them are the same document in one set.
//!
//! `build.rs` checks the catalogue as data (its tables, a file for every listed name, no unlisted file, the stroke
//! lists) and reads no drawing. The catalogue's `svg` resolves a name and a set to the document the rasteriser draws,
//! the set's own file or the base set's, and this trial goes through that routing rather than a list of file names.
#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
use super::{DIRECTIONAL, IconSet, find, svg};
use crate::primitives::svg_tree;
use crate::testing::trial;
use craft_svg::tree::usvg::tiny_skia_path::{self, PathSegment, Transform};
use craft_svg::tree::usvg::{Group, Node, Path};
use std::collections::BTreeMap;
/// How far an edge may drift from an axis, in the coordinates the drawing renders in, for the trial to count it as
/// along that axis.
const STRAIGHT: f32 = 0.01;
/// The slack the view-box check allows, in view-box units: a cap or a join just past the box is not a crop.
const SLACK: f32 = 1.0;
/// The length of the bar the two fixtures below draw, in view-box units.
const BAR: f32 = 16.0;
/// A drawing written the awkward way round: a bar that runs along x inside a group rotated 90 degrees about the centre
/// of its 24 unit box, inside another group that shifts it, so it draws down the box from the top to the bottom. Two
/// groups, because a reading that applied only the nearest transform and stopped there is a way to get this wrong.
const ROTATED: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><g transform="translate(2 2)"><g transform="rotate(90 12 12)"><path d="M4 8h16" fill="none" stroke="currentColor" stroke-width="2"/></g></g></svg>"#;
/// The same bar flattened: the edge written where those transforms land it, `M4 8h16` becoming `M18 6v16`, with no
/// transform at all. The two documents draw the same edge, so a reading of the drawing must give them the same axes.
const FLAT: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M18 6v16" fill="none" stroke="currentColor" stroke-width="2"/></svg>"#;
/// What a glyph's drawing must show. Each name is the axis or the side of the screen its control changes, never a
/// reading direction.
#[derive(Clone, Copy)]
enum Reads {
/// The two marks the drawing is made of separate further along x than along y: a mirror about the vertical axis,
/// or the gap between two items side by side. The ink's own box says nothing here (Lucide's flip is taller than it
/// is wide), so the reading is the separation of those two marks.
AlongX,
/// The same along y.
AlongY,
/// The ink's box is wider than tall: one mark across the axis of a scale, either a bar with outward arrows or a box
/// whose width outward arrows span.
ExtentX,
/// The same along y.
ExtentY,
/// The longest straight edge runs along x: a skew, whose leaning sides leave the top and bottom level. Tabler draws
/// both of its skew files wider than tall, so their boxes cannot tell the pair apart; the straight edges can.
LeansX,
/// The same along y.
LeansY,
/// One filled band, off centre towards this side, which is a sign on x and y: a padding.
Side(i32, i32),
}
/// The transform and layout glyphs this change adds, with the reading each one's drawing must have.
const ADDED: [(&str, Reads); 12] = [
("flip_horizontal", Reads::AlongX),
("flip_vertical", Reads::AlongY),
("scale_horizontal", Reads::ExtentX),
("scale_vertical", Reads::ExtentY),
("skew_horizontal", Reads::LeansX),
("skew_vertical", Reads::LeansY),
("padding_top", Reads::Side(0, -1)),
("padding_right", Reads::Side(1, 0)),
("padding_bottom", Reads::Side(0, 1)),
("padding_left", Reads::Side(-1, 0)),
("gap_horizontal", Reads::AlongX),
("gap_vertical", Reads::AlongY),
];
/// One painted path of a drawing: its box including the stroke, its longest straight edge along x and along y, and
/// whether it is filled.
struct Painted {
rect: [f32; 4],
straight: [f32; 2],
filled: bool,
}
impl Painted {
/// The centre of the box.
fn centre(&self) -> (f32, f32) {
((self.rect[0] + self.rect[2]) / 2.0, (self.rect[1] + self.rect[3]) / 2.0)
}
fn area(&self) -> f32 {
(self.rect[2] - self.rect[0]).max(0.0) * (self.rect[3] - self.rect[1]).max(0.0)
}
}
/// The path nodes of `group` that paint, depth first. A path with neither a fill nor a stroke paints nothing (Tabler
/// ships one as a placeholder) and is left out, and so is one drawn hidden.
fn drawn_paths(group: &Group) -> Vec<&Path> {
fn walk<'a>(group: &'a Group, out: &mut Vec<&'a Path>) {
for node in group.children() {
match node {
Node::Group(inner) => walk(inner, out),
Node::Path(path) if path.is_visible() && (path.fill().is_some() || path.stroke().is_some()) => out.push(path.as_ref()),
_ => {}
}
}
}
let mut out = Vec::new();
walk(group, &mut out);
out
}
/// Every painted path of `group`, read: its box including the stroke, its straight edges, and whether it is filled.
fn painted(group: &Group) -> Vec<Painted> {
drawn_paths(group)
.into_iter()
.map(|path| {
let rect = path.abs_stroke_bounding_box();
Painted { rect: [rect.left(), rect.top(), rect.right(), rect.bottom()], straight: straight_runs(path), filled: path.fill().is_some() }
})
.collect()
}
/// The longest straight edge of `path` along x and along y, in the coordinates the drawing renders in: its segments
/// placed by the path's absolute transform, the one the renderer draws it with.
fn straight_runs(path: &Path) -> [f32; 2] {
straight_edges(path.data(), path.abs_transform())
}
/// The longest straight edge of `data` along x and along y once `transform` has placed its points, in the units that
/// transform gives. usvg keeps a path's segments in the element's own coordinates and leaves every transform above them,
/// a `<g transform>`, the element's own and the root view box's scale, on the node's absolute transform for the renderer
/// to apply, so `data` alone is not where the drawing lands: `usvg::Path::data`'s "all segments are in absolute
/// coordinates" means that the commands are absolute (`M`, `L`, not `m`, `l`), never that they are in canvas coordinates.
/// An edge is along an axis when, drawn, one of its deltas is zero; a curve is read as its end point, which no edge of
/// these drawings depends on. An identity `transform` reads the document as written. This is the reading
/// `craft_svg::tree::document` takes when it converts a parsed tree into a document.
fn straight_edges(data: &tiny_skia_path::Path, transform: Transform) -> [f32; 2] {
let placed = |mut point: tiny_skia_path::Point| {
transform.map_point(&mut point);
(point.x, point.y)
};
let mut runs = [0.0f32; 2];
let mut from = (0.0f32, 0.0f32);
let mut start = from;
for segment in data.segments() {
let to = match segment {
PathSegment::MoveTo(point) => {
from = placed(point);
start = from;
continue;
}
PathSegment::Close => start,
PathSegment::LineTo(point) | PathSegment::QuadTo(.., point) | PathSegment::CubicTo(.., point) => placed(point),
};
let (dx, dy) = ((to.0 - from.0).abs(), (to.1 - from.1).abs());
if dy <= STRAIGHT {
runs[0] = runs[0].max(dx);
} else if dx <= STRAIGHT {
runs[1] = runs[1].max(dy);
}
from = to;
}
runs
}
/// How far a drawing spreads along x and along y: the separation of its two largest painted paths (a flip and a gap are
/// two marks either side of the axis they name), or the box of its one path (a scale and a skew each draw one mark
/// across their axis).
fn spread(painted: &[Painted]) -> (f32, f32) {
let mut ranked: Vec<&Painted> = painted.iter().collect();
ranked.sort_by(|a, b| b.area().total_cmp(&a.area()));
match ranked.as_slice() {
[first, second, ..] => {
let ((ax, ay), (bx, by)) = (first.centre(), second.centre());
((ax - bx).abs(), (ay - by).abs())
}
[only] => (only.rect[2] - only.rect[0], only.rect[3] - only.rect[1]),
[] => (0.0, 0.0),
}
}
/// Asserts that the drawing `name` gives in `set` reads as `reads` says, from its painted paths and its view box.
fn drawn_as(name: &str, set: &str, reads: Reads, ink: &[Painted], view: (f32, f32)) {
let tenth = view.0.max(view.1) / 10.0;
match reads {
Reads::AlongX | Reads::AlongY => {
let (dx, dy) = spread(ink);
let along_x = matches!(reads, Reads::AlongX);
let (along, across) = if along_x { (dx, dy) } else { (dy, dx) };
assert!(along > across, "`{name}` in `{set}` spreads {dx} along x and {dy} along y, not along the axis its name gives");
assert!(along >= tenth, "`{name}` in `{set}` spreads only {along} along its axis, under a tenth of the drawing");
}
Reads::ExtentX | Reads::ExtentY => {
let left = ink.iter().map(|shape| shape.rect[0]).fold(f32::INFINITY, f32::min);
let top = ink.iter().map(|shape| shape.rect[1]).fold(f32::INFINITY, f32::min);
let right = ink.iter().map(|shape| shape.rect[2]).fold(f32::NEG_INFINITY, f32::max);
let bottom = ink.iter().map(|shape| shape.rect[3]).fold(f32::NEG_INFINITY, f32::max);
let (wide, tall) = (right - left, bottom - top);
let along_x = matches!(reads, Reads::ExtentX);
let (along, across) = if along_x { (wide, tall) } else { (tall, wide) };
assert!(along > across, "`{name}` in `{set}` spans {wide} along x and {tall} along y, not the axis its name gives");
assert!(along >= tenth, "`{name}` in `{set}` spans only {along} along its axis, under a tenth of the drawing");
}
Reads::LeansX | Reads::LeansY => {
let leans_x = matches!(reads, Reads::LeansX);
let (mut along, mut across) = (0.0f32, 0.0f32);
for shape in ink {
let (long, short) = if leans_x { (shape.straight[0], shape.straight[1]) } else { (shape.straight[1], shape.straight[0]) };
along = along.max(long);
across = across.max(short);
}
let axis = if leans_x { "x" } else { "y" };
assert!(
along > across,
"`{name}` in `{set}` has its longest straight edges across the lean it names: {along} along {axis}, {across} the other way"
);
assert!(along >= tenth, "`{name}` in `{set}` has no straight edge along {axis} a tenth of the drawing long");
}
Reads::Side(dx, dy) => {
let bands: Vec<&Painted> = ink.iter().filter(|shape| shape.filled).collect();
assert_eq!(bands.len(), 1, "`{name}` in `{set}` fills {} parts: the space it names is one solid band", bands.len());
let band = bands[0];
assert!(band.area() > 0.0, "`{name}` in `{set}` fills an empty band");
let (x, y) = band.centre();
let (centre_x, centre_y) = (view.0 / 2.0, view.1 / 2.0);
// A tenth of the drawing off centre towards its side, and a twentieth the other way: the band is on one
// side rather than in a corner.
let (reach, slack) = (view.0.min(view.1) / 10.0, view.0.min(view.1) / 20.0);
let towards = if dx != 0 { (x - centre_x) * dx as f32 } else { (y - centre_y) * dy as f32 };
let across = if dx != 0 { y - centre_y } else { x - centre_x };
assert!(towards >= reach, "`{name}` in `{set}` puts its band {towards} off centre towards its side, short of {reach}");
assert!(across.abs() <= slack, "`{name}` in `{set}` puts its band {} off the other axis", across.abs());
}
}
}
/// The reading above is taken where a drawing lands, not where its `d` is written, which is what a glyph drawn sideways
/// inside a `<g>` exposes: the bar written along x in `ROTATED` draws along y, and `straight_runs` must say so.
///
/// The bar's own coordinates still read along x, and `straight_edges` with an identity transform is kept as the reading
/// of the document as written; that is the reading this trial would compare against if the segments were not placed by
/// the path's absolute transform, so this case fails the old measurement and passes the drawn one. `FLAT` writes that
/// same edge where the rotation lands it, with no transform to apply, and the two documents must read alike.
fn edges_are_read_in_the_coordinates_the_drawing_renders_in() {
let rotated = svg_tree::parse(ROTATED.as_bytes()).expect("the rotated fixture parses");
let flat = svg_tree::parse(FLAT.as_bytes()).expect("the flattened fixture parses");
let bars = drawn_paths(rotated.root());
assert_eq!(bars.len(), 1, "the rotated fixture draws one bar");
let drawn = straight_runs(bars[0]);
assert!(
drawn[1] >= BAR - STRAIGHT && drawn[0] <= STRAIGHT,
"a bar written along x inside two transformed groups that rotate it draws along y, but its edges read {drawn:?}"
);
let written = straight_edges(bars[0].data(), Transform::identity());
assert!(
written[0] >= BAR - STRAIGHT && written[1] <= STRAIGHT,
"the coordinates the rotated bar's `d` is written in read {written:?}, along x: that is not an axis the drawing has"
);
let flats = drawn_paths(flat.root());
assert_eq!(flats.len(), 1, "the flattened fixture draws one bar");
let flattened = straight_runs(flats[0]);
assert!(
flattened[1] >= BAR - STRAIGHT && (flattened[0] - drawn[0]).abs() <= STRAIGHT && (flattened[1] - drawn[1]).abs() <= STRAIGHT,
"the bar written where the rotation lands it reads {flattened:?} and the rotated one {drawn:?}: both draw the same edge"
);
// The catalogue's own check on that drawing, which only reads right once the segments are placed: it fails on the
// untransformed reading, where the longest straight edge is 16 along x and nothing along y.
let view = (rotated.size().width(), rotated.size().height());
drawn_as("the rotated bar", "a fixture", Reads::LeansY, &painted(rotated.root()), view);
}
#[trial]
fn the_added_transform_and_layout_glyphs_draw_where_their_names_say() {
edges_are_read_in_the_coordinates_the_drawing_renders_in();
for set in IconSet::ALL {
let mut documents: BTreeMap<&'static [u8], &str> = BTreeMap::new();
for (name, reads) in ADDED {
let index = find(name).unwrap_or_else(|| panic!("`{name}` is not in the catalogue"));
assert!(!DIRECTIONAL[index], "`{name}` names a side or an axis of the screen, so it must not mirror");
let document = svg(index, set);
let tree = svg_tree::parse(document).unwrap_or_else(|error| panic!("`{name}` in `{}`: {error}", set.id()));
let view = tree.size();
let ink = painted(tree.root());
assert!(!ink.is_empty(), "`{name}` in `{}` paints nothing", set.id());
// The ink, stroke and caps included: a cap past the view box is a cropped glyph.
let bounds = tree.root().abs_stroke_bounding_box();
assert!(
bounds.left() >= -SLACK
&& bounds.top() >= -SLACK
&& bounds.right() <= view.width() + SLACK
&& bounds.bottom() <= view.height() + SLACK,
"`{name}` in `{}` paints outside its view box: {bounds:?} of {view:?}",
set.id()
);
drawn_as(name, set.id(), reads, &ink, (view.width(), view.height()));
if let Some(other) = documents.insert(document, name) {
panic!("`{other}` and `{name}` are the same document in `{}`: a copied drawing?", set.id());
}
}
}
}
+18
View File
@@ -22,6 +22,7 @@ use crate::display::Icon;
use crate::primitives::IconSpec;
use crate::runtime::drag::OsFile;
use crate::runtime::env::{Env, Label};
use crate::runtime::memory::sub;
use crate::runtime::overlay::CloseReason;
use crate::runtime::windows::{ResizeEdge, WindowSpec};
use crate::sections::{HeaderAction, HeaderStrength, MenuRows, TitleRow};
@@ -213,8 +214,19 @@ pub struct FloatingGroupOutput {
pub resize: Vec<(ResizeEdge, Rect, Id)>,
/// Where `files` were dropped, in the group's layer space, when the drop session knew the pointer.
pub files_at: Option<Pos2>,
/// A move of the group's window is still running after this pass: its `Begin` has been reported in `placed`, and
/// its `Commit` or `Cancel` has not. The passes between two steps report no `placed`.
pub moving: bool,
}
/// Whether a move of the group's window is running: set by its `Begin` and `Update` steps, cleared by its `Commit`
/// or `Cancel` and by any step of a resize.
#[derive(Clone, Copy, Default)]
struct Gesture(bool);
/// The memory slot of [`Gesture`] under the group's id.
const GESTURE: &str = "window_gesture";
impl Outcome for FloatingGroupOutput {
type Value = NoValue;
@@ -619,6 +631,11 @@ impl Component for FloatingGroup<'_> {
// A dock window's band double click collapses or expands its column, as a dock column's bar does.
let collapsed = self.column.map(|column| column.collapsed.is_some());
let iconic = collapsed.filter(|_| self.chevron || self.toggled).map(|collapsed| !collapsed);
let gesture = &mut cx.core.memory.shown::<Gesture>(sub(cx.core.id, GESTURE)).0;
if let Some(change) = self.placed {
*gesture = change.kind == PlacementKind::Move && matches!(change.phase, GesturePhase::Begin | GesturePhase::Update);
}
let moving = *gesture;
let output = FloatingGroupOutput {
response: cx.response.clone(),
placed: self.placed,
@@ -632,6 +649,7 @@ impl Component for FloatingGroup<'_> {
grip: cx.move_band(),
resize: cx.resize_grips(),
files_at: self.files_at,
moving,
};
native::raise(&cx.core.ctx, &output, self.raise);
native::fade(&cx.core.ctx, &output);
+1 -1
View File
@@ -129,7 +129,7 @@ pub fn waited(ctx: &Context, opening: &Opening, output: &FloatingGroupOutput) {
/// app window's is recorded, with the rect `kept` gives for the rect the OS shows the window at (outer top-left corner
/// and inner size, in desktop points), so a collapsed window keeps its expanded rect
/// ([`WindowColumn::kept`](super::WindowColumn::kept)). `None` while the model already holds what the OS reports, so a
/// window at rest costs no action.
/// window at rest costs no action. A caller skips it while the window's move runs ([`FloatingGroupOutput::moving`]).
#[doc(hidden)]
pub fn reported<P: Clone>(ctx: &Context, window: &Floating<P>, viewport: ViewportId, kept: impl FnOnce(Rect) -> Rect) -> Option<Action<P>> {
let panel = window.panels().next()?;
+6 -2
View File
@@ -2316,8 +2316,12 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
kept.edge = keeps.unwrap_or(kept.edge);
self.report.actions.push(Action::move_floating_with_edge(anchor.clone(), rect, keeps));
}
let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, scene.rtl));
self.report.actions.extend(reported);
// The OS window's place changes in every pass of a move; the workspace records it once, when the move
// ends.
if !output.moving {
let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, scene.rtl));
self.report.actions.extend(reported);
}
}
} else if let Some(mut change) = output.placed.filter(|change| change.kind != PlacementKind::Move || change.phase == GesturePhase::Commit)
{
@@ -2,6 +2,7 @@
use crate::contract::{
Bind, BodyCx, CollectionEvent, NoValue, Outcome, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
Sizing,
};
use crate::dialog::{ButtonPlace, Dialog, DialogId, DialogOutput, DialogResult, DialogStack, StackDialog};
use crate::display::{Shade, Text};
@@ -321,6 +322,10 @@ impl StackDialog for HostedListManager {
}
}
/// The fewest rows the list is tall, and the most it shows before it scrolls.
const MIN_ROWS: u16 = 8;
const MAX_ROWS: u16 = 12;
/// The name box's text in `bind`: empty while a kept binding holds none.
fn text_of(bind: &mut Bind<'_, String>, cx: &mut BodyCx<'_>) -> String {
match bind.reborrow().read(cx) {
@@ -556,6 +561,11 @@ impl<'a> ListManager<'a> {
.id(list_id)
.select(SelectMode::Single)
.allow_empty(true)
// A capped list is sized from its rows: without a cap it takes no height in a dialog that sizes to its
// content, and the empty message or the first rows are drawn over the section under it.
.sizing(Sizing::Content)
.min_rows(MIN_ROWS)
.max_rows(MAX_ROWS)
.deletable(true)
.selection(Bind::bound(&mut selection));
if let Some(empty) = &empty {
@@ -126,6 +126,8 @@ pub struct RowSpec<'a> {
/// default a drop-down, and on a card ([`PreferencesLayout::Cards`](super::PreferencesLayout::Cards)) a short
/// choice of up to five options is segmented. Ignored by other kinds.
pub pills: Option<bool>,
/// A [`RowKind::Text`] row: the translated text shown while the field is empty. Ignored by other kinds.
pub placeholder: Option<&'a str>,
/// The control and the value it shows.
pub kind: RowKind<'a>,
}
@@ -133,7 +135,7 @@ pub struct RowSpec<'a> {
impl<'a> RowSpec<'a> {
/// A visible, enabled row with no keywords or help.
pub fn new(key: &'a str, label: &'a str, kind: RowKind<'a>) -> Self {
Self { key, label, keywords: "", help: None, visible: true, enabled: true, step: None, pills: None, kind }
Self { key, label, keywords: "", help: None, visible: true, enabled: true, step: None, pills: None, placeholder: None, kind }
}
/// Sets extra search text for the row.
@@ -171,6 +173,13 @@ impl<'a> RowSpec<'a> {
self
}
/// Sets the text a [`RowKind::Text`] row shows while empty.
#[must_use]
pub fn placeholder(mut self, placeholder: &'a str) -> Self {
self.placeholder = Some(placeholder);
self
}
/// Sets the step of a [`RowKind::Float`] row.
#[must_use]
pub fn step(mut self, step: f64) -> Self {
@@ -39,7 +39,7 @@ pub(super) enum Kind {
Int { value: i64, range: RangeInclusive<i64>, unit: Option<UnitKind>, unit_text: Option<Label> },
Float { value: f64, range: RangeInclusive<f64>, decimals: u8, step: Option<f64>, unit: Option<UnitKind>, unit_text: Option<Label> },
Length { value: f64, range: RangeInclusive<f64>, lengths: LengthUnits },
Text(String),
Text { value: String, placeholder: Option<Label> },
Custom,
CustomRows,
}
@@ -72,7 +72,7 @@ impl ShownRow {
unit_text: unit_text.map(|text| Label::from(text.to_owned())),
},
RowKind::Length { value, range, lengths } => Kind::Length { value: *value, range: range.clone(), lengths: *lengths },
RowKind::Text(text) => Kind::Text((*text).to_owned()),
RowKind::Text(text) => Kind::Text { value: (*text).to_owned(), placeholder: row.placeholder.map(|text| Label::from(text.to_owned())) },
RowKind::Custom => Kind::Custom,
RowKind::CustomRows => Kind::CustomRows,
};
@@ -229,10 +229,14 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(
});
record(next.map(PrefValue::Float));
}
Kind::Text(value) => {
Kind::Text { value, placeholder } => {
let mut next = None;
control(ui, row, cards, |ui| {
next = TextField::new(label.clone(), Bind::given(value.clone())).show(ui).events.landed().cloned();
let mut field = TextField::new(label.clone(), Bind::given(value.clone()));
if let Some(placeholder) = placeholder {
field = field.placeholder(placeholder.clone());
}
next = field.show(ui).events.landed().cloned();
});
record(next.map(PrefValue::Text));
}
@@ -528,6 +528,50 @@ fn a_native_palette_the_app_moves_follows_the_system_pointer_not_a_stale_event()
assert_eq!(window.min + ROW_AT.to_vec2(), desktop, "the window lands where the pointer let go");
}
/// While the app moves a native palette by its title row, the dock records no placement, though the OS window reports
/// a new place in every pass: the workspace takes no edit per pass of the drag, and records where the window was let
/// go once the move ends.
#[trial]
fn a_native_palette_records_its_place_once_its_move_ends_and_not_in_each_pass_of_it() {
let system = Arc::new(FakeSystem::new());
let mut dock = NativeDock::on(Os::Linux, Arc::clone(&system));
let mut window = FLOAT_AT;
let mut desktop = FLOAT_AT.min + ROW_AT.to_vec2();
system.set_pointer(Some([desktop.x, desktop.y]));
let recorded = |actions: &[Action<u32>]| actions.iter().filter(|action| matches!(action, Action::SetNative { .. })).count();
// Each frame, the OS puts the window where the app sent it, and the window reports that place in the next.
let frame = |dock: &mut NativeDock, window: &mut Rect, events: Vec<Event>| {
let (actions, commands) = dock.frame(events);
if let Some(to) = outer_positions(&commands).last() {
*window = Rect::from_min_size(*to, window.size());
dock.windows.child_info(info(true, *window));
}
actions
};
for events in [vec![moved(ROW_AT)], vec![press(ROW_AT)]] {
frame(&mut dock, &mut window, events);
}
// Away from the main window, so the release docks nothing.
let step = Vec2::new(40.0, 25.0);
let mut during = 0;
for _ in 0..6 {
desktop += step;
system.set_pointer(Some([desktop.x, desktop.y]));
let event = moved(desktop - window.min.to_vec2());
during += recorded(&frame(&mut dock, &mut window, vec![event]));
}
assert_ne!(window.min, FLOAT_AT.min, "the window follows the drag");
assert_eq!(during, 0, "no placement is recorded while the move runs");
let mut after = 0;
let let_go = release(desktop - window.min.to_vec2());
for events in [vec![let_go], vec![], vec![]] {
after += recorded(&frame(&mut dock, &mut window, events));
}
assert!(after >= 1, "the place the window was let go at is recorded once the move ends");
let placed = dock.workspace.layout().floating[0].native.as_ref().and_then(Placement::position);
assert_eq!(placed.map(Pos2::from), Some(window.min), "the workspace holds where the window was let go");
}
/// Where the OS moves windows and the app reads the system pointer and button meanwhile (macOS): the title row's press
/// hands the move to the OS in its own pass, the system pointer over the main window's group marks it (Cmd keeps the
/// drop floating), and the window docks when the system tells the button is up, not on the first pass after the
@@ -267,3 +267,21 @@ fn a_hosted_list_manager_hands_over_kept_open_choices_and_answers_with_the_closi
let answered = host.borrow_mut().take::<HostedListManager>();
assert!(matches!(&answered, Some(DialogResult::Ok(run)) if run.action == "run" && run.entry.as_deref() == Some("a")), "{answered:?}");
}
// #7979: with no entries the empty message stands in the list's own box, above the section under it, not over it.
#[trial]
fn an_empty_list_keeps_its_box_above_the_section_under_it() {
let mut fixture = Fixture::new(|ui| {
let actions = vec![ListManagerAction::new("add", "Add", ActionEnabled::OnNewName).keeps_open()];
let _ = ListManager::new("Marks", "Name:", Vec::new(), actions)
.empty(craft_ui::runtime::env::Label::Static("No marks yet."))
.under_list(|ui| {
Text::new("Under the list").show(ui);
})
.show(ui);
});
fixture.idle(10);
let empty = fixture.by_label("No marks yet.").expect("the empty message");
let under = fixture.by_label("Under the list").expect("the section under the list");
assert!(empty.rect.max.y <= under.rect.min.y, "the message {:?} clears the section {:?}", empty.rect, under.rect);
}
@@ -320,3 +320,33 @@ fn the_search_shows_how_many_settings_match() {
fixture.click(&search).type_text("snap").settle();
assert!(fixture.texts().iter().any(|t| t.text == "1 match"), "{:?}", fixture.texts().iter().map(|t| &t.text).collect::<Vec<_>>());
}
/// A text row with a placeholder shows it while the field is empty; one without shows none.
#[trial]
fn a_text_rows_placeholder_shows_while_empty() {
struct Initials(bool);
impl PreferencesModel for Initials {
fn pages(&self) -> Vec<PageSpec<'_>> {
let row = RowSpec::new("general.initials", "Initials", RowKind::Text(""));
vec![PageSpec::new("general", "General", vec![if self.0 { row.placeholder("AB") } else { row }])]
}
fn set(&mut self, _: &str, _: PrefValue) {}
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
false
}
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
false
}
fn reset_page(&mut self, _: &str) {}
}
let shown = |placeholder| {
let mut state = PreferencesState::default();
let mut fixture = Fixture::new(move |ui| {
PreferencesPage::new(Bind::bound(&mut state)).show(ui, &mut Initials(placeholder));
});
fixture.settle();
craft_ui::testing::text::painted(&fixture.frame_shapes()).iter().any(|text| text == "AB")
};
assert!(shown(true), "the placeholder is painted");
assert!(!shown(false), "no placeholder, none painted");
}
+9 -5
View File
@@ -142,7 +142,7 @@ pub struct MenuItemStyle {
/// The detail line under the label, in `text.muted`.
#[style(text)]
detail: TextLook,
/// The least space between the label and the shortcut: `space.gap.section`.
/// The least space between the label and the shortcut, and between the label and a sample: `space.gap.section`.
shortcut_gap: f32,
/// The gap between a submenu and its parent menu: `space.gap.tight`.
submenu_gap: f32,
@@ -478,7 +478,7 @@ impl<'a> MenuItem<'a> {
let side = cx.icon();
let command = cx.command();
let (mark, icon) = self.lead_columns(cx.ui.ctx(), side, cx.gap(), command, level);
let sample = self.sample_column(cx.ui.ctx(), line, cx.gap());
let sample = self.sample_column(cx.ui.ctx(), line, cx.style.shortcut_gap.max(cx.gap()));
let trail = if self.submenu { side } else { self.keys(command).map_or(0.0, |keys| cx.face(keys).x) };
Columns { mark, icon, sample, trail }
}
@@ -705,7 +705,8 @@ impl Component for MenuItem<'_> {
let detail_height = detail_run.as_ref().map_or(0.0, |run| draw.layout(run, f32::INFINITY).size().y);
let trail = if self.submenu { side } else { cx.part_if_declared(SHORTCUT).map_or(0.0, |part| part.rect.width()) };
let line = label_line(cx.content_rect, detail_height);
let sample_column = self.sample_column(&cx.core.ctx, line.height(), gap);
let sample_gap = cx.style.shortcut_gap.max(gap);
let sample_column = self.sample_column(&cx.core.ctx, line.height(), sample_gap);
let columns = Columns { mark: mark_column, icon: icon_column, sample: sample_column, trail };
let placed = self.place(&columns, line, rtl, cx.style.shortcut_gap.max(gap));
let ink = cx.resolve(&cx.style.icon.color);
@@ -747,8 +748,11 @@ impl Component for MenuItem<'_> {
// Samples start at one edge of the shared column, after its gap, so a level's samples line up; a sample-only
// row's sample takes the label's room and the column.
if let Some((aspect, face)) = &self.sample {
let rect =
if self.sample_only { placed.label.union(placed.sample) } else { Flow::new(placed.sample, rtl).span(gap, aspect.of(line.height())) };
let rect = if self.sample_only {
placed.label.union(placed.sample)
} else {
Flow::new(placed.sample, rtl).span(sample_gap, aspect.of(line.height()))
};
face.paint(&ui.content_painter(cx), rect);
}
if self.submenu {
@@ -5,7 +5,7 @@ use super::{Calendar, CalendarView, DatePrecision, PickedDate, offered};
use crate::buttons::Link;
use crate::choice::Segmented;
use crate::contract::{
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Entry, HeaderRegion, Mount, Overlay, POPUP_PAD, Props as _,
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Entry, HeaderRegion, Mount, Overlay, POPOVER_PAD, Props as _,
Remember as _, Role, Show as _, ShowContainer as _, Trigger, WordSetCx as _, clicked,
};
use crate::layout::RowAlign;
@@ -170,7 +170,7 @@ impl<'a> CalendarPopover<'a> {
/// `value` is a bound or kept binding: a given binding is never written, and the output carries no edit to report.
pub fn new(label: impl Into<Label>, open: Bind<'a, bool>, value: Bind<'a, Option<PickedDate>>) -> Self {
let props =
ContainerProps::new().surface(SurfaceKind::Popup).pad(POPUP_PAD).header(HeaderRegion::new()).mount(Mount::Layer(Overlay::popover()));
ContainerProps::new().surface(SurfaceKind::Popup).pad(POPOVER_PAD).header(HeaderRegion::new()).mount(Mount::Layer(Overlay::popover()));
CalendarPopover {
common: Common::new(),
props,
+2 -2
View File
@@ -2,7 +2,7 @@
use crate::contract::overlay::{Anchor, Dismiss, OverlayFit};
use crate::contract::{
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, Overlay, POPUP_PAD, Pad, Props as _, Role, SaveKey,
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, Overlay, POPOVER_PAD, Pad, Props as _, Role, SaveKey,
Trigger,
};
use crate::runtime::env::Label;
@@ -84,7 +84,7 @@ pub struct Popover<'a> {
impl<'a> Popover<'a> {
/// A popover named `label`, open while `open` is true.
pub fn new(label: impl Into<Label>, open: Bind<'a, bool>) -> Self {
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(POPUP_PAD).mount(Mount::Layer(Overlay::popover()));
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(POPOVER_PAD).mount(Mount::Layer(Overlay::popover()));
Popover { common: Common::new(), props, open, closed: None }.label(label)
}
+19 -10
View File
@@ -693,14 +693,18 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
let pinned = if rule { None } else { arrangement.pinned(offset.y as f32) };
let shift = view.min.to_vec2() - vec2(offset.x as f32, offset.y as f32);
let clip = area;
// Headers and tail rows end at the scroll bar while it shows, so a header's detail stays clear of it.
let clear = cx.rows_view().unwrap_or(view);
let clear_of_bar = |rect: Rect| Rect::from_x_y_ranges(rect.min.x.max(clear.min.x)..=rect.max.x.min(clear.max.x), rect.y_range());
for (group, header) in arrangement.headers.iter().enumerate() {
let (rect, held) = match pinned {
Some((at, lifted)) if at == group => (lifted, true),
_ => (*header, false),
};
let rect = Self::group_rect(rect.translate(shift), view, rtl);
let rect = clear_of_bar(Self::group_rect(rect.translate(shift), view, rtl));
let Some(declared) = self.groups.get(group) else { continue };
if !rect.intersects(clip) {
// A view narrower than the header's inset and the bar leaves the header no width, and it takes no part.
if rect.width() <= 0.0 || !rect.intersects(clip) {
continue;
}
if rule {
@@ -721,8 +725,8 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
}
}
for (at, (row, rect)) in self.tail.iter().zip(&arrangement.tails).enumerate() {
let rect = Self::group_rect(rect.translate(shift), view, rtl);
if !rect.intersects(clip) {
let rect = clear_of_bar(Self::group_rect(rect.translate(shift), view, rtl));
if rect.width() <= 0.0 || !rect.intersects(clip) {
continue;
}
self.placed_tail.push((at, rect));
@@ -883,11 +887,14 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
let selected = group.selectable && cx.collection_selection().is_some_and(|held| held.contains(&group.key));
let state = RowState { emphasized: lead == Some(Slot::Header(placed.group)), ..RowState::default() };
let header = self.header_row(group, state);
ui.face(section_part(&group.key), if selected { header.selected(true) } else { header });
if placed.toggle {
let disclosure = Disclosure::new(Bind::given(group.open)).node(false).label(group.title.clone());
ui.face(TOGGLE.at(placed.group as u64), disclosure);
}
// The header's text is cut at its end, which stops at the scroll bar while the bar shows.
ui.clipped(rect, |ui| {
ui.face(section_part(&group.key), if selected { header.selected(true) } else { header });
if placed.toggle {
let disclosure = Disclosure::new(Bind::given(group.open)).node(false).label(group.title.clone());
ui.face(TOGGLE.at(placed.group as u64), disclosure);
}
});
}
for &(at, rect) in &self.placed_tail {
let row = &self.tail[at];
@@ -895,7 +902,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
ui.draw().edge_rule(RuleKind::Divider, rect, RectSide::Top);
}
let state = RowState { emphasized: lead == Some(Slot::Tail(at)), ..RowState::default() };
ui.face(section_part(&row.key), ListRow::new(row.label.clone()).rows(self.items.row_height).node(false).state(state));
ui.clipped(rect, |ui| {
ui.face(section_part(&row.key), ListRow::new(row.label.clone()).rows(self.items.row_height).node(false).state(state));
});
}
// The gap under the pointer shows where an insertion lands; the part's state layer shows hover and focus.
for &(at, rect) in &self.placed_gaps {
+27
View File
@@ -90,6 +90,33 @@ fn a_row_sample_sits_between_the_label_and_the_shortcut_and_mirrors() {
}
}
/// A row whose label sets the menu's width keeps `space.gap.section` between the label and its sample, as between the
/// label and a shortcut, so a font's name does not run into its sample.
#[trial]
fn a_wide_label_keeps_the_section_gap_before_its_sample() {
const LABEL: &str = "A family name long enough to set the width of the whole menu";
let cells = Cells::default();
let painted = cells.clone();
let section = Rc::new(Cell::new(0.0));
let seen = Rc::clone(&section);
let mut fixture = Fixture::new(move |ui| {
seen.set(craft_ui::runtime::env::Env::of(ui).tokens.tokens().space.gap.section);
Menu::inline("Fonts").show(ui, |ui, _| {
let painted = painted.clone();
let face = FacePaint::new(1, move |_, rect| {
painted.lock().unwrap().insert(1, rect);
});
MenuItem::new(LABEL).sample(ThumbAspect::new(4, 1), face).show(ui);
});
});
fixture.settle();
let label = run(&fixture, LABEL).expect("the label is painted");
let sample = cells.lock().unwrap().get(&1).copied().expect("the sample is painted");
let (gap, section) = (sample.min.x - label.max.x, section.get());
assert!(section > 0.0, "the tokens give a section gap");
assert!(gap >= section - 0.5, "the sample stands {gap} after the label, under the section gap {section}: {label:?} then {sample:?}");
}
/// The app commands the shortcut trial's rows bind, each with a chord.
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
#[command(prefix = "menuRowsTrial")]
@@ -7,6 +7,7 @@ use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::pickers::{CalendarPopover, CalendarView, DatePicker, DatePrecision, PickedDate};
use craft_ui::runtime::env::Env;
use craft_ui::testing::Fixture;
use craft_ui::testing::snapshot::layer_rects;
use egui::{Key, Modifiers, Ui};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
@@ -113,6 +114,55 @@ fn the_calendar_popover_follows_a_value_set_while_it_is_open() {
follows(&mut fixture, &value, &titles, "the date picker's calendar");
}
/// How far the calendar's Previous button stands in from the start edge of the popup layer that holds it. The end
/// edge is left out: a date picker's popup is at least as wide as its field, so it can be wider than the calendar.
fn calendar_inset(fixture: &Fixture) -> f32 {
let previous = fixture.by_label("Previous").expect("the calendar's previous button is shown").rect;
let layers = layer_rects(fixture.ctx());
let popup = layers
.iter()
.copied()
.filter(|rect| rect.contains_rect(previous))
.min_by(|a, b| a.area().total_cmp(&b.area()))
.unwrap_or_else(|| panic!("no layer holds the calendar's previous button {previous:?}: {layers:?}"));
previous.left() - popup.left()
}
/// The date picker's calendar stands as far in from its popup's start edge as the calendar popover's does, the regular
/// pad: both are popovers.
#[craft_ui::testing::trial]
fn the_date_pickers_calendar_pads_as_the_calendar_popover() {
let pad = Rc::new(Cell::new(0.0));
let seen = Rc::clone(&pad);
let mut fixture = Fixture::new(move |ui| {
seen.set(Env::of(ui).tokens.tokens().space.pad.regular);
let opener = Button::new("Due").show(ui);
let mut open = true;
let mut now = Some(PickedDate::day(YEAR, AUGUST, 14));
CalendarPopover::new("Due date", Bind::bound(&mut open), Bind::bound(&mut now))
.precisions(&[DatePrecision::Day])
.opened_by(&opener)
.show(ui, |_, _| {});
});
fixture.room(egui::vec2(600.0, 500.0)).settle();
let popover = calendar_inset(&fixture);
let mut fixture = Fixture::new(move |ui| {
let mut now = Some(PickedDate::day(YEAR, AUGUST, 14));
DatePicker::new("From", Bind::bound(&mut now)).precisions(&[DatePrecision::Day]).show(ui);
});
fixture.room(egui::vec2(600.0, 500.0)).idle(10);
fixture.key(Key::Tab, Modifiers::NONE);
fixture.key(Key::ArrowDown, Modifiers::ALT);
fixture.idle(4);
let picker = calendar_inset(&fixture);
let pad = pad.get();
assert!(pad > 0.0, "the tokens give a regular pad");
assert!((popover - pad).abs() <= 0.5, "the calendar popover's calendar stands {popover} in, not the regular pad {pad}");
assert!((picker - popover).abs() <= 0.5, "the date picker's calendar stands {picker} in from its start edge, the calendar popover's {popover}");
}
/// A date format keeps the weeks starting where the app puts them, whatever the locale says.
#[craft_ui::testing::trial]
fn a_date_format_starts_its_weeks_where_the_app_says() {
@@ -173,6 +173,34 @@ fn a_document_popup_list_aligns_its_rows_with_the_opener() {
assert!((row.left() - opener.left()).abs() <= 1.0 && (row.right() - opener.right()).abs() <= 1.0, "row {row:?}, opener {opener:?}");
}
/// A popover's content stands `space.pad.regular` in from every edge of its surface, as a panel's does.
#[trial]
fn a_popover_pads_its_content_as_a_panel() {
let mut open = true;
let pad = Rc::new(Cell::new(0.0));
let seen = Rc::clone(&pad);
let mut fixture = Fixture::new(move |ui| {
seen.set(craft_ui::runtime::env::Env::of(ui).tokens.tokens().space.pad.regular);
let opener = Button::new("Open").show_at(ui, OPENER).response;
Popover::new("Options", Bind::bound(&mut open)).opened_by(&opener).show(ui, |ui, _| {
Button::new("Snap").show(ui);
});
});
fixture.room(Vec2::new(600.0, 400.0)).settle();
let popover = fixture.by_label("Options").expect("the popover").rect;
let snap = fixture.by_label("Snap").expect("the popover's button").rect;
let pad = pad.get();
assert!(pad > 0.0, "the tokens give a regular pad");
for (edge, inset) in [
("left", snap.left() - popover.left()),
("top", snap.top() - popover.top()),
("right", popover.right() - snap.right()),
("bottom", popover.bottom() - snap.bottom()),
] {
assert!((inset - pad).abs() <= 0.5, "the {edge} inset is {inset}, not the regular pad {pad}: {snap:?} in {popover:?}");
}
}
/// A scrolling page taller than the window: an "Open" button that opens a popup list of `ROWS` rows while `open`, then
/// `PAGE` buttons. The rows the list activates go to `activated`.
fn page(open: Rc<Cell<bool>>, activated: Rc<RefCell<Vec<usize>>>) -> Fixture {
+69 -2
View File
@@ -9,8 +9,10 @@ use craft_ui::display::Text;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::list::{ThumbAspect, ToggleState};
use craft_ui::runtime::env::Label;
use craft_ui::testing::{Fixture, pointer};
use craft_ui::tile_grid::{Around, ArrangeSpacing, GridEvent, GridZoom, GroupHeads, Tile, TileGrid, TileGroup, TileZoom, Tiling, ZoomStep, arrange};
use craft_ui::testing::{Fixture, Target, pointer};
use craft_ui::tile_grid::{
Around, ArrangeSpacing, GridEvent, GridZoom, GroupHeads, TailRow, Tile, TileGrid, TileGroup, TileZoom, Tiling, ZoomStep, arrange,
};
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -87,6 +89,71 @@ fn rule_group_heads_take_no_title_no_tab_stop_and_never_close() {
assert!(!grouped, "a click on a rule reports no group event: {:?}", events.borrow());
}
const DETAIL: &str = "128 tiles";
const MORE: &str = "More tiles";
/// A grid of `tiles` tiles in the group "Alpha", followed by the tail row "More tiles", in a room `width` points wide
/// and 400 points high.
fn headed_grid(tiles: usize, width: f32) -> Fixture {
let mut fixture = Fixture::new(move |ui| {
let keys: Vec<usize> = (0..tiles).collect();
let source = keyed(&keys, |key: &usize| *key);
let groups = [TileGroup::new(1000usize, 0, tiles, "Alpha").detail(DETAIL)];
let tail = [TailRow::new(2000usize, MORE)];
let _ = TileGrid::new("Library").groups(&groups).tail(&tail).show_items(ui, &source, &mut |key, _| Tile::new(format!("Tile {key}")));
});
fixture.room(Vec2::new(width, 400.0));
fixture.settle();
fixture
}
/// Where a group header's detail is painted and the header's heading node lies, in a grid of `tiles` tiles in a room
/// 300 points wide and 400 points high.
fn header_detail(tiles: usize) -> (Rect, Rect) {
let fixture = headed_grid(tiles, 300.0);
let detail = fixture.texts().iter().find(|run| run.text == DETAIL).map(|run| run.rect).expect("the header's detail is painted");
let head = fixture.by_label("Alpha, 128 tiles").expect("the header's heading node").rect;
(detail, head)
}
/// While the grid scrolls, a group header ends at its scroll bar, so the detail at the header's end stays clear of it.
#[craft_ui::testing::trial]
fn a_group_header_ends_at_the_scroll_bar() {
let (still, still_head) = header_detail(3);
let (scrolled, scrolled_head) = header_detail(TILES);
assert!(scrolled_head.right() < still_head.right() - 1.0, "the header ends before the bar: {scrolled_head:?} against {still_head:?}");
assert!(scrolled.right() < still.right() - 1.0, "the detail moves clear of the bar: {scrolled:?} against {still:?}");
assert!(scrolled.right() <= scrolled_head.right() + 0.5, "and stays inside its header: {scrolled:?} in {scrolled_head:?}");
}
/// While the grid scrolls, a header's face and a tail row's face are cut at the scroll bar, so text laid out past the
/// row's end is not painted under the bar.
#[craft_ui::testing::trial]
fn header_and_tail_faces_are_cut_at_the_scroll_bar() {
let mut fixture = headed_grid(TILES, 300.0);
let head = fixture.by_label("Alpha, 128 tiles").expect("the header's heading node").rect;
let detail = fixture.texts().iter().find(|run| run.text == DETAIL).map(|run| run.clip).expect("the header's detail is painted");
assert!(detail.right() <= head.right() + 0.5, "the detail's clip ends at the header's end: {detail:?} in {head:?}");
let center = fixture.shown().center();
fixture.frame(vec![pointer::moved(center), pointer::wheel(-100_000.0)]);
fixture.settle();
let row = fixture.by_label(MORE).expect("the tail row is in view at the end").rect;
let label = fixture.texts().iter().find(|run| run.text == MORE).map(|run| run.clip).expect("the tail row's label is painted");
assert!(label.right() <= row.right() + 0.5, "the tail row's clip ends at the row's end: {label:?} in {row:?}");
}
/// In a grid too narrow to hold a header beside its scroll bar, the header and the tail row take no part, so no
/// press lands on an empty row.
#[craft_ui::testing::trial]
fn a_grid_too_narrow_for_its_rows_places_no_empty_rows() {
let mut fixture = headed_grid(TILES, 8.0);
let empty = |target: Option<Target>| target.is_some_and(|target| target.rect.width() <= 0.0);
assert!(!empty(fixture.by_label("Alpha, 128 tiles")), "the header is not placed with no width");
fixture.frame(vec![pointer::moved(fixture.shown().center()), pointer::wheel(-100_000.0)]);
fixture.settle();
assert!(!empty(fixture.by_label(MORE)), "the tail row is not placed with no width");
}
/// A grid in a stack beside another takes its rows' height in the row's measuring run, so the stack holds the whole
/// grid and what follows it: a button under the grid takes clicks.
#[craft_ui::testing::trial]