AnyBot/src/app/pages_ui.rs

385 lines
22 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 頁面 in the window: the card under a reply (one compact card — icon, title, one line of what it
// says, one grey line of what it is), the
// page itself in a large dialog (the whole page drawn with the chat's Markdown, the version picker
// and 存成檔案), and the list under 資料庫 in the right panel.
use super::*;
const CARD_W: f32 = 520.0;
/// The narrowest a number tile gets inside before the tiles go two to a row.
const KPI_TILE_MIN: f32 = 150.0;
impl App {
/// The card for page `id` under a reply.
pub(super) fn page_card(&mut self, ui: &mut egui::Ui, id: u64) {
let p = self.pal;
let Some(page) = self.state.pages.iter().find(|x| x.id == id).cloned() else {
ui.label(RichText::new(t("(這個頁面已刪除)")).size(FONT_SM).color(p.text3));
return;
};
let now = crate::model::now_ms();
let w = ui.available_width().min(CARD_W);
// One compact card, the way Claude shows a document in a chat: the page's icon, its
// title once, one line of what it says (what changed, when it was updated), and one grey
// line of what it is. (It used to show the title twice and four fading lines of the page.)
let gist = if page.revision > 1 && !page.note.is_empty() {
format!("{}:{}", t("已更新"), page.note)
} else if !page.summary.is_empty() {
page.summary.clone()
} else {
crate::pages::preview(&page, 1).into_iter().next().unwrap_or_default()
};
let mut meta = format!("{} · {}", t("頁面"), crate::pages::ago(page.updated, now));
if let Some(k) = crate::pages::kind_label(&page.kind) {
meta = format!("{k} · {meta}");
}
if page.revision > 1 {
meta = format!("{meta} · {} {} {}", t("第"), page.revision, t("版"));
}
let resp = Frame::new().fill(p.pane).stroke(Stroke::new(1.0, p.border)).corner_radius(R_L).inner_margin(Margin::symmetric(14, 12)).show(ui, |ui| {
ui.set_width(w - 28.0);
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = crate::theme::sp::S3;
let (ir, _) = ui.allocate_exact_size(vec2(30.0, 36.0), egui::Sense::hover());
page_glyph(ui.painter(), ir, p);
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
ui.add(egui::Label::new(RichText::new(&page.title).size(FONT_BASE).family(crate::bold()).color(p.text)).truncate());
if !gist.is_empty() {
ui.add(egui::Label::new(RichText::new(&gist).size(FONT_SM).color(p.text2)).truncate());
}
ui.label(RichText::new(meta).size(FONT_XS).color(p.text3));
});
});
});
let r = ui.interact(resp.response.rect, egui::Id::unique(("page-card", id, self.msg_index)), egui::Sense::click());
if r.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
if r.on_hover_text(t("打開頁面")).clicked() {
self.page_view = Some((id, None));
}
}
/// The page, large: everything drawn like the chat, with the version picker and the footer.
/// The page's number tiles: each a stack — what (grey), the number (large), how it moved (green
/// or red) — all of a row the same width, in rows that fit the column: 4 side by side when
/// each gets KPI_TILE_MIN, else 2 a row (3 → 3, else 1). Words too long for a tile end in …
/// and say themselves on hover. (Inside the row's left-to-right layout the three lines sat side
/// by side, the tiles grew past the column and pushed the 頁面 window off its own title bar.)
fn page_kpis(&self, ui: &mut egui::Ui, kpis: &[crate::pages::Kpi]) {
use crate::theme::sp;
let p = self.pal;
let kpis = &kpis[..kpis.len().min(4)];
let gap = sp::S2;
// A tile's inner width when `per` share a row: less its padding (12 a side) and border.
let inner = |per: usize| (ui.available_width() - gap * (per as f32 - 1.0)) / per as f32 - 26.0;
let n = kpis.len();
let per = [n, n.div_ceil(2), 1].into_iter().find(|&k| inner(k) >= KPI_TILE_MIN).unwrap_or(1);
let kw = inner(per).max(40.0);
for (i, row) in kpis.chunks(per).enumerate() {
if i > 0 {
ui.add_space(gap);
}
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = gap;
for k in row {
Frame::new().stroke(Stroke::new(1.0, p.border)).corner_radius(R_M).inner_margin(Margin::symmetric(12, 10)).show(ui, |ui| {
ui.set_width(kw);
ui.vertical(|ui| {
ui.set_max_width(kw);
ui.spacing_mut().item_spacing.y = 2.0;
let line = |ui: &mut egui::Ui, text: RichText, full: &str| {
let r = ui.add(egui::Label::new(text).truncate());
if r.intrinsic_size().is_some_and(|s| s.x > kw + 0.5) {
r.on_hover_text(full);
}
};
line(ui, RichText::new(&k.label).size(FONT_XS).color(p.text3), &k.label);
line(ui, RichText::new(&k.value).size(FONT_H2).strong().family(crate::bold()).color(p.text), &k.value);
if !k.delta.is_empty() {
let c = match crate::pages::stat_trend(&k.delta) {
Some(true) => p.up,
Some(false) => p.danger,
None => p.text3,
};
line(ui, RichText::new(&k.delta).size(FONT_XS).color(c), &k.delta);
}
});
});
}
});
}
}
pub(super) fn page_viewer(&mut self, ctx: &egui::Context) {
let Some((id, rev)) = self.page_view else { return };
let p = self.pal;
let Some(cur) = self.state.pages.iter().find(|x| x.id == id).cloned() else {
self.page_view = None;
self.notice = Some(t("這個頁面已經刪除了"));
return;
};
let shown = rev.and_then(|r| crate::pages::version_of(&cur, r)).unwrap_or_else(|| cur.clone());
let old = shown.revision != cur.revision;
let bot_name = self.state.bot(cur.bot).map(|b| b.name.clone()).unwrap_or_default();
let w = (ctx.content_rect().width() - 80.0).clamp(360.0, 860.0);
let h = (dialog_max_height(ctx) - 150.0).max(240.0);
let mut keep = true;
let mut delete = false;
let mut pick: Option<Option<u32>> = None;
let close = dialog(ctx, "page-view", "頁面", w, true, p, |ui| {
dialog_body(ui, ("page-body", id), h, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
// 閱讀欄: the page rides in a centred column about 42 characters of 16 px text
// wide — lines short enough to read; nothing flush with the window edges.
let avail = ui.available_width();
let cw = avail.min(680.0);
ui.horizontal(|ui| {
ui.add_space(((avail - cw) * 0.5).max(0.0));
ui.vertical(|ui| {
ui.set_width(cw);
ui.spacing_mut().item_spacing.y = 0.0;
use crate::theme::sp;
// The head of a document: its title in the reading face, one grey line of
// what it is and when, then (when there is one) what changed this time.
ui.add(egui::Label::new(RichText::new(&shown.title).size(FONT_H1).family(crate::read_bold()).color(p.text)).wrap());
ui.add_space(sp::S2);
let mut meta = format!("{} · {} {}", bot_name, t("更新於"), crate::pages::when(shown.updated));
if let Some(k) = crate::pages::kind_label(&shown.kind) {
meta = format!("{k} · {meta}");
}
if cur.revision > 1 || old {
meta = format!("{meta} · {} {}", t("第"), shown.revision) + &t(" 版");
}
ui.label(RichText::new(meta).size(FONT_XS).color(p.text3));
if !old && !shown.note.is_empty() && shown.revision > 1 {
ui.add_space(sp::S1);
ui.add(egui::Label::new(RichText::new(format!("{}:{}", t("這一版更新了"), shown.note)).size(FONT_SM).color(p.text3)).wrap());
}
if old {
ui.add_space(sp::S3);
Frame::new().fill(p.muted).corner_radius(R_M).inner_margin(Margin::symmetric(12, 8)).show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(t("你在看舊的版本")).size(FONT_SM).color(p.text2));
if ui.add(secondary_button("回到最新版")).clicked() {
pick = Some(None);
}
});
});
} else if !shown.summary.is_empty() {
// The one-line conclusion opens the text, a step larger, unboxed.
ui.add_space(sp::S4);
ui.add(egui::Label::new(RichText::new(&shown.summary).size(FONT_H3).family(crate::read()).color(p.text)).wrap());
}
// 第一屏: the verdict, then the numbers — only what exists is drawn.
if !old && !shown.verdict.is_empty() {
ui.add_space(sp::S4);
Frame::new().fill(p.muted).corner_radius(R_M).inner_margin(Margin::symmetric(16, 12)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.spacing_mut().item_spacing.y = sp::S1;
ui.label(RichText::new(t("結論")).size(FONT_XS).strong().family(crate::bold()).color(p.text3));
ui.add(egui::Label::new(RichText::new(&shown.verdict).size(FONT_READ).family(crate::read_bold()).color(p.text)).wrap());
});
}
if !old && !shown.kpis.is_empty() {
ui.add_space(sp::S4);
self.page_kpis(ui, &shown.kpis);
}
// 目錄: a page with sections lists them on one quiet line — 「目錄 · N 節」 —
// that unfolds into the headings (click one to jump; the box narrows the
// list, ⌘F unfolds it and puts the caret there). It never fills the first screen.
let heads: Vec<(usize, String)> = crate::app::markdown_ui::parse(&shown.body)
.iter()
.filter_map(|b| match b {
crate::app::markdown_ui::Block::Heading(level, spans) => {
let text: String = spans.iter().map(|s| s.text.as_str()).collect();
let text = text.trim().to_string();
(!text.is_empty()).then_some((*level as usize, text))
}
_ => None,
})
.collect();
if !old && heads.len() >= 3 {
ui.add_space(sp::S4);
let open = self.page_toc_open || !self.page_find.is_empty();
let head = format!("{} {} · {} {}", if open { "▾" } else { "▸" }, t("目錄"), heads.len(), t("節"));
let r = ui.add(egui::Label::new(RichText::new(head).size(FONT_SM).color(p.text2)).sense(egui::Sense::click()));
if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
self.page_toc_open = !open;
if !self.page_toc_open {
self.page_find.clear();
}
}
if open {
ui.add_space(sp::S2);
ui.add(egui::TextEdit::singleline(&mut self.page_find).id(egui::Id::unique("page-find")).hint_text(t("找標題…")).desired_width(220.0));
ui.add_space(sp::S1);
let q = self.page_find.trim().to_lowercase();
let top = heads.iter().map(|(l, _)| *l).min().unwrap_or(1);
let mut n = 0;
for (level, text) in heads.iter().filter(|(_, h)| q.is_empty() || h.to_lowercase().contains(&q)) {
n += 1;
ui.horizontal(|ui| {
ui.add_space(sp::S4 * (level - top) as f32);
let color = if *level == top { p.text } else { p.text2 };
let r = ui.add(egui::Label::new(RichText::new(text).size(FONT_SM).color(color)).sense(egui::Sense::click()).truncate());
if r.hovered() {
ui.painter().hline(r.rect.x_range(), r.rect.bottom(), Stroke::new(1.0, p.text3));
}
if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
self.page_goto = Some(text.clone());
}
});
ui.add_space(sp::S1);
}
if n == 0 {
ui.label(RichText::new(t("沒有相符的標題")).size(FONT_XS).color(p.text3));
}
}
}
ui.add_space(crate::theme::sp::S5);
let body = shown.body.clone();
// 閱讀模式: the page's Markdown gets article typography (chat keeps the dense one).
self.md_article = true;
self.markdown(ui, &body, p.text, false);
self.md_article = false;
ui.add_space(8.0);
// 目錄 clicked: the body just measured its headings — scroll to the one asked for.
if let Some(want) = self.page_goto.take() {
if let Some((_, r)) = self.md_head_rects.iter().find(|(t, _)| *t == want) {
ui.scroll_to_rect(*r, Some(egui::Align::TOP));
}
}
});
});
});
dialog_footer(ui, p, |ui| {
// Left: what changes the page itself (its versions; 刪除, two presses, like the
// phone — a page can't come back). Right: what you take away, then 完成.
if !cur.history.is_empty() {
let label = if old { format!("{} {}", t("第"), shown.revision) + &t(" 版") } else { t("版本紀錄") };
egui::ComboBox::from_id_salt(("page-versions", id)).selected_text(label).width(150.0).show_ui(ui, |ui| {
if ui.selectable_label(!old, format!("{} {} {}({})", t("第"), cur.revision, t("版"), t("最新"))).clicked() {
pick = Some(None);
}
for v in cur.history.iter().rev() {
let text = format!("{} {} {} · {}", t("第"), v.revision, t("版"), crate::pages::when(v.at));
if ui.selectable_label(rev == Some(v.revision), text).clicked() {
pick = Some(Some(v.revision));
}
}
});
}
if !old {
if self.confirm_delete_page == Some(id) {
if ui.add(egui::Button::new(RichText::new(t("確定刪除")).color(p.danger)).frame(false)).clicked() {
delete = true;
self.confirm_delete_page = None;
}
if ui.add(egui::Button::new(RichText::new(t("取消")).color(p.text2)).frame(false)).clicked() {
self.confirm_delete_page = None;
}
} else if ui.add(egui::Button::new(RichText::new(t("刪除")).color(p.danger)).frame(false)).clicked() {
self.confirm_delete_page = Some(id);
}
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.add(primary_button("完成", p)).clicked() {
keep = false;
}
if ui.add(secondary_button("存成檔案")).on_hover_text(t("存成 Markdown 到「下載」")).clicked() {
let dir = dirs::download_dir().unwrap_or_else(std::env::temp_dir);
let name: String = shown.title.chars().filter(|c| !"/\\:*?\"<>|".contains(*c)).collect();
let path = dir.join(format!("{name}.md"));
let text = format!("# {}\n\n{}\n", shown.title, shown.body);
match std::fs::write(&path, text) {
Ok(()) => {
crate::preview::reveal(&path);
self.notice = Some(format!("{}{}", t("已存到 "), path.display()));
}
Err(e) => self.notice = Some(format!("{}{e}", t("存不了:"))),
}
}
if ui.add(secondary_button("複製")).on_hover_text(t("複製成 Markdown")).clicked() {
crate::platform::copy_text(ui.ctx(), &format!("# {}\n\n{}", shown.title, shown.body));
self.notice = Some(t("已複製"));
}
});
});
});
if let Some(v) = pick {
self.page_view = Some((id, v));
return;
}
if delete {
self.state.pages.retain(|x| x.id != id);
self.page_view = None;
self.notice = Some(format!("{}「{}」", t("已刪除頁面"), cur.title));
self.mark();
return;
}
if close || !keep {
self.page_view = None;
// The next page opens with its 目錄 folded and an empty search.
self.page_find.clear();
self.page_toc_open = false;
self.page_goto = None;
}
}
/// 資料庫 › 頁面: this bot's pages, newest change first. Whether there were any.
pub(super) fn pages_library(&mut self, ui: &mut egui::Ui, bot: &Bot) -> bool {
let p = self.pal;
let mut mine: Vec<crate::pages::Page> = self.state.pages.iter().filter(|x| x.bot == bot.id).cloned().collect();
if mine.is_empty() {
return false;
}
mine.sort_by_key(|x| std::cmp::Reverse(x.updated));
let now = crate::model::now_ms();
let mut open = None;
super::panel_ui::panel_title(ui, "頁面", p);
super::panel_ui::panel_card(ui, p, |ui| {
for pg in &mine {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), egui::Sense::click());
if r.hovered() {
ui.painter().rect_filled(rect, R_M, p.hover);
}
let ir = egui::Rect::from_center_size(rect.left_center() + vec2(20.0, 0.0), vec2(18.0, 24.0));
page_glyph(ui.painter(), ir, p);
let x = rect.left() + 38.0;
let title = super::panel_ui::shorten_size(ui, &pg.title, rect.right() - x - 8.0, 13.0);
ui.painter().text(egui::pos2(x, rect.top() + 6.0), egui::Align2::LEFT_TOP, title, egui::FontId::proportional(FONT_SM), p.text);
ui.painter().text(egui::pos2(x, rect.top() + 25.0), egui::Align2::LEFT_TOP, format!("{} · {}", t("頁面"), crate::pages::ago(pg.updated, now)), egui::FontId::proportional(FONT_XS), p.text3);
if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
open = Some(pg.id);
}
}
});
if let Some(id) = open {
self.page_view = Some((id, None));
}
true
}
}
/// The page icon: a sheet with a folded corner, two text lines and four coloured bars (like the
/// original's page glyph).
pub(super) fn page_glyph(painter: &egui::Painter, r: egui::Rect, p: Palette) {
let w = r.width().min(r.height() * 0.8);
let rect = egui::Rect::from_center_size(r.center(), vec2(w, w * 1.25));
painter.rect_filled(rect, R_S, p.hover);
painter.rect_stroke(rect, R_S, Stroke::new(1.0, p.border), egui::StrokeKind::Inside);
let u = rect.width() / 10.0;
let l = rect.left() + u * 2.0;
painter.hline(l..=(rect.left() + u * 6.0), rect.top() + u * 2.6, Stroke::new(u * 0.9, p.text3));
painter.hline(l..=(rect.left() + u * 4.6), rect.top() + u * 4.4, Stroke::new(u * 0.9, p.text3));
let colors = [Color32::from_rgb(0x34, 0xa8, 0x53), Color32::from_rgb(0xfb, 0xbc, 0x05), Color32::from_rgb(0xea, 0x43, 0x35), Color32::from_rgb(0x42, 0x85, 0xf4)];
let base = rect.bottom() - u * 2.0;
for (i, c) in colors.iter().enumerate() {
let h = u * (2.0 + i as f32 * 1.1);
let x = l + i as f32 * u * 1.7;
painter.rect_filled(egui::Rect::from_min_max(egui::pos2(x, base - h), egui::pos2(x + u * 1.1, base)), 1, *c);
}
}