panels-w13: net change of 2 commits

- panels-w13: written from its sheet
- panels-w13: written by an agent
This commit is contained in:
Dylan M. Taylor
2026-11-27 14:51:31 +00:00
parent 8e5fad6e42
commit 066dbb980c
6 changed files with 559 additions and 301 deletions
+1 -20
View File
@@ -21,15 +21,7 @@ fn harness() -> (Harness<'static, SlideApp>, usize) {
s.close_document(1);
s.set_active(0);
s.execute("review.compare", &json!({"name": "Q3 review.deckcraft", "data": rev})).unwrap();
// P3(panels-w13): sh.A2
let app = SlideApp::new_base(s, Services::default());
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = crate::test_harness::harness(s, Services::default());
h.run_steps(4);
(h, n)
}
@@ -62,14 +54,3 @@ fn reject_all_empties_the_pane_and_keeps_the_deck() {
assert_eq!(st.doc.slides.len(), n);
assert!(h.query_by_label("No differences left.").is_some());
}
#[test]
#[ignore = "writes a screenshot for review"]
fn screenshot() {
let _gpu = crate::gpu_lock::gpu_lock();
let (mut h, _) = harness();
// Review tab.
h.state_mut().ui.tab = "Review".into();
h.run_steps(4);
h.render().unwrap().save("/tmp/compare.png").unwrap();
}
+285 -152
View File
@@ -1,172 +1,305 @@
use super::{Align2, Color32, CornerRadius, Sense, SlideApp, Stroke, Tokens, Ui, Value, json, run, theme, vec2};
/// Review › Compare: the revised copy's slide-level changes; click to go there, Accept to take it,
/// Reject to drop it.
pub(super) fn revisions(app: &mut SlideApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let Ok(v) = app.session.execute("review.revisions", &json!({})) else {
ui.label(egui::RichText::new("Compare this presentation with a revised copy from Review › Compare.").color(t.text_dim));
return;
};
let changes = v["changes"].as_array().cloned().unwrap_or_default();
ui.label(egui::RichText::new(format!("Compared with {}", v["name"].as_str().unwrap_or("?"))).color(t.text_dim));
if v["byPosition"].as_bool() == Some(true) {
ui.label(egui::RichText::new("Not a copy of this presentation: slides are matched by position.").size(11.0).color(t.text_faint));
}
ui.add_space(4.0);
if changes.is_empty() {
ui.label("No differences left.");
if ui.button("End Review").clicked() {
run(app, "review.endCompare", json!({}));
app.ui.pane = None;
}
return;
}
ui.horizontal(|ui| {
if ui.button(format!("Accept All ({})", changes.len())).clicked() {
run(app, "review.accept", json!({"all": true}));
}
if ui.button(format!("Reject All ({})", changes.len())).clicked() {
run(app, "review.reject", json!({"all": true}));
}
});
ui.separator();
for (i, c) in changes.iter().enumerate() {
let slide = c["slide"].as_u64().unwrap_or(0);
let (head, col) = match c["kind"].as_str().unwrap_or("") {
"inserted" => (format!("Slide inserted after {slide}"), Color32::from_rgb(0x2E, 0xA3, 0x6F)),
"deleted" => (format!("Slide {} deleted", slide.saturating_add(1)), Color32::from_rgb(0xD8, 0x3F, 0x6B)),
_ => (format!("Slide {} changed", slide.saturating_add(1)), Color32::from_rgb(0x2E, 0x6F, 0xD8)),
};
egui::Frame::NONE.fill(t.chrome).corner_radius(CornerRadius::same(6)).inner_margin(egui::Margin::same(8)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(vec2(4.0, 16.0), Sense::hover());
ui.painter().rect_filled(r, CornerRadius::same(2), col);
if ui.link(egui::RichText::new(&head).font(theme::bold(12.5))).clicked() {
let max = app.session.active().map(|d| d.doc.slides.len().saturating_sub(1)).unwrap_or(0);
run(app, "slide.go", json!({"index": (slide as usize).min(max)}));
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button("Reject").clicked() {
run(app, "review.reject", json!({"index": i}));
}
if ui.small_button("Accept").clicked() {
run(app, "review.accept", json!({"index": i}));
}
});
});
for d in c["details"].as_array().into_iter().flatten().filter_map(Value::as_str).take(8) {
ui.label(egui::RichText::new(format!("• {d}")).size(11.5).color(t.text_dim));
}
});
ui.add_space(4.0);
}
}
use super::{SlideApp, Ui, json, run};
// PLAN: assumed chrono = { workspace = true } in normal dependencies (shell-w11)
use chrono::DateTime;
use craft::i18n::Word;
use craft::review::ui::comments::CommentsForm;
use craft::review::ui::{CommentEdit, CommentsHeader, CommentsPanel};
use craft::review::{CommentAnchor, CommentMessage, CommentThread, ThreadId};
use craft::ui::buttons::Button;
use craft::ui::contract::{Outcome as _, Show as _};
use craft::ui::display::Divider;
use craft::ui::primitives::SubmitKey;
use deckcraft_model::{Comment, Presentation};
/// Shows slide comments with the presentation's reply-only editing commands.
pub(super) fn comments(app: &mut SlideApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
if ui.button("+ New Comment").clicked() {
app.dialog = Some(crate::dialogs::Dialog::new("comment"));
if Button::new(Word::plain("+ New Comment")).show(ui).response().clicked() {
app.open_dialog("comment", json!({}));
}
ui.separator();
let threads: Vec<(usize, Vec<deckcraft_model::Comment>)> = app
.session
.active()
.map(|st| st.doc.slides.iter().enumerate().filter(|(_, sl)| !sl.comments.is_empty()).map(|(i, sl)| (i, sl.comments.clone())).collect())
.unwrap_or_default();
if threads.is_empty() {
ui.label(egui::RichText::new("No comments.").color(t.text_dim));
return;
}
let focus = app.ui.comment_focus;
for (si, list) in threads {
ui.label(egui::RichText::new(format!("Slide {}", si + 1)).font(theme::bold(12.0)).color(t.text_dim));
ui.add_space(2.0);
for (i, c) in list.iter().enumerate() {
comment_card(app, ui, si, i, c, focus == Some((si, i)));
ui.add_space(6.0);
}
Divider::horizontal().show(ui);
let threads = app.session.active().map(|st| threads(&st.doc)).unwrap_or_default();
let now = web_time::SystemTime::now()
.duration_since(web_time::UNIX_EPOCH)
.ok()
.and_then(|elapsed| i64::try_from(elapsed.as_secs()).ok())
.unwrap_or(0);
let out = CommentsPanel::new(Word::plain("Comments"), &threads, &mut app.comments_pane)
.header(CommentsHeader::Hosted)
.form(CommentsForm::Replies)
.page_label(|slide| slide.saturating_add(1).to_string())
.reply_submit(SubmitKey::Enter)
.now(now)
.show(ui);
// Each pass applies only the edits its panel reports; a rerun has no replay queue.
for edit in out.edits {
apply(app, edit);
}
}
// P3(panels-w13): pn.A13
fn thread_id(slide: usize, index: usize) -> Option<ThreadId> {
// Checked components keep distinct comments distinct on both native and wasm targets.
let slide = u64::from(u32::try_from(slide).ok()?);
let index = u64::from(u32::try_from(index).ok()?);
Some(ThreadId((slide << 32) | index))
}
fn location(app: &SlideApp, thread: ThreadId) -> Option<(usize, usize)> {
let slide = usize::try_from(thread.0 >> 32).ok()?;
let index = usize::try_from(thread.0 & u64::from(u32::MAX)).ok()?;
app.session.active()?.doc.slides.get(slide)?.comments.get(index)?;
Some((slide, index))
}
/// Focuses the slide's comment and reveals its card once, including a folded group.
// PLAN: plan error: panels-w5 must expose panels::comments for ribbon-w9 and shell-w4 to call focus_comment.
pub(crate) fn focus_comment(app: &mut SlideApp, slide: usize, index: usize) {
let Some(thread) = thread_id(slide, index) else { return };
let _ = app.run("slide.go", json!({"index": slide}));
app.ui.comment_focus = Some((slide, index));
app.comments_pane.reveal(thread);
}
/// Render one comment card, preserving its slide/index identity and focus state through actions.
fn comment_card(app: &mut SlideApp, ui: &mut Ui, slide: usize, index: usize, c: &deckcraft_model::Comment, focused: bool) {
let t = Tokens::get(ui.ctx());
let stroke = if focused { Stroke::new(2.0, t.accent) } else { Stroke::NONE };
let shown = egui::Frame::NONE
.fill(if focused { t.selected } else { t.chrome })
.stroke(stroke)
.corner_radius(CornerRadius::same(8))
.inner_margin(egui::Margin::same(8))
.show(ui, |ui| {
ui.set_width(ui.available_width());
let head = ui.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::hover());
ui.painter().circle_filled(r.center(), 12.0, t.accent);
ui.painter().text(r.center(), Align2::CENTER_CENTER, &c.initials, theme::bold(11.0), Color32::WHITE);
ui.vertical(|ui| {
let name = ui.add(egui::Label::new(egui::RichText::new(&c.author).font(theme::bold(12.5))).sense(Sense::click()));
if name.clicked() {
focus_comment(app, slide, index);
}
let when = c.date.replace('T', " ").trim_end_matches('Z').to_string();
let when = if c.resolved { format!("{when} · Resolved") } else { when };
ui.label(egui::RichText::new(when).size(10.5).color(t.text_faint));
});
});
if head.response.clicked() {
fn message(comment: &Comment, deletable: bool) -> CommentMessage {
CommentMessage {
author: comment.author.clone(),
created: DateTime::parse_from_rfc3339(&comment.date).map(|date| date.timestamp()).unwrap_or(0),
modified: None,
text: comment.text.clone(),
reactions: Vec::new(),
read: true,
deletable,
}
}
fn threads(doc: &Presentation) -> Vec<CommentThread> {
doc.slides
.iter()
.enumerate()
.flat_map(|(slide, page)| {
page.comments.iter().enumerate().filter_map(move |(index, comment)| {
Some(CommentThread {
id: thread_id(slide, index)?,
anchor: CommentAnchor::Slide { slide, at: Some([comment.x, comment.y]) },
kind: None,
color: None,
messages: std::iter::once(message(comment, true)).chain(comment.replies.iter().map(|reply| message(reply, false))).collect(),
statuses: Vec::new(),
reply_statuses: Vec::new(),
marked: false,
locked: false,
resolved: comment.resolved,
})
})
})
.collect()
}
fn apply(app: &mut SlideApp, edit: CommentEdit) {
match edit {
CommentEdit::Select(selected) => {
if let Some((slide, index)) = selected.first().and_then(|thread| location(app, *thread)) {
focus_comment(app, slide, index);
} else {
app.ui.comment_focus = None;
}
let body = ui.add(egui::Label::new(&c.text).sense(Sense::click()));
if body.clicked() {
}
CommentEdit::Reply { thread, text, .. } => {
if let Some((slide, index)) = location(app, thread) {
focus_comment(app, slide, index);
run(app, "comment.reply", json!({"index": index, "text": text}));
}
for r in &c.replies {
ui.label(egui::RichText::new(format!("↳ {}: {}", r.author, r.text)).color(t.text_dim));
}
CommentEdit::Resolve { thread, resolved, .. } => {
if let Some((slide, index)) = location(app, thread) {
focus_comment(app, slide, index);
run(app, "comment.resolve", json!({"index": index, "resolved": resolved}));
}
}
CommentEdit::Delete { thread, index: 0, .. } => {
let Some((slide, index)) = location(app, thread) else { return };
if app.run("slide.go", json!({"index": slide})).is_err() || app.run("comment.delete", json!({"index": index})).is_err() {
return;
}
match app.ui.comment_focus {
Some((fs, fi)) if fs == slide && fi == index => app.ui.comment_focus = None,
Some((fs, fi)) if fs == slide && fi > index => app.ui.comment_focus = Some((fs, fi - 1)),
_ => {}
}
if let Some(thread) = app.ui.comment_focus.and_then(|(slide, index)| thread_id(slide, index)) {
app.comments_pane.reveal(thread);
} else {
app.comments_pane.selected = Default::default();
}
}
// Replies exposes no add, inline edit, reply deletion, status, clipboard or reaction actions.
CommentEdit::Add { .. }
| CommentEdit::Edit { .. }
| CommentEdit::Delete { .. }
| CommentEdit::SetStatus { .. }
| CommentEdit::Mark { .. }
| CommentEdit::CopyText { .. }
| CommentEdit::React { .. }
| CommentEdit::CopyLink { .. }
| CommentEdit::MarkUnread { .. } => {}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use craft::review::ui::{CommentsPanelState, CommentsWords};
use craft::ui::contract::Role;
use craft::ui::runtime::env::Env;
use craft::ui::testing::Fixture;
use deckcraft_engine::Session;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
#[derive(Clone, Copy, Debug)]
enum Action {
Select,
Reply,
Resolve,
Reopen,
Delete,
}
fn panel_edits(doc: &Presentation, target: (usize, usize), action: Action, reply: &str) -> Vec<CommentEdit> {
let id = thread_id(target.0, target.1).unwrap();
let thread = threads(doc).into_iter().find(|thread| thread.id == id).unwrap();
let mut state = CommentsPanelState::default();
if !matches!(action, Action::Select) {
state.reveal(id);
}
let edits = Rc::new(RefCell::new(Vec::new()));
let reported = edits.clone();
let labels = Rc::new(RefCell::new(None));
let words = labels.clone();
let mut fixture = Fixture::new(move |ui| {
*words.borrow_mut() = Some(Env::of(ui).words::<CommentsWords>());
let out = CommentsPanel::new("Comments", std::slice::from_ref(&thread), &mut state)
.header(CommentsHeader::Hosted)
.form(CommentsForm::Replies)
.reply_submit(SubmitKey::Enter)
.show(ui);
reported.borrow_mut().extend(out.edits);
if ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the trial reruns the pass");
}
// The buttons are laid out first, from the right, so the reply field takes exactly the
// width they leave. A fixed allowance overflowed the card and widened the pane every
// frame until it stuck at its widest (#1431).
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button("🗑").clicked() {
let _ = app.run("slide.go", json!({"index": slide}));
let _ = app.run("comment.delete", json!({"index": index}));
match app.ui.comment_focus {
Some((fs, fi)) if fs == slide && fi == index => app.ui.comment_focus = None,
Some((fs, fi)) if fs == slide && fi > index => app.ui.comment_focus = Some((fs, fi - 1)),
_ => {}
}
}
if ui.small_button(if c.resolved { "Reopen" } else { "Resolve" }).clicked() {
focus_comment(app, slide, index);
run(app, "comment.resolve", json!({"index": index, "resolved": !c.resolved}));
}
let id = ui.scope_id().with(("reply", slide, index));
let mut txt: String = ui.data_mut(|d| d.get_temp(id).unwrap_or_default());
let r = ui.add(egui::TextEdit::singleline(&mut txt).hint_text("Reply…").desired_width(ui.available_width()));
if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && !txt.trim().is_empty() {
focus_comment(app, slide, index);
run(app, "comment.reply", json!({"index": index, "text": txt}));
txt.clear();
}
ui.data_mut(|d| d.insert_temp(id, txt));
});
});
});
if focused {
let key = egui::Id::unique("comment-focus-scrolled");
let seen = ui.data(|d| d.get_temp::<(usize, usize)>(key));
if seen != Some((slide, index)) {
ui.scroll_to_rect(shown.response.rect, Some(egui::Align::Center));
ui.data_mut(|d| d.insert_temp(key, (slide, index)));
fixture.settle();
let words = labels.borrow().as_ref().unwrap().clone();
match action {
Action::Select => {
let card = fixture
.by_role(Role::TREE_ITEM)
.into_iter()
.find(|row| fixture.tree().name_of(row.node).is_some_and(|name| name.contains(&doc.slides[target.0].comments[target.1].text)))
.unwrap();
fixture.click(&card).settle();
}
Action::Reply => {
let button = fixture.by_label(words.reply_button.as_str()).unwrap();
fixture.click(&button).type_text(reply).settle();
let post = fixture.by_label(words.post.as_str()).unwrap();
fixture.click(&post).settle();
}
Action::Resolve | Action::Reopen | Action::Delete => {
let label = if matches!(action, Action::Resolve) {
&words.resolve
} else if matches!(action, Action::Reopen) {
&words.reopen
} else {
&words.delete
};
let button = fixture.by_label(label.as_str()).unwrap();
fixture.click(&button).settle();
}
}
edits
.borrow_mut()
.drain(..)
.filter(|edit| {
matches!(
(action, edit),
(Action::Select, CommentEdit::Select(_))
| (Action::Reply, CommentEdit::Reply { .. })
| (Action::Resolve | Action::Reopen, CommentEdit::Resolve { .. })
| (Action::Delete, CommentEdit::Delete { .. })
)
})
.collect()
}
#[test]
fn comment_edits_send_their_commands_and_keep_the_focus() {
let cases = [
(Action::Select, (1, 1), (0, 2)),
(Action::Reply, (1, 1), (0, 2)),
(Action::Resolve, (1, 1), (0, 2)),
(Action::Reopen, (1, 1), (0, 2)),
(Action::Delete, (0, 0), (0, 2)),
(Action::Delete, (0, 2), (0, 2)),
(Action::Delete, (1, 0), (0, 2)),
];
for (action, target, focus) in cases {
let mut session = Session::with_new();
session.execute("slide.new", &json!({"layout": "blank"})).unwrap();
for (slide, count) in [(0, 3), (1, 2)] {
session.execute("slide.go", &json!({"index": slide})).unwrap();
for index in 0..count {
session.execute("comment.add", &json!({"text": format!("Note {slide}/{index}")})).unwrap();
}
}
if matches!(action, Action::Reopen) {
session.execute("slide.go", &json!({"index": target.0})).unwrap();
session.execute("comment.resolve", &json!({"index": target.1, "resolved": true})).unwrap();
}
session.execute("slide.go", &json!({"index": focus.0})).unwrap();
let mut harness = crate::test_harness::harness(session, crate::Services::default());
focus_comment(harness.state_mut(), focus.0, focus.1);
let before = harness.state().session.active().unwrap().doc.clone();
let reply = "A reply on the other slide";
for edit in panel_edits(&before, target, action, reply) {
apply(harness.state_mut(), edit);
}
let app = harness.state();
let st = app.session.active().unwrap();
let original = &before.slides[target.0].comments[target.1];
match action {
Action::Select => assert!(Arc::ptr_eq(&before, &st.doc)),
Action::Reply => {
let edited = &st.doc.slides[target.0].comments[target.1];
assert_eq!(edited.replies.len(), original.replies.len() + 1, "a reply is applied once across both passes");
assert_eq!(edited.replies.last().unwrap().text, reply);
}
Action::Resolve | Action::Reopen => assert_ne!(st.doc.slides[target.0].comments[target.1].resolved, original.resolved),
Action::Delete => assert!(st.doc.slides[target.0].comments.len() < before.slides[target.0].comments.len()),
}
for (slide, page) in before.slides.iter().enumerate() {
let mut expected = page.comments.clone();
if slide == target.0 {
match action {
Action::Delete => {
expected.remove(target.1);
}
Action::Reply => {
expected[target.1].replies = st.doc.slides[slide].comments[target.1].replies.clone();
}
Action::Resolve | Action::Reopen => expected[target.1].resolved = !expected[target.1].resolved,
Action::Select => {}
}
}
assert_eq!(st.doc.slides[slide].comments, expected, "{action:?} edits only its target");
}
let wanted = if matches!(action, Action::Delete) { focus } else { target };
let text = &before.slides[wanted.0].comments[wanted.1].text;
let expected = st.doc.slides[wanted.0].comments.iter().position(|comment| &comment.text == text).map(|index| (wanted.0, index));
assert_eq!(app.ui.comment_focus, expected, "{action:?} preserves comment identity through index shifts");
assert_eq!(st.selection.slide, target.0, "the command acts on the card's slide");
assert_eq!(app.comments_pane.selected.lead, expected.and_then(|(slide, index)| thread_id(slide, index)));
}
}
}
+110 -83
View File
@@ -1,94 +1,121 @@
use super::{Color32, CornerRadius, Rect, Sense, SlideApp, Stroke, Tokens, Ui, json, pos2, run, vec2};
use super::{SlideApp, Ui, json, run};
use craft::behavior::keyed;
use craft::i18n::Word;
use craft::ui::contract::{ActivateOn, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _};
use craft::ui::display::{Shade, Text};
use craft::ui::list::ThumbAspect;
use craft::ui::primitives::{
ContentPainterCx, LoadedPicture, Priority, Revision, StateLook, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails,
};
use craft::ui::runtime::env::Label;
use craft::ui::tile_grid::{CaptionPlace, ColumnRule, Tile, TileGrid, TilePartEvent};
use deckcraft_engine::Selection;
use deckcraft_model::Presentation;
use egui::Rect;
use std::sync::Arc;
/// Design Ideas: offline suggestions — the current slide in each theme and layout variations.
/// Rendered idea thumbnails, kept until the deck, slide or pane width changes (rendering eight
/// slides every frame made the pane cost ~25 ms a frame).
#[derive(Clone, Default)]
struct IdeaThumbs {
key: (u64, u64, usize, u32),
tex: Vec<(String, egui::TextureHandle, u32, u32)>,
doc: Arc<Presentation>,
selection: Selection,
slide: usize,
uid: u64,
revision: u64,
}
/// Render per-slide Design Ideas and whole-presentation theme thumbnails; a click runs
/// `design.applyIdea` or `design.theme`.
impl ThumbSource<String> for IdeaThumbs {
fn revision(&self, _key: &String, _request: &ThumbRequest) -> Revision {
Revision::of(&(self.uid, self.revision, self.slide))
}
fn render(&self, key: &String, request: &ThumbRequest) -> ThumbRender {
let (doc, selection, slide, key, side) = (self.doc.clone(), self.selection.clone(), self.slide, key.clone(), request.side);
ThumbRender::Later(Box::new(move |cancel| {
if cancel.is_cancelled() {
return Ok(LoadedPicture::Blank);
}
let mut doc = (*doc).clone();
if let Some(id) = key.strip_prefix("layout:") {
if deckcraft_engine::cmd::ideas::apply_idea(&mut doc, &selection, slide, id).is_err() {
return Ok(LoadedPicture::Blank);
}
} else if let Some(name) = key.strip_prefix("theme:") {
let Some(theme) = deckcraft_model::theme::builtin_themes().into_iter().find(|theme| theme.name == name) else {
return Ok(LoadedPicture::Blank);
};
if let Some(master) = doc.masters.first_mut() {
Arc::make_mut(master).theme = theme;
}
} else {
return Ok(LoadedPicture::Blank);
}
if cancel.is_cancelled() {
return Ok(LoadedPicture::Blank);
}
let (width, height) = (doc.slide_size.width.max(1.0), doc.slide_size.height.max(1.0));
let scale = f64::from(side) / width.max(height);
let size = ((width * scale).round().max(1.0) as u32, (height * scale).round().max(1.0) as u32);
let image = deckcraft_render::render_slide(&doc, slide, &deckcraft_render::RenderOpts { scale, size: Some(size), ..Default::default() });
Ok(LoadedPicture::Image(crate::textures::to_color_image(&image, false)))
}))
}
}
fn paint(cx: &ContentPainterCx<'_>, rect: Rect, key: &String, thumbs: &Thumbnails<String>, source: &IdeaThumbs) {
let request = ThumbRequest::for_cell(rect.width().max(rect.height()), cx.painter.ctx().pixels_per_point());
let state = thumbs.state(cx.painter.ctx(), source, key, &request, Priority::VISIBLE);
thumbs.paint(cx, rect, &state, &ThumbPaint::default().checker(false).states(StateLook::Captioned));
}
fn grid(
ui: &mut Ui,
label: Word,
entries: &[(String, Label)],
source: &IdeaThumbs,
thumbs: &Thumbnails<String>,
) -> Vec<CollectionEvent<String, TilePartEvent>> {
let aspect = (source.doc.slide_size.width.max(1.0) / source.doc.slide_size.height.max(1.0)) as f32;
let order = keyed(entries, |entry| entry.0.clone());
TileGrid::<String>::new(label)
.column_rule(ColumnRule::Exactly(1))
.caption(CaptionPlace::None)
.aspect(aspect)
.select(SelectMode::None)
.activate(ActivateOn::Click)
.natural_height(true)
.show_items(ui, &order, &mut |key, item| {
let tip = entries[item.at].1.clone();
let key = key.clone();
Tile::new(tip.clone()).tooltip(tip).thumb(ThumbAspect::from_ratio(aspect), move |cx, rect| paint(cx, rect, &key, thumbs, source))
})
.response
.events
}
/// Shows layout ideas and presentation themes using background-rendered document copies.
pub(super) fn designer(app: &mut SlideApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
ui.label(egui::RichText::new("Pick a design for this slide. Ideas are generated on your device.").color(t.text_dim));
ui.add_space(6.0);
Text::new(Word::plain("Pick a design for this slide. Ideas are generated on your device.")).shade(Shade::Muted).show(ui);
let Some(st) = app.session.active() else { return };
let doc = st.doc.clone();
let idx = st.selection.slide;
let sel = st.selection.clone();
let key_doc = (st.uid, st.revision);
let w = ui.available_width() - 8.0;
let ppp = ui.ctx().pixels_per_point();
let px = (w * ppp).round().max(16.0) as u32;
let ideas = deckcraft_engine::cmd::ideas::ideas_for(&doc, idx);
let themes = deckcraft_model::theme::builtin_themes();
let cache_id = egui::Id::unique("design-idea-thumbs");
let key = (key_doc.0, key_doc.1, idx, px);
let mut cache: IdeaThumbs = ui.ctx().data_mut(|d| d.get_temp(cache_id)).unwrap_or_default();
if cache.key != key || cache.tex.is_empty() {
cache = IdeaThumbs { key, tex: vec![] };
let mut render = |name: String, d: &deckcraft_model::Presentation| {
let (px, h) = crate::textures::fit_size(
(px, (px as f64 * d.slide_size.height / d.slide_size.width.max(1.0)).clamp(1.0, 1e9) as u32),
crate::textures::max_side(ui.ctx()),
);
let img = deckcraft_render::render_slide(
d,
idx,
&deckcraft_render::RenderOpts { scale: px as f64 / d.slide_size.width.max(1.0), size: Some((px, h)), ..Default::default() },
);
let tex = crate::textures::upload_editor(ui.ctx(), format!("idea-{name}"), crate::textures::to_color_image(&img, false));
cache.tex.push((name, tex, px, h));
};
for (id, _) in &ideas {
let mut d = (*doc).clone();
if deckcraft_engine::cmd::ideas::apply_idea(&mut d, &sel, idx, id).is_ok() {
render(format!("layout:{id}"), &d);
}
}
for th in &themes {
let mut d = (*doc).clone();
if let Some(m) = d.masters.first_mut() {
std::sync::Arc::make_mut(m).theme = th.clone();
}
render(format!("theme:{}", th.name), &d);
}
ui.ctx().data_mut(|d| d.insert_temp(cache_id, cache.clone()));
}
let thumb = |ui: &mut Ui, name: &str, tip: &str| -> bool {
let Some((_, tex, tw, th)) = cache.tex.iter().find(|e| e.0 == name) else { return false };
let (r, resp) = ui.allocate_exact_size(vec2(w, w * *th as f32 / (*tw).max(1) as f32), Sense::click());
// On the physical pixel grid, one texel per device pixel (#184).
let at = crate::textures::device_pixel_rect(r, ppp);
let at = Rect::from_min_size(at.min, vec2(*tw as f32 / ppp, *th as f32 / ppp));
ui.painter().image(tex.id(), at, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
ui.painter().rect_stroke(
at,
CornerRadius::same(2),
Stroke::new(if resp.hovered() { 2.5 } else { 1.0 }, if resp.hovered() { t.accent } else { t.border }),
egui::StrokeKind::Outside,
);
let clicked = resp.on_hover_text(tip).clicked();
ui.add_space(8.0);
clicked
};
let source = IdeaThumbs { doc: st.doc.clone(), selection: st.selection.clone(), slide: st.selection.slide, uid: st.uid, revision: st.revision };
let ideas: Vec<_> = deckcraft_engine::cmd::ideas::ideas_for(&source.doc, source.slide)
.into_iter()
.map(|(id, tip)| (format!("layout:{id}"), Label::from(Word::plain(tip))))
.collect();
let themes: Vec<_> =
deckcraft_model::theme::builtin_themes().into_iter().map(|theme| (format!("theme:{}", theme.name), Label::from(theme.name))).collect();
let thumbs = Thumbnails::in_context(ui.ctx(), "deckcraft.ideas", ThumbnailOptions::new());
if ideas.is_empty() {
ui.label(egui::RichText::new("Add a title with a picture or some text to get layout ideas.").color(t.text_dim));
Text::new(Word::plain("Add a title with a picture or some text to get layout ideas.")).shade(Shade::Muted).show(ui);
}
for (id, label) in &ideas {
if thumb(ui, &format!("layout:{id}"), label) {
run(app, "design.applyIdea", json!({"id": id}));
}
}
ui.add_space(4.0);
ui.label(egui::RichText::new("Themes (whole presentation)").color(t.text_dim));
ui.add_space(4.0);
for th in &themes {
if thumb(ui, &format!("theme:{}", th.name), &th.name) {
run(app, "design.theme", json!({"name": th.name}));
let mut events = grid(ui, Word::plain("Layout ideas"), &ideas, &source, &thumbs);
Text::new(Word::plain("Themes (whole presentation)")).shade(Shade::Muted).show(ui);
events.extend(grid(ui, Word::plain("Presentation themes"), &themes, &source, &thumbs));
for event in events {
if let CollectionEvent::Activate(key) = event {
if let Some(id) = key.strip_prefix("layout:") {
run(app, "design.applyIdea", json!({"id": id}));
} else if let Some(name) = key.strip_prefix("theme:") {
run(app, "design.theme", json!({"name": name}));
}
}
}
}
+63
View File
@@ -0,0 +1,63 @@
use super::{SlideApp, Ui, Value, json, run};
use craft::i18n::Word;
use craft::review::ui::RevisionsPanel;
use craft::review::{Revision, RevisionAction, RevisionKind};
use craft::ui::contract::Show as _;
use craft::ui::display::{Shade, Text};
use craft::ui::runtime::env::Env;
craft::ui::words! {
struct RevisionHeadings {
inserted: template "deckcraft.slideInserted" = "Slide inserted after {slide}";
deleted: template "deckcraft.slideDeleted" = "Slide {slide} deleted";
changed: template "deckcraft.slideChanged" = "Slide {slide} changed";
}
}
/// Shows compare results and applies the review actions to their original engine indices.
// PLAN: assumed revisions::revisions(app: &mut SlideApp, ui: &mut Ui) in panels.rs dispatch (panels-w5)
pub(super) fn revisions(app: &mut SlideApp, ui: &mut Ui) {
let Ok(value) = app.session.execute("review.revisions", &json!({})) else {
Text::new(Word::plain("Compare this presentation with a revised copy from Review › Compare.")).shade(Shade::Muted).show(ui);
return;
};
let words = Env::of(ui).words::<RevisionHeadings>();
let changes = value["changes"].as_array().cloned().unwrap_or_default();
let revisions: Vec<_> = changes
.iter()
.map(|change| {
let slide = change["slide"].as_u64().unwrap_or(0);
let (kind, heading, number) = match change["kind"].as_str().unwrap_or("") {
"inserted" => (RevisionKind::Inserted, &words.inserted, slide),
"deleted" => (RevisionKind::Deleted, &words.deleted, slide.saturating_add(1)),
_ => (RevisionKind::Changed, &words.changed, slide.saturating_add(1)),
};
Revision {
kind,
heading: heading.fill(&[("slide", &number.to_string())]),
details: change["details"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(),
}
})
.collect();
let name = value["name"].as_str().unwrap_or("?");
let out = RevisionsPanel::new(Word::plain("Revisions"), name, &revisions).by_position(value["byPosition"].as_bool() == Some(true)).show(ui);
for action in out.actions {
match action {
RevisionAction::AcceptAll => run(app, "review.accept", json!({"all": true})),
RevisionAction::RejectAll => run(app, "review.reject", json!({"all": true})),
RevisionAction::Accept(index) => run(app, "review.accept", json!({"index": index})),
RevisionAction::Reject(index) => run(app, "review.reject", json!({"index": index})),
RevisionAction::Go(index) => {
if let Some(slide) = changes.get(index).and_then(|change| change["slide"].as_u64()).and_then(|slide| usize::try_from(slide).ok()) {
let last = app.session.active().map(|st| st.doc.slides.len().saturating_sub(1)).unwrap_or(0);
run(app, "slide.go", json!({"index": slide.min(last)}));
}
}
RevisionAction::EndReview => {
run(app, "review.endCompare", json!({}));
app.ui.pane = None;
}
_ => {}
}
}
}
+89 -25
View File
@@ -1,36 +1,100 @@
use super::{SlideApp, Tokens, Ui, json, run, theme};
use super::{SlideApp, Ui, json, run};
use craft::behavior::{ColumnKey, ColumnWidth, DisplayOrder, ItemSource};
use craft::i18n::Word;
use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, ColumnSpec, Props as _, SelectMode, Show as _, ShowCollection as _, Sizing};
use craft::ui::display::{Shade, Text};
use craft::ui::list::{List, ListRow};
use craft::ui::runtime::env::Env;
use craft::ui::text::TextField;
use deckcraft_engine::thesaurus::Sense;
use std::borrow::Cow;
/// Review › Thesaurus: look a word up; clicking a synonym puts it in place of the selected word
/// when editing text, otherwise looks that synonym up in turn.
craft::ui::words! {
struct ThesaurusWords {
no_synonyms: template "deckcraft.noSynonyms" = "No synonyms for \"{word}\".";
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum ThesaurusRow {
Head(usize),
Synonym(usize, usize),
}
struct ThesaurusRows<'a> {
senses: &'a [Sense],
rows: Vec<ThesaurusRow>,
}
impl DisplayOrder<ThesaurusRow> for ThesaurusRows<'_> {
fn len(&self) -> usize {
self.rows.len()
}
fn key(&self, at: usize) -> ThesaurusRow {
self.rows[at]
}
fn is_section(&self, at: usize) -> bool {
matches!(self.rows[at], ThesaurusRow::Head(_))
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
Some(Cow::Borrowed(match self.rows[at] {
ThesaurusRow::Head(sense) => &self.senses[sense].word,
ThesaurusRow::Synonym(sense, synonym) => &self.senses[sense].synonyms[synonym],
}))
}
}
impl ItemSource<ThesaurusRow> for ThesaurusRows<'_> {}
/// Looks up the caret word and inserts a picked synonym while text is being edited.
pub(super) fn thesaurus(app: &mut SlideApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let mut q = app.thesaurus_query.clone();
let edit = ui.add(egui::TextEdit::singleline(&mut q).hint_text("Search for a word").desired_width(f32::INFINITY));
if edit.changed() {
app.thesaurus_query = q.clone();
}
ui.add_space(6.0);
let senses = deckcraft_engine::thesaurus::lookup(&q);
if q.trim().is_empty() {
ui.label(egui::RichText::new("Select a word on the slide, or type one above.").color(t.text_dim));
let hint = Word::plain("Search for a word");
TextField::new(hint, Bind::bound(&mut app.thesaurus_query)).placeholder(hint).sizing(Sizing::FillWidth).show(ui);
let query = app.thesaurus_query.trim();
if query.is_empty() {
Text::new(Word::plain("Select a word on the slide, or type one above.")).shade(Shade::Muted).show(ui);
return;
}
let senses = deckcraft_engine::thesaurus::lookup(query);
if senses.is_empty() {
ui.label(egui::RichText::new(format!("No synonyms for \"{}\".", q.trim())).color(t.text_dim));
let words = Env::of(ui).words::<ThesaurusWords>();
Text::new(words.no_synonyms.fill(&[("word", query)])).shade(Shade::Muted).show(ui);
return;
}
let editing = app.session.active().is_some_and(|d| d.selection.text.is_some());
for sense in senses {
ui.label(egui::RichText::new(&sense.word).font(theme::bold(13.0)));
for syn in sense.synonyms {
let r = ui.add(egui::Button::new(&syn).frame(false)).on_hover_text(if editing { "Insert" } else { "Look up" });
if r.clicked() {
if editing {
run(app, "review.replaceWord", json!({"with": syn}));
}
app.thesaurus_query = syn;
let editing = app.session.active().is_some_and(|st| st.selection.text.is_some());
let rows = senses
.iter()
.enumerate()
.flat_map(|(sense, words)| {
std::iter::once(ThesaurusRow::Head(sense)).chain((0..words.synonyms.len()).map(move |synonym| ThesaurusRow::Synonym(sense, synonym)))
})
.collect();
let source = ThesaurusRows { senses: &senses, rows };
const WORD: ColumnKey = ColumnKey::new("word");
let out = List::<ThesaurusRow>::new(Word::plain("Synonyms"))
.select(SelectMode::None)
.activate(ActivateOn::Click)
.natural_height(true)
.sizing(Sizing::Fill)
.columns(vec![ColumnSpec::new(WORD, Word::plain("Word"), ColumnWidth::fill(1.0))])
.header(false)
.show_items(ui, &source, &mut |key, _| match *key {
ThesaurusRow::Head(sense) => ListRow::new(senses[sense].word.clone()).section_heading().space_above(sense > 0),
ThesaurusRow::Synonym(sense, synonym) => {
let text = senses[sense].synonyms[synonym].clone();
ListRow::new(text.clone()).cell(WORD, text).cell_tip(WORD, Word::plain(if editing { "Insert" } else { "Look up" }))
}
});
for event in out.events {
if let CollectionEvent::Activate(ThesaurusRow::Synonym(sense, synonym)) = event {
let synonym = &senses[sense].synonyms[synonym];
if editing {
run(app, "review.replaceWord", json!({"with": synonym}));
}
app.thesaurus_query.clone_from(synonym);
}
ui.add_space(6.0);
}
}
+11 -21
View File
@@ -1,40 +1,30 @@
//! Review › Thesaurus driven like a person: caret in a word, open the pane, click a synonym.
use deckcraft_engine::Session;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use crate::{Services, SlideApp};
use crate::Services;
#[test]
fn thesaurus_pane_swaps_the_word_at_the_caret() {
let _gpu = crate::gpu_lock::gpu_lock();
let word = "Goal";
let original = format!("Our {word} is growth.");
let synonym = deckcraft_engine::thesaurus::lookup(word)[0].synonyms[1].clone();
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
let id = s.execute("insert.textBox", &json!({"rect": [100, 100, 500, 50]})).unwrap()["id"].as_u64().unwrap();
s.execute("text.edit", &json!({"id": id})).unwrap();
s.execute("text.insert", &json!({"text": "Our Goal is growth."})).unwrap();
s.execute("text.insert", &json!({"text": original})).unwrap();
s.execute("text.edit", &json!({"id": id, "at": [0, 6]})).unwrap();
// P3(panels-w13): sh.A2
let mut app = SlideApp::new_base(s, Services::default());
app.ui.tab = "Review".into();
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = crate::test_harness::harness(s, Services::default());
h.state_mut().ui.tab = "Review".into();
h.run_steps(3);
h.get_by_label("Thesaurus").click();
h.run_steps(3);
assert_eq!(h.state().ui.pane.as_deref(), Some("thesaurus"));
assert_eq!(h.state().thesaurus_query, "Goal");
if let Ok(img) = h.render() {
let _ = img.save("/tmp/thesaurus.png");
}
h.get_by_label("Objective").click();
assert_eq!(h.state().thesaurus_query, word);
h.get_by_role_and_label(egui::accesskit::Role::ListItem, &synonym).click();
h.run_steps(3);
let text = h
.state()
@@ -46,8 +36,8 @@ fn thesaurus_pane_swaps_the_word_at_the_caret() {
.find(|x| x.id.0 as u64 == id)
.and_then(|x| x.text.as_ref())
.map(|t| t.paragraphs[0].text());
assert_eq!(text.as_deref(), Some("Our Objective is growth."));
assert_eq!(h.state().thesaurus_query, "Objective", "the pane follows the new word");
assert_eq!(text, Some(original.replace(word, &synonym)));
assert_eq!(h.state().thesaurus_query, synonym, "the pane follows the new word");
// Typing a word that isn't listed says so instead of showing nothing.
h.state_mut().thesaurus_query = "zzxq".into();