hex/src/rune_ui/history.rs
2026-10-29 15:56:51 -07:00

430 lines
14 KiB
Rust

//! The History pane: retained dictations (newest first) with search, the
//! retention choice, two-step Clear all, and a detail view with Copy and
//! Delete. It shares the host's store, which the listener records into.
use rune::{El, TextEdit, Tx, col, text};
use rune_kit::{Select, SelectAppearance, TextInput};
use super::controls::{ButtonKind, Paint, button};
use super::list_detail::{self as ld, Item};
use super::lists::{error_panel, section_label};
use super::{Menu, Ui};
use crate::desktop_i18n::{event_age, tr, tr_fill, tr_named};
use crate::history::{History, HistoryEntry, HistoryKind, HistoryRetention};
#[derive(Default)]
pub(super) struct HistoryPane {
store: Option<History>,
pub(super) entries: Vec<HistoryEntry>,
search: TextEdit,
/// The query the entries were loaded for.
searched: String,
pub(super) selected: Option<u64>,
pub(super) clear_armed: bool,
pub(super) copied: Option<u64>,
error: Option<String>,
}
impl HistoryPane {
/// The host's store; `None` when it could not open one.
pub(super) fn shared(store: Option<History>) -> Self {
Self {
error: store
.is_none()
.then(|| tr("History could not be loaded.").to_string()),
store,
..Self::default()
}
}
/// Refreshes the bounded snapshot for the current query.
pub(super) fn reload(&mut self) {
self.searched = self.search.text.clone();
let Some(store) = &self.store else {
return;
};
self.entries = store.search(&self.searched);
if self
.selected
.is_some_and(|id| !self.entries.iter().any(|entry| entry.id == id))
{
self.selected = None;
}
}
/// While the pane shows, picks up new dictations and search edits.
pub(super) fn poll(&mut self, visible: bool) -> bool {
if !visible || self.store.is_none() {
return false;
}
let previous = std::mem::take(&mut self.entries);
self.reload();
self.entries != previous
}
fn entry(&self, id: u64) -> Option<&HistoryEntry> {
self.entries.iter().find(|entry| entry.id == id)
}
pub(super) fn fixture() -> Self {
let now = crate::history::now_ms();
let entry =
|id: u64, minutes: u64, kind, raw: &str, final_text: &str, app: Option<&str>| {
HistoryEntry {
id,
timestamp_ms: now - minutes * 60_000 - 30_000,
kind,
raw_text: raw.into(),
final_text: final_text.into(),
application: app.map(str::to_owned),
processing: None,
audio_ms: 4200,
inference_ms: 180,
total_ms: 640,
}
};
let mut rewritten = entry(
2,
42,
HistoryKind::Dictation,
"so um the deploy failed because the the cache key changed",
"The deploy failed because the cache key changed.",
Some("Slack"),
);
rewritten.processing = Some(crate::events::DictationProcessing {
profile: "Chat".into(),
latency_ms: 910,
fallback: None,
});
Self {
entries: vec![
entry(
3,
2,
HistoryKind::Dictation,
"Let's move the standup to ten thirty tomorrow.",
"Let's move the standup to ten thirty tomorrow.",
Some("WezTerm"),
),
rewritten,
entry(
1,
180,
HistoryKind::Dictation,
"Thanks for sending this over! I'll review it today and follow up with comments.",
"Thanks for sending this over! I'll review it today and follow up with comments.",
Some("Firefox"),
),
],
selected: Some(2),
..Self::default()
}
}
pub(super) fn fixture_empty() -> Self {
Self::default()
}
}
fn set_retention(ui: &mut Ui, retention: HistoryRetention) {
ui.open = None;
if ui.settings.history_retention == retention {
return;
}
if !ui.update(|settings| settings.history_retention = retention) {
return;
}
if let Some(store) = &ui.history.store
&& let Err(error) = store.set_retention(retention)
{
ui.history.error = Some(error.to_string());
}
ui.history.reload();
}
fn clear(ui: &mut Ui) {
if !ui.history.clear_armed {
ui.history.clear_armed = true;
return;
}
ui.history.clear_armed = false;
if let Some(store) = &ui.history.store {
if let Err(error) = store.clear() {
ui.history.error = Some(error.to_string());
}
ui.history.reload();
} else {
ui.history.entries.clear();
ui.history.selected = None;
}
}
fn delete(ui: &mut Ui, id: u64) {
if let Some(store) = &ui.history.store {
if let Err(error) = store.delete(id) {
ui.history.error = Some(error.to_string());
}
ui.history.reload();
} else {
ui.history.entries.retain(|entry| entry.id != id);
ui.history.selected = None;
}
}
/// The header actions (retention, Clear all) and the list + detail body.
pub(super) fn pane(ui: &Ui, p: Paint, layer: &mut Vec<El>) -> (Vec<El>, El) {
let pane = &ui.history;
let actions = header_actions(ui, p, layer);
let mut notices = Vec::new();
if let Some(error) = &pane.error {
notices.push(error_panel(
p,
"history-error",
tr("History could not be loaded."),
error,
));
}
let searching = !pane.searched.trim().is_empty();
let body = match empty(ui, p).filter(|_| !searching) {
Some(empty) => empty,
None => {
let mut list = col().key("history-list");
for entry in &pane.entries {
let id = entry.id;
let mut meta = tr(entry.kind.label()).to_string();
if let Some(application) = &entry.application {
meta.push_str(" · ");
meta.push_str(application);
}
list = list.child(ld::item(
p,
Item {
key: format!("history-entry{id}"),
title: entry.final_text.replace('\n', " "),
meta,
meta_ink: None,
time: event_age(entry.timestamp_ms),
hover: vec![copy_action(ui, p, id, true)],
selected: pane.selected == Some(id),
},
move |ui: &mut Ui| {
ui.history.selected = Some(id);
ui.history.clear_armed = false;
},
));
}
let search = TextInput::new(&pane.search)
.placeholder(tr("Search history"))
.width(None)
.leading_icon(p.k.glyph.search)
.on_edit(|ui: &mut Ui| &mut ui.history.search)
.build(p.k)
.key("history-search");
let column = ld::list_column(search, "history-scroll", list);
ld::body(p, "history-body", column, detail(ui, p))
}
};
(
actions,
col()
.key("history-pane")
.grow(1.0)
.shrink()
.children((!notices.is_empty()).then(|| ld::notices(notices)))
.child(body),
)
}
/// Retention as a borderless menu, and Clear all beside it while there is
/// something to clear.
fn header_actions(ui: &Ui, p: Paint, layer: &mut Vec<El>) -> Vec<El> {
let labels: Vec<&str> = HistoryRetention::ALL
.iter()
.map(|r| tr(r.label()))
.collect();
let current = tr_fill("Keep: {}", tr(ui.settings.history_retention.label()));
let retention = Select::new("history-retention", &labels)
.appearance(SelectAppearance::Inline)
.current(Some(&current))
.open(ui.open == Some(Menu::HistoryRetention))
.on_toggle(|ui: &mut Ui| {
ui.open = (ui.open != Some(Menu::HistoryRetention)).then_some(Menu::HistoryRetention);
})
.on_close(|ui: &mut Ui| ui.open = None)
.on_choose(|ui: &mut Ui, choice: &str, _: &mut Tx| {
if let Some(retention) = HistoryRetention::ALL
.into_iter()
.find(|r| tr(r.label()) == choice)
{
set_retention(ui, retention);
}
})
.build(p.k, layer);
let mut actions = vec![retention];
if !ui.history.entries.is_empty() || ui.history.clear_armed {
actions.push(if ui.history.clear_armed {
button(
p,
"history-clear",
tr("Really clear all?"),
ButtonKind::Danger,
|ui: &mut Ui, _| clear(ui),
)
} else {
button(
p,
"history-clear",
tr("Clear all"),
ButtonKind::Secondary,
|ui: &mut Ui, _| clear(ui),
)
});
}
actions
}
/// Copy as an icon: a row's hover action, or the card's.
fn copy_action(ui: &Ui, p: Paint, id: u64, in_row: bool) -> El {
let glyph = if ui.history.copied == Some(id) {
p.k.glyph.check_small
} else {
ld::COPY_ICON
};
let press = move |ui: &mut Ui, tx: &mut Tx| {
if let Some(entry) = ui.history.entry(id) {
tx.copy(entry.final_text.clone());
ui.history.copied = Some(id);
ui.history.error = None;
}
};
if in_row {
ld::row_action(p, "row-copy", glyph, tr("Copy"), press)
} else {
ld::ghost_icon(p, "history-copy", glyph, tr("Copy"), press)
}
}
/// Nothing retained, or nothing matching: what History keeps and for how
/// long.
fn empty(ui: &Ui, p: Paint) -> Option<El> {
let pane = &ui.history;
if !pane.entries.is_empty() {
return None;
}
let retention = ui.settings.history_retention;
Some(if !pane.searched.trim().is_empty() {
ld::empty_state(
p,
"history-empty",
ld::SEARCH_ICON,
tr("No dictations match."),
None,
)
} else if retention.is_off() {
ld::empty_state(
p,
"history-empty",
ld::HISTORY_ICON,
tr("History is off."),
Some(tr("Choose how long to keep dictations to see them here.")),
)
} else {
let hint = match retention {
HistoryRetention::Forever => tr("Everything you dictate is kept here.").to_string(),
other => tr_fill(
"Everything you dictate is kept here for {}.",
tr(other.label()),
),
};
ld::empty_state(
p,
"history-empty",
ld::HISTORY_ICON,
tr("No dictations retained yet."),
Some(&hint),
)
})
}
fn detail(ui: &Ui, p: Paint) -> El {
let pane = &ui.history;
let Some(entry) = pane.selected.and_then(|id| pane.entry(id)) else {
return empty(ui, p).unwrap_or_else(|| {
ld::empty_state(
p,
"history-detail",
ld::HISTORY_ICON,
tr("Select a history entry."),
None,
)
});
};
let id = entry.id;
let mut latency = tr_named(
"{audio} ms audio · {inference} ms inference",
&[
("audio", &entry.audio_ms.to_string()),
("inference", &entry.inference_ms.to_string()),
],
);
if entry.total_ms > 0 {
latency.push_str(&format!(
" · {}",
tr_fill("{} ms total", &entry.total_ms.to_string())
));
}
let mut facts = Vec::new();
if let Some(application) = &entry.application {
facts.push((tr("Application"), application.clone()));
}
if let Some(processing) = &entry.processing {
let mut summary = format!("{} · {} ms", processing.profile, processing.latency_ms);
if let Some(fallback) = &processing.fallback {
summary.push_str(&format!(" · {}", tr_fill("fell back: {}", fallback)));
}
facts.push((tr("Processing"), summary));
}
facts.push((tr("Latency"), latency));
let mut body = col().key("detail-body").gap(20.0).child(
text(entry.final_text.clone())
.key("final")
.font(p.k.ty.body)
.color(p.text())
.wrap(),
);
if entry.raw_text.trim() != entry.final_text.trim() {
body = body.child(
col()
.key("raw")
.gap(6.0)
.child(section_label(p, "label", tr("Raw transcript")))
.child(
text(entry.raw_text.clone())
.key("value")
.font(p.k.ty.body)
.color(p.muted())
.wrap(),
),
);
}
body = body.child(ld::facts(p, facts));
col()
.key("history-detail")
.grow(1.0)
.shrink()
.child(ld::card_header(
ld::card_title(p, tr(entry.kind.label())),
vec![ld::meta_text(p, &event_age(entry.timestamp_ms))],
vec![
copy_action(ui, p, id, false),
ld::ghost_icon(
p,
"history-delete",
ld::TRASH_ICON,
tr("Delete"),
move |ui: &mut Ui, _| delete(ui, id),
),
],
))
.child(ld::card_scroll("detail-scroll", body))
}