use std::sync::Arc; use serde::{Deserialize, Serialize}; use topcoat::{ Result, context::{Cx, app_context}, router::{ content::Form, error::{SeeOther, bad_request, see_other}, header, page, path_param, query_params, route, }, view::{View, attributes, view}, }; use crate::components::button::{ButtonSize, ButtonVariant, button}; use crate::export; use crate::i18n::{self, Msg, t}; use crate::import::{markdown_to_doc, markdown_to_update}; use crate::store::{ListFilter, Store, title_key}; mod note_id; path_param!(title); #[derive(Deserialize)] struct NewNote { /// Empty or absent when the note is created outside any notebook. #[serde(default)] notebook_id: String, } /// POST /notes: creates an empty note (in the notebook named by the form, if any) /// and redirects to the editor. #[route(POST)] async fn create_note(cx: &Cx, Form(input): Form) -> Result { let store = app_context::>(cx); let notebook_id = input.notebook_id.trim(); let notebook_id = if notebook_id.is_empty() { None } else { let exists = store .get_notebook(notebook_id) .await .map_err(topcoat::Error::from_anyhow)? .is_some(); if !exists { return Err(bad_request("unknown notebook").into()); } Some(notebook_id) }; let note = store .create_note(notebook_id) .await .map_err(topcoat::Error::from_anyhow)?; let init = crate::hub::initial_note_update().map_err(topcoat::Error::from_anyhow)?; store .append_update(¬e.id, &init) .await .map_err(topcoat::Error::from_anyhow)?; Ok(see_other(format!("/notes/{}", note.id))) } #[query_params(error = bad_request)] pub struct TitlesQuery { pub q: Option, } #[derive(Serialize)] struct TitleHit { id: String, title: String, } /// Most notes the link picker is answered with. const TITLE_HITS: usize = 8; /// Most title matches read before the prefix matches are put first. const TITLE_SEARCH_LIMIT: usize = 10_000; /// GET /notes/titles.json?q=...: up to 8 notes outside the trash whose title contains `q` /// (case-insensitive), prefix matches first. Without a query, the most recently updated. #[route(GET "./titles.json")] async fn titles_json(cx: &Cx) -> Result<([(&'static str, String); 1], String)> { let store = app_context::>(cx); let query = match query_params::(cx) { Ok(query) => query.q.clone().unwrap_or_default(), Err(_) => String::new(), }; let query = query.trim(); let mut notes = if query.is_empty() { store .list_notes_page(ListFilter::All, TITLE_HITS, 0) .await .map_err(topcoat::Error::from_anyhow)? } else { store .search_titles(query, TITLE_SEARCH_LIMIT) .await .map_err(topcoat::Error::from_anyhow)? }; let needle = crate::matcher::title_fold(query); if !needle.is_empty() { // Stable: within each group the most recently updated notes stay first. notes.sort_by_key(|note| !crate::matcher::title_fold(¬e.title).starts_with(&needle)); } let hits: Vec = notes .into_iter() .take(TITLE_HITS) .map(|note| TitleHit { id: note.id, title: note.title, }) .collect(); let body = serde_json::to_string(&hits) .map_err(anyhow::Error::from) .map_err(topcoat::Error::from_anyhow)?; Ok(([(header::CONTENT_TYPE.as_str(), "application/json".to_owned())], body)) } #[derive(Deserialize)] struct QuickNote { title: String, /// `1` from the by-title page's button: redirect to the new note instead of answering /// with its id. #[serde(default)] go: String, } /// A one-heading markdown document whose heading is `title` as literal text. Markdown /// syntax in the title is escaped and whitespace is collapsed. fn heading_markdown(title: &str) -> String { let collapsed = title.split_whitespace().collect::>().join(" "); let text = if collapsed.is_empty() { "Untitled".to_owned() } else { collapsed }; let escaped: String = text .chars() .flat_map(|c| { let escape = matches!(c, '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '~' | '#' | '&'); escape.then_some('\\').into_iter().chain(std::iter::once(c)) }) .collect(); format!("# {escaped}\n") } /// POST /notes/quick: creates an unfiled note titled `title` and answers with its id. With /// `go` set, it redirects to the note instead. #[route(POST "./quick")] async fn quick_note(cx: &Cx, Form(input): Form) -> Result { let store = app_context::>(cx); let markdown = heading_markdown(&input.title); let doc = markdown_to_doc(&markdown).map_err(topcoat::Error::from_anyhow)?; let update = markdown_to_update(&markdown).map_err(topcoat::Error::from_anyhow)?; let title = export::title(&doc); let body = export::to_markdown(&doc); let note = store .create_note(None) .await .map_err(topcoat::Error::from_anyhow)?; store .append_update(¬e.id, &update) .await .map_err(topcoat::Error::from_anyhow)?; store .set_title(¬e.id, &title) .await .map_err(topcoat::Error::from_anyhow)?; store .put_text(¬e.id, &title, &body) .await .map_err(topcoat::Error::from_anyhow)?; store .set_links(¬e.id, &export::note_links(&doc)) .await .map_err(topcoat::Error::from_anyhow)?; if input.go.is_empty() { return Ok(note.id); } Err(see_other(format!("/notes/{}", note.id)).into()) } /// GET /notes/by-title/{title}: redirects to the note with that title (case-insensitive, /// outside the trash). Otherwise offers to create a note with the title. #[page("./by-title/{title}")] async fn note_by_title(cx: &Cx) -> Result { let store = app_context::>(cx); let name = path_param::(cx).to_owned(); let key = title_key(&name); if let Some(note) = store.note_by_title_key(&key).await.map_err(topcoat::Error::from_anyhow)? { return Err(see_other(format!("/notes/{}", note.id)).into()); } let lang = i18n::lang(cx); let heading = t(lang, Msg::NoNoteNamed).replace("{title}", &name); let create = t(lang, Msg::CreateNote); Ok(view! { <div class="mx-auto flex w-full max-w-md flex-col gap-4 px-4 py-16 lg:px-8"> <p class="text-base">(heading)</p> <form method="post" action="/notes/quick" class="flex"> <input type="hidden" name="title" value=(name)> <input type="hidden" name="go" value="1"> button( variant: ButtonVariant::Outline, size: ButtonSize::Md, attrs: attributes! { type="submit" }, (create) ) </form> </div> }) }