use std::sync::Arc; use loro::Frontiers; use serde::Deserialize; use topcoat::{ Result, context::{Cx, app_context}, router::{ content::Form, error::{RouterErrorExt, SeeOther, bad_request, see_other}, page, path_param, query_params, route, }, view::{View, attributes, view}, }; use super::NoteId; use crate::app::shell; use crate::components::button::{ButtonSize, ButtonVariant, button}; use crate::hub::Hub; use crate::i18n::{self, Msg, t}; use crate::store::Store; /// Row styling of the version list, the same as the note list's rows. const ROW: &str = "flex min-h-14 flex-col justify-center gap-1 px-4 py-2 transition-colors hover:bg-foreground/5"; const ROW_SELECTED: &str = "marker flex min-h-14 flex-col justify-center gap-1 px-4 py-2"; #[query_params(error = bad_request)] pub struct HistoryQuery { /// `current` for the live document, or the `at` millis of a recorded version. pub v: Option, } #[derive(Deserialize)] struct RestoreForm { at: i64, } /// One row of the version list: its link, its label, and whether it is selected. struct Entry { href: String, label: String, /// Version time in ms; `None` for the current version. at: Option, selected: bool, } /// GET /notes/{note_id}/history: the note's recorded versions beside a read-only preview /// of the selected one. Without `?v`, the newest recorded version is shown. #[page] async fn history(cx: &Cx) -> Result { let store = app_context::>(cx); let hub = app_context::>(cx); let id = path_param::(cx).to_owned(); let meta = store .get_note(&id) .await .map_err(topcoat::Error::from_anyhow)? .ok_or_not_found()?; let versions = store.list_versions(&id).await.map_err(topcoat::Error::from_anyhow)?; let requested = match query_params::(cx) { Ok(query) => query.v.clone(), Err(_) => None, }; let lang = i18n::lang(cx); let trashed = meta.trashed_at.is_some(); // `None` selects the live document; `Some(at)` a recorded version. let selected: Option = match requested.as_deref() { Some("current") => None, Some(value) => match value.parse::() { Ok(at) if versions.iter().any(|(v, _)| *v == at) => Some(at), _ => versions.first().map(|(at, _)| *at), }, None => versions.first().map(|(at, _)| *at), }; let preview = if versions.is_empty() { String::new() } else { let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?; match selected { None => room.html().await.map_err(topcoat::Error::from_anyhow)?, Some(at) => { let bytes = store .get_version(&id, at) .await .map_err(topcoat::Error::from_anyhow)? .ok_or_not_found()?; let frontiers = Frontiers::decode(&bytes).map_err(|err| topcoat::Error::from_anyhow(err.into()))?; room.html_at(&frontiers).await.map_err(topcoat::Error::from_anyhow)? } } }; let title = t(lang, Msg::VersionHistory); let back_label = t(lang, Msg::BackToNote); let current_label = t(lang, Msg::CurrentVersion); let no_versions = t(lang, Msg::NoVersionsYet); let restore_label = t(lang, Msg::RestoreVersion); let note_title = shell::title_of(lang, &meta.title); let back_href = format!("/notes/{id}"); let restore_action = format!("/notes/{id}/history/restore"); let selected_label = match selected { Some(at) => i18n::date_time(lang, at), None => current_label.to_owned(), }; let restore_at = selected.unwrap_or(0); let mut entries = vec![Entry { href: format!("/notes/{id}/history?v=current"), label: current_label.to_owned(), at: None, selected: selected.is_none(), }]; entries.extend(versions.iter().map(|(at, _)| Entry { href: format!("/notes/{id}/history?v={at}"), label: i18n::date_time(lang, *at), at: Some(*at), selected: selected == Some(*at), })); let has_versions = !versions.is_empty(); let show_restore = has_versions && !trashed && selected.is_some(); Ok(view! {
if has_versions {

if let Some(at) = selected { } else { (selected_label) }

if show_restore {
button( variant: ButtonVariant::Outline, size: ButtonSize::Sm, attrs: attributes! { type="submit" }, (restore_label) )
}
(topcoat::view::Unescaped::new_unchecked(preview))
} else {

(no_versions)

}
}) } /// POST /notes/{note_id}/history/restore: makes the note match the version taken at `at`, /// then opens the note. #[route(POST "./restore")] async fn restore_version(cx: &Cx, Form(input): Form) -> Result { let store = app_context::>(cx); let hub = app_context::>(cx); let id = path_param::(cx).to_owned(); let meta = store .get_note(&id) .await .map_err(topcoat::Error::from_anyhow)? .ok_or_not_found()?; if meta.trashed_at.is_some() { return Err(bad_request("the note is in the trash; restore it first").into()); } let bytes = store .get_version(&id, input.at) .await .map_err(topcoat::Error::from_anyhow)? .ok_or_not_found()?; let frontiers = Frontiers::decode(&bytes).map_err(|err| topcoat::Error::from_anyhow(err.into()))?; let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?; room.restore(store, &frontiers) .await .map_err(topcoat::Error::from_anyhow)?; Ok(see_other(format!("/notes/{id}?toast=version-restored"))) }