Font picker: a preview is a per-pass Preview change, not a value proposal, so a typed query keeps its draft and list while a row previews; a click on the closed field opens the list and selects the name (Cx::select_all_text, TextOutcome::clicked); the text controls forward the change

This commit is contained in:
aiongg
2026-11-17 00:36:24 +00:00
parent 959927e686
commit ffebe34d7a
12 changed files with 156 additions and 44 deletions
+1 -1
View File
@@ -110,7 +110,7 @@ pub use selection::{
pub use sense::Sense;
pub use sizing::{ControlMetrics, Metrics, Proposal};
pub use typing::{EditRun, Ended, EscapeRule, Escaped, Typed, TypingRun};
pub use value::{Applied, CancelReason, EditEvent, EditEvents, EditPolicy, Gesture, GestureId, GestureNote, GesturePhase, Mixed, Validity, Value};
pub use value::{Applied, CancelReason, EditEvent, EditEvents, EditPolicy, Gesture, GestureId, GestureNote, GesturePhase, Mixed, Preview, Validity, Value};
pub use value_drag::{DragWarp, ValueDrag, wrap_value};
pub use wheel::{GESTURE_GAP, Wheel, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit};
+31
View File
@@ -505,6 +505,37 @@ impl<'a, T> IntoIterator for &'a EditEvents<T> {
}
}
/// What one pass did to a live preview a component shows beside its value (the family under the pointer in a font
/// list): only the pass that starts, moves or ends the preview reports it, so a second control that previews nothing
/// never ends the preview of another. A preview is not an edit: the component's value stays.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Preview<V> {
/// The preview did not change this pass.
Unchanged,
/// The preview starts, or moves to this value.
Shows(V),
/// The preview ended; the host shows the committed value again.
Ended,
}
impl<V> Default for Preview<V> {
fn default() -> Self {
Preview::Unchanged
}
}
impl<V> Preview<V> {
/// The same change over the value `f` makes of the shown one.
pub fn map<W>(self, f: impl FnOnce(V) -> W) -> Preview<W> {
match self {
Preview::Unchanged => Preview::Unchanged,
Preview::Shows(value) => Preview::Shows(f(value)),
Preview::Ended => Preview::Ended,
}
}
}
/// The running gesture of a value component, kept in shown memory under the component. Plain data; the pipeline
/// reads and writes it.
#[derive(Clone, Debug, PartialEq)]
+18 -14
View File
@@ -11,7 +11,7 @@ mod stories;
use std::sync::Arc;
use craft_behavior::{Codec, EditEvent, IconId, Mixed, NotAValue, PartKey, Sense, Value};
use craft_behavior::{HitLevel, HitPriority, NavMove};
use craft_behavior::{HitLevel, HitPriority, NavMove, Preview};
use craft_font_catalog::Catalog;
use craft_host::Section;
use craft_ui::buttons::IconButton;
@@ -301,7 +301,7 @@ pub fn family_rows(
#[derive(Debug)]
#[non_exhaustive]
pub struct FontPickerOutput {
/// The field's edit: a pick commits the family; a hovered or keyed row is a running proposal.
/// The field's edit: a pick commits the family.
pub edit: EditResponse<String>,
/// The style picked in an expanded family's style rows.
pub picked_style: Option<String>,
@@ -310,11 +310,13 @@ pub struct FontPickerOutput {
/// A family was picked: Enter or a click on a row, Enter on the exact typed name, or the wheel or arrows on the
/// closed field. The picker has already noted it as recent.
pub picked: Option<String>,
/// The family under the pointer or the keyboard row while the list is open, for a live preview of the selected
/// text (Photoshop previews on hover). `None` restores the committed family.
pub preview: Option<String>,
/// What this pass did to the live preview of the selected text: the family under the pointer or the keyboard row
/// of the open list (Photoshop previews on hover). It ends when the pointer leaves the rows, the list closes
/// (Escape, a press outside) or a row is picked. The field's value and text stay.
pub preview: Preview<String>,
}
impl Outcome for FontPickerOutput {
type Value = String;
@@ -429,7 +431,7 @@ fn read<T: Value>(bind: &mut Option<Bind<'_, T>>, cx: &mut impl StageAccess) ->
}
/// The font family field. Typing filters the list to the families whose name (in any language) matches, the best
/// match first, and opens it; the chevron and Alt+Down open it on every family, Alt+Up closes it. Rows: a star, the
/// match first, and opens it; a click on the name while the list is closed, the chevron and Alt+Down open it on every family (the click selects the name), Alt+Up closes it. Rows: a star, the
/// family name in the interface face, a sample in the family's own face at the preview size and the class mark.
/// Recent families form a group at the top. Up, Down and Page keys move the keyboard row, which previews, Enter or a
/// click on a row picks it, Enter on a typed name that is a family picks that family, Escape closes the list and
@@ -453,6 +455,7 @@ pub struct FontPicker<'a> {
picked: Option<String>,
picked_style: Option<String>,
rested: Option<String>,
preview: Preview<String>,
/// The preview banner's text.
#[prop]
preview_text: Option<&'a str>,
@@ -473,6 +476,7 @@ impl<'a> FontPicker<'a> {
picked: None,
picked_style: None,
rested: None,
preview: Preview::Unchanged,
preview_text: None,
served: &[],
}
@@ -557,18 +561,20 @@ impl Component for FontPicker<'_> {
None => list.close(cx),
}
}
// A click on the name while the list is closed opens it on every family and selects the name, so typing
// replaces it (Photoshop's font field).
if !list.is_open(cx) && cx.text(&text_key()).is_some_and(|outcome| outcome.clicked) {
cx.select_all_text();
list.open(cx);
}
if list.is_open(cx) {
return;
}
// The one place the picker forgets what belongs to an open list.
rows::end_preview(self, cx);
let typing = cx.memory::<Typing>();
typing.lead = None;
typing.lead_by_pointer = false;
typing.expanded.clear();
typing.rested.clear();
if matches!(cx.gesture(), Some(craft_behavior::GesturePhase::Begin | craft_behavior::GesturePhase::Update)) {
cx.cancel(craft_behavior::CancelReason::Dismissed);
}
let settings = read(&mut self.settings, cx);
let current = cx.value().cloned().unwrap_or_default();
let all = self.ordered(cx, settings.as_ref());
@@ -602,8 +608,6 @@ impl Component for FontPicker<'_> {
}
fn finish(self, mut cx: Cx<'_, Self>) -> FontPickerOutput {
let list = cx.popup(POPUP);
let preview = if list.is_open(&mut cx) { cx.memory::<Typing>().lead.clone() } else { None };
let edit = cx.edit_response();
let committed = edit.events.iter().rev().find_map(|event| match event {
EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } => Some(after.clone()),
@@ -617,6 +621,6 @@ impl Component for FontPicker<'_> {
settings.note_recent(family);
write(&mut bind, &mut cx, settings, "Recent font");
}
FontPickerOutput { edit, picked, preview, picked_style: self.picked_style, rested: self.rested }
FontPickerOutput { edit, picked, preview: self.preview, picked_style: self.picked_style, rested: self.rested }
}
}
+25 -14
View File
@@ -6,7 +6,7 @@ use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use craft_behavior::{DisplayOrder, IconId, ItemSource, Selection};
use craft_behavior::{DisplayOrder, IconId, ItemSource, Preview, Selection};
use craft_font_catalog::Catalog;
use craft_ui::buttons::{Button, ToggleButton};
use craft_ui::choice::{Radio, RadioGroup};
@@ -266,9 +266,28 @@ fn rest<'a>(picker: &mut FontPicker<'a>, cx: &mut Cx<'_, FontPicker<'a>>, family
}
}
/// Shows `family` as the live preview, led by the pointer or by the keys; the pass reports it when the family changes.
fn show_preview<'a>(picker: &mut FontPicker<'a>, cx: &mut Cx<'_, FontPicker<'a>>, family: String, by_pointer: bool) {
let typing = cx.memory::<Typing>();
typing.lead_by_pointer = by_pointer;
if typing.lead.as_ref() != Some(&family) {
typing.lead = Some(family.clone());
picker.preview = Preview::Shows(family);
}
}
/// Ends the live preview, if one runs; the pass reports the end.
pub(super) fn end_preview<'a>(picker: &mut FontPicker<'a>, cx: &mut Cx<'_, FontPicker<'a>>) {
let typing = cx.memory::<Typing>();
typing.lead_by_pointer = false;
if typing.lead.take().is_some() {
picker.preview = Preview::Ended;
}
}
/// The list popup: one option row per family, the committed family's row selected, and the styles of the open
/// families under their rows. A pick comes back as `Activate` (Enter, Tab or a click), a row the lead moves to is
/// proposed as the preview, and a star flips a favourite. Each pass reports only the events of its own input.
/// reported as the preview (the field's value and text stay), and a star flips a favourite. Each pass reports only the events of its own input.
pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, FontPicker<'a>>) {
let popup = cx.popup(POPUP);
let words = cx.words::<FontPickerWords>();
@@ -390,10 +409,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
match event {
CollectionEvent::LeadMoved { key, by } => {
if let Some(family) = slot_of(&slots, &key).and_then(Slot::family) {
let typing = cx.memory::<Typing>();
typing.lead = Some(family.to_owned());
typing.lead_by_pointer = by == LeadSource::Pointer;
cx.propose(family.to_owned());
show_preview(picker, cx, family.to_owned(), by == LeadSource::Pointer);
}
}
CollectionEvent::Rested(key) => {
@@ -428,18 +444,12 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
(typing.lead_by_pointer, typing.lead.is_some())
};
if by_pointer && !over_rows {
let typing = cx.memory::<Typing>();
typing.lead = None;
typing.lead_by_pointer = false;
cx.cancel(craft_behavior::CancelReason::Dismissed);
end_preview(picker, cx);
} else if over_rows
&& !led
&& let Some(family) = under_pointer.and_then(|key| slot_of(&slots, &key).and_then(Slot::family).map(str::to_owned))
{
let typing = cx.memory::<Typing>();
typing.lead = Some(family.clone());
typing.lead_by_pointer = true;
cx.propose(family);
show_preview(picker, cx, family, true);
}
if let Some(mut changed) = settings.clone().filter(|_| !stars.is_empty()) {
for (family, on) in &stars {
@@ -456,6 +466,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
if let Some((family, style)) = picked.and_then(|key| slot_of(&slots, &key)).and_then(Slot::pick) {
picker.picked = Some(family.to_owned());
picker.picked_style = style.map(str::to_owned);
end_preview(picker, cx);
cx.propose(family.to_owned());
cx.commit();
popup.close(cx);
+45 -2
View File
@@ -7,6 +7,7 @@ use std::sync::Arc;
use craft_font_manager::craft_font_catalog::{Limits, Os, Source};
use craft_font_manager::picker::{FontFilters, FontPicker, FontPickerSettings, SIMILAR_COUNT, family_rows};
use craft_behavior::Preview;
use craft_font_manager::{Catalog, FontEnv};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::testing::focus::AccessActionKind;
@@ -42,7 +43,11 @@ fn rig(catalog: Arc<Catalog>, served: Vec<String>) -> (Fixture, Rc<RefCell<Seen>
let mut seen = shown.borrow_mut();
let out =
FontPicker::new("Font family", Bind::bound(&mut seen.family), &catalog).settings(Bind::bound(&mut settings)).served(&served).show(ui);
seen.preview = out.preview;
match out.preview {
Preview::Shows(family) => seen.preview = Some(family),
Preview::Ended => seen.preview = None,
_ => {}
}
if let Some(family) = out.picked {
seen.picks.push((family, out.picked_style));
}
@@ -128,8 +133,9 @@ fn the_row_under_the_pointer_is_proposed_as_the_preview_until_the_pointer_leaves
let hack = fx.by_label("Hack").expect("the Hack row");
fx.frame(vec![Event::PointerMoved(hack.center())]);
fx.settle();
assert_eq!(seen.borrow().preview.as_deref(), Some("Hack"), "the hovered row proposes its family");
assert_eq!(seen.borrow().preview.as_deref(), Some("Hack"), "the hovered row previews its family");
assert!(seen.borrow().picks.is_empty(), "a hover picks nothing");
assert_ne!(seen.borrow().family, "Hack", "a preview leaves the value");
fx.frame(vec![Event::PointerGone]);
fx.settle();
@@ -143,3 +149,40 @@ fn the_row_under_the_pointer_is_proposed_as_the_preview_until_the_pointer_leaves
fx.settle();
assert_eq!(seen.borrow().preview, None, "a list closed without a pick cancels the preview");
}
#[trial]
fn a_preview_over_a_typed_query_keeps_the_query_and_the_list() {
let (mut fx, seen) = rig(catalog_of(&[INTER_REGULAR, epaint_default_fonts::HACK_REGULAR]), vec![]);
let field = fx.by_label("Font family").expect("the family field");
fx.click(&field);
fx.settle();
fx.type_text("Ha");
fx.settle();
let hack = fx.by_label("Hack").expect("the typed query lists Hack");
fx.frame(vec![Event::PointerMoved(hack.center())]);
fx.settle();
assert_eq!(seen.borrow().preview.as_deref(), Some("Hack"), "the hovered row previews its family");
assert!(present(&fx, "Ha"), "the field keeps the typed query while the row previews");
assert!(fx.by_label("Hack").is_some(), "the list stays open on the query");
fx.frame(vec![Event::PointerGone]);
fx.settle();
assert_eq!(seen.borrow().preview, None, "leaving the rows ends the preview");
assert!(fx.by_label("Hack").is_some(), "the list stays open after the preview ends");
assert!(present(&fx, "Ha"), "and the query stays");
}
#[trial]
fn a_click_on_the_focused_closed_field_selects_the_name_so_typing_replaces_it() {
let (mut fx, seen) = rig(catalog_of(&[INTER_REGULAR, epaint_default_fonts::HACK_REGULAR]), vec![]);
for family in ["Inter", "Hack"] {
let field = fx.by_label("Font family").expect("the family field");
fx.click(&field);
fx.settle();
fx.type_text(family);
fx.settle();
fx.key(Key::Enter, Modifiers::NONE);
fx.settle();
assert_eq!(seen.borrow().picks.last().map(|(picked, _)| picked.as_str()), Some(family), "the typed name is picked");
}
}
+5 -5
View File
@@ -16,7 +16,7 @@ use std::ops::RangeInclusive;
use std::sync::Arc;
use crate::ui::length::DocUnit;
use craft_behavior::{ColumnWidth, EditEvent, IconId};
use craft_behavior::{ColumnWidth, EditEvent, IconId, Preview};
use craft_theme::{Rgba, Srgba};
use craft_ui::choice::Swatch;
#[cfg(feature = "font-picker")]
@@ -428,9 +428,9 @@ pub struct CharacterControlsOutput {
/// `Cancel` on Esc): the app merges its steps into one history step. A preset, toggle or select is a `Set`. The
/// app applies them in order.
pub edits: Vec<EditEvent<CharacterChange>>,
/// The family under the pointer in the open font list, for a live preview of the selected text (only with
/// `font-picker`).
pub preview_family: Option<String>,
/// What this pass did to the live preview of the selected text: the family under the pointer or the keyboard row
/// of the open font list (only with `font-picker`).
pub preview_family: Preview<String>,
/// The family the pointer rested on in the open font list long enough for the app to load its preview.
pub rested_family: Option<String>,
/// The colour swatch was clicked: the app opens its colour picker for this request (key [`COLOR_KEY`]) and sets
@@ -549,7 +549,7 @@ impl<'a> CharacterControls<'a> {
});
let mut edits: Vec<EditEvent<CharacterChange>> = Vec::new();
let mut preview_family = None;
let mut preview_family = Preview::Unchanged;
let mut rested_family = None;
let mut requests = HostRequests::new();
+3 -3
View File
@@ -4,7 +4,7 @@ use std::ops::RangeInclusive;
use std::sync::Arc;
use crate::ui::length::{DocUnit, length_field, shown};
use craft_behavior::{EditEvent, EditEvents, IconId, Mixed, NumberCodec};
use craft_behavior::{EditEvent, EditEvents, IconId, Mixed, NumberCodec, Preview};
use craft_ui::buttons::ToggleButton;
use craft_ui::contract::{
Bind, Entry, FieldLayout, GlyphLabel, LabelKind, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, TooltipSpec,
@@ -261,8 +261,8 @@ pub(crate) fn toggle_row<C>(ui: &mut Ui, label: Option<&Label>, toggles: &[Toggl
pub(crate) struct FamilyField {
/// The family edit, and the style edit of a style picked in an expanded family's rows; a hovered row is not one.
pub edits: Vec<EditEvent<CharacterChange>>,
/// The family under the pointer or keyboard row in the open list.
pub preview: Option<String>,
/// What this pass did to the live preview: the family under the pointer or keyboard row in the open list.
pub preview: Preview<String>,
/// The family the pointer or keyboard rested on in the open list.
pub rested: Option<String>,
}
+5 -4
View File
@@ -1,7 +1,7 @@
//! `TypeBar`: the type tool's options bar, the family, style, size, alignment, colour and panels buttons in one
//! strip.
use craft_behavior::{EditEvent, IconId};
use craft_behavior::{EditEvent, IconId, Preview};
use craft_theme::Srgba;
use craft_ui::buttons::{IconButton, ToggleButton};
use craft_ui::choice::Swatch;
@@ -67,8 +67,9 @@ pub struct TypeBarOutput {
pub response: Response,
/// The edit events of this pass.
pub edits: Vec<EditEvent<TypeBarChange>>,
/// The family under the pointer in the open font list, for a live preview.
pub preview_family: Option<String>,
/// What this pass did to the live preview of the selected text: the family under the pointer or the keyboard row
/// of the open font list.
pub preview_family: Preview<String>,
/// The family the pointer rested on in the open font list.
pub rested_family: Option<String>,
/// The colour well was clicked.
@@ -162,7 +163,7 @@ impl<'a> TypeBar<'a> {
let directions = direction_toggles(paragraph, &paragraph_words);
let mut edits: Vec<EditEvent<TypeBarChange>> = Vec::new();
let mut preview_family = None;
let mut preview_family = Preview::Unchanged;
let mut rested_family = None;
let mut requests = HostRequests::new();
let (mut warp, mut panels) = (false, false);
+12
View File
@@ -422,6 +422,10 @@ pub(crate) fn run<C: Component>(
let ink = if enabled { ink } else { crate::style::rgba_color(crate::runtime::env::Env::of(ui).tokens.color.text.disabled) };
let held = cx.popup(EDIT_MENU).is_open_in(&mut cx.core);
serve_access(cx, &mut state, widget, &decl.shown, read_only);
if std::mem::take(&mut state.select_all) {
let len = state.draft.as_deref().unwrap_or(&decl.shown).chars().count();
adapter::select(&ctx, widget, 0, len);
}
cx.core.surface_slot = Some(ui.painter().add(egui::Shape::Noop));
let menu_held = state.held_selection.is_some();
let out = adapter::run(
@@ -505,6 +509,7 @@ pub(crate) fn run<C: Component>(
outcome.caret_visible = caret_visible;
outcome.composing = crate::runtime::ime::composing(&ctx, widget);
outcome.completions = completions;
outcome.clicked = out.clicked;
// The focus service moved focus off the widget with Tab before this pass's widgets ran.
let left_by_tab = if was_focused && !out.focused { crate::runtime::focus::tabbed_off(&ctx, widget) } else { None };
cx.core.texts = Some((decl.key, Box::new(RecordedText { outcome, submit_mods: resolved.submit_mods, left_by_tab })));
@@ -529,6 +534,13 @@ impl<C: Component> Cx<'_, C> {
crate::runtime::egui::repaint::request(&self.core.ctx);
}
/// Selects the whole text of the text part at the start of the next pass, as a field that takes focus with
/// `select_on_focus` does: a font field's click that opens its list selects the name, so typing replaces it.
pub fn select_all_text(&mut self) {
self.core.memory.shown::<TextState>(state_id(self.core.id)).select_all = true;
crate::runtime::egui::repaint::request(&self.core.ctx);
}
/// Accepts candidate `at` of the text part's completion list in the next pass: a click on a row of the list.
#[doc(hidden)]
pub fn pick_completion(&mut self, at: usize) {
@@ -89,6 +89,8 @@ pub struct TextOutcome<V> {
pub composing: bool,
/// The completion candidates the list shows; empty while it is closed.
pub completions: Vec<super::Completion>,
/// A primary click on the text ended this pass.
pub clicked: bool,
}
impl<V> TextOutcome<V> {
@@ -104,6 +106,7 @@ impl<V> TextOutcome<V> {
committed: None,
composing: false,
completions: Vec::new(),
clicked: false,
}
}
}
@@ -81,6 +81,8 @@ pub(crate) struct TextState {
pub completions: completion::Completions,
/// The draft change `Cx::set_draft` asked for, applied at the start of the next pass.
pub change: Option<DraftChange>,
/// `Cx::select_all_text` asked for the whole text to be selected at the start of the next pass.
pub select_all: bool,
/// The selection, `(caret, anchor)`, the text part had when its edit menu took the focus: egui collapses the
/// selection of a widget without focus, and the menu's command acts on it once the focus is back, which reaches the
/// widget the pass after the menu closes.
@@ -157,6 +159,8 @@ pub(crate) struct AdapterIn<'a> {
pub(crate) struct AdapterOut {
pub layout: TextLayout,
pub focused: bool,
/// A primary click on the text ended this pass.
pub clicked: bool,
/// The screen y of the first row's baseline; `None` while the text is empty.
pub baseline: Option<f32>,
}
@@ -468,7 +472,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
let full = display;
let layout = TextLayout::new(shown.galley, false, full);
let baseline = (!layout.full.is_empty()).then_some(shown.galley_pos.y + layout.first_baseline);
AdapterOut { layout, focused: shown.focused, baseline }
AdapterOut { layout, focused: shown.focused, clicked: shown.clicked, baseline }
}
/// What [`show_selectable`] shows: the read-only text of a selection part.
@@ -49,6 +49,8 @@ pub(crate) struct Shown {
pub lost_focus: bool,
/// Enter was pressed while the widget held focus.
pub entered: bool,
/// A primary click on the widget ended this pass.
pub clicked: bool,
pub caret: Option<Rect>,
pub galley: std::sync::Arc<egui::Galley>,
/// Where the galley sits on screen.
@@ -207,6 +209,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown {
focused,
lost_focus: output.response.lost_focus() || (had_focus && !focused),
entered,
clicked: output.response.clicked(),
caret,
galley: output.galley,
galley_pos: output.galley_pos,