diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index ae845b4b6..712fcab94 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -3,7 +3,7 @@ //! drawn in their own face, favourites (stars), recent families at the top, class and feature filters above the //! list and a "similar fonts" filter. Behaviour follows Photoshop's font menu. -mod banner; +pub(crate) mod banner; pub(crate) mod rank; mod rows; #[cfg(feature = "suite")] @@ -618,6 +618,9 @@ pub struct FontPickerStyle { /// The list's sample height and family row height at each preview size, none first: the thumbnail sides /// (`size.thumb.*`) and the height of a list row holding one. pub(crate) samples: [Sample; 4], + /// The width of the list's name column: [`NAME_SAMPLE`] in a row's text, so the list holds the names the field + /// holds. + pub(crate) name_column: f32, } /// The sample of a family row at one preview size: how high its band is, and how high the row holding it is. @@ -662,7 +665,8 @@ impl Component for FontPicker<'_> { sample(ThumbSize::Large, thumb.lg), ]; let warning = Stateful::new(warn).off(States::new(warn, warn, warn, off)); - FontPickerStyle { surface: cx.field(), metrics: field.metrics(), field, warning, samples } + let name_column = cx.text_width(craft_theme::TypeRole::Body, NAME_SAMPLE); + FontPickerStyle { surface: cx.field(), metrics: field.metrics(), field, warning, samples, name_column } } /// The wheel steps the family through the list. diff --git a/crates/font-manager/src/picker/banner.rs b/crates/font-manager/src/picker/banner.rs index fdd1c4e95..24ce43589 100644 --- a/crates/font-manager/src/picker/banner.rs +++ b/crates/font-manager/src/picker/banner.rs @@ -5,14 +5,18 @@ use craft_behavior::Sense; use craft_theme::TypeRole; use craft_ui::contract::{Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role}; use craft_ui::fonts::FontRef; +use craft_ui::primitives::DocRun; use craft_ui::primitives::TextRun; use craft_ui::runtime::env::Label; use craft_ui::style::{ComponentStyle, Corners, DataColor, Metrics, StyleColor, StyleCx, SurfaceKind}; -use egui::{Pos2, Rect, Vec2}; +use egui::{Color32, Pos2, Rect, Vec2}; use crate::panel::faces::{self, Shown}; use crate::panel::specimen::SampleFace; +#[cfg(feature = "suite")] +pub(crate) mod stories; + /// The share of the sample band's height the sample's em takes, as in the list's rows. const SAMPLE_EM: f32 = 0.7; @@ -81,10 +85,20 @@ impl Component for FontPreviewBanner<'_> { Sense::empty() } - /// As wide as the room; as high as the padding, the name line, the gap and the sample band. + /// As wide as the name or the sample, whichever is wider, in the room less the padding (it fills the width the flow + /// offers beyond that); as high as the padding, the name line, the gap and the sample band. fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { let style = cx.style; - Vec2::new(cx.room.unwrap_or(0.0), 2.0 * style.pad + style.name_line + style.gap + style.band) + let inner = cx.room.map(|room| (room - 2.0 * style.pad).max(0.0)); + let font = match self.face.shown(cx) { + Shown::Ready(font) => font, + _ => FontRef::proportional(), + }; + let runs = [DocRun::new(self.text, font, style.band * SAMPLE_EM, DataColor::new(Color32::PLACEHOLDER))]; + let sample = cx.layout_doc(&faces::sample_text(&runs, inner)).size().x; + let name = TextRun::new(self.name).role(TypeRole::Caption); + let name = inner.map_or_else(|| cx.layout(&name), |width| cx.layout_at(&name, width)).size().x; + Vec2::new(2.0 * style.pad + sample.max(name), 2.0 * style.pad + style.name_line + style.gap + style.band) } fn fills(&self) -> Option { diff --git a/crates/font-manager/src/picker/banner/stories.rs b/crates/font-manager/src/picker/banner/stories.rs new file mode 100644 index 000000000..b9ef83a6f --- /dev/null +++ b/crates/font-manager/src/picker/banner/stories.rs @@ -0,0 +1,28 @@ +//! Stories of `FontPreviewBanner`. + +use craft_ui::contract::Show as _; +use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; +use egui::Ui; + +use super::FontPreviewBanner; +use crate::panel::faces::Owner; +use crate::panel::fixtures::story_catalog; +use crate::panel::specimen::SampleFace; + +/// The host's text in the family's face, under its name. +#[story(FontPreviewBanner<'static>, covers = [Default], drive = Drive::Never)] +fn host_text(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + let catalog = story_catalog(); + let faces = catalog.styles("Hack"); + let face = match faces.first() { + Some(face) => SampleFace::Face { catalog: &catalog, owner: Owner::Installed, face }, + None => SampleFace::Interface, + }; + FontPreviewBanner::new("Font preview: Hack", "Hack", "The quick brown fox", face).show(ui).into() +} + +/// A family the catalog lacks: the sample word in the interface face. +#[story(FontPreviewBanner<'static>, covers = [], drive = Drive::Never)] +fn unavailable(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + FontPreviewBanner::new("Font preview: Gotham", "Gotham", "Sample", SampleFace::Interface).show(ui).into() +} diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index 7465f5e7a..1e893c80a 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -5,7 +5,6 @@ use std::borrow::Cow; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; -use std::sync::Arc; use craft_behavior::{ColumnKey, ColumnWidth, DisplayOrder, IconId, ItemSource, Preview, Selection, SizeHint}; use craft_font_catalog::Catalog; @@ -14,7 +13,7 @@ use craft_ui::buttons::{Button, ToggleButton}; use craft_ui::contract::overlay::Dismiss; use craft_ui::contract::{ Bind, CollectionEvent, ColumnSpec, Cx, Edit as _, LeadSource, Overlay, OverlayUi, Overlays as _, Props as _, Remember as _, Show as _, - ShowCollection as _, ShowContainer as _, Styled as _, ToggleColumn, WordSetCx as _, clicked, + ShowCollection as _, ShowContainer as _, ToggleColumn, WordSetCx as _, clicked, }; use craft_ui::display::{Divider, Text}; use craft_ui::layout_components::{Row, Stack}; @@ -281,12 +280,13 @@ fn class_column(ui: &mut egui::Ui, filters: &mut FontFilters, words: &FontPicker filters.class = usize::from(picked).checked_sub(1).and_then(|i| FontClass::ALL.get(i).copied()); } -/// The sample of a family row: `text` in the regular face of `family` at `points`, named by the family; the -/// interface face for a family the catalog lacks. -fn sample<'a>(catalog: &'a Catalog, infos: &'a FamilyInfos, family: &str, text: String, points: f32) -> FontSample<'a> { +/// The sample of a family row: `text` in the regular face of `family` at `points`, named "{shown}: {text}" as the font +/// manager names its samples, so the row keeps the family's name to itself; the interface face for a family the +/// catalog lacks. +fn sample<'a>(catalog: &'a Catalog, infos: &'a FamilyInfos, family: &str, shown: &str, text: String, points: f32) -> FontSample<'a> { let face = infos.families.get(family).map_or(SampleFace::Interface, |info| SampleFace::Face { catalog, owner: Owner::Installed, face: &info.regular }); - FontSample::new(Label::from(family.to_owned()), text, face, points) + FontSample::new(format!("{shown}: {text}"), text, face, points) } /// The name the banner shows for `family`: its row's shown name when the list holds one, else its name in the @@ -373,7 +373,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: if !plain { columns.push(ColumnSpec::toggle(STAR, words.favorites.clone(), ToggleColumn::default()).icon(IconId::new("star"))); } - columns.push(ColumnSpec::new(NAME, words.list.clone(), ColumnWidth::fill(1.0))); + columns.push(ColumnSpec::new(NAME, words.list.clone(), ColumnWidth::Fixed(cx.style.name_column))); if size != ThumbSize::None { columns.push(ColumnSpec::new(SAMPLE, words.sample.clone(), ColumnWidth::Fixed(sample_size.side * SAMPLE_WIDTH))); } @@ -425,12 +425,15 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: return; } let source = Slots { slots: &slots, row: sample_size.row }; + // Names line up past the disclosure column only where a family has styles to open. + let leaves = if (0..source.len()).any(|at| source.has_children(at)) { TreeLeaves::Aligned } else { TreeLeaves::Compact }; let selection = current.filter(|_| query.trim().is_empty()).map_or_else(Selection::default, |at| Selection::single(slots[at].key())); let rows = List::::options(name.clone()) .tree(true) - .tree_leaves(TreeLeaves::Aligned) + .tree_leaves(leaves) .columns(columns.clone()) + .header(false) .selection(Bind::given(selection)) .rows_stamp(stamp.finish()) .show_items(ui, &source, &mut |_, item| match &slots[item.at] { @@ -438,7 +441,9 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: Slot::Heading(Heading::Recent) => ListRow::new(words.recently_used.clone()).section_heading(), Slot::Heading(Heading::All) => ListRow::new(words.all_fonts.clone()).section_heading(), Slot::Action(at) => ListRow::new(actions[*at].clone()).option().depth(0), - Slot::Style { style, .. } => ListRow::new(style.clone()).cells(item.cells()).option().depth(1), + Slot::Style { style, .. } => { + ListRow::new(style.clone()).cells(item.cells()).in_label_column().option().depth(1).check(false) + } Slot::Family { row, open } => { let mut line = ListRow::new(row.shown.clone()).cells(item.cells()).option().depth(0).check(current == Some(item.at)); if !plain { @@ -461,10 +466,11 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: } let samples = infos.sample_text(catalog, &row.family, words.sample.as_str(), words.sample_arabic.as_str(), &row.shown); - line = line.cell_field(SAMPLE, sample(catalog, &infos, &row.family, samples.latin, points), |_| {}); - // The Arabic sample ends the name's band, so the sample column keeps one width. + line = line.cell_field(SAMPLE, sample(catalog, &infos, &row.family, &row.shown, samples.latin, points), |_| {}); + // The Arabic sample ends the name's band, so the sample column keeps one width; it + // drops out before it would narrow the name. match samples.arabic { - Some(arabic) => line.trailing_space(sample(catalog, &infos, &row.family, arabic, points)), + Some(arabic) => line.optional_field(sample(catalog, &infos, &row.family, &row.shown, arabic, points), |_| {}), None => line, } } diff --git a/crates/font-manager/src/picker/stories.rs b/crates/font-manager/src/picker/stories.rs index 9971b0f94..5886003aa 100644 --- a/crates/font-manager/src/picker/stories.rs +++ b/crates/font-manager/src/picker/stories.rs @@ -123,10 +123,12 @@ fn open_list(fixture: &mut Fixture) { fixture.settle(); } +/// The library list: Hack starred and recent, so the recent group and its rule head the list; Inter has two styles +/// to open and its name lines up with the one-style families'. #[story(FontPicker<'static>, covers = [Open], drive = Drive::Custom(open_list))] fn font_picker_open_with_filters(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = FontPickerSettings { favorites: vec!["Hack".to_owned()], ..FontPickerSettings::default() }; - show_picker(ui, data, demo("Hack", settings, FontFilters { favorites: true, ..FontFilters::default() })) + let settings = FontPickerSettings { favorites: vec!["Hack".to_owned()], recent: vec!["Hack".to_owned()], ..FontPickerSettings::default() }; + show_with(ui, data, demo("Inter", settings, FontFilters::default()), &styled_catalog(), &Extras::default()) } /// Opens the list and expands Inter through its row's expand request: focus stays in the field, whose caret keeps diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index bba127373..f9edf5ea2 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -504,7 +504,7 @@ fn family_names_line_up_after_the_star_and_before_the_sample() { let names: Vec = fx .texts() .iter() - .filter(|painted| (painted.text == "Inter" || painted.text == "Hack") && !banner.intersects(painted.rect)) + .filter(|painted| (painted.text == "Inter" || painted.text == "Hack") && painted.rect.top() >= banner.bottom()) .map(|painted| painted.rect) .collect(); assert_eq!(names.len(), 3, "Hack in the recent group and in the list, Inter once: {names:?}"); @@ -512,7 +512,8 @@ fn family_names_line_up_after_the_star_and_before_the_sample() { let star = fx.by_label("Favorite Inter").expect("Inter's star").rect; let inter = names.iter().find(|rect| (rect.center().y - star.center().y).abs() < star.height()).expect("Inter's name beside its star"); assert!(star.right() <= inter.left(), "the star comes first: {star:?} {inter:?}"); - let sample = fx.texts().iter().all(|painted| painted.text != "Sample" || painted.rect.left() >= inter.right()); + let sample = + fx.texts().iter().all(|painted| painted.text != "Sample" || painted.rect.top() < banner.bottom() || painted.rect.left() >= inter.right()); assert!(sample, "no sample before a name"); let recent = names.iter().map(|rect| rect.bottom()).fold(f32::INFINITY, f32::min); let rule = fx.shape_bounds().iter().any(|shape| shape.top() >= recent && shape.height() < 2.0 && shape.width() > star.width() * 4.0); diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 2e09d9699..84e126713 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -115,6 +115,11 @@ impl BodyHooks<'_> { scoped.flow_body = None; scoped.column_row = self.in_column && matches!(props.layout, crate::layout::BodyLayout::Row { wrap: false, align: crate::layout::RowAlign::Start }); + // Children side by side share the layer's width, so none of them spans it: a collection in a row or a grid takes + // its own content width, not the layer's floor. + if !matches!(props.layout, crate::layout::BodyLayout::Stack) { + scoped.inherited_mut().values.set(crate::contract::overlay::LayerFloor(0.0)); + } // A bracketed row's rows report to it up to the first labelled container, whose body is its own control. if props.bracket.is_some() { scoped.bracket = Some(layout); diff --git a/crates/ui-contract/src/contract/overlay/opener.rs b/crates/ui-contract/src/contract/overlay/opener.rs index d00d8c6fd..e530d4461 100644 --- a/crates/ui-contract/src/contract/overlay/opener.rs +++ b/crates/ui-contract/src/contract/overlay/opener.rs @@ -168,7 +168,8 @@ pub(crate) fn anchor_floor(overlay: &Overlay) -> f32 { } /// The least width of the layer the content runs in ([`anchor_floor`]), which a layer's container gives its regions: -/// a content-sized collection in the layer is at least this wide, so its rows fill the layer. 0 outside a layer. +/// a content-sized collection in the layer is at least this wide, so its rows fill the layer. 0 outside a layer, and +/// inside a row or grid, whose children share the layer's width. #[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] pub(crate) struct LayerFloor(pub(crate) f32); diff --git a/crates/ui-widgets/src/list/row.rs b/crates/ui-widgets/src/list/row.rs index 0a78d34cd..1bf42c22a 100644 --- a/crates/ui-widgets/src/list/row.rs +++ b/crates/ui-widgets/src/list/row.rs @@ -268,7 +268,8 @@ pub struct ListRow<'a> { /// The host declares and paints the disclosure part of this group row (a face has no parts of its own): the row /// keeps the disclosure column and paints no disclosure. pub(super) disclosure_by_host: bool, - /// How the row's tree lines up its leaves, from the collection (`List::tree_leaves`). + /// How the row's tree lines up its leaves: the collection gives it (`List::tree_leaves`). + #[prop] pub(super) leaves: TreeLeaves, /// The row is an option of a listbox, not an item of a list: inset and rounded, the chosen option outlined. #[style_key] @@ -385,13 +386,6 @@ impl<'a> ListRow<'a> { row } - /// How the row's tree lines up its leaves: the collection gives it (`List::tree_leaves`). - #[must_use] - pub(crate) fn leaves(mut self, leaves: TreeLeaves) -> Self { - self.leaves = leaves; - self - } - /// The rects of the row's columns, which the item context lists (`ItemCx::cells`): toggle cells and text cells /// draw in theirs and the rest of the row lays out in what they leave. #[must_use] diff --git a/crates/ui-widgets/src/list/row/placement.rs b/crates/ui-widgets/src/list/row/placement.rs index 3768e994b..52288faac 100644 --- a/crates/ui-widgets/src/list/row/placement.rs +++ b/crates/ui-widgets/src/list/row/placement.rs @@ -268,7 +268,13 @@ impl ListRow<'_> { if self.sub_row { return 0; } - self.depth.map_or(0, |depth| self.leaves.steps(depth, self.group.is_some())) + self.depth.map_or(0, |depth| tree_steps(depth, self.group.is_some())) + } + + /// Whether the row holds the disclosure column: a group, and under [`TreeLeaves::Aligned`] a top-level leaf, whose + /// column stays empty. The column is room the label never gives up, as an indent does. + fn keeps_disclosure(&self) -> bool { + self.group.is_some() || (self.leaves == TreeLeaves::Aligned && self.depth == Some(0) && !self.sub_row) } /// The widths of the trailing items and the leading text's slot: as `text_width` measures a text, the icon side for @@ -400,7 +406,7 @@ impl ListRow<'_> { let inner = Flow::new(band, rtl); let leading = self.leading(sizes, widths); let leading_width = leading.map_or(0.0, |side| side + sizes.gap); - let disclosure = if self.group.is_some() { sizes.icon } else { 0.0 }; + let disclosure = if self.keeps_disclosure() { sizes.icon } else { 0.0 }; let marker = if self.clipped { sizes.icon } else { 0.0 }; let check = if self.check.is_some() { sizes.icon + sizes.gap } else { 0.0 }; let column = disclosure + marker + check; @@ -452,7 +458,7 @@ impl ListRow<'_> { let column_start = base + indent + if self.leading_first { leading_width } else { 0.0 }; let leading_start = base + indent + if self.leading_first { 0.0 } else { column }; let label_start = base + indent + column + leading_width; - let disclosure_rect = (disclosure > 0.0).then(|| inner.span(column_start, disclosure)); + let disclosure_rect = self.group.is_some().then(|| inner.span(column_start, disclosure)); let marker_rect = (marker > 0.0).then(|| inner.span(column_start + disclosure, marker)); let check_rect = (check > 0.0).then(|| inner.span(column_start + disclosure + marker, sizes.icon)); let mut at = leading_start; @@ -519,20 +525,11 @@ pub enum TreeLeaves { /// no disclosure column. #[default] Compact, - /// Every leaf keeps the disclosure column, so its label lines up with the labels of the groups beside it: a font - /// menu's families with and without styles. + /// A top-level leaf keeps an empty disclosure column, so its label lines up with the labels of the groups beside + /// it: a font menu's families with and without styles. Aligned, } -impl TreeLeaves { - /// The indent steps of a tree row at `depth` under this rule: [`tree_steps`], and for `Aligned` one step more for - /// a top-level leaf. - pub fn steps(self, depth: usize, group: bool) -> usize { - let aligned = self == TreeLeaves::Aligned && depth == 0 && !group; - tree_steps(depth, group) + usize::from(aligned) - } -} - /// The width of a character of a trailing text under fixed sizes. #[cfg(feature = "testing")] const FIXED_ADVANCE: f32 = 10.0;