use std::sync::Arc; use serde::Deserialize; use topcoat::{ Result, context::{Cx, app_context}, router::{ content::Form, error::{RouterErrorExt, SeeOther, bad_request, see_other}, header, module_param, page, path_param, route, }, view::{Child, Unescaped, View, attributes, view}, }; use crate::app::pane::{self, MENU_LINK, Mobile}; use crate::app::shell; use crate::components::button::{ButtonSize, ButtonVariant, button, button_variants}; use crate::components::dropdown_menu::{ dropdown_menu, dropdown_menu_content, dropdown_menu_item, dropdown_menu_label, dropdown_menu_separator, dropdown_menu_sub, dropdown_menu_sub_content, dropdown_menu_sub_trigger, dropdown_menu_trigger, }; use crate::components::floating::{FloatingAlign, FloatingSide}; use crate::components::input::input as text_input; use crate::editor_assets::EditorAssets; use crate::export::html_page; use crate::hub::Hub; use crate::i18n::{self, Msg, t}; use crate::store::{ListFilter, NoteMeta, Notebook, Store}; mod history; mod ws; module_param!(note_id); /// Most notebooks listed in the "Move to" menu. One form per notebook makes the page huge /// with thousands of notebooks; the others are moved to by name. const MOVE_TARGETS: usize = 30; /// How much of a note's imported markdown is previewed while its doc is built. const PREVIEW_MARKDOWN_BYTES: usize = 64 * 1024; #[derive(Deserialize)] struct MoveNote { /// Empty means "no notebook". #[serde(default)] notebook_id: String, /// Typed name of the target notebook, from the "Move to" menu's name field. #[serde(default)] notebook_name: String, } /// One note in the "Linked from" list of a note. struct LinkRow { href: String, title: String, /// Empty when the note is not in a notebook. notebook: String, } /// One entry of the "Move to" menu. #[derive(Clone)] struct MoveTarget { id: String, name: String, current: bool, } /// Where the note's list goes: the notebook's notes, or every note when it has no /// notebook. Returns the list's title, the notes it selects, and the list's URL. fn context_list( lang: i18n::Lang, meta: &NoteMeta, notebooks: &[Notebook], ) -> (String, ListFilter, String, bool) { match shell::notebook_name(notebooks, meta.notebook_id.as_deref()) { Some(name) => { let nb = meta.notebook_id.clone().unwrap_or_default(); (name, ListFilter::Notebook(nb.clone()), format!("/notebooks/{nb}"), false) } None => ( t(lang, Msg::AllNotes).to_owned(), ListFilter::All, "/".to_owned(), true, ), } } /// GET /notes/{note_id}: the note's editor beside the list it belongs to. A trashed note /// shows a banner with Restore and no editor. #[page] async fn note(cx: &Cx) -> Result { let store = app_context::>(cx); let editor: &Option = 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 notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?; let lang = crate::i18n::lang(cx); let title = shell::title_of(lang, &meta.title); let trashed = meta.trashed_at.is_some(); let prerender = if trashed { String::new() } else if let Some(head) = store.pending_head(&id, PREVIEW_MARKDOWN_BYTES).await.map_err(topcoat::Error::from_anyhow)? { // The doc is still being built from an import: preview the markdown's start. tokio::task::spawn_blocking(move || crate::import::preview_markdown(&head)) .await .map_err(|e| topcoat::Error::from_anyhow(e.into()))? } else { let hub = app_context::>(cx); let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?; room.editor_html().await }; let backlinks = if trashed { Vec::new() } else { store .backlinks(&id, &meta.title) .await .map_err(topcoat::Error::from_anyhow)? }; let linked_rows: Vec = backlinks .iter() .map(|note| LinkRow { href: format!("/notes/{}", note.id), title: shell::title_of(lang, ¬e.title), notebook: shell::notebook_name(¬ebooks, note.notebook_id.as_deref()) .unwrap_or_default(), }) .collect(); let current_nb = meta.notebook_id.clone().unwrap_or_default(); let crumb_nb = shell::notebook_name(¬ebooks, meta.notebook_id.as_deref()); let crumb_label = crumb_nb .clone() .unwrap_or_else(|| t(lang, Msg::Unfiled).to_owned()); let crumb_href = match &meta.notebook_id { Some(nb) => format!("/notebooks/{nb}"), None => "/unfiled".to_owned(), }; let (list_title, list_filter, list_href, show_notebook) = context_list(lang, &meta, ¬ebooks); // Only the first page of the list is read. The open note is in it when it is near the top. let page = pane::load_page(cx, store, list_filter) .await .map_err(topcoat::Error::from_anyhow)?; let groups = pane::groups( lang, &page.notes, ¬ebooks, &page.previews, Some(id.as_str()), show_notebook, ); let spec = pane::ListSpec { title: list_title, heading: false, count: page.total, notebook_id: current_nb.clone(), groups, empty: t(lang, Msg::NoNotesYet), more: page.more, }; let list = pane::list_pane(cx, lang, spec, Child::new(())); let mut moves: Vec = std::iter::once(MoveTarget { id: String::new(), name: t(lang, Msg::Unfiled).to_owned(), current: current_nb.is_empty(), }) .chain(notebooks.iter().take(MOVE_TARGETS).map(|nb| MoveTarget { id: nb.id.clone(), name: nb.name.clone(), current: nb.id == current_nb, })) .collect(); // The note's own notebook stays listed even when it is past the first MOVE_TARGETS. if !current_nb.is_empty() && !moves.iter().any(|m| m.current) { if let Some(nb) = notebooks.iter().find(|nb| nb.id == current_nb) { moves.push(MoveTarget { id: nb.id.clone(), name: nb.name.clone(), current: true, }); } } let hidden = notebooks.len() + 1 - moves.len(); let by_name_label = t(lang, Msg::NotebookByName); let already_here = t(lang, Msg::AlreadyHere); let move_reason = if trashed { t(lang, Msg::RestoreFirst) } else { "" }; let trash_reason = if trashed { t(lang, Msg::AlreadyInTrash) } else { "" }; let move_action = format!("/notes/{id}/move"); let trash_action = format!("/notes/{id}/trash"); let restore_action = format!("/notes/{id}/restore"); let export_href = format!("/notes/{id}/export.md"); let export_html_href = format!("/notes/{id}/export.html"); let print_href = format!("/notes/{id}/print"); let history_href = format!("/notes/{id}/history"); let history_label = t(lang, Msg::VersionHistory); let export_html_label = t(lang, Msg::ExportHtml); let export_pdf = t(lang, Msg::ExportPdf); let back_label = t(lang, Msg::BackToList); let in_trash = t(lang, Msg::InTrash); let restore = t(lang, Msg::Restore); let breadcrumb = t(lang, Msg::Breadcrumb); let move_to_notebook = t(lang, Msg::MoveToNotebook); let export_as = t(lang, Msg::ExportAs); let export_md = t(lang, Msg::ExportMarkdown); let trash_label = t(lang, Msg::MoveToTrash); let note_actions = t(lang, Msg::NoteActions); let linked_label = t(lang, Msg::LinkedFrom); // The one actions menu, at every width: move, export, trash. let actions = Child::new(view! { dropdown_menu( dropdown_menu_trigger( target: "note-actions-menu", attrs: attributes! { class=(button_variants(ButtonVariant::Outline, ButtonSize::Icon)) aria-label=(note_actions) }, ) dropdown_menu_content( id: "note-actions-menu", align: FloatingAlign::End, dropdown_menu_label((move_to_notebook)) for target in moves {
dropdown_menu_item( attrs: attributes! { type="submit" disabled=(trashed || target.current) title=(if trashed { move_reason } else if target.current { already_here } else { "" }) }, (target.name) )
} if hidden > 0 {
text_input(attrs: attributes! { type="text" name="notebook_name" placeholder=(by_name_label) aria-label=(by_name_label) required=(true) autocomplete="off" maxlength="120" disabled=(trashed) onclick="event.stopPropagation()" onkeydown="if (event.key !== 'Escape') event.stopPropagation()" class="h-8 text-sm" })
} dropdown_menu_separator() if !trashed { (history_label) } dropdown_menu_sub( dropdown_menu_sub_trigger(target: "note-export-menu", (export_as)) dropdown_menu_sub_content( id: "note-export-menu", side: FloatingSide::Left, (export_md) (export_html_label) (export_pdf) ) ) dropdown_menu_separator()
dropdown_menu_item( attrs: attributes! { type="submit" class="text-destructive" disabled=(trashed) title=(trash_reason) }, (trash_label) )
) ) }); let detail = Child::new(view! {
if !trashed {
}
if !trashed { } (actions)
if trashed {

(in_trash)

button( variant: ButtonVariant::Outline, size: ButtonSize::Sm, attrs: attributes! { type="submit" }, (restore) )
} else {
(Unescaped::new_unchecked(prerender.clone()))
if let Some(assets) = editor { } if !linked_rows.is_empty() {

(linked_label)

} }
}); Ok(pane::split(cx, Mobile::Detail, Child::new(list), detail)) } /// POST /notes/{note_id}/move: moves the note into a notebook, or unfiles it. #[route(POST "./move")] async fn move_note(cx: &Cx, Form(input): Form) -> Result { let store = 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 typed = input.notebook_name.trim(); let picked = if typed.is_empty() { None } else { let wanted = typed.to_lowercase(); let nb_id = store .list_notebooks() .await .map_err(topcoat::Error::from_anyhow)? .iter() .find(|nb| nb.name.trim().to_lowercase() == wanted) .map(|nb| nb.id.clone()); let Some(nb_id) = nb_id else { return Err(bad_request(t(i18n::lang(cx), Msg::NoSuchNotebook)).into()); }; Some(nb_id) }; let target = picked.as_deref().unwrap_or(input.notebook_id.trim()); let target = if target.is_empty() { None } else { let exists = store .get_notebook(target) .await .map_err(topcoat::Error::from_anyhow)? .is_some(); if !exists { return Err(bad_request("unknown notebook").into()); } Some(target) }; store .move_note(&id, target) .await .map_err(topcoat::Error::from_anyhow)?; Ok(see_other(format!("/notes/{id}?toast=moved"))) } /// POST /notes/{note_id}/trash: moves the note to the trash and returns to its list, with /// an Undo toast. #[route(POST "./trash")] async fn trash_note(cx: &Cx) -> Result { let store = 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()?; store.trash_note(&id).await.map_err(topcoat::Error::from_anyhow)?; let back = match meta.notebook_id { Some(nb) => format!("/notebooks/{nb}"), None => "/".to_owned(), }; Ok(see_other(format!("{back}?toast=trashed&undo={id}"))) } /// POST /notes/{note_id}/restore: takes the note out of the trash and opens it. #[route(POST "./restore")] async fn restore_note(cx: &Cx) -> Result { let store = app_context::>(cx); let id = path_param::(cx).to_owned(); store.get_note(&id).await.map_err(topcoat::Error::from_anyhow)?.ok_or_not_found()?; store.restore_note(&id).await.map_err(topcoat::Error::from_anyhow)?; Ok(see_other(format!("/notes/{id}?toast=restored"))) } /// ASCII-only file name stem from a note title. Falls back to "note". /// The note title as a safe file name, without extension. fn file_stem(title: &str) -> String { crate::app::export_all::sanitize(title) } /// `Content-Disposition` for a download: an ASCII `filename` for old clients and the /// real title as UTF-8 in `filename*`. fn attachment(stem: &str, ext: &str) -> String { let ascii: String = stem .chars() .map(|c| match c { 'ı' | 'İ' => 'i', 'ş' | 'Ş' => 's', 'ğ' | 'Ğ' => 'g', 'ü' | 'Ü' => 'u', 'ö' | 'Ö' => 'o', 'ç' | 'Ç' => 'c', c if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' => c, _ => '-', }) .collect(); let ascii = ascii.trim_matches('-'); let ascii = if ascii.is_empty() { "note" } else { ascii }; let encoded: String = format!("{stem}.{ext}") .bytes() .map(|b| match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), _ => format!("%{b:02X}"), }) .collect(); format!("attachment; filename=\"{ascii}.{ext}\"; filename*=UTF-8''{encoded}") } /// Standalone HTML of the live note, and the file name stem to save it under. async fn note_page(cx: &Cx, print: bool) -> Result<(String, String)> { 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 room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?; let body = room.html().await.map_err(topcoat::Error::from_anyhow)?; let lang = i18n::lang(cx); let title = shell::title_of(lang, &meta.title); let page = html_page(&title, &body, lang.code(), print); Ok((file_stem(&title), page)) } /// GET /notes/{note_id}/export.md: markdown of the live document. #[route(GET "./export.md")] async fn export_markdown(cx: &Cx) -> Result<([(&'static str, String); 2], String)> { 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 markdown = match store.pending_markdown(&id).await.map_err(topcoat::Error::from_anyhow)? { Some(markdown) => markdown, None => { let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?; room.markdown_with(store).await.map_err(topcoat::Error::from_anyhow)? } }; let stem = file_stem(&shell::title_of(i18n::lang(cx), &meta.title)); Ok(( [ (header::CONTENT_TYPE.as_str(), "text/markdown; charset=utf-8".to_owned()), (header::CONTENT_DISPOSITION.as_str(), attachment(&stem, "md")), ], markdown, )) } /// GET /notes/{note_id}/export.html: standalone HTML file of the live document. #[route(GET "./export.html")] async fn export_html(cx: &Cx) -> Result<([(&'static str, String); 2], String)> { let (stem, page) = note_page(cx, false).await?; Ok(( [ (header::CONTENT_TYPE.as_str(), "text/html; charset=utf-8".to_owned()), (header::CONTENT_DISPOSITION.as_str(), attachment(&stem, "html")), ], page, )) } /// GET /notes/{note_id}/print: the same HTML, shown inline. It opens the print dialog, /// where "Save as PDF" makes the PDF. #[route(GET "./print")] async fn print_note(cx: &Cx) -> Result<([(&'static str, &'static str); 1], String)> { let (_, page) = note_page(cx, true).await?; Ok(([(header::CONTENT_TYPE.as_str(), "text/html; charset=utf-8")], page)) }