Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
FredApps committed 2026-11-28 21:55:10 +01:00
commit 6c65ee321d
17 files changed
+460 -73

No files matched your search

+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)
}
+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");
}
+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;
@@ -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));
}
@@ -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");
}