type-w5: net change of 2 commits

- type-w5: written from its sheet
- type-w5: repair 1
This commit is contained in:
bflatastic
2026-11-21 21:27:26 +07:00
parent 5b26e4fd3d
commit 848fd48a5e
13 changed files with 441 additions and 103 deletions
+116 -59
View File
@@ -6,7 +6,7 @@ use craft_behavior::{SelectionChange, keyed};
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Trigger, clicked};
use craft_ui::dialog::{ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft_ui::dialog::{ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft_ui::display::Text;
use craft_ui::menu::Menu;
use craft_ui::pickers::Select;
@@ -15,7 +15,7 @@ use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::tabs::{Tab, TabKind, TabStrip};
use craft_ui::text::TextField;
use egui::{Context, Ui};
use serde_json::Value;
use serde_json::{Map, Value};
use super::FindLabels;
use crate::find::FindOptions;
@@ -48,8 +48,7 @@ pub struct FindCheck {
impl FindCheck {
/// A check box `key` named `label`, `on` or off.
pub fn new(key: impl Into<String>, label: impl Into<Label>, on: bool) -> Self {
let _ = (key.into(), label.into(), on);
todo!("ty.X84")
FindCheck { key: key.into(), label: label.into(), on }
}
}
@@ -126,14 +125,12 @@ impl FindRequest {
/// Replace the current match of `query` with `with`.
pub fn replace(query: impl Into<String>, with: impl Into<String>, options: FindOptions) -> Self {
// P3(type-w5): ty.X91
FindRequest::Replace { query: query.into(), with: with.into(), options, find_next: true }
}
/// Replace the current match of `query` with `with` and stop there.
pub fn replace_only(query: impl Into<String>, with: impl Into<String>, options: FindOptions) -> Self {
let _ = (query.into(), with.into(), options);
todo!("ty.X93")
FindRequest::Replace { query: query.into(), with: with.into(), options, find_next: false }
}
/// Replace every match of `query` with `with`.
@@ -163,6 +160,8 @@ enum Field {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Press {
Replace,
/// Replace & Find, on the Separate arrangement.
ReplaceFind,
ReplaceAll,
Highlight(bool),
/// PowerPoint's Replace… on the Find tab.
@@ -197,13 +196,10 @@ pub struct FindReplaceDialog {
go_to_kind: usize,
go_to_target: String,
/// The host's check boxes, drawn after the layout's own options.
#[allow(dead_code)] // P3(type-w5): ty.X85
checks: Vec<FindCheck>,
/// The arrangement of the Replace buttons.
#[allow(dead_code)] // P3(type-w5): ty.X88
replace_buttons: ReplaceButtons,
/// Whether a match is current; the Replace buttons are enabled only while it is.
#[allow(dead_code)] // P3(type-w5): ty.X90
matched: bool,
}
@@ -254,35 +250,43 @@ impl FindReplaceDialog {
/// The host's check boxes, drawn after the layout's own options, in order, in both layouts.
#[must_use]
pub fn checks(self, checks: Vec<FindCheck>) -> Self {
let _ = checks;
todo!("ty.X85")
pub fn checks(mut self, checks: Vec<FindCheck>) -> Self {
self.checks = checks;
self
}
/// The current value of the host check `key`.
pub fn checked(&self, key: &str) -> Option<bool> {
let _ = key;
todo!("ty.X86")
self.checks.iter().find(|check| check.key == key).map(|check| check.on)
}
/// The arrangement of the Replace buttons on the Replace tab, both layouts.
#[must_use]
pub fn replace_buttons(self, buttons: ReplaceButtons) -> Self {
let _ = buttons;
todo!("ty.X88")
pub fn replace_buttons(mut self, buttons: ReplaceButtons) -> Self {
self.replace_buttons = buttons;
self
}
/// Opens with `with` in Replace with (the host's last search).
#[must_use]
pub fn replace_with(self, with: impl Into<String>) -> Self {
let _ = with.into();
todo!("ty.X89")
pub fn replace_with(mut self, with: impl Into<String>) -> Self {
self.with = with.into();
self
}
/// Whether a match is current; the Replace buttons are enabled only while it is. Starts `true`.
pub fn set_matched(&mut self, matched: bool) {
let _ = matched;
todo!("ty.X90")
self.matched = matched;
}
/// The search options the shown layout has, by their serde names: PowerPoint's layout has Match case and Whole
/// words only.
fn option_fields(&self) -> Map<String, Value> {
let Ok(Value::Object(mut fields)) = serde_json::to_value(self.options) else { return Map::new() };
if !self.word {
fields.retain(|name, _| matches!(name.as_str(), "matchCase" | "wholeWord"));
}
fields
}
/// The request the user made since the last call, if any.
@@ -319,10 +323,20 @@ impl StackDialog for FindReplaceDialog {
let pending = self.insert.take();
let kinds = self.go_to_kinds.clone();
let message = self.message.clone();
let matched = self.matched;
let separate = self.replace_buttons == ReplaceButtons::Separate;
let mut checks = std::mem::take(&mut self.checks);
let accept_label = if tab == FindTab::GoTo { words.go_to.clone() } else { words.find_next.clone() };
let extras: Vec<(Label, Press)> = match (tab, word) {
(FindTab::Replace, _) => vec![(words.replace.clone(), Press::Replace), (words.replace_all.clone(), Press::ReplaceAll)],
(FindTab::Replace, _) => {
let mut extras = vec![(words.replace.clone(), Press::Replace)];
if separate {
extras.push((words.replace_find.clone(), Press::ReplaceFind));
}
extras.push((words.replace_all.clone(), Press::ReplaceAll));
extras
}
(FindTab::Find, true) => {
vec![(words.highlight_all.clone(), Press::Highlight(true)), (words.clear_highlight.clone(), Press::Highlight(false))]
}
@@ -331,7 +345,10 @@ impl StackDialog for FindReplaceDialog {
};
let accept_enabled = if tab == FindTab::GoTo { !kinds.is_empty() } else { !query.is_empty() };
let mut buttons = vec![FooterButton::new(accept_label, DialogRole::Accept).stays_open(true).enabled(accept_enabled)];
buttons.extend(extras.iter().map(|(label, _)| FooterButton::new(label.clone(), DialogRole::Other).stays_open(true)));
buttons.extend(extras.iter().map(|(label, which)| {
let needs_match = matches!(which, Press::Replace | Press::ReplaceFind);
FooterButton::new(label.clone(), DialogRole::Other).stays_open(true).enabled(matched || !needs_match)
}));
buttons.push(FooterButton::new(words.close_button.clone(), DialogRole::Cancel));
let close_at = buttons.len() - 1;
@@ -400,33 +417,40 @@ impl StackDialog for FindReplaceDialog {
let check = |ui: &mut Ui, label: &Label, value: &mut bool, enabled: bool| {
Checkbox::new(Bind::bound(value)).label(label.clone()).enabled(enabled).show(ui);
};
if !word {
check(ui, &words.match_case.clone(), &mut options.match_case, true);
check(ui, &words.whole_words.clone(), &mut options.whole_word, true);
return;
'options: {
if !word {
check(ui, &words.match_case.clone(), &mut options.match_case, true);
check(ui, &words.whole_words.clone(), &mut options.whole_word, true);
break 'options;
}
if clicked(&Button::new(words.search_options.clone()).show(ui)) {
more = !more;
}
if !more {
break 'options;
}
// Word greys the case, word and ignore options out while wildcards are on.
let free = !options.wildcards || options.regex;
let no_regex = !options.regex;
check(ui, &words.match_case.clone(), &mut options.match_case, free);
check(ui, &words.whole_words.clone(), &mut options.whole_word, free);
check(ui, &words.use_wildcards.clone(), &mut options.wildcards, no_regex);
check(ui, &words.match_prefix.clone(), &mut options.prefix, free);
check(ui, &words.match_suffix.clone(), &mut options.suffix, free);
check(ui, &words.ignore_punctuation.clone(), &mut options.ignore_punctuation, free);
check(ui, &words.ignore_space.clone(), &mut options.ignore_space, free);
check(ui, &words.regular_expressions.clone(), &mut options.regex, true);
let entries = special_entries(&words, tab == FindTab::Replace);
let button = Button::new(words.special.clone()).show(ui);
if let Some(code) = Menu::new(words.special.clone()).opened_by(&button, Trigger::Press).pick(ui, &entries).picked {
let field = if last_field == Field::With && tab == FindTab::Replace { Field::With } else { Field::Find };
picked_code = Some((field, code.to_owned()));
}
}
if clicked(&Button::new(words.search_options.clone()).show(ui)) {
more = !more;
}
if !more {
return;
}
// Word greys the case, word and ignore options out while wildcards are on.
let free = !options.wildcards || options.regex;
let no_regex = !options.regex;
check(ui, &words.match_case.clone(), &mut options.match_case, free);
check(ui, &words.whole_words.clone(), &mut options.whole_word, free);
check(ui, &words.use_wildcards.clone(), &mut options.wildcards, no_regex);
check(ui, &words.match_prefix.clone(), &mut options.prefix, free);
check(ui, &words.match_suffix.clone(), &mut options.suffix, free);
check(ui, &words.ignore_punctuation.clone(), &mut options.ignore_punctuation, free);
check(ui, &words.ignore_space.clone(), &mut options.ignore_space, free);
check(ui, &words.regular_expressions.clone(), &mut options.regex, true);
let entries = special_entries(&words, tab == FindTab::Replace);
let button = Button::new(words.special.clone()).show(ui);
if let Some(code) = Menu::new(words.special.clone()).opened_by(&button, Trigger::Press).pick(ui, &entries).picked {
let field = if last_field == Field::With && tab == FindTab::Replace { Field::With } else { Field::Find };
picked_code = Some((field, code.to_owned()));
if !word || more {
for host in &mut checks {
Checkbox::new(Bind::bound(&mut host.on)).label(host.label.clone()).show(ui);
}
}
if !message.is_empty() {
Text::new(message.clone()).show(ui);
@@ -442,6 +466,7 @@ impl StackDialog for FindReplaceDialog {
self.go_to_target = target;
self.tab = next_tab;
self.insert = picked_code;
self.checks = checks;
let picked = shown.output.picked;
if picked == Some(0) || (submitted && tab != FindTab::GoTo) {
@@ -458,22 +483,54 @@ impl StackDialog for FindReplaceDialog {
match which {
Press::ShowReplace => self.tab = FindTab::Replace,
Press::Highlight(on) => self.request = Some(FindRequest::Highlight { query, options, on: *on }),
// P3(type-w5): ty.X91
Press::Replace if !query.is_empty() => self.request = Some(FindRequest::Replace { query, with, options, find_next: true }),
Press::ReplaceAll if !query.is_empty() => self.request = Some(FindRequest::ReplaceAll { query, with, options }),
Press::Replace | Press::ReplaceAll => {}
Press::Replace if !query.is_empty() && separate => self.request = Some(FindRequest::replace_only(query, with, options)),
Press::Replace | Press::ReplaceFind if !query.is_empty() => self.request = Some(FindRequest::replace(query, with, options)),
Press::ReplaceAll if !query.is_empty() => self.request = Some(FindRequest::replace_all(query, with, options)),
Press::Replace | Press::ReplaceFind | Press::ReplaceAll => {}
}
}
(picked == Some(close_at) || shown.output.closed.is_some()).then_some(DialogResult::Ok(()))
}
fn json_fields(&self) -> Option<Value> {
todo!("ty.X95")
let mut fields = Map::new();
fields.insert("find".to_owned(), Value::String(self.query.clone()));
fields.insert("replace".to_owned(), Value::String(self.with.clone()));
fields.extend(self.option_fields());
for check in &self.checks {
fields.insert(check.key.clone(), Value::Bool(check.on));
}
fields.insert("message".to_owned(), Value::String(self.message.clone()));
Some(Value::Object(fields))
}
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("ty.X95")
fn set_json_field(&mut self, _: &Context, field: &str, value: Value) -> Result<(), String> {
let rejects = || FieldRefusal::Rejects(&value).message(field);
match field {
"message" => Err(FieldRefusal::ReadOnly.message(field)),
"find" | "replace" => {
let text = value.as_str().ok_or_else(rejects)?.to_owned();
if field == "find" {
self.query = text;
} else {
self.with = text;
}
Ok(())
}
_ => {
if let Some(check) = self.checks.iter_mut().find(|check| check.key == field) {
check.on = value.as_bool().ok_or_else(rejects)?;
return Ok(());
}
if !self.option_fields().contains_key(field) {
return Err(FieldRefusal::Unknown.message(field));
}
let Ok(Value::Object(mut all)) = serde_json::to_value(self.options) else { return Err(FieldRefusal::Unknown.message(field)) };
all.insert(field.to_owned(), value.clone());
self.options = serde_json::from_value(Value::Object(all)).map_err(|_| rejects())?;
Ok(())
}
}
}
}
+27 -7
View File
@@ -4,7 +4,7 @@ use craft_ui::dialog::{DialogStack, StackDialog as _};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use super::{FindBar, FindReplaceDialog, FindTab};
use super::{FindBar, FindCheck, FindReplaceDialog, FindTab, ReplaceButtons};
use crate::find::{FindMatches, FindOptions, FindPattern, MAX_COUNT};
fn matches(text: &str, query: &str) -> FindMatches {
@@ -39,10 +39,14 @@ fn refused_pattern(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
FindBar::new(&mut query, &mut options, &mut found).show(ui).response.into()
}
/// The Word layout of the dialog on `tab`, with "craft" in Find what, while `open`. The dialog keeps what is typed
/// in it until it closes; the card's Show dialog opens a fresh one.
fn dialog(ui: &mut Ui, data: &mut StoryData, tab: FindTab) -> StoryOutput {
let fresh = || FindReplaceDialog::new("craft", tab).word(true).go_to_kinds(vec!["Page".into(), "Line".into()]);
/// The Word layout of the dialog on `tab`, with "craft" in Find what.
fn word(tab: FindTab) -> FindReplaceDialog {
FindReplaceDialog::new("craft", tab).word(true).go_to_kinds(vec!["Page".into(), "Line".into()])
}
/// The dialog `fresh` builds, while `open`. The dialog keeps what is typed in it until it closes; the card's Show
/// dialog opens a fresh one.
fn dialog(ui: &mut Ui, data: &mut StoryData, fresh: impl Fn() -> FindReplaceDialog) -> StoryOutput {
if !*data.value("open", true) {
return StoryOutput::default();
}
@@ -63,10 +67,26 @@ fn dialog(ui: &mut Ui, data: &mut StoryData, tab: FindTab) -> StoryOutput {
#[story(FindReplaceDialog, covers = [], drive = Drive::Never, title = "Dialog")]
fn find_tab(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
dialog(ui, data, FindTab::Find)
dialog(ui, data, || word(FindTab::Find))
}
#[story(FindReplaceDialog, covers = [], drive = Drive::Never)]
fn replace_tab(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
dialog(ui, data, FindTab::Replace)
dialog(ui, data, || word(FindTab::Replace))
}
#[story(FindReplaceDialog, covers = [], drive = Drive::Never)]
fn find_tab_with_checks(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let checks = || vec![FindCheck::new("backwards", "Search Backwards", false), FindCheck::new("hidden", "Check Hidden Layers", true)];
dialog(ui, data, move || word(FindTab::Find).checks(checks()))
}
#[story(FindReplaceDialog, covers = [], drive = Drive::Never)]
fn replace_tab_separate_buttons(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
dialog(ui, data, || word(FindTab::Replace).replace_buttons(ReplaceButtons::Separate))
}
#[story(FindReplaceDialog, covers = [], drive = Drive::Never)]
fn powerpoint_layout(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
dialog(ui, data, || FindReplaceDialog::new("craft", FindTab::Find).word(false))
}
+1 -2
View File
@@ -360,8 +360,7 @@ impl TextRuler<'_> {
/// The running drag of the ruler whose id is `ruler`, read outside its pass; `None` while no drag runs and while
/// the dragged stop is off the ruler.
pub fn dragging(ctx: &egui::Context, ruler: egui::Id) -> Option<RulerDrag> {
let _ = (ctx, ruler);
todo!("ty.X59")
craft_ui::runtime::edit::gesture_note::<RulerValues, Option<RulerDrag>>(ctx, ruler).flatten()
}
}
+18
View File
@@ -98,6 +98,24 @@ pub(super) fn without(values: &RulerValues, at: usize) -> RulerValues {
cleared
}
/// `values` with every stop moved by the offset that takes the stop `grab` to `to` points: spacing and kinds stay, the
/// lowest stop stays at 0 or above and the highest within the column. A column the stops do not fit in moves none.
pub(super) fn moved_all(values: &RulerValues, grab: usize, to: f32, width: f32) -> RulerValues {
let mut next = values.clone();
let Some(start) = values.stops.get(grab).map(|stop| stop.position) else { return next };
if !to.is_finite() {
return next;
}
let lowest = values.stops.iter().map(|stop| stop.position).fold(f32::INFINITY, f32::min);
let highest = values.stops.iter().map(|stop| stop.position).fold(f32::NEG_INFINITY, f32::max);
let (least, most) = (-lowest, width.max(0.0) - highest);
let offset = if least <= most { (to - start).clamp(least, most) } else { 0.0 };
for stop in &mut next.stops {
stop.position += offset;
}
next
}
/// `values` with `item` moved to `to` points (kept within the column), and where the item is
/// afterwards (a stop moved past another has a new index).
pub(super) fn moved(values: &RulerValues, item: RulerItem, to: f32, width: f32) -> (RulerValues, RulerItem) {
+36 -23
View File
@@ -1,8 +1,8 @@
//! One pass of the ruler's input: the gestures on the items, the strip and the column borders, keys and the
//! screen reader's requests.
use super::items::{COLUMN, RulerItem, STRIP, moved, place, without};
use super::{ColumnBorder, ColumnDrag, RulerValues, SAME_POSITION, TabLeader, TabStop, TextRuler, dropped_off, snap_stop};
use super::items::{COLUMN, RulerItem, STRIP, moved, moved_all, place, without};
use super::{ColumnBorder, ColumnDrag, RulerDrag, RulerValues, SAME_POSITION, TabLeader, TabStop, TextRuler, dropped_off, snap_stop};
use crate::ui::length::{DocUnit, shown};
use craft_behavior::{CancelReason, GesturePhase, Granularity, Intent, NavMove, PointerButton, PressPhase, RulerUnits, Ticks};
use craft_ui::canvas::{INCH_SIXTEENTHS, RulerText, Rulers, TickRule, readout};
@@ -22,6 +22,10 @@ pub(super) struct Held {
from: Option<RulerItem>,
/// A new stop is being placed, not an existing one moved.
placing: bool,
/// Cmd was held when a stop was grabbed: every stop moves with it.
all: bool,
/// The value last proposed on the ruler; a stop off the ruler proposes it again so the drag note goes.
shown: Option<RulerValues>,
/// Where the item is now (a stop's index follows it through the sorted stops).
pub(super) now: Option<RulerItem>,
/// The pointer is far enough off the ruler to clear the stop on release.
@@ -107,6 +111,8 @@ impl TextRuler<'_> {
if !cx.gesture().is_some() && held.columns.is_none() {
held.off = false;
held.placing = false;
held.all = false;
held.shown = None;
held.anchor = None;
}
@@ -133,18 +139,16 @@ impl TextRuler<'_> {
let Some(press) = cx.part_if_declared(part).map(|declared| declared.press) else { return };
match press.phase {
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
if let RulerItem::Stop(at) = item {
// P3(type-w5): ty.X57
self.report.picked = Some(RulerItem::Stop(at));
if start.clicks >= 2 {
self.report.open_tabs_dialog = true;
}
self.report.picked = Some(item);
if matches!(item, RulerItem::Stop(_)) && start.clicks >= 2 {
self.report.open_tabs_dialog = true;
}
cx.focus_part(part);
}
PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => {
let anchor = cx.value().cloned().unwrap_or_default();
*held = Held { anchor: Some(anchor), from: Some(item), now: Some(item), ..Held::default() };
let all = press.mods.cmd && matches!(item, RulerItem::Stop(_));
*held = Held { anchor: Some(anchor), from: Some(item), now: Some(item), all, ..Held::default() };
cx.focus_part(part);
cx.begin();
self.drag_item(cx, g, step, held, text, start.origin, pos, press.mods.alt);
@@ -160,7 +164,7 @@ impl TextRuler<'_> {
if held.off
&& let (Some(anchor), Some(RulerItem::Stop(grab))) = (held.anchor.clone(), held.from)
{
cx.propose(without(&anchor, grab));
cx.propose_with(without(&anchor, grab), None::<RulerDrag>);
}
cx.commit();
if let Some(now) = held.now {
@@ -192,13 +196,27 @@ impl TextRuler<'_> {
let (Some(anchor), Some(from)) = (held.anchor.clone(), held.from) else { return };
let start = from.position(&anchor, g.width);
let target = snap_stop(start + (pos.x - origin.x) / g.scale * g.sign(), step, g.width, free);
let (value, now) = moved(&anchor, from, target, g.width);
let moved = match from {
RulerItem::Stop(grab) if held.all => (moved_all(&anchor, grab, target, g.width), from),
_ => moved(&anchor, from, target, g.width),
};
held.off = matches!(from, RulerItem::Stop(_)) && dropped_off(pos.y, g.strip);
if !held.off {
held.now = Some(now);
cx.propose(value.clone());
self.show_position(cx, text, pos, now, &value, g.width);
self.follow(cx, g, held, text, pos, moved);
}
/// Proposes the dragged value with its note. Off the ruler the stop keeps its last shown value and the note goes, so
/// [`TextRuler::dragging`] never reports a position the pointer left.
fn follow(&mut self, cx: &mut Cx<'_, Self>, g: &super::Geometry, held: &mut Held, text: &RulerText, pos: Pos2, moved: (RulerValues, RulerItem)) {
let (value, now) = moved;
if held.off {
let kept = held.shown.clone().or_else(|| held.anchor.clone()).unwrap_or_default();
cx.propose_with(kept, None::<RulerDrag>);
return;
}
held.now = Some(now);
held.shown = Some(value.clone());
cx.propose_with(value.clone(), Some(RulerDrag { item: now, position: now.position(&value, g.width) }));
self.show_position(cx, text, pos, now, &value, g.width);
}
/// The position of the dragged item at the pointer.
@@ -226,7 +244,7 @@ impl TextRuler<'_> {
if held.off
&& let Some(anchor) = held.anchor.clone()
{
cx.propose(anchor);
cx.propose_with(anchor, None::<RulerDrag>);
}
cx.commit();
*held = Held::default();
@@ -238,7 +256,6 @@ impl TextRuler<'_> {
PressPhase::Release { start, click: true, pos, .. } if start.button == PointerButton::Primary && g.column().contains(pos) => {
let (value, at) = place(values, stop_at(pos.x, press.mods.alt));
cx.set(value);
// P3(type-w5): ty.X57
self.report.picked = Some(RulerItem::Stop(at));
}
_ => {}
@@ -248,12 +265,8 @@ impl TextRuler<'_> {
fn drag_placing(&mut self, cx: &mut Cx<'_, Self>, g: &super::Geometry, held: &mut Held, text: &RulerText, pos: Pos2, stop: &TabStop) {
let Some(anchor) = held.anchor.clone() else { return };
held.off = dropped_off(pos.y, g.strip);
if !held.off {
let (value, at) = place(&anchor, *stop);
held.now = Some(RulerItem::Stop(at));
cx.propose(value.clone());
self.show_position(cx, text, pos, RulerItem::Stop(at), &value, g.width);
}
let (value, at) = place(&anchor, *stop);
self.follow(cx, g, held, text, pos, (value, RulerItem::Stop(at)));
}
/// The table column borders: one gesture per border drag, reported with its phase. The columns right of a dragged
+20 -6
View File
@@ -149,9 +149,10 @@ impl SpellingItem {
/// Sets the sentence's text before and after the word.
#[must_use]
pub fn context(self, before: impl Into<String>, after: impl Into<String>) -> Self {
let _ = (before.into(), after.into());
todo!("ty.X97")
pub fn context(mut self, before: impl Into<String>, after: impl Into<String>) -> Self {
self.before = before.into();
self.after = after.into();
self
}
}
@@ -224,8 +225,8 @@ impl CheckSpellingDialog {
/// Replaces the list and shows its first item (Change To from its first suggestion): a host that walks its text
/// itself hands the dialog the words from its current place.
pub fn restart(&mut self, items: Vec<SpellingItem>) {
let _ = items;
todo!("ty.X100")
self.index = 0;
self.set_items(items);
}
/// The misspellings found again after an action. The dialog keeps its position in the list (after Change, Ignore
@@ -278,7 +279,17 @@ impl CheckSpellingDialog {
let shown = dialog.show(ui, |ui, _| {
let word = item.as_ref().map_or_else(String::new, |i| i.word.clone());
Field::new(words.not_in_dictionary.clone()).id_salt("word").show(ui, |ui, _| {
TextField::new(words.not_in_dictionary.clone(), Bind::given(word.clone())).enabled(false).show(ui);
// PLAN: the word should be strong, underlined and in the accent ink inside the sunken field; no display
// component takes a run of `Span`s (`Text::spans` wants `DocRun`s with fonts and data colours) and `Span`
// has no colour (contract-03 OQ1), so the context reads as one wrapped line.
match item.as_ref().filter(|i| !i.before.is_empty() || !i.after.is_empty()) {
Some(i) => {
Text::new(format!("{}{}{}", i.before, i.word, i.after)).show(ui);
}
None => {
TextField::new(words.not_in_dictionary.clone(), Bind::given(word.clone())).enabled(false).show(ui);
}
}
});
Field::new(words.change_to.clone()).id_salt("change-to").show(ui, |ui, _| {
TextField::new(words.change_to.clone(), Bind::bound(&mut *change_to)).enabled(has_item).show(ui);
@@ -326,6 +337,9 @@ impl CheckSpellingDialog {
match body_press.get().or(button_press) {
Some(Press::Ignore) => {
if let Some(item) = item {
self.action = Some(SpellingAction::Ignore(item));
}
self.index = (self.index + 1).min(self.items.len());
self.change_to = self.items.get(self.index).and_then(|i| i.suggestions.first()).cloned().unwrap_or_default();
}
+6
View File
@@ -16,6 +16,12 @@ fn check_spelling_with_suggestions(ui: &mut Ui, data: &mut StoryData) -> StoryOu
data.value("suggestions", CheckSpellingDialog::new(items())).show(ui).into()
}
#[story(CheckSpellingDialog, covers = [], drive = Drive::Never)]
fn check_spelling_in_context(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let item = SpellingItem::new(1, 6..9, "teh", vec!["the".to_owned(), "tea".to_owned()]).context("I saw ", " cat on the mat.");
data.value("context", CheckSpellingDialog::new(vec![item])).show(ui).into()
}
#[story(CheckSpellingDialog, covers = [], drive = Drive::Never)]
fn check_spelling_complete(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
data.value("complete", CheckSpellingDialog::new(Vec::new())).show(ui).into()
+10 -3
View File
@@ -195,7 +195,7 @@ impl Facts {
TextStyleCommand::Redefine => {
(self.target && self.current.is_some_and(|id| id != 0 || self.paragraph)).then_some(TextStyleAction::Redefine)
}
TextStyleCommand::New => Some(TextStyleAction::New { from_selection: self.target, ask_name: false }),
TextStyleCommand::New => Some(TextStyleAction::new_style(self.target, false)),
TextStyleCommand::Duplicate if several => Some(TextStyleAction::DuplicateHighlighted),
TextStyleCommand::Delete if several => Some(TextStyleAction::DeleteHighlighted),
TextStyleCommand::Duplicate => editable.map(TextStyleAction::Duplicate),
@@ -315,7 +315,7 @@ impl<'a> TextStylesPanel<'a> {
/// Shows the panel and returns what the user asked for.
pub fn show(self, ui: &mut Ui) -> TextStylesPanelOutput {
let TextStylesPanel { label, kind, rows, mut selection, current, overridden, target, text_selected, highlighting, empty, reveal } = self;
let _ = reveal; // P3(type-w5): ty.X63
let words = Env::of(ui).words::<TextStylesWords>();
let paragraph = kind == TextStyleKind::Paragraph;
let action = Cell::new(None::<TextStyleAction>);
@@ -364,7 +364,10 @@ impl<'a> TextStylesPanel<'a> {
} else if let Some(command) = bar.picked.and_then(|at| FOOTER.get(at))
&& let Some(found) = facts.action(*command)
{
action.set(Some(found));
action.set(Some(match found {
TextStyleAction::New { from_selection, .. } => TextStyleAction::new_style(from_selection, bar.mods.alt),
other => other,
}));
}
};
@@ -403,6 +406,10 @@ impl<'a> TextStylesPanel<'a> {
.can_drag(move |_| highlighting)
.drag_payload(|drag: &ListDrag<u64>| Some(drag.clone()))
.selection(selection.reborrowed());
let list = match reveal {
Some(id) => list.reveal(id),
None => list,
};
let list = match &empty {
Some(text) => list.empty(text.clone()),
None => list,
+63
View File
@@ -0,0 +1,63 @@
//! The Find and Replace dialog's protocol: fields set by automation are what the next request carries.
use std::cell::RefCell;
use std::rc::Rc;
use craft_text::find::FindOptions;
use craft_text::ui::find::{FindCheck, FindReplaceDialog, FindRequest, FindTab, ReplaceButtons};
use craft_ui::contract::Role;
use craft_ui::dialog::{DialogStack, StackDialog as _};
use craft_ui::testing::{Fixture, trial};
use serde_json::json;
/// Presses the button named `name`.
fn press(fixture: &mut Fixture, name: &str) {
let button = fixture
.by_role(Role::BUTTON)
.into_iter()
.find(|button| fixture.tree().name_of(button.node) == Some(name))
.unwrap_or_else(|| panic!("a button named {name}"));
fixture.click(&button).settle();
}
#[trial]
fn find_fields_set_by_automation_reach_the_next_request() {
let dialog = Rc::new(RefCell::new(
FindReplaceDialog::new("craft", FindTab::Replace)
.word(true)
.replace_buttons(ReplaceButtons::Separate)
.checks(vec![FindCheck::new("backwards", "Search Backwards", false)]),
));
let shown = dialog.clone();
let mut fixture = Fixture::new(move |ui| {
let _ = shown.borrow_mut().show(ui, &DialogStack::default());
});
fixture.settle();
let ctx = fixture.ctx().clone();
let mut set = |field: &str, value: serde_json::Value| dialog.borrow_mut().set_json_field(&ctx, field, value);
set("find", json!("teh")).unwrap();
set("replace", json!("the")).unwrap();
set("matchCase", json!(true)).unwrap();
set("backwards", json!(true)).unwrap();
assert_eq!(dialog.borrow().checked("backwards"), Some(true));
assert!(set("message", json!("x")).unwrap_err().contains("read only"));
assert!(set("nope", json!(true)).unwrap_err().contains("unknown field"));
assert!(set("matchCase", json!("yes")).unwrap_err().contains("can't take"));
let options = FindOptions { match_case: true, ..FindOptions::default() };
press(&mut fixture, "Find Next");
assert_eq!(dialog.borrow_mut().take_request(), Some(FindRequest::find_next("teh", options)));
press(&mut fixture, "Replace");
assert_eq!(dialog.borrow_mut().take_request(), Some(FindRequest::replace_only("teh", "the", options)), "Separate's Replace replaces only");
press(&mut fixture, "Replace & Find");
assert_eq!(dialog.borrow_mut().take_request(), Some(FindRequest::replace("teh", "the", options)));
dialog.borrow_mut().set_matched(false);
fixture.settle();
press(&mut fixture, "Replace");
assert_eq!(dialog.borrow_mut().take_request(), None, "no match, no Replace");
dialog.borrow_mut().set_message("nothing found");
let fields = dialog.borrow().json_fields().expect("fields");
assert_eq!(fields["message"], json!("nothing found"));
assert_eq!(fields["backwards"], json!(true));
}
+2
View File
@@ -3,10 +3,12 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod editor;
mod find_dialog;
mod notes;
mod path_text;
mod ruler;
mod spelling;
mod style_options;
mod style_panel;
mod tabs;
+79 -3
View File
@@ -1,13 +1,13 @@
//! The text ruler's keys: the ruler is one Tab stop, Page Down moves between its markers and stops, and the arrows
//! move the focused one. Alt in a column border drag shows the column widths.
use craft_text::ui::ruler::{RulerValues, TabAlign, TabLeader, TabStop, TextRuler};
use craft_text::ui::ruler::{RulerItem, RulerValues, TabAlign, TabLeader, TabStop, TextRuler};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Props as _, Role, Show as _, ShowContainer as _};
use craft_ui::layout_components::Stack;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Vec2};
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// Which of `labels` holds the focus.
@@ -63,3 +63,79 @@ fn alt_in_a_column_border_drag_shows_the_column_widths() {
assert_eq!(fixture.texts().len(), without, "letting Alt go hides them");
fixture.release_at(border + Vec2::new(6.0, 0.0)).settle();
}
/// The centres of the left stops' sliders, left to right.
fn stop_centres(fixture: &Fixture) -> Vec<egui::Pos2> {
let mut found: Vec<egui::Pos2> = fixture
.by_role(Role::SLIDER)
.into_iter()
.filter(|target| fixture.tree().name_of(target.node).is_some_and(|name| name.starts_with("Left Tab at")))
.map(|target| target.center())
.collect();
found.sort_by(|a, b| a.x.total_cmp(&b.x));
found
}
#[trial]
fn a_command_drag_moves_every_stop_and_keeps_their_spacing_within_the_column() {
let id = egui::Id::new("ruler");
let stops = [72.0, 144.0, 216.0].map(|at| TabStop::new(at, TabAlign::Left, TabLeader::None)).to_vec();
let values = Rc::new(RefCell::new(RulerValues { stops, ..Default::default() }));
let shown = values.clone();
let mut fixture = Fixture::new(move |ui| {
TextRuler::new("Ruler", Bind::bound(&mut *shown.borrow_mut()), 300.0).id(id).show(ui);
});
fixture.settle();
let grabbed = stop_centres(&fixture)[1];
let by = Vec2::new(600.0, 0.0);
fixture.hold(Modifiers::COMMAND);
fixture.drag_hold_at(grabbed, by).idle(2);
let drag = TextRuler::dragging(fixture.ctx(), id).expect("the drag is running");
assert_eq!(drag.item, RulerItem::Stop(1), "the grabbed stop keeps its index");
assert!((drag.position - 228.0).abs() < 0.01, "the highest stop stops at the column width: {}", drag.position);
fixture.release_at(grabbed + by).settle();
fixture.hold(Modifiers::NONE).idle(2);
let moved: Vec<f32> = values.borrow().stops.iter().map(|stop| stop.position).collect();
assert_eq!(moved.len(), 3);
for (got, want) in moved.iter().zip([156.0, 228.0, 300.0]) {
assert!((got - want).abs() < 0.01, "every stop moved by one offset: {moved:?}");
}
assert_eq!(TextRuler::dragging(fixture.ctx(), id), None, "no drag after the release");
}
#[trial]
fn dragging_is_none_off_the_ruler_after_escape_and_once_the_ruler_stops_showing() {
let id = egui::Id::new("ruler");
let values = Rc::new(RefCell::new(RulerValues {
stops: vec![TabStop::new(72.0, TabAlign::Left, TabLeader::None)],
..Default::default()
}));
let (shown, visible) = (values.clone(), Rc::new(Cell::new(true)));
let show = visible.clone();
let mut fixture = Fixture::new(move |ui| {
if show.get() {
TextRuler::new("Ruler", Bind::bound(&mut *shown.borrow_mut()), 300.0).id(id).show(ui);
}
});
fixture.settle();
let from = stop_centres(&fixture)[0];
fixture.drag_hold_at(from, Vec2::new(20.0, 0.0)).idle(2);
assert!(TextRuler::dragging(fixture.ctx(), id).is_some(), "a drag on the ruler is reported");
fixture.frame(vec![egui::Event::PointerMoved(from + Vec2::new(20.0, 200.0))]).idle(1);
assert_eq!(TextRuler::dragging(fixture.ctx(), id), None, "off the ruler");
fixture.release_at(from + Vec2::new(20.0, 200.0)).settle();
let from = stop_centres(&fixture)[0];
fixture.drag_hold_at(from, Vec2::new(20.0, 0.0)).idle(2);
assert!(TextRuler::dragging(fixture.ctx(), id).is_some());
fixture.key(egui::Key::Escape, Modifiers::NONE).idle(2);
assert_eq!(TextRuler::dragging(fixture.ctx(), id), None, "after Escape");
fixture.release_at(from + Vec2::new(20.0, 0.0)).settle();
let from = stop_centres(&fixture)[0];
fixture.drag_hold_at(from, Vec2::new(20.0, 0.0)).idle(2);
assert!(TextRuler::dragging(fixture.ctx(), id).is_some());
visible.set(false);
fixture.idle(2);
assert_eq!(TextRuler::dragging(fixture.ctx(), id), None, "once the ruler stops showing");
}
+42
View File
@@ -0,0 +1,42 @@
//! Check Spelling's Ignore and restart.
use std::cell::RefCell;
use std::rc::Rc;
use craft_text::ui::spelling::{CheckSpellingDialog, SpellingAction, SpellingItem};
use craft_ui::contract::Role;
use craft_ui::dialog::StackDialog as _;
use craft_ui::testing::{Fixture, trial};
use serde_json::json;
fn items() -> Vec<SpellingItem> {
vec![
SpellingItem::new(1, 0..3, "teh", vec!["the".to_owned(), "tea".to_owned()]),
SpellingItem::new(1, 4..11, "recieve", vec!["receive".to_owned()]),
]
}
#[trial]
fn ignore_reports_its_item_and_restart_shows_the_first_item() {
let dialog = Rc::new(RefCell::new(CheckSpellingDialog::new(items())));
let shown = dialog.clone();
let mut fixture = Fixture::new(move |ui| {
shown.borrow_mut().show(ui);
});
fixture.settle();
let ignore = fixture
.by_role(Role::BUTTON)
.into_iter()
.find(|button| fixture.tree().name_of(button.node) == Some("Ignore"))
.expect("the Ignore button");
fixture.click(&ignore).settle();
assert_eq!(dialog.borrow_mut().take_action(), Some(SpellingAction::Ignore(items()[0].clone())));
let word = |dialog: &Rc<RefCell<CheckSpellingDialog>>| dialog.borrow().json_fields().expect("fields")["word"].clone();
assert_eq!(word(&dialog), json!("recieve"), "Ignore moves on");
dialog.borrow_mut().set_items(items());
assert_eq!(word(&dialog), json!("recieve"), "set_items keeps the position");
dialog.borrow_mut().restart(items());
assert_eq!(word(&dialog), json!("teh"), "restart shows the first item");
assert_eq!(dialog.borrow().json_fields().expect("fields")["changeTo"], json!("the"), "with its first suggestion");
}
+21
View File
@@ -45,6 +45,27 @@ fn a_click_applies_alt_clears_overrides_and_a_double_click_opens_options_except_
assert!(!taken(&state).contains(&TextStyleAction::Options(0)), "a double click on None opens nothing");
}
#[trial]
fn alt_on_new_asks_for_a_name() {
let state = Rc::new(RefCell::new((Selection::<u64>::default(), Vec::<TextStyleAction>::new())));
let shared = state.clone();
let mut fixture = Fixture::new(move |ui| {
let rows = [TextStyleRow::new(0, "None"), TextStyleRow::new(1, "Emphasis")];
let mut guard = shared.borrow_mut();
let (selection, actions) = &mut *guard;
let out = TextStylesPanel::new("Character Styles", TextStyleKind::Character, &rows, Bind::bound(selection)).target(true).show(ui);
actions.extend(out.action);
});
fixture.idle(10);
let new = fixture.by_label("Create new style (from the selected type)").expect("the New footer button");
fixture.click(&new).idle(4);
assert_eq!(std::mem::take(&mut state.borrow_mut().1), vec![TextStyleAction::new_style(true, false)], "a plain click does not ask");
fixture.advance(1.0).hold(Modifiers::ALT);
fixture.click(&new).idle(4);
fixture.hold(Modifiers::NONE);
assert_eq!(std::mem::take(&mut state.borrow_mut().1), vec![TextStyleAction::new_style(true, true)], "an Alt-click asks for a name");
}
#[trial]
fn every_attempt_to_apply_a_character_style_at_a_bare_caret_warns_and_applies_nothing() {
let state = Rc::new(RefCell::new((Selection::<u64>::default(), Vec::<TextStyleAction>::new(), 0usize)));