From 180aa09ba6258625f45d289011b7866f4deeda5a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 27 Nov 2026 14:51:32 +0000 Subject: [PATCH] panels-w6: net change of 2 commits - panels-w6: written by an agent - panels-w6: review fixes (review-1) --- crates/ui-egui/src/sorter.rs | 818 +++++++++++--------------- crates/ui-egui/src/sorter/ui_tests.rs | 354 +++++------ 2 files changed, 515 insertions(+), 657 deletions(-) diff --git a/crates/ui-egui/src/sorter.rs b/crates/ui-egui/src/sorter.rs index 5b9881c15..4ca006c27 100644 --- a/crates/ui-egui/src/sorter.rs +++ b/crates/ui-egui/src/sorter.rs @@ -2,37 +2,60 @@ use std::collections::HashSet; +use craft::behavior::{Selection, SelectionModel as _, keyed}; +use craft::text::ui::notes::NotesEditor; +use craft::ui::buttons::Button; +use craft::ui::contract::{ + Bind, BodyCx, CollectionEvent, Lazy, Pad, Props as _, ReorderRule, Scroll, Show as _, ShowCollection as _, ShowContainer as _, Sizing, + WordSetCx as _, +}; +use craft::ui::display::{Picture, Text}; +use craft::ui::layout_components::{Row, Stack}; +use craft::ui::list::ThumbAspect; +use craft::ui::menu::{Menu, MenuItem}; +use craft::ui::primitives::{ContentPainterCx, DocRun, DocText, PaintShape, StrokeWidth}; +use craft::ui::runtime::commands::{CommandRef, CommandScope, CommandState, Commands as _, EditCommands}; +use craft::ui::runtime::env::{Env, Label}; +use craft::ui::style::{DataColor, Ink, SurfaceKind}; +use craft::ui::text::TextField; +use craft::ui::tile_grid::{CaptionPlace, GridEvent, GridZoom, GroupHeads, Tile, TileGrid, TileGroup, TileZoom}; use deckcraft_model::{Presentation, SlideId}; -use egui::{Align2, Color32, CornerRadius, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use egui::{Color32, CornerRadius, Rect, Ui, vec2}; use serde_json::json; use crate::SlideApp; -use crate::icons::{self, Icon}; -use crate::theme::{self, Tokens}; +use crate::thumb_source::{self, DeckThumbs, ThumbKey}; -/// Sorter-only state. Nothing here is part of the document. +craft::ui::words! { + /// Words shared by the Sorter, Outline and Notes Page. + struct SorterWords { + sorter: plain = "Slide Sorter"; + add_section: plain = "Add Section"; + section_menu: plain = "Section"; + rename_section: plain = "Rename Section…"; + remove_section: plain = "Remove Section"; + remove_slides: plain = "Remove Section & Slides"; + move_up: plain = "Move Section Up"; + move_down: plain = "Move Section Down"; + slide: template "deckcraft.sorterSlide" = "Slide {number}"; + transition: template "deckcraft.sorterTransition" = "★ {kind}"; + slide_title: plain = "Slide title"; + slide_text: plain = "Slide text"; + notes: plain = "Notes"; + } +} + +/// Sorter-only state, independent of the document. #[derive(Debug, Default)] pub struct State { - /// Sections folded shut, keyed by (document uid, that section's first slide) so moving a - /// section does not fold a different one. An empty section has nothing to hide. + /// Fold keys follow a section's first slide across section moves; empty sections stay open. pub collapsed: HashSet<(u64, u32)>, - /// Inline rename: (document uid, section index, text typed so far). - pub renaming: Option<(u64, usize, String)>, - rename_started: bool, - /// Whole-section drag: (section index, insertion slot among the bars). - pub drag: Option<(usize, usize)>, } -/// Where a dragged section would land. `centers` are the header centre-y values, top to bottom; -/// `slot` is the gap (0 = before the first bar, `len` = after the last). -fn drop_slot(centers: &[f32], y: f32) -> usize { - centers.iter().position(|cy| y < *cy).unwrap_or(centers.len()) -} - -/// `section.move`'s `to` for a drag from `from` released at `slot`. `None` when the section -/// would stay where it is (the gap before it, or the gap just after it). -fn move_dest(from: usize, slot: usize) -> Option { - if slot == from || slot == from + 1 { None } else { Some(if slot > from { slot - 1 } else { slot }) } +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Key { + Slide(SlideId), + Section(usize), } /// One section's slides, in the section's order, then any slide that belongs to none. @@ -62,490 +85,315 @@ fn groups(doc: &Presentation) -> Vec<(Option, Vec)> { out } -struct Header<'a> { - uid: u64, - index: usize, - name: &'a str, - count: usize, - first: Option, -} - -/// Render one slide-sorter section header, handle its collapse/drag interactions, and return the -/// occupied rectangle. -fn section_header(app: &mut SlideApp, ui: &mut Ui, h: &Header<'_>) -> Rect { - let t = Tokens::get(ui.ctx()); - let width = ui.available_width(); - let (r, _) = ui.allocate_exact_size(vec2(width, 32.0), Sense::hover()); - let resp = ui.interact(r, ui.scope_id().with(("sorter-section", h.uid, h.index)), Sense::click_and_drag()); - resp.widget_info(|| WidgetInfo::labeled(Role::Button, true, h.name)); - let open = h.first.is_none_or(|id| !app.sorter.collapsed.contains(&(h.uid, id))); - let dragging = app.sorter.drag.is_some_and(|(from, _)| from == h.index); - let bg = if dragging { - t.selected - } else if resp.hovered() { - t.hover - } else { - t.card - }; - let painter = ui.painter_at(r); - painter.rect_filled(r, CornerRadius::same(4), bg); - let chev = Rect::from_center_size(pos2(r.min.x + 20.0, r.center().y), vec2(24.0, 24.0)); - let cresp = ui.interact(chev, ui.scope_id().with(("sorter-fold", h.uid, h.index)), Sense::click()); - let fold = format!("{} {}", if open { "Collapse" } else { "Expand" }, h.name); - cresp.widget_info(|| WidgetInfo::labeled(Role::Button, true, &fold)); - icons::paint(&painter, chev.shrink(4.0), if open { Icon::ChevronDown } else { Icon::ChevronRight }, t.text_dim, h.first.is_none()); - let renaming = app.sorter.renaming.clone().filter(|(uid, index, _)| *uid == h.uid && *index == h.index).map(|(_, _, text)| text); - let name_rect = Rect::from_min_max(pos2(r.min.x + 40.0, r.min.y + 4.0), pos2(r.max.x - 56.0, r.max.y - 4.0)); - if let Some(mut buf) = renaming { - let edit_id = ui.scope_id().with(("sorter-rename", h.uid, h.index)); - let out = - ui.put(name_rect, egui::TextEdit::singleline(&mut buf).id(edit_id).hint_text("Name").font(theme::bold(13.0)).margin(vec2(4.0, 2.0))); - let already = app.sorter.rename_started; - if !already { - out.request_focus(); - if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), edit_id) { - let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(buf.chars().count())); - state.cursor.set_char_range(Some(all)); - state.store(ui.ctx(), edit_id); - } - app.sorter.rename_started = true; - } - let (enter, esc) = ui.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape))); - // The frame that asks for focus has not had it yet; committing then would cancel the rename. - if already && (out.lost_focus() || enter || esc) { - app.sorter.renaming = None; - app.sorter.rename_started = false; - let trimmed = buf.trim(); - if !esc && !trimmed.is_empty() && trimmed != h.name { - let _ = app.run("section.rename", json!({"index": h.index, "name": trimmed})); - } - } else if let Some((_, _, text)) = app.sorter.renaming.as_mut() { - *text = buf; - } - } else { - painter.text(pos2(name_rect.min.x, r.center().y), Align2::LEFT_CENTER, h.name, theme::bold(13.0), t.text); - } - painter.text(pos2(r.max.x - 16.0, r.center().y), Align2::RIGHT_CENTER, format!("({})", h.count), theme::font(12.0), t.text_dim); - if cresp.clicked() - && let Some(id) = h.first - { - let key = (h.uid, id); - if open { - app.sorter.collapsed.insert(key); - } else { - app.sorter.collapsed.remove(&key); - } - } else if resp.double_clicked() && app.sorter.renaming.is_none() { - app.sorter.renaming = Some((h.uid, h.index, h.name.to_string())); - app.sorter.rename_started = false; - } - let on_chevron = resp.interact_pointer_pos().is_some_and(|p| chev.contains(p)); - if resp.drag_started() && !on_chevron && app.sorter.renaming.is_none() { - app.sorter.drag = Some((h.index, h.index)); - app.thumb_drag = None; - } - let index = h.index; - let name = h.name.to_string(); - resp.context_menu(|ui| { - if ui.button("Rename Section…").clicked() { - let mut d = crate::dialogs::Dialog::new("renameSection"); - d.params = json!({"index": index, "name": name}); - app.dialog = Some(d); - ui.close(); - } - if ui.button("Add Section").clicked() { - if let Some(at) = app.session.active().map(|st| st.selection.slide) { - let _ = app.run("section.add", json!({"at": at})); - } - ui.close(); - } - if ui.button("Remove Section").clicked() { - let _ = app.run("section.remove", json!({"index": index})); - ui.close(); - } - if ui.button("Remove Section & Slides").clicked() { - let _ = app.run("section.remove", json!({"index": index, "slides": true})); - ui.close(); - } - if ui.button("Move Section Up").clicked() { - let _ = app.run("section.move", json!({"index": index, "to": index.saturating_sub(1)})); - ui.close(); - } - if ui.button("Move Section Down").clicked() { - let _ = app.run("section.move", json!({"index": index, "to": index + 1})); - ui.close(); - } - }); - r -} - -struct Grid<'a> { - doc: &'a Presentation, - indices: &'a [usize], - cur: usize, - multi: &'a [SlideId], - tw: f32, - th: f32, -} - -/// One section's thumbnails. Returns whether a thumbnail is still being drawn. -fn place_slides(app: &mut SlideApp, ui: &mut Ui, g: &Grid<'_>, budget: &mut u32, rects: &mut Vec<(usize, Rect)>) -> bool { - let t = Tokens::get(ui.ctx()); - let ppp = ui.ctx().pixels_per_point(); - let cols = ((ui.available_width() - 32.0) / (g.tw + 36.0)).floor().max(1.0) as usize; - let mut need_more = false; - let rows = g.indices.len().div_ceil(cols); - for row in 0..rows { - ui.horizontal(|ui| { - ui.add_space(24.0); - for c in 0..cols { - let Some(&i) = g.indices.get(row * cols + c) else { break }; - let (cell, resp) = ui.allocate_exact_size(vec2(g.tw + 36.0, g.th + 36.0), Sense::click_and_drag()); - let label = format!("Slide {}", i + 1); - resp.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label)); - let img = crate::textures::device_pixel_rect(Rect::from_min_size(cell.min + vec2(18.0, 8.0), vec2(g.tw, g.th)), ppp); - rects.push((i, cell)); - let p = ui.painter(); - // Only cells in view (plus a little margin) ask for a thumbnail, so a deck bigger - // than the thumbnail cache does not evict its own thumbnails forever (#969). - let near = ui.clip_rect().expand2(vec2(0.0, 2.0 * cell.height())).intersects(cell); - let tex = - if near { app.textures.thumb(ui.ctx(), g.doc, i, (img.width() * ppp).round() as u32, app.ui.grayscale, budget) } else { None }; - match tex { - Some(tex) => { - p.image(tex.id(), img, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - } - None => { - p.rect_filled(img, CornerRadius::ZERO, Color32::WHITE); - need_more |= near; - } - } - let id = g.doc.slides.get(i).map(|s| s.id); - let selected = i == g.cur || id.is_some_and(|id| g.multi.contains(&id)); - p.rect_stroke( - img.expand(if selected { 2.0 } else { 0.0 }), - CornerRadius::same(3), - Stroke::new(if selected { 3.0 } else { 1.0 }, if selected { t.accent } else { t.border }), - egui::StrokeKind::Outside, - ); - p.text(pos2(img.min.x, img.max.y + 12.0), Align2::LEFT_CENTER, format!("{}", i + 1), theme::font(12.0), t.text_dim); - if let Some(tr) = g.doc.slides.get(i).and_then(|s| s.transition.as_ref()).filter(|tr| tr.kind != "none") { - p.text(pos2(img.max.x, img.max.y + 12.0), Align2::RIGHT_CENTER, format!("★ {}", tr.kind), theme::font(10.5), t.text_faint); - } - if resp.clicked() { - let (shift, add) = ui.input(|inp| (inp.modifiers.shift, inp.modifiers.command)); - if shift { - let _ = app.run("slide.selectRange", json!({"to": i, "add": add})); - } else if add { - if let Some(id) = id { - let _ = app.run("slide.selectSlides", json!({"ids": [id.0], "add": true})); - } - } else { - let _ = app.run("slide.go", json!({"index": i})); - } - } - if resp.double_clicked() { - let _ = app.run("slide.go", json!({"index": i})); - app.ui.view = crate::ViewMode::Normal; - } - if resp.drag_started() && app.sorter.drag.is_none() { - crate::thumbs::start_slide_drag(app, i); - } - // P3(panels-w6): pn.A3 - resp.context_menu(|ui| crate::thumbs::slide_menu(ui, app, i as u64, &resp)); - } - }); - } - need_more -} - -/// Grid of slides; click selects, double-click opens in Normal view, drag reorders. -/// With sections, each one is a bar: add, rename, collapse, and drag the whole section. +/// Grid of slides with collapsible, editable and movable sections. pub fn show(app: &mut SlideApp, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); - let Some(st) = app.session.active() else { - app.sorter.drag = None; - app.sorter.renaming = None; - app.sorter.rename_started = false; - return; - }; - let uid = st.uid; - if app.sorter.renaming.as_ref().is_some_and(|(u, i, _)| *u != uid || *i >= st.doc.sections.len()) { - app.sorter.renaming = None; - app.sorter.rename_started = false; + let Some(st) = app.session.active() else { return }; + let (uid, doc, cur) = (st.uid, st.doc.clone(), st.selection.slide); + let lead = doc.slides.get(cur).map(|slide| Key::Slide(slide.id)); + // PLAN: plan error: slide.selectSlides clears range_anchor; shell-w4 must preserve the grid anchor and a deselected lead in its command interface. + let anchor = st.selection.range_anchor.map(|(first, _)| Key::Slide(first)).or(lead); + let mut selection = Selection::new(st.selection.slides.iter().copied().map(Key::Slide).collect(), lead, anchor); + let mut keys = Vec::with_capacity(doc.slides.len()); + let mut heads = Vec::with_capacity(doc.sections.len()); + for (section, slides) in groups(&doc) { + if let Some(index) = section { + let section = &doc.sections[index]; + let open = section.slides.first().is_none_or(|id| !app.sorter.collapsed.contains(&(uid, id.0))); + heads.push(TileGroup::new(Key::Section(index), keys.len(), slides.len(), section.name.clone()).detail(slides.len().to_string()).open(open)); + } + keys.extend(slides.iter().map(|&index| Key::Slide(doc.slides[index].id))); } - let doc = st.doc.clone(); - let cur = st.selection.slide; - let multi = st.selection.slides.clone(); - let zoom = app.ui.sorter_zoom.clamp(0.5, 3.0); - let grouped = groups(&doc); - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.add_space(12.0); - ui.horizontal(|ui| { - ui.add_space(24.0); - if ui.add(egui::Button::new("Add Section").stroke(Stroke::new(1.0, t.border))).clicked() { + let source = keyed(&keys, |key: &Key| *key); + let thumbs = thumb_source::thumbnails(ui.ctx()); + let pictures = DeckThumbs::new(doc.clone(), app.ui.grayscale); + let mut zoom = f64::from(app.ui.sorter_zoom); + let aspect = (doc.slide_size.width / doc.slide_size.height.max(1.0)) as f32; + // PLAN: assumed SlideApp::slide_reveal: Option (shell-w11). + let reveal = app.slide_reveal.take().map(Key::Slide); + Stack::new() + .id_salt(("sorter-scope", uid)) + .command_scope(CommandScope::new("sorter")) + .fill() + .show(ui, |ui, cx| { + let words = cx.words::(); + cx.publish(EditCommands::SelectAll, CommandState::new().enabled(!keys.is_empty())); + while let Some((command, fired)) = cx.take_command::() { + if command == EditCommands::SelectAll { + let _ = app.run("edit.selectAll", json!({"scope": "slides"})); + } else { + let _ = app.run(&fired.command.id, fired.command.params); + } + } + if Button::new(words.add_section.clone()).show(ui).clicked() { let _ = app.run("section.add", json!({"at": cur})); } + let make_grid = || { + TileGrid::new(words.sorter.clone()) + .id_salt(("sorter", uid)) + .caption(CaptionPlace::Below) + .detail_line() + .groups(&heads) + .group_heads(GroupHeads::Titled) + .collapsible() + .can_rename_groups() + .can_move_groups() + .reorder(ReorderRule::new()) + .aspect(aspect) + }; + let mut grid = make_grid() + .zoom(GridZoom::Bound(Bind::bound(&mut zoom), TileZoom::bounded(0.5, 3.0, 0.1, 1.0))) + .selection(Bind::given(selection.clone())); + if let Some(key) = reveal { + grid = grid.reveal(key); + } + let out = grid.show_items(ui, &source, &mut |key, _| { + let label = match *key { + Key::Slide(id) => doc.slide_index(id).map(|index| (index + 1).to_string()).unwrap_or_else(|| id.0.to_string()), + Key::Section(index) => doc.sections.get(index).map(|section| section.name.clone()).unwrap_or_default(), + }; + let mut tile = Tile::new(label); + if let Key::Slide(id) = *key + && let Some(index) = doc.slide_index(id) + { + let slide = &doc.slides[index]; + tile = tile.picture( + ThumbAspect::from_ratio(aspect), + thumb_source::picture(words.slide.fill(&[("number", &(index + 1).to_string())]), ThumbKey::Slide(id), &thumbs, &pictures), + ); + if let Some(transition) = slide.transition.as_ref().filter(|transition| transition.kind != "none") { + tile = tile.detail(words.transition.fill(&[("kind", &transition.kind)])); + } + if slide.hidden { + tile = tile.hidden(); + } + } + tile + }); + app.ui.sorter_zoom = zoom as f32; + let opener = &out.response.response; + // PLAN: plan error: panels-w2 must retain pointer GroupMenu requests in CollectionResponse::menu; grid.rs emits them outside the collection menu lifecycle. + if let Some(request) = &out.response.menu { + match request.key { + Key::Slide(id) => crate::thumbs::slide_menu(ui, app, u64::from(id.0), opener), + Key::Section(index) => section_menu(app, ui, index, opener, &words), + } + } + for event in out.response.events { + match event { + CollectionEvent::Selection { change, .. } => { + selection.apply(change); + select_slides(app, &doc, &selection); + } + CollectionEvent::Picked { key: Key::Slide(id), .. } => { + let _ = app.run("slide.go", json!({"id": id.0})); + } + CollectionEvent::Activate(Key::Slide(id)) => { + let _ = app.run("slide.go", json!({"id": id.0})); + let _ = app.run("view.normal", json!({})); + } + CollectionEvent::Reorder(edit) => { + if let Some(movement) = edit.value() + && let Some(movement) = make_grid().tile_reorder(&source, movement) + { + // In [hA,A,hB,B,C], A after C has outline to=4 and tile to=2. + let ids: Vec<_> = movement + .keys + .iter() + .filter_map(|key| match key { + Key::Slide(id) => Some(id.0), + Key::Section(_) => None, + }) + .collect(); + let _ = app.run("slide.move", json!({"ids": ids, "to": movement.to})); + } + } + _ => {} + } + } + for event in out.events { + match event { + GridEvent::GroupOpen { group, open } => { + if let Some(Key::Section(index)) = heads.get(group).map(|head| head.key) + && let Some(first) = doc.sections[index].slides.first() + { + if open { + app.sorter.collapsed.remove(&(uid, first.0)); + } else { + app.sorter.collapsed.insert((uid, first.0)); + } + } + } + GridEvent::GroupRenamed { group, title, .. } => { + if let Some(Key::Section(index)) = heads.get(group).map(|head| head.key) { + let _ = app.run("section.rename", json!({"index": index, "name": title})); + } + } + GridEvent::GroupMoved { group, to, .. } => { + if let Some(Key::Section(index)) = heads.get(group).map(|head| head.key) { + let _ = app.run("section.move", json!({"index": index, "to": to})); + } + } + _ => {} + } + } }); - ui.add_space(8.0); - let tw = 200.0 * zoom; - let th = tw * (doc.slide_size.height / doc.slide_size.width.max(1.0)) as f32; - let mut budget = 4u32; - let mut rects = vec![]; - let mut headers: Vec = Vec::new(); - let mut need_more = false; - for (si, slides) in &grouped { - if let Some(si) = *si - && let Some(sec) = doc.sections.get(si) - { - let first = sec.slides.first().map(|id| id.0); - let rect = section_header(app, ui, &Header { uid, index: si, name: &sec.name, count: sec.slides.len(), first }); - headers.push(rect); - let folded = first.is_some_and(|id| app.sorter.collapsed.contains(&(uid, id))); - if folded { - ui.add_space(8.0); - continue; - } - } - let grid = Grid { doc: &doc, indices: slides, cur, multi: &multi, tw, th }; - if place_slides(app, ui, &grid, &mut budget, &mut rects) { - need_more = true; - } - ui.add_space(8.0); +} + +fn select_slides(app: &mut SlideApp, doc: &Presentation, selection: &Selection) { + let selected: HashSet<_> = selection.items.iter().copied().collect(); + let mut ids: Vec<_> = doc.slides.iter().filter(|slide| selected.contains(&Key::Slide(slide.id))).map(|slide| slide.id.0).collect(); + if let Some(Key::Slide(lead)) = selection.lead + && let Some(at) = ids.iter().position(|id| *id == lead.0) + { + ids.remove(at); + ids.push(lead.0); + } + let _ = app.run("slide.selectSlides", json!({"ids": ids, "add": false})); +} + +fn section_menu(app: &mut SlideApp, ui: &mut Ui, index: usize, opener: &egui::Response, words: &SorterWords) { + let Some(st) = app.session.active() else { return }; + let Some(section) = st.doc.sections.get(index) else { return }; + let (name, current, count) = (section.name.clone(), st.selection.slide, st.doc.sections.len()); + Menu::context(words.section_menu.clone(), opener).id_salt(("sorter-section-menu", index)).show(ui, |ui, _| { + if MenuItem::new(words.rename_section.clone()).show(ui).ran { + app.open_dialog("renameSection", json!({"index": index, "name": name})); } - if need_more { - ui.ctx().request_repaint(); - } - if let Some((from, _)) = app.sorter.drag { - if let Some(pp) = ui.input(|i| i.pointer.interact_pos()) { - let centers: Vec = headers.iter().map(|r| r.center().y).collect(); - let slot = drop_slot(¢ers, pp.y); - app.sorter.drag = Some((from, slot)); - let y = headers.get(slot).map(|r| r.min.y).or_else(|| headers.last().map(|r| r.max.y + 2.0)); - if let Some(y) = y { - ui.painter().line_segment([pos2(16.0, y), pos2(ui.available_width(), y)], Stroke::new(2.0, t.accent)); - } - } - if ui.input(|i| i.pointer.any_released()) { - if let Some((from, slot)) = app.sorter.drag.take() - && let Some(to) = move_dest(from, slot) - { - let _ = app.run("section.move", json!({"index": from, "to": to})); - } - app.sorter.drag = None; - } - } - if app.sorter.drag.is_none() && crate::thumbs::slide_drag_live(app, crate::thumbs::drag_button(ui)) { - if let Some(pp) = ui.input(|i| i.pointer.interact_pos()) { - let to = - rects.iter().find(|(_, r)| r.contains(pp)).map(|(i, r)| if pp.x > r.center().x { i + 1 } else { *i }).unwrap_or(doc.slides.len()); - if let Some(d) = app.thumb_drag.as_mut() { - d.slot = to; - } - if let Some((_, r)) = rects.iter().find(|(i, _)| *i == to).or(rects.last()) { - let x = if to >= doc.slides.len() { r.max.x - 6.0 } else { r.min.x + 6.0 }; - ui.painter().line_segment([pos2(x, r.min.y + 6.0), pos2(x, r.max.y - 20.0)], Stroke::new(3.0, t.accent)); - } - } - if ui.input(|i| i.pointer.any_released()) { - crate::thumbs::drop_slide_drag(app); - } - } - // Ctrl/⌘ + wheel zooms the sorter. - let (zd, cmd) = ui.input(|i| (i.zoom_delta(), i.modifiers.command)); - if (zd - 1.0).abs() > 1e-3 || cmd { - app.ui.sorter_zoom = (zoom * zd).clamp(0.5, 3.0); + for (label, command, params, enabled) in [ + (words.add_section.clone(), "section.add", json!({"at": current}), true), + (words.remove_section.clone(), "section.remove", json!({"index": index}), true), + (words.remove_slides.clone(), "section.remove", json!({"index": index, "slides": true}), true), + (words.move_up.clone(), "section.move", json!({"index": index, "to": index.saturating_sub(1)}), index > 0), + (words.move_down.clone(), "section.move", json!({"index": index, "to": index + 1}), index + 1 < count), + ] { + MenuItem::command(CommandRef::with_params(command, params)).label(label).enabled(enabled).show(ui); } }); } -/// Notes Page: the slide on top and its notes underneath, on a page. +/// Notes Page: a slide and its editable notes on a Letter page. pub fn notes_page(app: &mut SlideApp, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); - let avail = ui.available_rect_before_wrap(); - ui.painter().rect_filled(avail, CornerRadius::ZERO, t.canvas); let Some(st) = app.session.active() else { return }; - let doc = st.doc.clone(); - let idx = st.selection.slide; - let page_h = avail.height() - 40.0; - let page_w = page_h * 8.5 / 11.0; - let page = Rect::from_center_size(avail.center(), vec2(page_w, page_h)); - ui.painter().rect_filled(page.translate(vec2(2.0, 2.0)), CornerRadius::ZERO, t.shadow); - ui.painter().rect_filled(page, CornerRadius::ZERO, Color32::WHITE); - // The notes master places the slide, the notes and the header and footer text (in Letter - // points, as the PDF notes pages do). + let (doc, index, uid) = (st.doc.clone(), st.selection.slide, st.uid); + let Some(slide) = doc.slides.get(index) else { return }; + let env = Env::of(ui); + let words = env.words::(); + let avail = ui.available_rect_before_wrap(); + let room = avail.shrink(env.tokens.space.pad.regular); + let height = room.height().max(0.0).min(room.width().max(0.0) * 11.0 / 8.5); + let page = Rect::from_center_size(avail.center(), vec2(height * 8.5 / 11.0, height)); + let k = page.width() / 612.0; let paper = (612.0, 792.0); - let k = page_w / paper.0 as f32; - let to_screen = |(x0, y0, x1, y1): (f64, f64, f64, f64)| { - Rect::from_min_max(page.min + vec2(x0 as f32 * k, y0 as f32 * k), page.min + vec2(x1 as f32 * k, y1 as f32 * k)) + let to_screen = |rect: deckcraft_geom::Rect| { + Rect::from_min_max(page.min + vec2(rect.x0 as f32 * k, rect.y0 as f32 * k), page.min + vec2(rect.x1 as f32 * k, rect.y1 as f32 * k)) }; let (slide_box, notes_box) = deckcraft_engine::pdf::notes_frames(&doc, paper); - // On the physical pixel grid, so the thumbnail is one texel per device pixel (#184). - let srect = crate::textures::device_pixel_rect(to_screen((slide_box.x0, slide_box.y0, slide_box.x1, slide_box.y1)), ui.ctx().pixels_per_point()); - if let Some(m) = doc.notes_master.as_deref() { - // Laid out by the text engine as on the PDF page: wrapped, each run in its size and colour. - for piece in deckcraft_engine::pdf::master_text_pieces(&doc, m, paper, idx + 1) { - let size = (piece.size as f32 * k).max(4.0); - let at = page.min + vec2(piece.at.0 as f32 * k, piece.at.1 as f32 * k - size * 0.8); - let c = Color32::from_rgba_unmultiplied(piece.color.r, piece.color.g, piece.color.b, piece.color.a); - ui.painter().text(at, egui::Align2::LEFT_TOP, &piece.text, theme::font(size), c); + let painter = ContentPainterCx::new(ui.painter_at(avail), &env, Ink::OnPanel); + painter.with_draw(|draw| { + draw.fill(&PaintShape::Rect(avail, CornerRadius::ZERO), draw.role(|color| color.surface.canvas)); + let [x, y] = env.tokens.elevation.knob.offset; + draw.fill(&PaintShape::Rect(page.translate(vec2(x, y)), CornerRadius::ZERO), draw.role(|color| color.surface.shadow)); + draw.data_fill(&PaintShape::Rect(page, CornerRadius::ZERO), DataColor::new(Color32::WHITE)); + if let Some(master) = doc.notes_master.as_deref() { + for piece in deckcraft_engine::pdf::master_text_pieces(&doc, master, paper, index + 1) { + let size = piece.size as f32 * k; + let at = page.min + vec2(piece.at.0 as f32 * k, piece.at.1 as f32 * k - size * 0.8); + let color = DataColor::new(Color32::from_rgba_unmultiplied(piece.color.r, piece.color.g, piece.color.b, piece.color.a)); + let runs = [DocRun::new(piece.text.as_str(), craft::ui::fonts::FontRef::proportional(), size, color)]; + draw.doc(Rect::from_min_max(at, page.max), &DocText::new(&runs)); + } } - } - let ppp = ui.ctx().pixels_per_point(); - let mut budget = 2; - if let Some(tex) = app.textures.thumb(ui.ctx(), &doc, idx, (srect.width() * ppp).round() as u32, app.ui.grayscale, &mut budget) { - ui.painter().image(tex.id(), srect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - } - ui.painter().rect_stroke(srect, CornerRadius::ZERO, Stroke::new(1.0, Color32::GRAY), egui::StrokeKind::Outside); - let notes_rect = to_screen((notes_box.x0, notes_box.y0, notes_box.x1, notes_box.y1)); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(notes_rect)); - // A draft belongs to this document and to the notes it started from (#413): another document, - // a reorder or an undo that changes them drops it. - let id = egui::Id::unique(("notespage", st.uid, idx)); - let edit_id = egui::Id::unique(("notespage-edit", idx)); - let focused = child.ctx().memory(|m| m.has_focus(edit_id)); - let notes_of = |app: &SlideApp| app.session.active().and_then(|st| st.doc.slides.get(idx)).map(|s| s.notes.clone()).unwrap_or_default(); - let notes = notes_of(app); - let stored: Option<(deckcraft_model::text::TextBody, crate::notes::Draft)> = child.data_mut(|d| d.get_temp(id)); - let mut draft = stored.filter(|(base, _)| *base == notes).map(|(_, d)| d); - // Save an edited draft once the field has lost focus, before anything reloads it. - if !focused && let Some(d) = draft.as_mut().filter(|d| d.edited) { - d.edited = false; - let _ = app.run("slide.notes", json!({"body": d.body, "index": idx})); - } - let notes = notes_of(app); - let mut draft = draft.filter(|d| focused || d.body == notes).unwrap_or_else(|| crate::notes::Draft::new(¬es)); - let look = crate::notes::Look { size: 14.0, color: Some(Color32::from_gray(30)) }; - let width = notes_rect.width(); - let r = crate::notes::editor(&mut child, &mut draft, &look, |e| { - e.id(edit_id).hint_text("Click to add text").desired_width(width).desired_rows(12).frame(egui::Frame::NONE) - }) - .response - .response; - if r.lost_focus() && draft.edited { - draft.edited = false; - let _ = app.run("slide.notes", json!({"body": draft.body, "index": idx})); - } - let base = notes_of(app); - child.data_mut(|d| d.insert_temp(id, (base, draft))); - let nav = ui.input(|i| (i.key_pressed(egui::Key::PageDown), i.key_pressed(egui::Key::PageUp))); - if nav.0 { - let _ = app.run("slide.next", json!({})); - } - if nav.1 { - let _ = app.run("slide.previous", json!({})); + }); + let thumbs = thumb_source::thumbnails(ui.ctx()); + let source = DeckThumbs::new(doc.clone(), app.ui.grayscale); + thumb_source::picture(words.slide.fill(&[("number", &(index + 1).to_string())]), ThumbKey::Slide(slide.id), &thumbs, &source) + .show_at(ui, to_screen(slide_box)); + painter.with_draw(|draw| { + draw.stroke(&PaintShape::Rect(to_screen(slide_box), CornerRadius::ZERO), StrokeWidth::Thin, draw.role(|color| color.line.frame)); + }); + let mut edited = crate::notes::to_notes(&slide.notes); + let out = NotesEditor::new(words.notes.clone(), &mut edited).id_salt(("notes-page", uid, slide.id.0)).zoom(k).show_at(ui, to_screen(notes_box)); + if out.changed { + let body = crate::notes::apply(&slide.notes, &edited); + let _ = app.run("slide.notes", json!({"body": body, "index": index, "coalesce": true})); } } -/// Outline view: slide titles and body text as an editable outline. -pub fn outline_pane(app: &mut SlideApp, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); - egui::Panel::left("outline").resizable(true).default_size(360.0).frame(egui::Frame::NONE.fill(t.card).inner_margin(egui::Margin::same(10))).show( - ui, - |ui| { - let Some(st) = app.session.active() else { return }; - let doc = st.doc.clone(); - let cur = st.selection.slide; - // Only the slides in view (and the current one, whose editor may have the focus) are - // laid out; the rest take their last measured height (estimated until first shown). - // Laying out every slide's editors each frame made a 2000-slide outline crawl. - egui::ScrollArea::vertical().auto_shrink([false, false]).show_viewport(ui, |ui, viewport| { - let origin = ui.cursor().top(); - let margin = 300.0; - for (i, s) in doc.slides.iter().enumerate() { - let hid = egui::Id::unique(("ol-height", s.id.0)); - let known: Option = ui.data(|d| d.get_temp(hid)); - let h = known.unwrap_or_else(|| outline_estimate(s)); - let y = ui.cursor().top() - origin; - if i == cur || (y + h >= viewport.min.y - margin && y <= viewport.max.y + margin) { - outline_slide(app, ui, &t, i, s, cur); - let real = ui.cursor().top() - origin - y; - ui.data_mut(|d| d.insert_temp(hid, real)); - } else { - ui.allocate_exact_size(vec2(ui.available_width(), (h - ui.spacing().item_spacing.y).max(0.0)), Sense::hover()); - } - } - }); - }, - ); +/// Editable slide titles and body text inside the editor's Outline pane. +pub(crate) fn outline_body(app: &mut SlideApp, ui: &mut Ui, cx: &mut BodyCx<'_>) { + let Some(st) = app.session.active() else { return }; + let (uid, doc, current) = (st.uid, st.doc.clone(), st.selection.slide); + let words = cx.words::(); + Stack::new() + .id_salt(("outline", uid)) + .surface(SurfaceKind::Panel) + .pad(Pad::Regular) + .scroll(Scroll::vertical()) + .fill() + .show(ui, |ui, _| { + for (index, slide) in doc.slides.iter().enumerate() { + let title = slide.shapes.iter().find(|shape| shape.ph_type().is_some_and(|kind| kind.is_title())); + let body: Vec<_> = slide + .shapes + .iter() + .filter(|shape| !shape.ph_type().is_some_and(|kind| kind.is_title() || kind.is_footer_kind())) + .filter(|shape| shape.text.as_ref().is_some_and(|text| !text.is_empty())) + .collect(); + // PLAN: plan error: Lazy::new has no estimate-free form; the first extent of an unshown row has no framework value. + let _ = Lazy::new(("outline", uid, slide.id.0), 0.0).show(ui, |ui| { + Stack::new().fill_width().show(ui, |ui, _| { + Row::new().fill_width().show(ui, |ui, _| { + Text::new((index + 1).to_string()).show(ui); + Picture::painter(Label::Empty, ThumbAspect::new(4, 3), |cx, rect| { + cx.with_draw(|draw| { + let shape = PaintShape::Rect(rect, CornerRadius::ZERO); + if index == current { + draw.fill(&shape, draw.role(|color| color.accent.solid)); + } else { + draw.stroke(&shape, StrokeWidth::Thin, draw.role(|color| color.line.frame)); + } + }); + }) + .show(ui); + if let Some(title) = title { + let text = title.text.as_ref().map(|text| text.text()).unwrap_or_default(); + // PLAN: plan error: TextField has no title type role or weight prop for the Outline title. + outline_field(app, ui, (uid, title.id.0), index, &text, words.slide_title.clone(), false); + } + }); + Stack::new().indent(2).fill_width().show(ui, |ui, _| { + for shape in &body { + if let Some(text) = &shape.text { + let text = text + .paragraphs + .iter() + .map(|paragraph| format!("{}{}", "\t".repeat(paragraph.level as usize), paragraph.text())) + .collect::>() + .join("\n"); + outline_field(app, ui, (uid, shape.id.0), index, &text, words.slide_text.clone(), true); + } + } + }); + }); + }); + } + }); +} + +fn outline_field(app: &mut SlideApp, ui: &mut Ui, key: (u64, u32), slide: usize, text: &str, label: Label, multiline: bool) { + let mut field = + TextField::new(label.clone(), Bind::given(text.to_owned())).id_salt(("outline-field", key)).placeholder(label).sizing(Sizing::FillWidth); + if multiline { + field = field.lines(text.lines().count().max(1)); + } + let out = field.show(ui); + if out.response.gained_focus() { + let _ = app.run("slide.go", json!({"index": slide})); + } + if let Some(edited) = out.events.committed().filter(|edited| edited.as_str() != text) { + let _ = app.run("text.set", json!({"id": key.1, "text": edited})); + } } #[cfg(test)] pub(crate) mod ui_tests; - -/// A slide's outline block height before it has been laid out: title row plus its text lines. -fn outline_estimate(s: &deckcraft_model::Slide) -> f32 { - let lines: usize = s - .shapes - .iter() - .filter(|x| !x.ph_type().is_some_and(|k| k.is_title() || k.is_footer_kind())) - .filter_map(|x| x.text.as_ref()) - .filter(|tb| !tb.is_empty()) - .map(|tb| tb.paragraphs.len().max(1)) - .sum(); - 30.0 + lines as f32 * 19.0 -} - -/// One slide in the outline: number, title editor, then its other text. -fn outline_slide(app: &mut SlideApp, ui: &mut Ui, t: &Tokens, i: usize, s: &deckcraft_model::Slide, cur: usize) { - let title_shape = s.shapes.iter().find(|x| x.ph_type().is_some_and(|k| k.is_title())).map(|x| x.id.0); - ui.horizontal(|ui| { - ui.label(egui::RichText::new(format!("{}", i + 1)).color(t.text_dim)); - let (r, _) = ui.allocate_exact_size(vec2(14.0, 10.0), Sense::hover()); - ui.painter().rect_stroke(r, CornerRadius::same(1), Stroke::new(1.0, if i == cur { t.accent } else { t.text_dim }), egui::StrokeKind::Inside); - let id = egui::Id::unique(("ol-title", s.id.0)); - let cur_title = s.title(); - let mut v: String = ui.data_mut(|d| d.get_temp(id).unwrap_or_else(|| cur_title.clone())); - let resp = ui.add( - egui::TextEdit::singleline(&mut v).hint_text("Slide title").font(theme::bold(14.0)).frame(egui::Frame::NONE).desired_width(f32::INFINITY), - ); - if resp.gained_focus() { - let _ = app.run("slide.go", json!({"index": i})); - } - if resp.lost_focus() - && v != cur_title - && let Some(tid) = title_shape - { - let _ = app.run("text.set", json!({"id": tid, "text": v})); - } - if !resp.has_focus() { - ui.data_mut(|d| d.remove::(id)); - } else { - ui.data_mut(|d| d.insert_temp(id, v)); - } - }); - // Footer, date and slide-number placeholders are not outline text, as in PowerPoint. - for sh in s.shapes.iter().filter(|x| !x.ph_type().is_some_and(|k| k.is_title() || k.is_footer_kind())) { - let Some(tb) = &sh.text else { continue }; - if tb.is_empty() { - continue; - } - let id = egui::Id::unique(("ol-body", s.id.0, sh.id.0)); - let cur_text: String = tb.paragraphs.iter().map(|p| format!("{}{}", "\t".repeat(p.level as usize), p.text())).collect::>().join("\n"); - let mut v: String = ui.data_mut(|d| d.get_temp(id).unwrap_or_else(|| cur_text.clone())); - ui.horizontal(|ui| { - ui.add_space(36.0); - let resp = ui - .add(egui::TextEdit::multiline(&mut v).hint_text("Slide text").frame(egui::Frame::NONE).desired_width(f32::INFINITY).desired_rows(1)); - if resp.gained_focus() { - let _ = app.run("slide.go", json!({"index": i})); - } - if resp.lost_focus() && v != cur_text { - let _ = app.run("text.set", json!({"id": sh.id.0, "text": v})); - } - if !resp.has_focus() { - ui.data_mut(|d| d.remove::(id)); - } else { - ui.data_mut(|d| d.insert_temp(id, v.clone())); - } - }); - } - ui.add_space(6.0); -} - -/// Shows the Outline view as a pane body. -#[allow(dead_code)] // P3(panels-w6): pn.A5 -pub(crate) fn outline_body(app: &mut SlideApp, ui: &mut Ui, cx: &mut craft::ui::contract::BodyCx<'_>) { - let _ = (app, ui, cx); - todo!("pn.A5") -} diff --git a/crates/ui-egui/src/sorter/ui_tests.rs b/crates/ui-egui/src/sorter/ui_tests.rs index 7d691d50a..d975f4883 100644 --- a/crates/ui-egui/src/sorter/ui_tests.rs +++ b/crates/ui-egui/src/sorter/ui_tests.rs @@ -1,7 +1,9 @@ -//! Slide Sorter sections: add, rename, collapse, and dragging a whole section. +//! App selection mapping, section fold identity, rename isolation and Outline placeholders. +use craft::behavior::PartKey; +use craft::ui::runtime::inspect; use deckcraft_engine::Session; -use egui::Pos2; +use egui::{Pos2, accesskit::Role}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; @@ -17,13 +19,17 @@ fn harness(with_sections: bool) -> Harness<'static, SlideApp> { s.execute("section.add", &json!({"name": "Alpha", "at": 0})).unwrap(); s.execute("section.add", &json!({"name": "Beta", "at": 2})).unwrap(); } - // P3(panels-w6): sh.A2 let mut app = SlideApp::new_base(s, Services::default()); app.ui.view = crate::ViewMode::Sorter; 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| { + let rerun = ui.input(|input| !input.events.is_empty()); app.logic(ui.ctx()); - app.ui(ui); + let _ = inspect::record(ui, egui::Id::new("sorter-trial"), |ui| app.ui(ui)); + // egui supplies events to the first pass only; rerunning that frame must not repeat them. + if rerun { + craft::ui::runtime::frame::discard_pass(ui.ctx(), "exercise the input frame's second pass"); + } }, app, ); @@ -66,110 +72,29 @@ pub(crate) fn drag(h: &mut Harness<'_, SlideApp>, from: Pos2, to: Pos2) { h.run_steps(3); } -#[test] -fn drop_slot_and_move_dest() { - assert_eq!(super::drop_slot(&[10.0, 40.0, 70.0], 0.0), 0); - assert_eq!(super::drop_slot(&[10.0, 40.0, 70.0], 20.0), 1); - assert_eq!(super::drop_slot(&[10.0, 40.0, 70.0], 100.0), 3); - assert_eq!(super::move_dest(1, 1), None); - assert_eq!(super::move_dest(1, 2), None); - assert_eq!(super::move_dest(1, 0), Some(0)); - assert_eq!(super::move_dest(0, 2), Some(1)); -} - -#[test] -fn add_section_splits_at_the_current_slide() { - let mut h = harness(false); - assert!(h.query_by_label("Slide 4").is_some()); - assert!(section_names(&h).is_empty()); - h.get_by_label("Add Section").click(); - h.run_steps(3); - assert_eq!(section_names(&h), ["Default Section", "Untitled Section"]); - let slides = section_slides(&h); - assert_eq!(slides[0].len(), 3); - assert_eq!(slides[1].len(), 1); - assert!(h.query_by_label("Default Section").is_some()); - assert!(h.query_by_label("Untitled Section").is_some()); - assert!(h.query_by_label("Slide 1").is_some() && h.query_by_label("Slide 4").is_some()); -} - -#[test] -fn collapse_hides_that_sections_slides_and_expand_brings_them_back() { - let mut h = harness(true); - assert_eq!(section_names(&h), ["Alpha", "Beta"]); - assert_eq!(section_slides(&h).iter().map(|s| s.len()).collect::>(), [2, 2]); - assert!(h.query_by_label("Slide 1").is_some() && h.query_by_label("Slide 4").is_some()); - h.get_by_label("Collapse Beta").click(); - h.run_steps(2); - assert!(h.query_by_label("Slide 1").is_some() && h.query_by_label("Slide 2").is_some()); - assert!(h.query_by_label("Slide 3").is_none() && h.query_by_label("Slide 4").is_none()); - assert!(h.query_by_label("Expand Beta").is_some()); - h.get_by_label("Expand Beta").click(); - h.run_steps(2); - assert!(h.query_by_label("Slide 3").is_some() && h.query_by_label("Slide 4").is_some()); -} - -#[test] -fn double_click_renames_and_switching_documents_drops_the_draft() { - let mut h = harness(true); - let beta = h.get_by_label("Beta").rect().center(); - double_click(&mut h, beta); - assert!(h.state().sorter.renaming.is_some(), "double-click starts renaming"); - h.event(egui::Event::Text("Gamma".into())); +fn fold(h: &mut Harness<'_, SlideApp>, group: usize) { + let record = inspect::recorded(&h.ctx, egui::Id::new("sorter-trial")).unwrap(); + let disclosure = record.hits.iter().find(|hit| hit.part == Some(PartKey::new("group_toggle").at(group as u64))).unwrap().rect.center(); + h.hover_at(disclosure); h.run_steps(1); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(section_names(&h), ["Alpha", "Gamma"]); - assert!(h.state().sorter.renaming.is_none()); - - // Past the double-click window, so the next two clicks count as a new double-click. - h.run_steps(25); - let gamma = h.get_by_label("Gamma").rect().center(); - double_click(&mut h, gamma); - assert!(h.state().sorter.renaming.is_some()); - h.event(egui::Event::Text("Nope".into())); - h.run_steps(1); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(section_names(&h), ["Alpha", "Gamma"]); - assert!(h.query_by_label("Nope").is_none()); - - h.run_steps(25); - let gamma = h.get_by_label("Gamma").rect().center(); - double_click(&mut h, gamma); - assert!(h.state().sorter.renaming.is_some()); - h.event(egui::Event::Text("Draft".into())); - h.run_steps(1); - h.state_mut().run("file.new", json!({})).unwrap(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: disclosure, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } h.run_steps(2); - assert!(h.state().sorter.renaming.is_none(), "a different presentation drops the draft"); - h.state_mut().session.set_active(0); - h.run_steps(2); - assert_eq!(section_names(&h), ["Alpha", "Gamma"]); } -#[test] -fn dragging_a_section_moves_it_and_keeps_it_collapsed() { - let mut h = harness(true); - let before = section_slides(&h); - h.get_by_label("Collapse Beta").click(); - h.run_steps(2); - let (alpha, beta) = (h.get_by_label("Alpha").rect(), h.get_by_label("Beta").rect()); - assert!(beta.top() > alpha.bottom()); - drag(&mut h, beta.center(), Pos2::new(alpha.center().x, alpha.top() - 4.0)); - assert_eq!(section_names(&h), ["Beta", "Alpha"]); - let after = section_slides(&h); - assert_eq!(after[0], before[1]); - assert_eq!(after[1], before[0]); - let doc = &h.state().session.active().unwrap().doc; - let order: Vec = doc.slides.iter().map(|s| s.id.0).collect(); - let expect: Vec = after.iter().flatten().copied().collect(); - assert_eq!(order, expect, "slides follow the section order"); - assert!(h.query_by_label("Expand Beta").is_some(), "Beta stays collapsed after the move"); - assert!(h.query_by_label("Slide 1").is_none() && h.query_by_label("Slide 2").is_none()); - assert!(h.query_by_label("Slide 3").is_some() && h.query_by_label("Slide 4").is_some()); - let (beta, alpha) = (h.get_by_label("Beta").rect(), h.get_by_label("Alpha").rect()); - assert!(beta.top() < alpha.top()); +fn header_rect(h: &Harness<'_, SlideApp>, index: usize) -> egui::Rect { + let names = section_names(h); + let record = inspect::recorded(&h.ctx, egui::Id::new("sorter-trial")).unwrap(); + let label = record + .elements + .iter() + .filter_map(|element| element.facts.as_ref()) + .filter_map(|facts| facts.name.as_ref()) + .find(|label| label.starts_with(&names[index])) + .unwrap(); + h.get_by_role_and_label(Role::Heading, label).rect() } fn slide_order(h: &Harness<'_, SlideApp>) -> Vec { @@ -180,57 +105,6 @@ fn selected_slides(h: &Harness<'_, SlideApp>) -> Vec { h.state().session.active().unwrap().selection.slides.iter().map(|s| s.0).collect() } -#[test] -fn dragging_a_selected_slide_moves_the_whole_selection() { - let mut h = harness(false); - let ids = slide_order(&h); - h.state_mut().run("slide.selectSlides", json!({"ids": [ids[0], ids[2]]})).unwrap(); - h.run_steps(2); - let (first, last) = (h.get_by_label("Slide 1").rect(), h.get_by_label("Slide 4").rect()); - // The right half of the last slide: the gap after it. - drag(&mut h, first.center(), Pos2::new(last.right() - 10.0, last.center().y)); - assert_eq!(slide_order(&h), [ids[1], ids[3], ids[0], ids[2]]); - assert_eq!(selected_slides(&h), [ids[0], ids[2]], "the moved slides stay selected"); - assert!(h.state().thumb_drag.is_none()); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(slide_order(&h), ids, "one undo puts both back"); -} - -#[test] -fn dragging_an_unselected_slide_moves_only_it() { - let mut h = harness(false); - let ids = slide_order(&h); - h.state_mut().run("slide.selectSlides", json!({"ids": [ids[0], ids[2]]})).unwrap(); - h.run_steps(2); - let (second, last) = (h.get_by_label("Slide 2").rect(), h.get_by_label("Slide 4").rect()); - drag(&mut h, second.center(), Pos2::new(last.right() - 10.0, last.center().y)); - assert_eq!(slide_order(&h), [ids[0], ids[2], ids[3], ids[1]]); - assert_eq!(selected_slides(&h), [ids[1]]); -} - -#[test] -fn dropping_a_selection_where_it_is_changes_nothing() { - let mut h = harness(false); - let ids = slide_order(&h); - h.state_mut().run("slide.selectSlides", json!({"ids": [ids[1], ids[2]]})).unwrap(); - h.run_steps(2); - let steps = h.state().session.active().unwrap().history.undo.len(); - let (second, third) = (h.get_by_label("Slide 2").rect(), h.get_by_label("Slide 3").rect()); - drag(&mut h, second.center(), Pos2::new(third.right() - 10.0, third.center().y)); - assert_eq!(slide_order(&h), ids); - assert_eq!(h.state().session.active().unwrap().history.undo.len(), steps, "a drop in place adds no undo step"); -} - -#[test] -fn ctrl_a_selects_every_slide() { - let mut h = harness(false); - h.key_combination_modifiers(egui::Modifiers::COMMAND, &[egui::Key::A]); - h.run_steps(2); - let st = h.state().session.active().unwrap(); - let all = st.doc.slides.len(); - assert_eq!(st.selection.slides.len(), all, "Ctrl+A in the sorter selects every slide"); -} - fn selected(h: &Harness<'_, SlideApp>) -> Vec { let st = h.state().session.active().unwrap(); let mut v: Vec = st.selection.slides.iter().filter_map(|id| st.doc.slide_index(*id)).collect(); @@ -238,46 +112,182 @@ fn selected(h: &Harness<'_, SlideApp>) -> Vec { v } +#[test] +fn collapse_hides_that_sections_slides_and_expand_brings_them_back() { + let mut h = harness(true); + let names = section_names(&h); + let before = section_slides(&h); + let alpha: Vec<_> = (1..=before[0].len()).map(|n| n.to_string()).collect(); + let beta: Vec<_> = (before[0].len() + 1..=slide_order(&h).len()).map(|n| n.to_string()).collect(); + for label in alpha.iter().chain(&beta) { + assert!(h.query_by_label(label).is_some()); + } + fold(&mut h, 1); + for label in &alpha { + assert!(h.query_by_label(label).is_some(), "the other section remains visible"); + } + for label in &beta { + assert!(h.query_by_label(label).is_none(), "folding hides this section's tiles"); + } + assert_eq!(section_names(&h), names); + assert_eq!(section_slides(&h), before); + h.run_steps(40); + fold(&mut h, 1); + for label in &beta { + assert!(h.query_by_label(label).is_some(), "expanding restores every tile"); + } +} + +#[test] +fn double_click_renames_and_switching_documents_drops_the_draft() { + let mut h = harness(true); + let mut names = section_names(&h); + let beta = header_rect(&h, 1).center(); + double_click(&mut h, beta); + assert!(h.query_all_by_role(Role::TextInput).any(|node| node.is_focused())); + let renamed = "Gamma"; + h.event(egui::Event::Text(renamed.into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); + names[1] = renamed.to_owned(); + assert_eq!(section_names(&h), names); + + h.run_steps(40); + let gamma = header_rect(&h, 1).center(); + double_click(&mut h, gamma); + h.event(egui::Event::Text("Cancelled title".into())); + h.run_steps(1); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(section_names(&h), names, "Escape leaves the section unchanged"); + + h.run_steps(40); + let gamma = header_rect(&h, 1).center(); + double_click(&mut h, gamma); + h.event(egui::Event::Text("Draft".into())); + h.run_steps(1); + h.state_mut().run("file.new", json!({})).unwrap(); + h.run_steps(2); + let other = section_names(&h); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(section_names(&h), other, "a draft cannot rename another document"); + h.state_mut().session.set_active(0); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(section_names(&h), names, "returning cannot commit an abandoned draft"); +} + +#[test] +fn dragging_a_section_moves_it_and_keeps_it_collapsed() { + let mut h = harness(true); + let before = section_slides(&h); + let names = section_names(&h); + fold(&mut h, 1); + let (alpha, beta) = (header_rect(&h, 0), header_rect(&h, 1)); + assert!(beta.top() > alpha.bottom()); + drag(&mut h, beta.center(), alpha.center_top()); + assert_eq!(section_names(&h), names.into_iter().rev().collect::>()); + let after = section_slides(&h); + assert_eq!(after, before.into_iter().rev().collect::>()); + assert_eq!(slide_order(&h), after.iter().flatten().copied().collect::>(), "slides follow their sections"); + let st = h.state().session.active().unwrap(); + let fold_key = (st.uid, after[0][0]); + assert!(h.state().sorter.collapsed.contains(&fold_key), "fold state follows the first slide"); + for n in 1..=after[0].len() { + assert!(h.query_by_label(&n.to_string()).is_none(), "the moved section stays folded"); + } + for n in after[0].len() + 1..=slide_order(&h).len() { + assert!(h.query_by_label(&n.to_string()).is_some(), "the other section stays open"); + } +} + +#[test] +fn ctrl_a_selects_every_slide() { + let mut h = harness(false); + let all = slide_order(&h); + assert!(selected_slides(&h).len() < all.len()); + h.key_combination_modifiers(egui::Modifiers::COMMAND, &[egui::Key::A]); + h.run_steps(2); + let mut selected = selected_slides(&h); + selected.sort_unstable(); + let mut all = all; + all.sort_unstable(); + assert_eq!(selected, all, "Select All reaches the Sorter before any click"); +} + #[test] fn shift_and_ctrl_shift_clicks_select_ranges() { use egui::Modifiers; let mut h = harness(false); - let click = |h: &mut Harness<'_, SlideApp>, n: usize, m: Modifiers| { - h.get_by_label(&format!("Slide {n}")).click_modifiers(m); + let click = |h: &mut Harness<'_, SlideApp>, n: usize, modifiers: Modifiers| { + h.get_by_label(&n.to_string()).click_modifiers(modifiers); h.run_steps(2); }; - // Click slide 2, Shift+click slide 4: slides 2–4, slide 4 current. click(&mut h, 2, Modifiers::NONE); click(&mut h, 4, Modifiers::SHIFT); - assert_eq!(selected(&h), vec![1, 2, 3]); + assert_eq!(selected(&h), (1..4).collect::>()); assert_eq!(h.state().session.active().unwrap().selection.slide, 3); - // A second Shift+click extends from slide 2 again, not from slide 4. click(&mut h, 1, Modifiers::SHIFT); - assert_eq!(selected(&h), vec![0, 1]); - // Click 1, Ctrl+click 2, Ctrl+Shift+click 4: the range joins what is selected. + assert_eq!(selected(&h), (0..2).collect::>(), "a later range retains the original anchor"); + h.run_steps(40); click(&mut h, 1, Modifiers::NONE); click(&mut h, 3, Modifiers::COMMAND); + assert_eq!(selected(&h), vec![0, 2]); + assert_eq!(h.state().session.active().unwrap().selection.slide, 2); click(&mut h, 4, Modifiers::COMMAND | Modifiers::SHIFT); assert_eq!(selected(&h), vec![0, 2, 3]); + assert_eq!(h.state().session.active().unwrap().selection.slide, 3); } -/// The outline view lists a slide's title and body text, not its footer, date and slide-number -/// placeholders, as PowerPoint's does: turning them on leaves the slide's outline block as it was. #[test] fn the_outline_view_leaves_footer_date_and_slide_number_out() { let mut s = Session::with_new(); s.execute("slide.new", &json!({"layout": "titleAndContent", "title": "Agenda", "body": "First point\nSecond point"})).unwrap(); - let slide = |s: &Session| { - let st = s.doc().unwrap(); - st.doc.slides[st.selection.slide].clone() - }; - let plain = super::outline_estimate(&slide(&s)); s.execute( "design.headerFooter", &json!({"footer": true, "footerText": "Company Confidential", "slideNumber": true, "date": true, "dateText": "1 May 2026"}), ) .unwrap(); - let with_footer = slide(&s); - assert!(with_footer.shapes.iter().any(|x| x.ph_type().is_some_and(|k| k.is_footer_kind())), "the footers are on the slide"); - assert_eq!(super::outline_estimate(&with_footer), plain); + let st = s.active().unwrap(); + let slide = &st.doc.slides[st.selection.slide]; + let excluded: Vec<_> = slide + .shapes + .iter() + .filter(|shape| shape.ph_type().is_some_and(|kind| kind.is_footer_kind())) + .filter_map(|shape| shape.text.as_ref()) + .map(|text| text.text()) + .filter(|text| !text.is_empty()) + .collect(); + assert!(!excluded.is_empty(), "the slide contains footer placeholders"); + let included: Vec<_> = slide + .shapes + .iter() + .filter(|shape| !shape.ph_type().is_some_and(|kind| kind.is_footer_kind())) + .filter_map(|shape| shape.text.as_ref()) + .map(|text| text.text()) + .filter(|text| !text.is_empty()) + .collect(); + let mut app = SlideApp::new_base(s, Services::default()); + app.ui.view = crate::ViewMode::Outline; + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut SlideApp| { + app.logic(ui.ctx()); + crate::panels::show_editor(app, ui); + }, + app, + ); + h.run_steps(3); + let words = craft::ui::runtime::env::Env::of_root(&h.ctx).words::(); + let values: Vec<_> = h.query_all_by_role(Role::TextInput).filter_map(|node| node.value()).collect(); + assert!(h.query_by_role_and_label(Role::TextInput, words.slide_title.as_str()).is_some()); + assert!(h.query_by_role_and_label(Role::TextInput, words.slide_text.as_str()).is_some()); + for text in included { + assert!(values.contains(&text), "title and body belong in the Outline"); + } + for text in excluded { + assert!(!values.contains(&text), "footer, date and slide number stay out of Outline fields"); + } }