ribbon-w7: net change of 2 commits

- ribbon-w7: written from its sheet
- ribbon-w7: review fixes (review-1)
This commit is contained in:
Martin Ball
2026-11-18 21:02:55 +00:00
parent 1a73cb40fc
commit e37e44d869
5 changed files with 287 additions and 40 deletions
+3 -1
View File
@@ -47,7 +47,9 @@ craft_ui::words! {
warning: template "missingFonts.warning" = "font '{family}' is not installed; text may render using a fallback face";
/// The note for a shown font that is not installed, with `{family}` the missing family and `{face}` the face shown
/// in its place.
shown_as: template "missingFonts.shownAs" = "{family} is not installed; shown as {face}";
shown_as: template "missingFonts.shownAs" = "{family} isn't installed on this computer, so its text is shown in {face}. Line breaks and page count can differ from where the document was made.";
/// The advice that follows the note when the host's list has a row that adds a font.
add_font: "missingFonts.addFont" = "If you have the font file, add it with Add Font… at the end of this list.";
missing_font: template "missingFonts.missingFont" = "{font} ({status})";
installed_style: template "missingFonts.installedStyle" = "{status} ({style})";
font_status: template "missingFonts.fontStatus" = "{font}: {status}";
+74 -15
View File
@@ -14,7 +14,6 @@ use craft_behavior::{Codec, EditEvent, IconId, Mixed, NotAValue, PartKey, Sense,
use craft_behavior::{HitLevel, HitPriority, NavMove, Preview};
use craft_font_catalog::Catalog;
use craft_host::Section;
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
@@ -27,6 +26,7 @@ use craft_ui::text::{Adornment, place, reserve};
use egui::{Rect, Response, Vec2};
use serde::{Deserialize, Serialize};
use crate::missing::{DocumentFont, FontStatus, MissingFontsWords, document_fonts};
use rank::{Info, infos, shown_name};
craft_ui::words! {
@@ -312,6 +312,17 @@ pub enum FontPickerKind {
Plain,
}
/// What the note of a shown font that is not installed advises.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MissingAdvice {
/// The note alone.
#[default]
None,
/// The note, then the advice to add the font file with the host's Add Font row.
AddFont,
}
/// What a [`FontPicker`] reports.
#[derive(Debug)]
#[non_exhaustive]
@@ -351,6 +362,9 @@ const TEXT: PartKey = PartKey::new("text");
/// The chevron that opens and closes the list.
const CHEVRON: PartKey = PartKey::new("chevron");
const CHEVRON_ICON: &str = "chevron_down";
/// The mark before the chevron of a shown font that is not installed; its tooltip is the note.
const WARNING: PartKey = PartKey::new("missing");
const WARNING_ICON: &str = "warning";
/// The popup the chevron and Alt+Down toggle.
const POPUP: &str = "list";
/// The star at the end of a row.
@@ -367,6 +381,8 @@ fn text_key() -> TextKey<String> {
struct FamilyCodec {
infos: Arc<rank::Infos>,
language: String,
/// A typed name that is no installed family is a value too (Word's font box applies it as typed).
free: bool,
}
impl FamilyCodec {
@@ -382,13 +398,18 @@ impl Codec for FamilyCodec {
self.infos.families.get(family).map_or_else(|| family.clone(), |info| self.shown(family, info))
}
/// A family whose name, shown or in the catalog, is the text apart from case.
/// A family whose name, shown or in the catalog, is the text apart from case; for a `free` codec, else the
/// trimmed text when it is not empty.
fn parse(&self, text: &str, _: &String) -> Result<String, NotAValue> {
let wanted = text.trim().to_lowercase();
let named = |(family, info): (&String, &Info)| {
(family.to_lowercase() == wanted || self.shown(family, info).to_lowercase() == wanted).then(|| family.clone())
};
self.infos.families.iter().find_map(named).ok_or(NotAValue)
match self.infos.families.iter().find_map(named) {
Some(family) => Ok(family),
None if self.free && !wanted.is_empty() => Ok(text.trim().to_owned()),
None => Err(NotAValue),
}
}
fn sample(&self, current: &String) -> std::borrow::Cow<'_, str> {
@@ -480,16 +501,17 @@ pub struct FontPicker<'a> {
served: &'a [String],
/// How the list is laid out: the library picker, or Word's plain font box.
#[prop]
#[allow(dead_code)] // P3(ribbon-w7): rb.R21
kind: FontPickerKind,
/// Action rows above the families (the `Plain` box), reported through `FontPickerOutput::action`.
/// Action rows after the families (the `Plain` box), reported through `FontPickerOutput::action`.
#[prop]
#[allow(dead_code)] // P3(ribbon-w7): rb.R21
actions: &'a [Label],
/// The face the shown font is displayed in when it is not installed, for the note beside it.
#[prop]
#[allow(dead_code)] // P3(ribbon-w7): rb.R21
shown_as: Option<&'a str>,
/// What the note advises beyond naming the face; `AddFont` when an action row adds a font.
#[prop]
advice: MissingAdvice,
action: Option<usize>,
}
impl<'a> FontPicker<'a> {
@@ -510,16 +532,41 @@ impl<'a> FontPicker<'a> {
kind: FontPickerKind::default(),
actions: &[],
shown_as: None,
advice: MissingAdvice::default(),
action: None,
}
.label(label)
}
fn trailing(name: Label) -> [Adornment; 1] {
[Adornment::button(CHEVRON, IconSpec::svg(IconId::new(CHEVRON_ICON)), name)]
/// The adornments at the end of the field: the missing mark when `missing`, then the chevron. The mark is a glyph
/// whose part carries the note.
fn trailing(name: Label, missing: bool) -> Vec<Adornment> {
let mut all = Vec::with_capacity(2);
if missing {
all.push(Adornment::glyph(IconSpec::svg(IconId::new(WARNING_ICON))));
}
all.push(Adornment::button(CHEVRON, IconSpec::svg(IconId::new(CHEVRON_ICON)), name));
all
}
/// The note for `family` when it is shown in another face because the catalog lacks it, by the rule the Missing
/// Fonts dialog uses: the missing-font sentence, then the advice the host chose.
fn missing_note(&self, family: &str, words: &MissingFontsWords) -> Option<Label> {
let face = self.shown_as?;
let status = document_fonts(self.catalog, &[DocumentFont::new(family, "", None)]).into_iter().next()?.status;
if status != FontStatus::Missing {
return None;
}
let mut note = words.shown_as.fill(&[("family", family), ("face", face)]);
if self.advice == MissingAdvice::AddFont {
note.push(' ');
note.push_str(words.add_font.as_str());
}
Some(Label::from(note))
}
fn codec(&self, env: &EnvView<'_>) -> FamilyCodec {
FamilyCodec { infos: infos(self.catalog), language: ui_language(env) }
FamilyCodec { infos: infos(self.catalog), language: ui_language(env), free: self.kind == FontPickerKind::Plain }
}
/// The families in list order without filters or recents, which the arrows and the wheel step through.
@@ -554,14 +601,20 @@ impl Component for FontPicker<'_> {
let current = cx.value().map_or("", String::as_str);
let widest = [NAME_SAMPLE, current].into_iter().map(|text| cx.field_text(&TextRun::new(text))).fold(Vec2::ZERO, Vec2::max);
let name = cx.words::<FontPickerWords>().list.clone();
Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name)), widest.y)
let note = self.missing_note(current, &cx.words::<MissingFontsWords>());
Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name, note.is_some())), widest.y)
}
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
let name = cx.words::<FontPickerWords>().list.clone();
let trailing = Self::trailing(name);
let family = cx.value().cloned().unwrap_or_default();
let note = self.missing_note(&family, &cx.words::<MissingFontsWords>());
let trailing = Self::trailing(name, note.is_some());
let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.flow.is_rtl());
if let Some(at) = placed.trailing.first() {
if let (Some(note), Some(at)) = (note, placed.trailing.first()) {
cx.part(WARNING, *at).tooltip(note);
}
if let Some(at) = placed.trailing.last() {
cx.part(CHEVRON, *at)
.sense(Sense::CLICK | Sense::KEEP_FOCUS)
.priority(HitPriority::new(HitLevel::Handle, 0))
@@ -569,7 +622,6 @@ impl Component for FontPicker<'_> {
.toggles(POPUP);
}
let codec = self.codec(&cx.env);
let family = cx.value().cloned().unwrap_or_default();
let mut options = TextOptions::new();
options.select_on_focus = true;
cx.text(text_key(), placed.text, &codec, &family, &options);
@@ -635,6 +687,13 @@ impl Component for FontPicker<'_> {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let name = cx.words::<FontPickerWords>().list.clone();
let family = cx.value().cloned().unwrap_or_default();
let missing = self.missing_note(&family, &cx.words::<MissingFontsWords>()).is_some();
let trailing = Self::trailing(name.clone(), missing);
let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.env.direction().is_rtl());
if let (true, Some(at)) = (missing, placed.trailing.first()) {
ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON)));
}
ui.face(CHEVRON, IconButton::new(IconId::new(CHEVRON_ICON)).label(name));
}
@@ -652,6 +711,6 @@ impl Component for FontPicker<'_> {
settings.note_recent(family);
write(&mut bind, &mut cx, settings, "Recent font");
}
FontPickerOutput { edit, picked, preview: self.preview, picked_style: self.picked_style, rested: self.rested, action: None }
FontPickerOutput { edit, picked, preview: self.preview, picked_style: self.picked_style, rested: self.rested, action: self.action }
}
}
+68 -18
View File
@@ -24,7 +24,7 @@ use egui::Rect;
use super::rank::{Infos, Language, Listing, list, shown_name};
use super::{
FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos, read, ui_language,
FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos, read, ui_language,
write,
};
use crate::panel::faces::{Owner, Shown, paint_sample, shown};
@@ -37,12 +37,29 @@ const SAMPLE_ASPECT: (u16, u16) = (4, 1);
/// The banner's sample is this many times as wide as high.
const BANNER_ASPECT: (u16, u16) = (12, 1);
/// One position of the list: a family, one style of an open family, or the gap between the recents and the other
/// families.
/// The headings of the `Plain` list.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Heading {
Recent,
All,
}
/// One position of the list: a family, one style of an open family, the gap between the recents and the other
/// families, a heading of the `Plain` list, or one of the host's action rows.
enum Slot {
Family { row: FamilyRow, open: bool },
Style { family: String, style: String },
Gap,
Heading(Heading),
Action(usize),
}
/// What shapes the slots besides the rows.
struct Layout {
/// Headings over the recents and the families, and the action rows after them: the `Plain` list with nothing typed.
sections: bool,
/// How many action rows follow the families.
actions: usize,
}
/// What names a slot across passes. A family opening shifts the positions after it, so the list keys its rows by what
@@ -50,6 +67,8 @@ enum Slot {
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum SlotKey {
Gap,
Heading(Heading),
Action(usize),
Family { family: String, recent: bool },
Style { family: String, style: String },
}
@@ -60,6 +79,8 @@ impl Slot {
Slot::Family { row, .. } => SlotKey::Family { family: row.family.clone(), recent: row.recent },
Slot::Style { family, style } => SlotKey::Style { family: family.clone(), style: style.clone() },
Slot::Gap => SlotKey::Gap,
Slot::Heading(heading) => SlotKey::Heading(*heading),
Slot::Action(at) => SlotKey::Action(*at),
}
}
@@ -68,7 +89,7 @@ impl Slot {
match self {
Slot::Family { row, .. } => Some(&row.family),
Slot::Style { family, .. } => Some(family),
Slot::Gap => None,
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
}
}
@@ -77,7 +98,7 @@ impl Slot {
match self {
Slot::Family { row, .. } => Some((&row.family, None)),
Slot::Style { family, style } => Some((family, Some(style))),
Slot::Gap => None,
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
}
}
}
@@ -116,26 +137,35 @@ impl DisplayOrder<SlotKey> for Slots<'_> {
}
fn is_section(&self, at: usize) -> bool {
matches!(self.0[at], Slot::Gap)
matches!(self.0[at], Slot::Gap | Slot::Heading(_))
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
match &self.0[at] {
Slot::Family { row, .. } => Some(Cow::Borrowed(row.shown.as_str())),
Slot::Style { style, .. } => Some(Cow::Borrowed(style.as_str())),
Slot::Gap => None,
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
}
}
}
impl ItemSource<SlotKey> for Slots<'_> {}
/// The rows with a gap after the recents and the styles of each expanded family under its row.
fn slots(catalog: &Catalog, rows: Vec<FamilyRow>, expanded: &[String]) -> Vec<Slot> {
/// The rows with a gap after the recents (headings over the recents and the families under `layout.sections`), the
/// styles of each expanded family under its row, and the action rows at the end.
fn slots(catalog: &Catalog, rows: Vec<FamilyRow>, expanded: &[String], layout: &Layout) -> Vec<Slot> {
let recents = rows.iter().take_while(|row| row.recent).count();
let mut slots: Vec<Slot> = Vec::with_capacity(rows.len() + 1);
let mut slots: Vec<Slot> = Vec::with_capacity(rows.len() + 2);
for (at, row) in rows.into_iter().enumerate() {
if at == recents && recents > 0 {
if layout.sections {
if at == 0 && recents > 0 {
slots.push(Slot::Heading(Heading::Recent));
}
if at == recents {
slots.push(Slot::Heading(Heading::All));
}
} else if at == recents && recents > 0 {
slots.push(Slot::Gap);
}
let open = !row.recent && row.styles > 1 && expanded.contains(&row.family);
@@ -151,6 +181,9 @@ fn slots(catalog: &Catalog, rows: Vec<FamilyRow>, expanded: &[String]) -> Vec<Sl
}
}
}
if layout.sections {
slots.extend((0..layout.actions).map(Slot::Action));
}
slots
}
@@ -298,7 +331,10 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
let mut hide_classes = cx.memory::<Typing>().hide_classes;
let family = cx.value().cloned().unwrap_or_default();
let settings = read(&mut picker.settings, cx);
let mut filters = read(&mut picker.filters, cx);
let plain = picker.kind == FontPickerKind::Plain;
// The plain list has no filters: neither the bar nor the column shows, and nothing narrows the list.
let mut filters = read(&mut picker.filters, cx).filter(|_| !plain);
let actions = picker.actions;
let has_filters = filters.is_some();
let narrowing = filters.clone().unwrap_or_default();
let catalog = picker.catalog;
@@ -314,7 +350,8 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
served: picker.served,
};
let (found, comparable) = list(catalog, &infos, &listing, &Language { folder: &folder, collator: &collator }, true);
let slots = slots(catalog, found, &expanded);
let layout = Layout { sections: plain && query.trim().is_empty(), actions: actions.len() };
let slots = slots(catalog, found, &expanded, &layout);
let current = slots.iter().position(|slot| matches!(slot, Slot::Family { row, .. } if row.family == family));
let size = settings.as_ref().map_or(ThumbSize::None, |s| s.preview.thumb());
let favorites_empty = settings.as_ref().is_none_or(|s| s.favorites.is_empty());
@@ -365,21 +402,29 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
.rows_stamp(stamp.finish())
.show_items(ui, &source, &mut |_, item| match &slots[item.at] {
Slot::Gap => ListRow::spacer(),
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()).option().depth(1),
Slot::Family { row, open } => {
let icon = if row.starred { "star_filled" } else { "star" };
let name = Label::from(words.favorite.fill(&[("row", row.shown.as_str())]));
let star = TrailingFace::Icon(IconSpec::svg(IconId::new(icon)));
let mut line =
ListRow::new(row.shown.clone()).option().depth(0).check(current == Some(item.at)).trailing_part(STAR, star, name);
let mut line = ListRow::new(row.shown.clone()).option().depth(0).check(current == Some(item.at));
if !plain {
line = line.trailing_part(STAR, star, name);
}
if source.has_children(item.at) {
line = line.group(*open);
}
if let Some(class) = row.class {
if let Some(class) = row.class.filter(|_| !plain) {
line = line.trailing_named(class_mark(class, &words), class_label(class, &words));
}
line = match row.format {
Some(format) => line.trailing_named(Label::from(format.badge().to_owned()), format_label(format, &words)),
Some(format) if !plain => {
line.trailing_named(Label::from(format.badge().to_owned()), format_label(format, &words))
}
Some(_) => line,
None => line.trailing_named(words.served.clone(), words.served.clone()),
};
if size == ThumbSize::None {
@@ -463,7 +508,12 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
{
write(&mut picker.filters, cx, filters, "Font filters");
}
if let Some((family, style)) = picked.and_then(|key| slot_of(&slots, &key)).and_then(Slot::pick) {
let chosen = picked.and_then(|key| slot_of(&slots, &key));
if let Some(Slot::Action(at)) = chosen {
picker.action = Some(*at);
end_preview(picker, cx);
popup.close(cx);
} else if let Some((family, style)) = chosen.and_then(Slot::pick) {
picker.picked = Some(family.to_owned());
picker.picked_style = style.map(str::to_owned);
end_preview(picker, cx);
+52 -5
View File
@@ -5,12 +5,12 @@ use std::sync::{Arc, OnceLock};
use craft_behavior::Mixed;
use craft_ui::contract::{Bind, Show as _, Validity};
use craft_ui::runtime::env::Message;
use craft_ui::runtime::env::{Label, Message};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use egui::{Key, Modifiers, Ui};
use super::{FontFilters, FontPicker, FontPickerSettings};
use super::{FontFilters, FontPicker, FontPickerKind, FontPickerSettings, MissingAdvice};
use crate::Catalog;
use crate::craft_font_catalog::{Limits, Source};
use crate::panel::fixtures::story_catalog;
@@ -55,6 +55,10 @@ fn styled_catalog() -> Arc<Catalog> {
struct Extras<'a> {
served: &'a [String],
banner: Option<&'a str>,
kind: FontPickerKind,
actions: &'a [Label],
shown_as: Option<&'a str>,
advice: MissingAdvice,
}
fn show_with(ui: &mut Ui, data: &mut StoryData, init: Demo, catalog: &Arc<Catalog>, extras: &Extras<'_>) -> StoryOutput {
@@ -62,7 +66,13 @@ fn show_with(ui: &mut Ui, data: &mut StoryData, init: Demo, catalog: &Arc<Catalo
let mut picker = FontPicker::new("Font family", Bind::bound(family), catalog)
.settings(Bind::bound(settings))
.filters(Bind::bound(filters))
.served(extras.served);
.served(extras.served)
.kind(extras.kind)
.actions(extras.actions)
.advice(extras.advice);
if let Some(face) = extras.shown_as {
picker = picker.shown_as(face);
}
if let Some(text) = extras.banner {
picker = picker.preview_text(text);
}
@@ -123,13 +133,13 @@ fn font_picker_expanded_styles(ui: &mut Ui, data: &mut StoryData) -> StoryOutput
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
fn font_picker_served(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let served = ["Gotham".to_owned(), "Proxima Nova".to_owned()];
show_with(ui, data, demo("Hack", FontPickerSettings::default(), FontFilters::default()), &catalog(), &Extras { served: &served, banner: None })
show_with(ui, data, demo("Hack", FontPickerSettings::default(), FontFilters::default()), &catalog(), &Extras { served: &served, ..Extras::default() })
}
/// The preview banner above the filters.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
fn font_picker_banner_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let extras = Extras { served: &[], banner: Some("The quick brown fox") };
let extras = Extras { banner: Some("The quick brown fox"), ..Extras::default() };
show_with(ui, data, demo("Ubuntu", FontPickerSettings::default(), FontFilters::default()), &catalog(), &extras)
}
@@ -140,6 +150,43 @@ fn font_picker_arabic_sample(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show_with(ui, data, demo("Inter", settings, FontFilters::default()), &styled_catalog(), &Extras::default())
}
/// Settings whose recents are the families `recent`.
fn recents(recent: &[&str]) -> FontPickerSettings {
FontPickerSettings { recent: recent.iter().map(|family| (*family).to_owned()).collect(), ..FontPickerSettings::default() }
}
/// Word's plain font box, closed.
#[story(FontPicker<'static>, covers = [], drive = Drive::Never)]
fn font_picker_plain(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let extras = Extras { kind: FontPickerKind::Plain, ..Extras::default() };
show_with(ui, data, demo("Ubuntu", recents(&["Hack"]), FontFilters::default()), &catalog(), &extras)
}
/// The plain list open: recent fonts, all fonts and an action row.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
fn font_picker_plain_open_with_recents(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let actions = [Label::from("Add Font…")];
let extras = Extras { kind: FontPickerKind::Plain, actions: &actions, ..Extras::default() };
show_with(ui, data, demo("Ubuntu", recents(&["Hack"]), FontFilters::default()), &catalog(), &extras)
}
/// The plain list on a typed query: matches only, no headings and no action rows.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(type_query))]
fn font_picker_plain_typed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let actions = [Label::from("Add Font…")];
let extras = Extras { kind: FontPickerKind::Plain, actions: &actions, ..Extras::default() };
show_with(ui, data, demo("Ubuntu", recents(&["Ubuntu"]), FontFilters::default()), &catalog(), &extras)
}
/// A font the catalog lacks, shown in another face: the field carries the missing mark and its note.
#[story(FontPicker<'static>, covers = [], drive = Drive::Never)]
fn font_picker_plain_missing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let actions = [Label::from("Add Font…")];
let extras =
Extras { kind: FontPickerKind::Plain, actions: &actions, shown_as: Some("Inter"), advice: MissingAdvice::AddFont, ..Extras::default() };
show_with(ui, data, demo("Gotham", FontPickerSettings::default(), FontFilters::default()), &catalog(), &extras)
}
/// The family of a selection whose members differ.
#[story(FontPicker<'static>, covers = [Mixed], drive = Drive::Never)]
fn font_picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+90 -1
View File
@@ -7,9 +7,13 @@ use std::sync::Arc;
use craft_behavior::Preview;
use craft_font_manager::craft_font_catalog::{Limits, Os, Source};
use craft_font_manager::picker::{FontFilters, FontPicker, FontPickerSettings, SIMILAR_COUNT, family_rows};
use craft_font_manager::missing::MissingFontsWords;
use craft_font_manager::picker::{
FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows,
};
use craft_font_manager::{Catalog, FontEnv};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::runtime::env::Label;
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Fixture, Room, trial};
use egui::{Event, Key, Modifiers};
@@ -33,6 +37,7 @@ struct Seen {
rested: Vec<String>,
/// The family the open list proposes as a live preview, as the last pass reported it.
preview: Option<String>,
actions: Vec<usize>,
}
fn rig(catalog: Arc<Catalog>, served: Vec<String>) -> (Fixture, Rc<RefCell<Seen>>) {
@@ -186,3 +191,87 @@ fn a_click_on_the_focused_closed_field_selects_the_name_so_typing_replaces_it()
assert_eq!(seen.borrow().picks.last().map(|(picked, _)| picked.as_str()), Some(family), "the typed name is picked");
}
}
/// A `Plain` picker over `family` with `recent` families, `actions` rows and the face `shown_as`.
fn plain_rig(
catalog: Arc<Catalog>,
family: &str,
recent: &[&str],
actions: Vec<Label>,
shown_as: Option<&'static str>,
) -> (Fixture, Rc<RefCell<Seen>>) {
let seen = Rc::new(RefCell::new(Seen { family: family.to_owned(), ..Seen::default() }));
let shown = Rc::clone(&seen);
let mut settings = FontPickerSettings::default();
settings.recent = recent.iter().map(|family| (*family).to_owned()).collect();
let mut fx = Fixture::new(move |ui| {
let mut seen = shown.borrow_mut();
let mut picker = FontPicker::new("Font family", Bind::bound(&mut seen.family), &catalog)
.settings(Bind::bound(&mut settings))
.kind(FontPickerKind::Plain)
.actions(&actions)
.advice(if actions.is_empty() { MissingAdvice::None } else { MissingAdvice::AddFont });
if let Some(face) = shown_as {
picker = picker.shown_as(face);
}
let out = picker.show(ui);
if let Some(family) = out.picked {
seen.picks.push((family, out.picked_style));
}
seen.actions.extend(out.action);
});
fx.in_room(Room::Window);
fx.settle();
(fx, seen)
}
#[trial]
fn a_plain_box_commits_an_unknown_typed_name_lists_recents_first_and_again_after_a_cleared_query() {
let catalog = catalog_of(&[INTER_REGULAR, epaint_default_fonts::HACK_REGULAR]);
let (mut fx, seen) = plain_rig(catalog, "Inter", &["Hack"], vec![], None);
let words = FontPickerWords::default();
let (recently, all) = (words.recently_used.as_str(), words.all_fonts.as_str());
open(&mut fx);
assert!(present(&fx, recently), "the recents have their heading");
assert!(present(&fx, all), "the families have theirs");
fx.key(Key::Escape, Modifiers::NONE);
fx.settle();
let field = fx.by_label("Font family").expect("the family field");
fx.click(&field);
fx.settle();
fx.type_text("x");
fx.settle();
assert!(!present(&fx, recently), "a query lists its matches only");
fx.key(Key::Backspace, Modifiers::NONE);
fx.settle();
assert!(present(&fx, recently), "a cleared query lists the recents again");
fx.type_text("Zapfino");
fx.settle();
fx.key(Key::Enter, Modifiers::NONE);
fx.settle();
assert_eq!(seen.borrow().family, "Zapfino", "a name that is no family is applied as typed");
assert_eq!(seen.borrow().picks.last().map(|(picked, _)| picked.as_str()), Some("Zapfino"));
}
#[trial]
fn an_action_row_is_reported_not_committed_and_a_missing_family_shows_the_note_naming_the_face() {
let words = MissingFontsWords::default();
let note = format!("{} {}", words.shown_as.fill(&[("family", "Gotham"), ("face", "Inter")]), words.add_font.as_str());
let note = note.as_str();
let (mut fx, seen) = plain_rig(catalog_of(&[INTER_REGULAR]), "Gotham", &[], vec![Label::from("Add Font…")], Some("Inter"));
assert!(present(&fx, note), "the field carries the note while the family is not installed");
open(&mut fx);
let action = fx.by_label("Add Font…").expect("the action row");
fx.click(&action);
fx.settle();
assert_eq!(seen.borrow().actions, [0], "the action is reported by its index");
assert_eq!(seen.borrow().family, "Gotham", "an action leaves the family");
assert!(seen.borrow().picks.is_empty(), "and picks nothing");
let (fx, _) = plain_rig(catalog_of(&[INTER_REGULAR]), "Inter", &[], vec![Label::from("Add Font…")], Some("Inter"));
assert!(!present(&fx, note), "an installed family has no note");
}