// 記憶 in the window: the memory page (a dialog: counts, live search, filters, what could be // cleaned up, and every memory with what it is, when, how often it rode along), the suggestions // above the composer (searched 300 ms after typing stops; the strong ones ticked), and the tag // under a message of the person's saying which memories it carried. // // Where the memories live: on the brain. A screen asks it (/api/sync/memory); a brain or a // computer on its own answers itself — reads on a thread, changes here (they touch the bot's list). use super::*; use serde_json::{json, Value}; use std::sync::mpsc::{channel, Receiver}; /// Typing has to stop this long before the shelf is searched. const SUGGEST_WAIT: std::time::Duration = std::time::Duration::from_millis(300); const PAGE_W: f32 = 780.0; /// The composer's suggestions for one bot. #[derive(Default)] pub struct Suggest { /// The draft as last seen, and when it changed (searched once it rests). draft: String, changed: Option, /// The draft the hits answer. asked: String, hits: Vec, /// The person's own ticks (by memory id), over the ticked-in-advance ones. toggled: HashMap, rx: Option<(String, Receiver)>, pub ms: f64, } impl Suggest { fn on(&self, h: &Value) -> bool { h["id"].as_i64().and_then(|id| self.toggled.get(&id).copied()).unwrap_or(h["pick"] == true) } /// What the message will carry: the ticked ones, once the shelf has answered this draft (or /// one a moment older). None: it never answered — the brain chooses. pub fn picks(&self) -> Option> { if self.asked.trim().is_empty() { return None; } Some(self.hits.iter().filter(|h| self.on(h)).filter_map(|h| h["text"].as_str().map(String::from)).collect()) } /// Already answered (screenshots, tests): the draft and the shelf's answer. pub fn answered(asked: &str, hits: Vec) -> Self { Suggest { asked: asked.into(), draft: asked.into(), hits, ..Default::default() } } } /// The memory page. pub struct MemPage { pub bot: u64, filter: &'static str, q: String, q_changed: Option, /// What the list on screen answers (filter, words, how many). shown: (String, String, usize), items: Vec, total: usize, ms: f64, overview: Value, limit: usize, rx_list: Option<((String, String, usize), Receiver)>, rx_over: Option>, /// Changes on their way, with the words typed into 新增 (put back if not kept). rx_write: Vec<(Receiver, Option)>, need_list: bool, need_over: bool, editing: Option<(i64, String)>, adding: String, note: String, stale_open: bool, /// Pairs the person said to keep both of (this visit). kept: Vec<(i64, i64)>, } impl MemPage { pub fn new(bot: u64) -> Self { MemPage { bot, filter: "all", q: String::new(), q_changed: None, shown: (String::new(), String::new(), 0), items: vec![], total: 0, ms: 0.0, overview: Value::Null, limit: 60, rx_list: None, rx_over: None, rx_write: vec![], need_list: true, need_over: true, editing: None, adding: String::new(), note: String::new(), stale_open: false, kept: vec![], } } } const FILTERS: [(&str, &str); 5] = [("all", "全部"), ("fact", "記得的事"), ("event", "做過的事"), ("pinned", "釘選"), ("trash", "最近刪除")]; fn kind_label(k: &str) -> &'static str { match k { "fact" => "記得的事", "rollup" => "整理過的", _ => "做過的事", } } fn day(ms: i64) -> String { use chrono::TimeZone; crate::routines::person_tz().timestamp_millis_opt(ms).single().map(|t| t.format("%Y/%-m/%-d").to_string()).unwrap_or_default() } fn mb(b: i64) -> String { if b < 1 << 20 { format!("{:.0} KB", (b as f64 / 1024.0).max(1.0)) } else { format!("{:.1} MB", b as f64 / (1 << 20) as f64) } } fn chip(ui: &mut egui::Ui, text: &str, on: bool, p: Palette) -> egui::Response { let (fill, stroke, ink) = if on { (p.accent.gamma_multiply(0.14), Stroke::new(1.0, p.accent.gamma_multiply(0.7)), p.text) } else { (Color32::TRANSPARENT, Stroke::new(1.0, p.border), p.text2) }; ui.add(egui::Button::new(RichText::new(text).size(12.5).color(ink)).fill(fill).stroke(stroke).corner_radius(14).min_size(vec2(0.0, 26.0))) } impl App { /// A memory call: a screen asks its brain; otherwise reads run on a thread and changes here. fn mem_call(&mut self, body: Value) -> Receiver { let (tx, rx) = channel(); let repaint = self.repaint_fn(); if self.mir.on { let s = self.state.remote.clone(); std::thread::spawn(move || { let _ = tx.send(crate::remote::sync_post(&s, "memory", &body).unwrap_or_else(|e| json!({"error": e}))); repaint(); }); } else if matches!(body["op"].as_str(), Some("suggest" | "search" | "list" | "stats" | "overview")) { std::thread::spawn(move || { let _ = tx.send(crate::memory::api_read(&body).unwrap_or(Value::Null)); repaint(); }); } else { let v = crate::memory::api_write(&mut self.state, &body); if v.get("ok").is_some() { self.mark(); } let _ = tx.send(v); } rx } pub(super) fn open_memory(&mut self, bot: u64) { self.mem_page = Some(MemPage::new(bot)); } // ---------- the composer ---------- /// Keep the suggestions in step with the draft (searched once typing rests). pub(super) fn mem_suggest_tick(&mut self, ctx: &egui::Context, bot: u64, draft: &str) { let st = self.mem_suggest.entry(bot).or_default(); if draft != st.draft { st.draft = draft.to_string(); st.changed = Some(Instant::now()); } if let Some((q, rx)) = &st.rx { if let Ok(v) = rx.try_recv() { // Unanswered (the brain unreachable, or too old to have a shelf) is not "the // person picked none": nothing is ticked, and the brain chooses for itself. if v.get("error").is_some() || !v["hits"].is_array() { st.asked.clear(); st.hits.clear(); st.toggled.clear(); st.rx = None; return; } st.asked = q.clone(); st.hits = v["hits"].as_array().cloned().unwrap_or_default(); st.ms = v["ms"].as_f64().unwrap_or(0.0); let ids: Vec = st.hits.iter().filter_map(|h| h["id"].as_i64()).collect(); st.toggled.retain(|id, _| ids.contains(id)); st.rx = None; } } let want = draft.trim().to_string(); let due = st.changed.map(|t| t.elapsed() >= SUGGEST_WAIT).unwrap_or(false); if st.changed.is_some() && !due { ctx.request_repaint_after(SUGGEST_WAIT); } if !due || st.rx.is_some() { return; } st.changed = None; if want == st.asked { return; } if want.chars().count() < 2 { st.asked.clear(); st.hits.clear(); st.toggled.clear(); return; } let rx = self.mem_call(json!({"op": "suggest", "bot": bot, "q": want})); if let Some(st) = self.mem_suggest.get_mut(&bot) { st.rx = Some((want, rx)); } } /// The row above the composer: the memories this draft may want, ticked or not. pub(super) fn mem_chips(&mut self, ui: &mut egui::Ui, bot: u64) { let p = self.pal; let Some(st) = self.mem_suggest.get(&bot) else { return }; if st.hits.is_empty() || st.draft.trim().is_empty() { return; } let hits = st.hits.clone(); let mut flip: Option<(i64, bool)> = None; let mut open = false; let tokens: i64 = hits.iter().filter(|h| st.on(h)).map(|h| h["tokens"].as_i64().unwrap_or(0)).sum(); let n_on = hits.iter().filter(|h| st.on(h)).count(); ui.horizontal_wrapped(|ui| { ui.add_space(12.0); ui.spacing_mut().item_spacing = vec2(6.0, 6.0); let r = crate::icons::label(ui, crate::icons::Icon::Bookmark, &t("帶入記憶"), 12.0, p.text3); if r.on_hover_text(t("打開這個 Bot 的記憶頁")).on_hover_cursor(egui::CursorIcon::PointingHand).interact(egui::Sense::click()).clicked() { open = true; } for h in &hits { let on = st.on(h); let text = h["text"].as_str().unwrap_or(""); let short: String = text.chars().take(22).collect(); let short = if text.chars().count() > 22 { format!("{short}…") } else { short }; let tip = format!("{text}\n\n{} · {} · 相關度 {:.2}{}", kind_label(h["kind"].as_str().unwrap_or("")), day(h["created"].as_i64().unwrap_or(0)), h["score"].as_f64().unwrap_or(0.0), if on { "\n點一下:這次不帶" } else { "\n點一下:這次帶上" }); if chip(ui, &format!("{}{short}", if on { "✓ " } else { "" }), on, p).on_hover_text(tip).clicked() { flip = h["id"].as_i64().map(|id| (id, !on)); } } ui.label(RichText::new(if n_on == 0 { t("這次不帶") } else { format!("帶 {n_on} 條,約 {tokens} token") }).size(11.5).color(p.text3)); }); ui.add_space(4.0); if let (Some((id, on)), Some(st)) = (flip, self.mem_suggest.get_mut(&bot)) { st.toggled.insert(id, on); } if open { self.open_memory(bot); } } /// Under a message of the person's: which memories it carried (click to see them). pub(super) fn mem_carried(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: u64, idx: usize, memories: &[String]) { let p = self.pal; let id = egui::Id::unique(("mem-carried", bot, idx)); let open = ctx.data(|d| d.get_temp::(id)).unwrap_or(false); let mut go = false; ui.with_layout(Layout::right_to_left(Align::Min), |ui| { ui.add_space(6.0); // Drawn left to right inside a box placed from the right (a nested row would follow // the right-to-left layout and put the icon last). let text = format!("帶了 {} 條記憶", memories.len()); let galley = ui.painter().layout_no_wrap(text, egui::FontId::proportional(11.5), p.text3); let size = vec2(13.0 + 4.0 + galley.size().x + 4.0 + 11.0, 18.0); let (rect, r) = ui.allocate_exact_size(size, egui::Sense::click()); let col = if r.hovered() { p.text2 } else { p.text3 }; crate::icons::paint(ui.painter(), egui::Rect::from_center_size(rect.left_center() + vec2(6.5, 0.0), vec2(12.0, 12.0)), crate::icons::Icon::Bookmark, col); ui.painter().galley(rect.left_center() + vec2(17.0, -galley.size().y / 2.0), galley, col); let chev = egui::Rect::from_center_size(rect.right_center() - vec2(5.5, 0.0), vec2(11.0, 11.0)); crate::icons::paint(ui.painter(), chev, if open { crate::icons::Icon::ArrowDown } else { crate::icons::Icon::ChevronRight }, col); if r.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(t("這則訊息送給模型時附上的記憶")).clicked() { ctx.data_mut(|d| d.insert_temp(id, !open)); } }); if open { ui.with_layout(Layout::right_to_left(Align::Min), |ui| { ui.add_space(6.0); Frame::new().fill(p.hover).corner_radius(10).inner_margin(Margin::symmetric(12, 8)).show(ui, |ui| { ui.set_max_width(message_max_width(ui.available_width()) - 40.0); ui.vertical(|ui| { for m in memories { ui.add(egui::Label::new(RichText::new(format!("• {m}")).size(12.5).color(p.text2)).wrap()); } if small_button(ui, "打開記憶頁", p).clicked() { go = true; } }); }); }); } if go { self.open_memory(bot); } } // ---------- the page ---------- pub(super) fn memory_page(&mut self, ctx: &egui::Context) { let Some(mut pg) = self.mem_page.take() else { return }; let p = self.pal; // Answers that came back. if let Some((key, rx)) = &pg.rx_list { if let Ok(v) = rx.try_recv() { if v.get("error").is_some() { pg.note = v["error"].as_str().unwrap_or("").to_string(); } else { pg.items = v["items"].as_array().cloned().unwrap_or_default(); pg.total = v["total"].as_u64().unwrap_or(0) as usize; pg.ms = v["ms"].as_f64().unwrap_or(0.0); pg.shown = key.clone(); } pg.rx_list = None; } } if let Some(rx) = &pg.rx_over { if let Ok(v) = rx.try_recv() { // An unanswered header says why, not 「記得的事 0」 as if they were gone. match v["error"].as_str() { Some(e) => pg.note = e.to_string(), None => pg.overview = v, } pg.rx_over = None; } } let mut done = vec![]; for (i, (rx, typed)) in pg.rx_write.iter().enumerate() { if let Ok(v) = rx.try_recv() { pg.note = v["text"].as_str().or(v["error"].as_str()).unwrap_or("").to_string(); // Not kept: the words go back in the box, to try again. if v.get("error").is_some() && pg.adding.trim().is_empty() { if let Some(t) = typed { pg.adding = t.clone(); } } done.push(i); } } if !done.is_empty() { for i in done.into_iter().rev() { pg.rx_write.remove(i); } pg.need_list = true; pg.need_over = true; } if pg.q_changed.map(|t| t.elapsed() >= SUGGEST_WAIT).unwrap_or(false) { pg.q_changed = None; pg.need_list = true; } else if pg.q_changed.is_some() { ctx.request_repaint_after(SUGGEST_WAIT); } let key = (pg.filter.to_string(), pg.q.trim().to_string(), pg.limit); if (pg.need_list || key != pg.shown) && pg.rx_list.is_none() && pg.q_changed.is_none() { pg.need_list = false; let rx = self.mem_call(json!({"op": "list", "bot": pg.bot, "filter": key.0, "q": key.1, "limit": key.2})); pg.rx_list = Some((key, rx)); } if pg.need_over && pg.rx_over.is_none() { pg.need_over = false; pg.rx_over = Some(self.mem_call(json!({"op": "overview", "bot": pg.bot}))); } let name = self.state.bot(pg.bot).map(|b| b.name.clone()).unwrap_or_default(); let max_h = dialog_max_height(ctx).min(760.0) - 60.0; let mut writes: Vec = vec![]; let close = dialog(ctx, "memory", &format!("{name} 的記憶"), PAGE_W, true, p, |ui| { // A steady height (not shrunk to the content): the list arrives after the first frame, // and a dialog sized to an empty list stayed that small. egui::ScrollArea::vertical().id_salt(("memory-page", pg.bot)).max_height(max_h).min_scrolled_height(max_h).auto_shrink([false, false]).show(ui, |ui| { Frame::new().inner_margin(Margin { left: 20, right: 20, top: 16, bottom: 16 }).show(ui, |ui| { ui.set_width(ui.available_width()); ui.spacing_mut().item_spacing.y = 6.0; self.mem_header(ui, &mut pg); ui.add_space(10.0); self.mem_suggestions(ui, &mut pg, &mut writes); self.mem_list(ui, &mut pg, &mut writes); }); }); }); for w in writes { let rx = self.mem_call(w); pg.rx_write.push((rx, None)); } if !close { self.mem_page = Some(pg); } } fn mem_header(&mut self, ui: &mut egui::Ui, pg: &mut MemPage) { let p = self.pal; let st = &pg.overview["stats"]; let n = |k: &str| st[k].as_i64().unwrap_or(0); // Counts, in one calm line; the files and the engine under it. ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 18.0; for (label, v) in [("記得的事", n("facts")), ("做過的事", n("events") + n("rollups")), ("釘選", n("pinned")), ("最近刪除", n("trash"))] { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; ui.label(RichText::new(t(label)).size(FONT_SM).color(p.text3)); ui.label(RichText::new(v.to_string()).size(FONT_SM).strong().color(p.text)); }); } }); let files: Vec = pg.overview["files"].as_array().map(|a| a.iter().map(|f| format!("{} {}", f["name"].as_str().unwrap_or(""), mb(f["bytes"].as_i64().unwrap_or(0)))).collect()).unwrap_or_default(); let pinned_tokens = n("pinned_tokens"); let line = format!( "釘選的每次都帶(約 {pinned_tokens} token);其他的只在相關時帶,最多 {} 條 · {}", crate::memory::AUTO_MAX, files.join(" · ") ); ui.label(RichText::new(line).size(11.5).color(p.text3)); if let Some(e) = pg.overview["engine"].as_str() { crate::icons::label(ui, crate::icons::Icon::Brain, &format!("語意搜尋:{e}"), 11.5, p.text3); } ui.add_space(10.0); // Search, and adding one. ui.horizontal(|ui| { let w = (ui.available_width() - 8.0) * 0.55; let r = ui.add_sized([w, 30.0], egui::TextEdit::singleline(&mut pg.q).hint_text(t("搜尋記憶(打字就找)")).margin(Margin::symmetric(10, 6))); if r.changed() { pg.q_changed = Some(Instant::now()); } let w2 = ui.available_width() - 70.0; let a = ui.add_sized([w2.max(80.0), 30.0], egui::TextEdit::singleline(&mut pg.adding).hint_text(t("新增一條要記得的事")).margin(Margin::symmetric(10, 6))); let enter = a.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)); if (ui.add(secondary_button("記住")).clicked() || enter) && !pg.adding.trim().is_empty() { let text = std::mem::take(&mut pg.adding); let rx = self.mem_call(json!({"op": "add", "bot": pg.bot, "text": text.clone()})); pg.rx_write.push((rx, Some(text))); } }); ui.add_space(8.0); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(6.0, 6.0); for (k, label) in FILTERS { if chip(ui, &t(label), pg.filter == k, p).clicked() && pg.filter != k { pg.filter = k; pg.limit = 60; pg.editing = None; } } if !pg.note.is_empty() { ui.add_space(8.0); ui.label(RichText::new(&pg.note).size(11.5).color(p.accent)); } }); } /// 整理建議: what could go, merged or folded — offered, never done on its own. fn mem_suggestions(&mut self, ui: &mut egui::Ui, pg: &mut MemPage, writes: &mut Vec) { let p = self.pal; if pg.filter == "trash" || !pg.q.trim().is_empty() { return; } let s = pg.overview["suggestions"].clone(); let dupes: Vec = s["dupes"].as_array().cloned().unwrap_or_default().into_iter().filter(|d| !pg.kept.contains(&(d[0]["id"].as_i64().unwrap_or(0), d[1]["id"].as_i64().unwrap_or(0)))).collect(); let stale = s["stale"].as_array().cloned().unwrap_or_default(); let (old_events, old_weeks) = (s["old_events"].as_i64().unwrap_or(0), s["old_weeks"].as_i64().unwrap_or(0)); if dupes.is_empty() && stale.is_empty() && old_events == 0 && old_weeks == 0 { return; } Frame::new().fill(p.hover).corner_radius(12).inner_margin(Margin::symmetric(14, 12)).show(ui, |ui| { ui.set_width(ui.available_width()); ui.spacing_mut().item_spacing.y = 8.0; crate::icons::label(ui, crate::icons::Icon::Sparkle, &t("整理建議"), FONT_SM, p.text); for d in &dupes { let (a, b) = (&d[0], &d[1]); ui.add(egui::Label::new(RichText::new(format!("這兩條很像:「{}」/「{}」", a["text"].as_str().unwrap_or(""), b["text"].as_str().unwrap_or(""))).size(12.5).color(p.text2)).wrap()); ui.horizontal(|ui| { if small_button(ui, "合併(留下較新的)", p).clicked() { let (keep, drop) = if a["created"].as_i64() >= b["created"].as_i64() { (a, b) } else { (b, a) }; writes.push(json!({"op": "merge", "bot": pg.bot, "keep": keep["id"], "drop": [drop["id"]]})); } if small_button(ui, "兩條都留著", p).clicked() { pg.kept.push((a["id"].as_i64().unwrap_or(0), b["id"].as_i64().unwrap_or(0))); } }); } if !stale.is_empty() { ui.horizontal(|ui| { ui.label(RichText::new(format!("{} 條記得的事半年沒被帶入過,可能過時了", stale.len())).size(12.5).color(p.text2)); if small_button(ui, if pg.stale_open { "收起" } else { "看看是哪些" }, p).clicked() { pg.stale_open = !pg.stale_open; } if small_button(ui, "全部忘記", p).clicked() { writes.push(json!({"op": "forget", "bot": pg.bot, "ids": stale.iter().map(|m| m["id"].clone()).collect::>()})); } }); if pg.stale_open { for m in &stale { ui.horizontal(|ui| { ui.add_space(10.0); ui.label(RichText::new(format!("• {}", m["text"].as_str().unwrap_or(""))).size(12.0).color(p.text3)); if small_button(ui, "忘記", p).clicked() { writes.push(json!({"op": "forget", "bot": pg.bot, "id": m["id"]})); } }); } } } if old_events > 0 || old_weeks > 0 { ui.horizontal(|ui| { let what = match (old_events, old_weeks) { (e, 0) => format!("{e} 條做過的事超過 30 天,可以壓成每週一行"), (0, w) => format!("{w} 行每週的整理超過半年,可以壓成每月一行"), (e, w) => format!("{e} 條做過的事可以壓成每週一行,{w} 行每週的可以壓成每月一行"), }; ui.label(RichText::new(what).size(12.5).color(p.text2)); if small_button(ui, "現在整理", p).clicked() { writes.push(json!({"op": "tidy", "bot": pg.bot})); } }); ui.label(RichText::new(t("每晚也會自動整理;壓掉的原文放在「最近刪除」30 天。")).size(11.0).color(p.text3)); } }); ui.add_space(10.0); } fn mem_list(&mut self, ui: &mut egui::Ui, pg: &mut MemPage, writes: &mut Vec) { let p = self.pal; let trash = pg.filter == "trash"; if pg.items.is_empty() { let empty = if pg.rx_list.is_some() && pg.shown.0.is_empty() { "載入中…" } else if !pg.q.trim().is_empty() { "沒有找到相關的記憶。" } else if trash { "最近刪除是空的。忘記、合併、壓縮掉的記憶會在這裡放 30 天。" } else { "還沒有記憶。在聊天裡說「記住…」,或在上面新增一條。" }; ui.add_space(16.0); ui.label(RichText::new(t(empty)).size(FONT_SM).color(p.text3)); return; } let now = crate::model::now_ms(); for m in pg.items.clone() { let id = m["id"].as_i64().unwrap_or(0); let text = m["text"].as_str().unwrap_or("").to_string(); let kind = m["kind"].as_str().unwrap_or("fact").to_string(); let pinned = m["pinned"] == true; Frame::new() .fill(p.elevated) .stroke(Stroke::new(1.0, if pinned { p.accent.gamma_multiply(0.45) } else { p.border })) .corner_radius(12) .inner_margin(Margin::symmetric(14, 10)) .show(ui, |ui| { ui.set_width(ui.available_width()); ui.spacing_mut().item_spacing.y = 6.0; // The words get the whole width (the old list put a wrapping label and a // right-aligned button on one row: the label took the row, the button fell out). if let Some((eid, draft)) = &mut pg.editing { if *eid == id { ui.add(egui::TextEdit::multiline(draft).desired_rows(2).desired_width(f32::INFINITY)); let (mut save, mut cancel) = (false, false); ui.horizontal(|ui| { save = ui.add(primary_button("儲存", p)).clicked(); cancel = ui.add(secondary_button("取消")).clicked(); }); if save { writes.push(json!({"op": "edit", "bot": pg.bot, "id": id, "text": draft.clone()})); } if save || cancel { pg.editing = None; } return; } } ui.add(egui::Label::new(RichText::new(&text).size(FONT_BASE).color(p.text)).wrap()); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 10.0; let tag = |ui: &mut egui::Ui, s: &str| ui.label(RichText::new(s).size(11.5).color(p.text3)); if pinned { crate::icons::label(ui, crate::icons::Icon::Pin, &t("釘選"), 11.5, p.accent); } tag(ui, kind_label(&kind)); tag(ui, &day(m["created"].as_i64().unwrap_or(0))); if trash { let by = m["superseded_by"].as_i64().unwrap_or(0); tag(ui, &format!("{}刪除{}", crate::pages::ago(m["deleted"].as_i64().unwrap_or(0), now), if by > 0 { "(被新的一條取代或壓縮)" } else { "" })); } else { let uses = m["uses"].as_i64().unwrap_or(0); tag(ui, &if uses == 0 { t("還沒被帶入過") } else { format!("帶過 {uses} 次 · 上次 {}", crate::pages::ago(m["last_used"].as_i64().unwrap_or(0), now)) }); } ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.spacing_mut().item_spacing.x = 2.0; if trash { if small_button(ui, "還原", p).clicked() { writes.push(json!({"op": "restore", "bot": pg.bot, "id": id})); } return; } if small_button(ui, "忘記", p).clicked() { writes.push(json!({"op": "forget", "bot": pg.bot, "id": id})); } if small_button(ui, "編輯", p).clicked() { pg.editing = Some((id, text.clone())); } if small_button(ui, if pinned { "取消釘選" } else { "釘選" }, p).on_hover_text(t("釘選的記憶每次聊天都會帶著")).clicked() { writes.push(json!({"op": "pin", "bot": pg.bot, "id": id, "on": !pinned})); } }); }); }); ui.add_space(6.0); } ui.horizontal(|ui| { let more = pg.total.saturating_sub(pg.items.len()); ui.label(RichText::new(format!("共 {} 條{}", pg.total, if pg.q.trim().is_empty() { String::new() } else { format!("(搜尋 {:.1} 毫秒)", pg.ms) })).size(11.5).color(p.text3)); if more > 0 && small_button(ui, &format!("再顯示 {}", more.min(60)), p).clicked() { pg.limit += 60; } if trash && small_button(ui, "清空最近刪除", p).clicked() { writes.push(json!({"op": "empty_trash", "bot": pg.bot})); } }); } } #[cfg(test)] mod tests { use super::*; #[test] fn picks_are_the_ticked_ones_once_the_shelf_answered() { let hits = vec![json!({"id": 1, "text": "我喜歡靠窗", "pick": true}), json!({"id": 2, "text": "週五不開會", "pick": false})]; let mut s = Suggest::answered("訂票靠窗", hits); assert_eq!(s.picks(), Some(vec!["我喜歡靠窗".to_string()])); s.toggled.insert(1, false); s.toggled.insert(2, true); assert_eq!(s.picks(), Some(vec!["週五不開會".to_string()])); // Never answered: the brain chooses. assert_eq!(Suggest::default().picks(), None); } }