Framework batch 3 d: port follow-ups (see runs/fwb3-d.md)

This commit is contained in:
Dylan M. Taylor
2026-11-19 15:48:27 -05:00
parent 019f0bc634
commit 88b867f4dc
13 changed files with 386 additions and 50 deletions
+6 -2
View File
@@ -139,6 +139,10 @@ pub struct CommentThread {
pub messages: Vec<CommentMessage>,
/// Each reviewer's latest status, oldest first.
pub statuses: Vec<ReviewerStatus>,
/// The statuses reviewers set on the thread's replies rather than on the comment: the search finds their text,
/// and the card shows only [`statuses`](Self::statuses).
#[serde(default)]
pub reply_statuses: Vec<ReviewerStatus>,
/// Acrobat's per-comment checkmark.
pub marked: bool,
/// A locked thread can't be edited.
@@ -259,12 +263,12 @@ pub fn sort_threads(threads: &[CommentThread], sort: CommentSort, page_order: Pa
}
/// Whether `thread` matches the search `query`: in any message's text or author, the text of a
/// reviewer's status reply, or the reader's name of the kind (`kind_name`), ignoring case (and the
/// reviewer's status reply on the comment or on one of its replies, or the reader's name of the kind (`kind_name`), ignoring case (and the
/// Turkish dotted and dotless i, as PdfCraft's `fold_case` does) through `folder`.
// pdfcraft: crates/ui-egui/src/panels/comments_panel.rs:104 `matches`, `:107` `any_contains`.
pub fn matches(thread: &CommentThread, query: &str, folder: &Folder, kind_name: impl Fn(AnnotationKind) -> String) -> bool {
let has = |text: &str| folder.contains(text, query);
thread.kind.is_some_and(|kind| has(&kind_name(kind)))
|| thread.messages.iter().any(|m| has(&m.text) || has(&m.author))
|| thread.statuses.iter().any(|reviewer| has(&reviewer.text))
|| thread.statuses.iter().chain(&thread.reply_statuses).any(|reviewer| has(&reviewer.text))
}
+12 -6
View File
@@ -375,7 +375,7 @@ pub enum HandlesWhileDrawing {
/// The press continues the drawing.
#[default]
Draw,
/// The press edits through the handle.
/// A press on a resize handle edits through it; one on an end or corner point continues the drawing.
Edit,
}
@@ -624,8 +624,8 @@ impl AnnotateTool {
}
/// The selection rule of a press on an annotation's body and of a click on its part: a second click opens it (by
/// [`OpenOn`]), the toggle modifiers toggle it, and a plain press on an unselected one selects only it. Returns
/// whether it opened.
/// [`OpenOn`]), the toggle modifiers toggle it, a plain press on an unselected one selects only it and on a
/// selected one makes it the primary, keeping the others. Returns whether it opened.
fn select_part(&mut self, target: AnnotationId, mods: Mods, clicks: u32, words: &AnnotateWords) -> bool {
let selected = self.selected.contains(&target);
if clicks >= 2 && self.opens(target) {
@@ -639,13 +639,19 @@ impl AnnotateTool {
self.select(SelectionChange::Toggle(target), words);
} else if !selected {
self.select(SelectionChange::Set(vec![target]), words);
} else if self.primary() != [target] {
// A set's last key is its lead: the primary, whose handles show.
let mut ids: Vec<AnnotationId> = self.selected.iter().copied().filter(|id| *id != target).collect();
ids.push(target);
self.select(SelectionChange::Set(ids), words);
}
false
}
/// The handle of the primary selection under `at` that a press of the drawing tool of `kind` edits: only under
/// [`HandlesWhileDrawing::Edit`], for a shape or point kind, and never while a polygon is being clicked out, which
/// keeps its clicks.
/// [`HandlesWhileDrawing::Edit`], for a shape or point kind, never while a polygon is being clicked out, which
/// keeps its clicks, and only a resize handle: a drawing tool draws from where it is pressed, so a new line starts
/// at the end of the one just drawn rather than dragging it.
fn handle_while_drawing(&self, kind: AnnotationKind, at: Point, tolerance: f64, icon_side: f64) -> Option<(AnnotationId, AnnotationHandle)> {
use AnnotationKind as K;
let edits = self.select_options.handles_while_drawing == HandlesWhileDrawing::Edit
@@ -656,7 +662,7 @@ impl AnnotateTool {
return None;
}
match hit(&self.annotations, self.primary(), at, tolerance, icon_side) {
Some(AnnotationHit::Handle(target, handle)) => Some((target, handle)),
Some(AnnotationHit::Handle(target, handle @ AnnotationHandle::Box(..))) => Some((target, handle)),
_ => None,
}
}
+22 -3
View File
@@ -121,8 +121,10 @@ pub struct CommentsPanelState {
pub search_open: bool,
/// The thread the next `show` reveals, once.
revealing: Option<ThreadId>,
/// The message being edited inline: (thread, message index, text).
/// The message being edited inline: (thread, message index, text). [`edit`](Self::edit) opens it with the focus.
pub editing: Option<(ThreadId, usize, String)>,
/// The inline editor takes the focus the next time its card is built, once.
focus_editor: bool,
/// The selected card's reply draft.
pub reply: String,
/// The "Add a comment" box's draft.
@@ -143,6 +145,14 @@ impl CommentsPanelState {
set_selection(self, Selection::single(thread));
self.revealing = Some(thread);
}
/// Opens the inline editor on message `index` of `thread` (0: the comment) with `text`, and has the editor take
/// the focus the next time its card is built, once: for an editor the app opens (a new comment's note), as a
/// double click on a card or the message menu's Edit opens one.
pub fn edit(&mut self, thread: ThreadId, index: usize, text: impl Into<String>) {
self.editing = Some((thread, index, text.into()));
self.focus_editor = true;
}
}
/// What the panel asks of the app.
@@ -455,6 +465,7 @@ fn set_selection(state: &mut CommentsPanelState, next: Selection<ThreadId>) -> b
if next.lead != state.selected.lead {
state.reply.clear();
state.editing = None;
state.focus_editor = false;
}
state.selected = next;
changed
@@ -644,6 +655,8 @@ impl<H: Value> CommentsPanel<'_, H> {
let mut selection = card_selection(&state.selected);
let reply: &str = &state.reply;
let editing = state.editing.as_ref().map(|(thread, index, text)| (*thread, *index, text.as_str()));
let focus_editor = state.focus_editor;
let mut editor_built = false;
let mut openers = Vec::new();
let out = CommentList::new(label.clone(), Some(Bind::bound(&mut selection)), grouped, select_mode)
.revealing(revealing.map(CardKey::Thread))
@@ -656,6 +669,7 @@ impl<H: Value> CommentsPanel<'_, H> {
.map_or_else(String::new, |first| words.card_name.fill(&[("author", &first.author), ("text", &first.text)]));
let is_lead = lead == Some(thread.id);
let editing = editing.filter(|(id, ..)| *id == thread.id).map(|(_, index, text)| (index, text));
editor_built |= editing.is_some();
if is_lead {
openers.extend((0..thread.messages.len()).map(|index| (index, item.part_opener(MORE.at(index as u64)))));
}
@@ -663,10 +677,15 @@ impl<H: Value> CommentsPanel<'_, H> {
.state(chosen.contains(&thread.id), !read_only && !thread.locked, now)
.lead(is_lead)
.focus_reply(is_lead && item.row.activated_by_key)
.focus_editor(focus_editor && editing.is_some())
.submit_key(reply_submit)
.drafts(editing, if is_lead { reply } else { "" })
}
});
// The editor's card took the focus request this pass.
if editor_built {
state.focus_editor = false;
}
let list = out.response.clone();
let clicks = out.activation_clicks;
let buttons: Vec<(usize, Response)> =
@@ -698,7 +717,7 @@ impl<H: Value> CommentsPanel<'_, H> {
CollectionEvent::Activate(CardKey::Thread(id)) if clicks == 2 && !read_only => {
if let Some(thread) = threads.iter().find(|thread| thread.id == id && !thread.locked) {
let text = thread.messages.first().map(|message| message.text.clone()).unwrap_or_default();
state.editing = Some((id, 0, text));
state.edit(id, 0, text);
}
}
CollectionEvent::Open(change) => {
@@ -777,7 +796,7 @@ fn apply_menu<H: Value>(
match action {
CardMenu::Edit => {
let text = thread.messages.get(index).map(|message| message.text.clone()).unwrap_or_default();
state.editing = Some((id, index, text));
state.edit(id, index, text);
}
CardMenu::Status(status) => edits.push(CommentEdit::SetStatus { thread: id, status }),
CardMenu::Copy => edits.push(CommentEdit::CopyText { thread: id, index }),
+54 -12
View File
@@ -18,7 +18,7 @@ use egui::{Color32, CornerRadius, Pos2, Rect, Vec2, vec2};
use super::list::{CardEvent, RowOut};
use super::{CommentsWords, EDIT_LINES, Line, REPLY_LINES, age_text, status_label};
use crate::annotate::AnnotationKind;
use crate::comments::{CommentThread, ReviewStatus, ReviewerStatus, ThreadId};
use crate::comments::{CommentMessage, CommentThread, ReviewStatus, ReviewerStatus, ThreadId};
use crate::ui::avatar::paint_face;
/// The style of a card or heading row.
@@ -122,11 +122,16 @@ trait Sink {
fn badge_size(&mut self, slot: Slot, label: &str) -> Vec2;
/// A status badge showing `label` in the tone of `status`.
fn badge(&mut self, slot: Slot, rect: Rect, label: &str, status: ReviewStatus);
/// The extent of reply `index` (a message after the first), from its author line to the bottom of its text.
fn reply(&mut self, index: usize, rect: Rect);
}
/// The "..." button of message `index` of a card: a part of the row that opens the message's menu.
pub(super) const MORE: PartKey = PartKey::new("more");
/// Reply `index` of a card: the access node that names it.
const REPLY: PartKey = PartKey::new("reply");
/// A card or a heading of the card collection.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
pub(crate) struct CommentRow<'r> {
@@ -144,6 +149,9 @@ pub(crate) struct CommentRow<'r> {
/// The activation key reached the card this pass: its reply box takes the focus, when it shows one.
#[prop]
focus_reply: bool,
/// The inline editor takes the focus this pass, when the card shows one.
#[prop]
focus_editor: bool,
/// The key that submits the reply box.
submit_key: SubmitKey,
words: Option<Arc<CommentsWords>>,
@@ -155,6 +163,8 @@ pub(crate) struct CommentRow<'r> {
badges: Vec<Vec2>,
/// The messages whose "..." button the parts step declared.
mores: Vec<usize>,
/// Each reply's index and its rect on the screen, from the parts step.
replies: Vec<(usize, Rect)>,
events: Vec<CardEvent>,
}
@@ -171,12 +181,14 @@ impl<'r> CommentRow<'r> {
editing: None,
reply: "",
focus_reply: false,
focus_editor: false,
submit_key: SubmitKey::default(),
words: None,
heights: [0.0; 2],
buttons: [Vec2::ZERO; 3],
badges: Vec::new(),
mores: Vec::new(),
replies: Vec::new(),
events: Vec::new(),
}
.label(name)
@@ -316,6 +328,7 @@ impl CommentRow<'_> {
y = self.statuses(thread, st, Line { at: Pos2::new(pad, y), room }, &words, sink);
for index in 1..thread.messages.len() {
let Some(message) = thread.messages.get(index) else { break };
let top = y;
sink.avatar(square(Pos2::new(pad, y), h), &message.author);
let x = pad + h + gap;
let name_room = width - pad - h - gap - x;
@@ -337,7 +350,9 @@ impl CommentRow<'_> {
};
sink.button(Slot::More(index), square(Pos2::new(width - pad - h, y), h), "more", &words.more, false);
y += h.max(head) + gap;
y = self.message(index, thread, st, Line { at: Pos2::new(x, y), room: width - pad - x }, &words, sink) + gap;
let bottom = self.message(index, thread, st, Line { at: Pos2::new(x, y), room: width - pad - x }, &words, sink);
sink.reply(index, Rect::from_min_max(Pos2::new(pad, top), Pos2::new(width - pad, bottom)));
y = bottom + gap;
}
if self.lead && self.editable {
let field = sink.field(Slot::ReplyField, strip(Pos2::new(pad, y), room), &words.reply, self.reply, REPLY_LINES);
@@ -407,6 +422,8 @@ struct Measure<'a, 'b, 'r> {
more: Vec<(usize, Rect)>,
/// The size of each status badge, in the order the row lays them.
badges: Vec<Vec2>,
/// The message index and left-to-right rect of each reply.
replies: Vec<(usize, Rect)>,
}
impl Sink for Measure<'_, '_, '_> {
@@ -454,6 +471,10 @@ impl Sink for Measure<'_, '_, '_> {
}
fn badge(&mut self, _: Slot, _: Rect, _: &str, _: ReviewStatus) {}
fn reply(&mut self, index: usize, rect: Rect) {
self.replies.push((index, rect));
}
}
/// Where the push button `slot`'s measured size is kept.
@@ -477,8 +498,9 @@ struct Paint<'a, 'b> {
buttons: [Vec2; 3],
badges: &'a [Vec2],
reply_submit: SubmitKey,
/// Set when the reply box takes the focus as it shows: the context the request goes to.
focus_reply: Option<&'a egui::Context>,
/// The field that takes the focus as it shows (the reply box or the inline editor), and the context the request
/// goes to.
focus: Option<(Slot, &'a egui::Context)>,
events: &'a mut Vec<CardEvent>,
}
@@ -578,8 +600,8 @@ impl Sink for Paint<'_, '_> {
if out.escaped && slot == Slot::EditField {
self.events.push(CardEvent::EditCancel);
}
if slot == Slot::ReplyField
&& let Some(ctx) = self.focus_reply
if let Some((focused, ctx)) = self.focus
&& focused == slot
{
focus::request(ctx, FocusTarget::Id(out.response.id));
}
@@ -614,6 +636,8 @@ impl Sink for Paint<'_, '_> {
let badge = Badge::new(label.to_owned()).variant(Variant::look(Emphasis::Soft, badge_tone(status)));
let _ = self.ui.child(slot, self.place(rect), badge);
}
fn reply(&mut self, _: usize, _: Rect) {}
}
impl Component for CommentRow<'_> {
@@ -627,9 +651,22 @@ impl Component for CommentRow<'_> {
access.node(MORE.at(index as u64), Role::BUTTON).name = craft_ui::contract::Name::Text(words.more.as_str().to_owned());
}
}
let Some(first) = self.thread.and_then(|thread| thread.messages.first()) else { return };
let age = age_text(&cx.env, first.modified.unwrap_or(first.created), self.now);
access.name(craft_ui::contract::Name::Joined(vec![cx.resolved.label.to_owned(), age]));
let Some(thread) = self.thread else { return };
let Some(first) = thread.messages.first() else { return };
let named = |name: String, message: &CommentMessage| {
let age = age_text(&cx.env, message.modified.unwrap_or(message.created), self.now);
craft_ui::contract::Name::Joined(if age.is_empty() { vec![name] } else { vec![name, age] })
};
access.name(named(cx.resolved.label.to_owned(), first));
// Each reply is a node of its own inside the card, named as the card is by its comment.
let Some(words) = &self.words else { return };
for &(index, rect) in &self.replies {
let Some(message) = thread.messages.get(index) else { continue };
let name = words.card_name.fill(&[("author", &message.author), ("text", &message.text)]);
let node = access.node(REPLY.at(index as u64), Role::GROUP);
node.name = named(name, message);
node.bounds(rect);
}
}
fn style(cx: &StyleCx<'_>, _: CommentRowStyleKey) -> CommentRowStyle {
@@ -661,7 +698,7 @@ impl Component for CommentRow<'_> {
self.words = Some(cx.words::<CommentsWords>());
let now = self.now;
let age = |then: i64| age_text(&cx.env, then, now);
let mut sink = Measure { cx, fields: [0.0; 2], buttons: [Vec2::ZERO; 3], more: Vec::new(), badges: Vec::new() };
let mut sink = Measure { cx, fields: [0.0; 2], buttons: [Vec2::ZERO; 3], more: Vec::new(), badges: Vec::new(), replies: Vec::new() };
let height = self.lay(cx.style, width, &age, &mut sink);
self.heights = sink.fields;
self.buttons = sink.buttons;
@@ -673,9 +710,10 @@ impl Component for CommentRow<'_> {
self.words = Some(cx.words::<CommentsWords>());
let (now, rtl) = (self.now, cx.flow.is_rtl());
let age = |then: i64| age_text(&cx.env, then, now);
let mut sink = Measure { cx, fields: self.heights, buttons: self.buttons, more: Vec::new(), badges: Vec::new() };
let mut sink = Measure { cx, fields: self.heights, buttons: self.buttons, more: Vec::new(), badges: Vec::new(), replies: Vec::new() };
self.lay(cx.style, rect.width(), &age, &mut sink);
self.mores = sink.more.iter().map(|(index, _)| *index).collect();
self.replies = sink.replies.iter().map(|&(index, local)| (index, placed(rect.min, rect.width(), rtl, local))).collect();
for (index, local) in sink.more {
cx.part(MORE.at(index as u64), placed(rect.min, rect.width(), rtl, local))
.sense(Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS)
@@ -711,7 +749,11 @@ impl Component for CommentRow<'_> {
buttons: self.buttons,
badges: &self.badges,
reply_submit: self.submit_key,
focus_reply: self.focus_reply.then_some(&cx.ctx),
focus: if self.focus_editor {
Some((Slot::EditField, &cx.ctx))
} else {
self.focus_reply.then_some((Slot::ReplyField, &cx.ctx))
},
events: &mut events,
};
self.lay(st, rect.width(), &age, &mut sink);
+1
View File
@@ -31,6 +31,7 @@ fn thread(id: u64, page: usize, text: &str, replies: usize) -> CommentThread {
color: Some([255, 200, 0]),
messages,
statuses: if id == 1 { vec![reviewer("Bo", ReviewStatus::Accepted)] } else { Vec::new() },
reply_statuses: Vec::new(),
marked: id == 3,
locked: false,
resolved: false,
+61 -19
View File
@@ -8,7 +8,7 @@ use craft_theme::variant::Variant;
use craft_ui::buttons::{Button, IconButton};
use craft_ui::contract::overlay::{PlacementChange, PlacementKind, ResizeEdges};
use craft_ui::contract::{
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, MeasureCx, Mount, NoValue, Outcome, Overlay,
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, MeasureCx, Mount, NoValue, Outcome, Overlay, Pad,
PaintUi, Pattern, Props as _, Role, Show as _, ShowContainer as _, SizeLimits, clicked,
};
use craft_ui::display::{Shade, Text};
@@ -95,8 +95,8 @@ impl NoteDrafts {
}
}
/// The pop-up's body: the messages, each indented by its depth, then the reply box. It reads and writes the host's
/// drafts and gathers what the pass committed.
/// The pop-up's body: the note's text and Reply, then each reply as a panel holding the panels of its answers. It reads
/// and writes the host's drafts and gathers what the pass committed.
struct NoteBody<'a, 'm> {
id: u64,
messages: &'a [NotePopupMessage<'m>],
@@ -110,21 +110,43 @@ struct NoteBody<'a, 'm> {
impl NoteBody<'_, '_> {
fn show(&mut self, ui: &mut Ui, words: &ThreadWords, view: &EnvView<'_>) {
let messages = self.messages;
let (answers, replies) = nest(messages);
Stack::new().fill_width().show(ui, |ui, _| {
for (index, message) in messages.iter().enumerate() {
let depth = u8::try_from(message.depth.min(MAX_NESTING)).unwrap_or(u8::MAX);
// The indent steps are the theme's, from the start edge.
Stack::new().fill_width().indent(depth).show(ui, |ui, _| {
if index > 0 {
byline(ui, message, view, self.now);
}
if index == 0 && self.allowed && message.editable {
self.note_text(ui, message, words);
} else {
Text::new(message.text.to_owned()).show(ui);
}
if self.allowed {
self.reply_box(ui, words, message.id);
if let Some(note) = messages.first() {
if self.allowed && note.editable {
self.note_text(ui, note, words);
} else {
Text::new(note.text.to_owned()).show(ui);
}
if self.allowed {
self.reply_box(ui, words, note.id);
}
}
for &at in &replies {
self.reply_panel(ui, words, view, &answers, at);
}
});
}
/// The panel of reply `at`: its author line, text and Reply, then the panels of its answers (`answers[at]`), one
/// indent step in. A reply's answers sit deeper than it and no deeper than [`MAX_NESTING`], so this recurses no
/// deeper than that.
fn reply_panel(&mut self, ui: &mut Ui, words: &ThreadWords, view: &EnvView<'_>, answers: &[Vec<usize>], at: usize) {
let messages = self.messages;
let Some(message) = messages.get(at) else { return };
let name = words.pin.fill(&[("author", message.author)]);
Stack::new().surface(SurfaceKind::Frame).pad(Pad::Control).fill_width().label(name).show(ui, |ui, _| {
byline(ui, message, view, self.now);
Text::new(message.text.to_owned()).show(ui);
if self.allowed {
self.reply_box(ui, words, message.id);
}
let own = answers.get(at).map_or(&[][..], Vec::as_slice);
if !own.is_empty() {
// The indent step is the theme's, from the start edge.
Stack::new().fill_width().indent(1).show(ui, |ui, _| {
for &answer in own {
self.reply_panel(ui, words, view, answers, answer);
}
});
}
@@ -178,6 +200,26 @@ impl NoteBody<'_, '_> {
}
}
/// The thread of `messages` (the note first, each reply after the message it answers, by depth): for each message the
/// replies whose panels sit in its panel, and the replies to the note. A reply deeper than [`MAX_NESTING`] counts as at
/// that depth, and one at depth 0 after the note as a reply to it.
fn nest(messages: &[NotePopupMessage<'_>]) -> (Vec<Vec<usize>>, Vec<usize>) {
let mut answers: Vec<Vec<usize>> = vec![Vec::new(); messages.len()];
let mut replies = Vec::new();
// The replies open at each depth above the one being placed.
let mut open: Vec<usize> = Vec::new();
for (at, message) in messages.iter().enumerate().skip(1) {
let depth = message.depth.clamp(1, MAX_NESTING);
open.truncate(depth - 1);
match open.last().and_then(|&parent| answers.get_mut(parent)) {
Some(own) => own.push(at),
None => replies.push(at),
}
open.push(at);
}
(answers, replies)
}
/// A reply's author line: avatar, name and age.
fn byline(ui: &mut Ui, message: &NotePopupMessage<'_>, view: &EnvView<'_>, now: i64) {
Row::new().fill_width().show(ui, |ui, _| {
@@ -218,8 +260,8 @@ pub struct NotePopupOutput {
}
/// A modeless note pop-up window over a note's messages: a title band in the note's colour with its kind, author and
/// age, and Close; the note's text, typed in place while the note may be edited; its replies, each indented by its
/// depth; and a Reply button under each message that opens a box to answer it (Post or Cmd/Ctrl+Enter posts, Cancel
/// age, and Close; the note's text, typed in place while the note may be edited; its replies, each a bordered panel
/// named for its author, an answer to a reply inside that reply's panel; and a Reply button under each message that opens a box to answer it (Post or Cmd/Ctrl+Enter posts, Cancel
/// or Escape drops it).
///
/// - Place: at the host's `rect`, its size kept within [`NOTE_POPUP_LIMITS`] on screen at every zoom, so it takes no
+14 -4
View File
@@ -243,6 +243,7 @@ pub struct CommentComposer<'a> {
anchor: Option<Pos2>,
draft: &'a mut String,
header: Option<(Label, &'a str)>,
hint: Option<Label>,
kind: ComposerDraft,
close: ComposerClose,
}
@@ -250,7 +251,7 @@ pub struct CommentComposer<'a> {
impl<'a> CommentComposer<'a> {
/// A composer at `anchor` (screen points; `None` hides it) that edits `draft`.
pub fn new(anchor: Option<Pos2>, draft: &'a mut String) -> Self {
CommentComposer { anchor, draft, header: None, kind: ComposerDraft::New, close: ComposerClose::OnOutsidePress }
CommentComposer { anchor, draft, header: None, hint: None, kind: ComposerDraft::New, close: ComposerClose::OnOutsidePress }
}
/// A header of `title` and the `author` above the field; the card is named `title`.
@@ -260,6 +261,14 @@ impl<'a> CommentComposer<'a> {
self
}
/// What the field asks for, in place of "Add a comment": its name and its placeholder ("Text to insert" for an
/// insertion).
#[must_use]
pub fn hint(mut self, hint: impl Into<Label>) -> Self {
self.hint = Some(hint.into());
self
}
/// The rule the post applies to the draft.
#[must_use]
pub fn draft_kind(mut self, kind: ComposerDraft) -> Self {
@@ -325,7 +334,7 @@ pub struct CommentComposerOutput {
impl CommentComposer<'_> {
/// Shows the composer and reports whether the user posted or closed it.
pub fn show(self, ui: &mut Ui) -> CommentComposerOutput {
let CommentComposer { anchor, draft, header, kind, close } = self;
let CommentComposer { anchor, draft, header, hint, kind, close } = self;
let mut output = CommentComposerOutput::default();
let Some(anchor) = anchor else { return output };
let words = Env::of(ui).words::<ThreadWords>();
@@ -348,9 +357,10 @@ impl CommentComposer<'_> {
});
});
}
let field = TextField::new(words.add_comment.clone(), Bind::bound(&mut *draft))
let hint = hint.clone().unwrap_or_else(|| words.add_comment.clone());
let field = TextField::new(hint.clone(), Bind::bound(&mut *draft))
.lines(COMPOSER_ROWS)
.placeholder(words.add_comment.clone())
.placeholder(hint)
.submits()
.default_stop()
.show(ui);
+9
View File
@@ -27,6 +27,7 @@ fn thread() -> CommentThread {
color: None,
messages: vec![message("Ana", "Check @Bo before we ship.", NOW - 7_200), message("Bo", "On it.", NOW - 600)],
statuses: Vec::new(),
reply_statuses: Vec::new(),
marked: false,
locked: false,
resolved: false,
@@ -84,6 +85,14 @@ fn comment_composer_edit_draft(ui: &mut Ui, data: &mut StoryData) -> StoryOutput
opener.into()
}
#[story(CommentComposer<'static>, covers = [], drive = Drive::Never)]
fn comment_composer_hint(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let opener = Button::new("Insert").show(ui);
let draft = data.value("draft", String::new());
let _ = CommentComposer::new(Some(pos2(40.0, 60.0)), draft).header("Inserted Text", "Ana").hint("Text to insert").show(ui);
opener.into()
}
#[story(CommentComposer<'static>, covers = [], drive = Drive::Never)]
fn comment_composer_long_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let opener = Button::new("Add").show(ui);
+47 -3
View File
@@ -3,7 +3,7 @@
use craft_behavior::{CancelReason, CanvasView, EditEvent};
use craft_keymap::Mods;
use craft_review::annotate::{Annotation, AnnotationEdit, AnnotationId, AnnotationKind, AnnotationTool, HandleRule, SLIP_MOVE};
use craft_review::ui::annotate::{DrawOptions, EmptyPress, EraseMode, InkStrokes, MarkupPress, OpenOn, SelectOptions, ToggleMods};
use craft_review::ui::annotate::{DrawOptions, EmptyPress, EraseMode, HandlesWhileDrawing, InkStrokes, MarkupPress, OpenOn, SelectOptions, ToggleMods};
use craft_review::ui::{AnnotateTool, AnnotateWords};
use craft_ui::testing::{ToolFixture, pointer, trial};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect as ScreenRect, vec2};
@@ -404,8 +404,50 @@ fn a_fixed_aspect_holds_on_every_corner_and_shift_takes_the_boxs_own() {
assert_eq!(resized_ids, vec![square.id], "the handles are the last selected annotation's");
}
/// `AnnotateTool::click`, the host's part click: a plain click selects only the comment, the toggle modifiers toggle
/// it (Command only under `ToggleMods::ShiftOrCommand`), a double click opens a note or text box (any comment under
/// Under `HandlesWhileDrawing::Edit` a drawing tool's press on the selected box's corner resizes it, but a press on a
/// selected line's end draws a new line from there: the drawing tools do not take end and corner points.
#[trial]
fn while_drawing_edit_takes_resize_handles_but_not_point_handles() {
let mut options = SelectOptions::default();
options.handles_while_drawing = HandlesWhileDrawing::Edit;
let commits = |rig: &ToolFixture<AnnotateTool>| -> Vec<AnnotationEdit> {
rig.tool_mut()
.take_edits()
.into_iter()
.filter_map(|edit| match edit {
EditEvent::Commit { after, .. } => Some(after),
EditEvent::Set { after, .. } => Some(after),
_ => None,
})
.collect()
};
let boxed = annotation(1, AnnotationKind::Rectangle, Rect::new(100.0, 100.0, 200.0, 160.0));
let mut tool = AnnotateTool::new(AnnotationTool::Draw(AnnotationKind::Rectangle), 0).select_options(options);
tool.annotations = vec![boxed.clone()];
tool.selected = vec![boxed.id];
let mut shapes = rig(tool);
drag_holding(&mut shapes, Point::new(200.0, 160.0), Point::new(240.0, 200.0), Modifiers::NONE);
let edits = commits(&shapes);
assert!(edits.iter().any(|edit| matches!(edit, AnnotationEdit::Resize { .. })), "the corner resizes the box: {edits:?}");
let mut line = annotation(2, AnnotationKind::Line, Rect::new(100.0, 100.0, 200.0, 100.0));
line.points = vec![Point::new(100.0, 100.0), Point::new(200.0, 100.0)];
let mut tool = AnnotateTool::new(AnnotationTool::Draw(AnnotationKind::Line), 0).select_options(options);
tool.annotations = vec![line.clone()];
tool.selected = vec![line.id];
let mut lines = rig(tool);
drag_holding(&mut lines, Point::new(200.0, 100.0), Point::new(260.0, 140.0), Modifiers::NONE);
let edits = commits(&lines);
assert!(!edits.iter().any(|edit| matches!(edit, AnnotationEdit::Reshape { .. })), "the line's end is not dragged: {edits:?}");
assert!(
edits.iter().any(|edit| matches!(edit, AnnotationEdit::Create(made) if made.kind == AnnotationKind::Line)),
"a new line is drawn from the end: {edits:?}"
);
}
/// `AnnotateTool::click`, the host's part click: a plain click selects only the comment (on one already selected it
/// keeps the selection and makes that one the primary, whose handles show), the toggle modifiers toggle it (Command only under `ToggleMods::ShiftOrCommand`), a double click opens a note or text box (any comment under
/// `OpenOn::Every`), and the edits carry the tool's undo labels. A double press on the page runs the same rule.
#[trial]
fn a_click_on_a_hosts_part_selects_toggles_and_opens_by_the_tools_rules() {
@@ -438,6 +480,8 @@ fn a_click_on_a_hosts_part_selects_toggles_and_opens_by_the_tools_rules() {
edits.len() == 2 && edits.iter().all(|(edit, label)| matches!(edit, AnnotationEdit::Selection(_)) && label == words.edit_select.as_str()),
"each change is a selection step under its label: {edits:?}"
);
tool.click(AnnotationId(2), Mods::NONE, 1, &words);
assert_eq!(tool.selected, vec![AnnotationId(1), AnnotationId(2)], "a plain click on a selected comment keeps the others and makes it the primary");
let mut options = SelectOptions::default();
options.toggle = ToggleMods::ShiftOrCommand;
+71
View File
@@ -27,6 +27,7 @@ fn thread(id: u64, page: usize, text: &str) -> CommentThread {
color: None,
messages: vec![message("Ana", text)],
statuses: Vec::new(),
reply_statuses: Vec::new(),
marked: false,
locked: false,
resolved: false,
@@ -282,6 +283,76 @@ fn host_rows_follow_the_cards_rows_and_report_their_value() {
assert_eq!(ran.borrow().as_slice(), &[9_u32], "the More menu returns the host row that ran");
}
/// Each reply of a card is a node of its own, named by its author and text, inside the card and in message order;
/// the card is named by its comment.
#[trial]
fn a_cards_replies_are_nodes_inside_it() {
let mut first = thread(1, 1, "Note 1.");
first.messages.extend([message("Bo", "A first reply."), message("Cy", "A second reply.")]);
let threads = vec![first];
let mut state = CommentsPanelState::default();
let mut fixture = Fixture::new(move |ui| {
let _ = CommentsPanel::new("Comments", &threads, &mut state).show(ui);
});
fixture.in_room(Room::Panel).settle();
let card = card(&fixture, "Note 1.").expect("the card");
let names = row_names(&fixture);
assert!(names.iter().all(|name| !name.contains("reply.")), "the card is named by its comment: {names:?}");
let reply = |author: &str, text: &str| {
fixture
.by_role(Role::GROUP)
.into_iter()
.find(|node| fixture.tree().name_of(node.node).is_some_and(|name| name.contains(author) && name.contains(text)))
.map(|node| node.rect)
};
let one = reply("Bo", "A first reply.").expect("the first reply's node");
let two = reply("Cy", "A second reply.").expect("the second reply's node");
assert!(card.contains_rect(one) && card.contains_rect(two), "the replies sit inside the card: {card:?} holds {one:?} and {two:?}");
assert!(one.bottom() <= two.top(), "the replies follow message order: {one:?} then {two:?}");
}
/// The search finds a comment by the text of a status set on one of its replies, which its card does not show.
#[trial]
fn the_search_finds_a_status_set_on_a_reply() {
let mut first = thread(1, 1, "Note 1.");
first.messages.push(message("Bo", "A reply."));
first.reply_statuses = vec![ReviewerStatus { reviewer: "Cy".into(), status: ReviewStatus::Accepted, text: "Reply-status token".into() }];
let threads = vec![first, thread(2, 1, "Note 2.")];
let mut state = CommentsPanelState::default();
state.search = "reply-status".into();
let mut fixture = Fixture::new(move |ui| {
let _ = CommentsPanel::new("Comments", &threads, &mut state).show(ui);
});
fixture.in_room(Room::Panel).settle();
assert!(card(&fixture, "Note 1.").is_some(), "the comment whose reply has the status matches");
assert!(card(&fixture, "Note 2.").is_none(), "the other does not");
}
/// An editor the app opens takes the keyboard as it shows, once: after the focus goes elsewhere the editor does not
/// take it back.
#[trial]
fn an_editor_the_app_opens_takes_the_focus_once() {
let state = Rc::new(RefCell::new(CommentsPanelState::default()));
let shown_state = state.clone();
let threads = vec![thread(1, 1, "Note 1.")];
let mut fixture = Fixture::new(move |ui| {
let mut state = shown_state.borrow_mut();
let _ = CommentsPanel::new("Comments", &threads, &mut state).show(ui);
});
fixture.in_room(Room::Panel).settle();
state.borrow_mut().edit(ThreadId(1), 0, String::new());
fixture.settle();
fixture.type_text("Typed").settle();
let draft = || state.borrow().editing.as_ref().map(|(_, _, text)| text.clone());
assert_eq!(draft().as_deref(), Some("Typed"), "the opened editor has the keyboard");
let add = fixture.by_label("Add a comment").expect("the add box");
fixture.click(&add).settle();
fixture.idle(3);
fixture.type_text("Elsewhere").settle();
assert_eq!(draft().as_deref(), Some("Typed"), "the editor does not take the keyboard back");
assert_eq!(state.borrow().new_comment, "Elsewhere", "the add box keeps it");
}
/// A panel over 120 threads on page 1, scrolled by a reveal to thread 100; the threads are shared so a trial can
/// change them between frames.
fn long_list() -> (Rc<RefCell<Vec<CommentThread>>>, Rc<RefCell<CommentsPanelState>>, Fixture) {
+46
View File
@@ -119,6 +119,33 @@ fn a_corner_drag_resizes_within_the_limits_and_reports_on_release() {
assert!((rect.size() - NOTE_POPUP_LIMITS.min).length() < SLACK, "the window stops at its least size: {rect:?}");
}
/// Each reply is a panel of its own, in thread order: an answer to a reply sits inside that reply's panel, inset on
/// both sides, and the replies to the note line up.
#[trial]
fn a_pop_up_nests_each_answer_in_the_panel_of_the_reply_it_answers() {
let message = |id: u64, author: &'static str, text: &'static str, depth: usize| NotePopupMessage {
id,
title: "Sticky Note",
author,
text,
modified: None,
depth,
editable: depth == 0,
};
let thread = [message(1, "Ana", "First", 0), message(2, "Bo", "Second", 1), message(3, "Cy", "Second, first answer", 2), message(4, "Di", "Third", 1)];
let mut drafts = NoteDrafts::default();
let mut fixture = Fixture::new(move |ui| {
let _ = NotePopup::new(1, "Note", Rect::from_min_size(pos2(100.0, 100.0), vec2(320.0, 600.0)), &thread, &mut drafts).show(ui);
});
fixture.room(vec2(1000.0, 800.0)).settle();
let panel = |author: &str| fixture.by_label(&format!("Comment by {author}")).unwrap_or_else(|| panic!("{author}'s reply panel")).rect;
let (second, answer, third) = (panel("Bo"), panel("Cy"), panel("Di"));
assert!(second.bottom() <= third.top(), "thread order: {second:?} then {third:?}");
assert!(second.contains_rect(answer), "the answer sits inside its reply's panel: {second:?} holds {answer:?}");
assert!(answer.left() > second.left() && answer.right() < second.right(), "inset on both sides: {second:?} {answer:?}");
assert!((third.left() - second.left()).abs() < SLACK && (third.right() - second.right()).abs() < SLACK, "replies to the note line up");
}
/// The host of one composer: it shows the composer until it posts or cancels.
struct ComposerHost {
open: Cell<bool>,
@@ -130,6 +157,25 @@ struct ComposerHost {
/// Where a press lands outside the composer's card.
const OUTSIDE: egui::Pos2 = egui::Pos2::new(700.0, 550.0);
/// A composer's hint names its field; without one the field is "Add a comment".
#[trial]
fn a_composer_hint_names_its_field() {
for hint in [Some("Text to insert"), None] {
let mut draft = String::new();
let mut fixture = Fixture::new(move |ui| {
let composer = CommentComposer::new(Some(pos2(200.0, 200.0)), &mut draft);
let _ = match hint {
Some(hint) => composer.hint(hint),
None => composer,
}
.show(ui);
});
fixture.room(vec2(800.0, 600.0)).settle();
let name = hint.unwrap_or("Add a comment");
assert!(fixture.by_label(name).is_some(), "the field is named {name}");
}
}
/// `ComposerClose::OnPostOrCancel` keeps the card open on a press outside and closes it on Post or Cancel; the default
/// closes it on the press outside.
#[trial]
+19
View File
@@ -1070,6 +1070,25 @@ fn prompt_id() -> craft_ui::dialog::DialogId {
#[cfg(feature = "screen-testing")]
impl Updater {
/// An updater for `app`, running `version`, whose update to `release` has installed and waits for the app to close,
/// as a finished installation leaves it, for a screen test of the app's Restart to Update path: a requested check
/// reports [`Status::Ready`], [`Self::restart_to_update`] asks the app to close, and the exit runs `restart` in place
/// of the install helper. Nothing checks, downloads or installs. The close the installation asked for as it finished
/// is taken as answered, so the app is asked to close only after Restart to Update. A `restart` that fails is
/// recorded as a failed update: give the updater [`Self::with_paths`] so the record stays out of the app's folders.
pub fn ready_for_tests(
app: &'static App,
version: impl Into<String>,
release: Release,
restart: impl FnOnce() -> Result<(), String> + Send + 'static,
) -> Self {
let mut updater = Self::new(app, version);
updater.installed = true;
updater.known = Some((release.clone(), true));
updater.restart = Some((Restart::later(restart), release));
updater
}
/// Waits for the running check's answer on its channel (its thread always sends one, or ends
/// and closes the channel), then hands it to `tick` as a pass would; then does the same for
/// each offer still being inspected, until none is left (tests).
+24 -1
View File
@@ -8,7 +8,7 @@ use craft_update::pins::{Pins, VersionTrack};
use craft_update::release::Release;
use craft_update::stack_dialogs::UpdatePromptDialog;
use craft_update::suite::PHOTOCRAFT;
use craft_update::updater::{CheckSource, Status, Updater};
use craft_update::updater::{Action, CheckSource, Status, Updater};
use std::cell::RefCell;
use std::path::Path;
use std::rc::Rc;
@@ -59,6 +59,29 @@ fn a_request_during_the_startup_check_is_not_lost() {
assert_eq!(u.status(), &Status::UpToDate);
}
/// A ready updater built for a screen test reports Ready to a requested check, asks the app to close only on Restart
/// to Update while the app may close, and starts its helper once, at the exit.
#[trial]
fn a_ready_updater_closes_on_restart_and_starts_its_helper_at_the_exit() {
let (_fixture, dialogs) = rig(DialogHost::new());
let started = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let helper = started.clone();
let mut u = Updater::ready_for_tests(&PHOTOCRAFT, "0.1.0", newer(), move || {
helper.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(())
})
.with_pins_path(no_pins());
u.check_now();
assert_eq!(u.status(), &Status::Ready, "a requested check finds the update ready");
assert_eq!(u.run(&mut dialogs.borrow_mut(), true), Action::None, "nothing closes the app before Restart to Update");
u.restart_to_update();
assert_eq!(u.run(&mut dialogs.borrow_mut(), false), Action::None, "unsaved work holds the close");
assert_eq!(u.run(&mut dialogs.borrow_mut(), true), Action::Close, "Restart to Update asks the app to close");
assert_eq!(started.load(std::sync::atomic::Ordering::SeqCst), 0, "the helper waits for the exit");
drop(u);
assert_eq!(started.load(std::sync::atomic::Ordering::SeqCst), 1, "the exit starts the helper once");
}
#[trial]
fn a_panicking_check_is_an_error_not_a_hang() {
let ctx = ctx();