| 1 | use std::sync::Arc; |
| 2 | |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use topcoat::{ |
| 5 | Result, |
| 6 | context::{Cx, app_context}, |
| 7 | router::{ |
| 8 | content::Form, |
| 9 | error::{SeeOther, bad_request, see_other}, |
| 10 | header, page, path_param, query_params, route, |
| 11 | }, |
| 12 | view::{View, attributes, view}, |
| 13 | }; |
| 14 | |
| 15 | use crate::components::button::{ButtonSize, ButtonVariant, button}; |
| 16 | use crate::export; |
| 17 | use crate::i18n::{self, Msg, t}; |
| 18 | use crate::import::{markdown_to_doc, markdown_to_update}; |
| 19 | use crate::store::{ListFilter, Store, title_key}; |
| 20 | |
| 21 | mod note_id; |
| 22 | |
| 23 | path_param!(title); |
| 24 | |
| 25 | #[derive(Deserialize)] |
| 26 | struct NewNote { |
| 27 | |
| 28 | #[serde(default)] |
| 29 | notebook_id: String, |
| 30 | } |
| 31 | |
| 32 | |
| 33 | |
| 34 | #[route(POST)] |
| 35 | async fn create_note(cx: &Cx, Form(input): Form<NewNote>) -> Result<SeeOther> { |
| 36 | let store = app_context::<Arc<Store>>(cx); |
| 37 | let notebook_id = input.notebook_id.trim(); |
| 38 | let notebook_id = if notebook_id.is_empty() { |
| 39 | None |
| 40 | } else { |
| 41 | let exists = store |
| 42 | .get_notebook(notebook_id) |
| 43 | .await |
| 44 | .map_err(topcoat::Error::from_anyhow)? |
| 45 | .is_some(); |
| 46 | if !exists { |
| 47 | return Err(bad_request("unknown notebook").into()); |
| 48 | } |
| 49 | Some(notebook_id) |
| 50 | }; |
| 51 | let note = store |
| 52 | .create_note(notebook_id) |
| 53 | .await |
| 54 | .map_err(topcoat::Error::from_anyhow)?; |
| 55 | let init = crate::hub::initial_note_update().map_err(topcoat::Error::from_anyhow)?; |
| 56 | store |
| 57 | .append_update(¬e.id, &init) |
| 58 | .await |
| 59 | .map_err(topcoat::Error::from_anyhow)?; |
| 60 | Ok(see_other(format!("/notes/{}", note.id))) |
| 61 | } |
| 62 | |
| 63 | #[query_params(error = bad_request)] |
| 64 | pub struct TitlesQuery { |
| 65 | pub q: Option<String>, |
| 66 | } |
| 67 | |
| 68 | #[derive(Serialize)] |
| 69 | struct TitleHit { |
| 70 | id: String, |
| 71 | title: String, |
| 72 | } |
| 73 | |
| 74 | |
| 75 | const TITLE_HITS: usize = 8; |
| 76 | |
| 77 | const TITLE_SEARCH_LIMIT: usize = 10_000; |
| 78 | |
| 79 | |
| 80 | |
| 81 | #[route(GET "./titles.json")] |
| 82 | async fn titles_json(cx: &Cx) -> Result<([(&'static str, String); 1], String)> { |
| 83 | let store = app_context::<Arc<Store>>(cx); |
| 84 | let query = match query_params::<TitlesQuery>(cx) { |
| 85 | Ok(query) => query.q.clone().unwrap_or_default(), |
| 86 | Err(_) => String::new(), |
| 87 | }; |
| 88 | let query = query.trim(); |
| 89 | let mut notes = if query.is_empty() { |
| 90 | store |
| 91 | .list_notes_page(ListFilter::All, TITLE_HITS, 0) |
| 92 | .await |
| 93 | .map_err(topcoat::Error::from_anyhow)? |
| 94 | } else { |
| 95 | store |
| 96 | .search_titles(query, TITLE_SEARCH_LIMIT) |
| 97 | .await |
| 98 | .map_err(topcoat::Error::from_anyhow)? |
| 99 | }; |
| 100 | let needle = crate::matcher::title_fold(query); |
| 101 | if !needle.is_empty() { |
| 102 | |
| 103 | notes.sort_by_key(|note| !crate::matcher::title_fold(¬e.title).starts_with(&needle)); |
| 104 | } |
| 105 | let hits: Vec<TitleHit> = notes |
| 106 | .into_iter() |
| 107 | .take(TITLE_HITS) |
| 108 | .map(|note| TitleHit { |
| 109 | id: note.id, |
| 110 | title: note.title, |
| 111 | }) |
| 112 | .collect(); |
| 113 | let body = serde_json::to_string(&hits) |
| 114 | .map_err(anyhow::Error::from) |
| 115 | .map_err(topcoat::Error::from_anyhow)?; |
| 116 | Ok(([(header::CONTENT_TYPE.as_str(), "application/json".to_owned())], body)) |
| 117 | } |
| 118 | |
| 119 | #[derive(Deserialize)] |
| 120 | struct QuickNote { |
| 121 | title: String, |
| 122 | |
| 123 | |
| 124 | #[serde(default)] |
| 125 | go: String, |
| 126 | } |
| 127 | |
| 128 | |
| 129 | |
| 130 | fn heading_markdown(title: &str) -> String { |
| 131 | let collapsed = title.split_whitespace().collect::<Vec<_>>().join(" "); |
| 132 | let text = if collapsed.is_empty() { |
| 133 | "Untitled".to_owned() |
| 134 | } else { |
| 135 | collapsed |
| 136 | }; |
| 137 | let escaped: String = text |
| 138 | .chars() |
| 139 | .flat_map(|c| { |
| 140 | let escape = matches!(c, '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '~' | '#' | '&'); |
| 141 | escape.then_some('\\').into_iter().chain(std::iter::once(c)) |
| 142 | }) |
| 143 | .collect(); |
| 144 | format!("# {escaped}\n") |
| 145 | } |
| 146 | |
| 147 | |
| 148 | |
| 149 | #[route(POST "./quick")] |
| 150 | async fn quick_note(cx: &Cx, Form(input): Form<QuickNote>) -> Result<String> { |
| 151 | let store = app_context::<Arc<Store>>(cx); |
| 152 | let markdown = heading_markdown(&input.title); |
| 153 | let doc = markdown_to_doc(&markdown).map_err(topcoat::Error::from_anyhow)?; |
| 154 | let update = markdown_to_update(&markdown).map_err(topcoat::Error::from_anyhow)?; |
| 155 | let title = export::title(&doc); |
| 156 | let body = export::to_markdown(&doc); |
| 157 | |
| 158 | let note = store |
| 159 | .create_note(None) |
| 160 | .await |
| 161 | .map_err(topcoat::Error::from_anyhow)?; |
| 162 | store |
| 163 | .append_update(¬e.id, &update) |
| 164 | .await |
| 165 | .map_err(topcoat::Error::from_anyhow)?; |
| 166 | store |
| 167 | .set_title(¬e.id, &title) |
| 168 | .await |
| 169 | .map_err(topcoat::Error::from_anyhow)?; |
| 170 | store |
| 171 | .put_text(¬e.id, &title, &body) |
| 172 | .await |
| 173 | .map_err(topcoat::Error::from_anyhow)?; |
| 174 | store |
| 175 | .set_links(¬e.id, &export::note_links(&doc)) |
| 176 | .await |
| 177 | .map_err(topcoat::Error::from_anyhow)?; |
| 178 | |
| 179 | if input.go.is_empty() { |
| 180 | return Ok(note.id); |
| 181 | } |
| 182 | Err(see_other(format!("/notes/{}", note.id)).into()) |
| 183 | } |
| 184 | |
| 185 | |
| 186 | |
| 187 | #[page("./by-title/{title}")] |
| 188 | async fn note_by_title(cx: &Cx) -> Result<impl View> { |
| 189 | let store = app_context::<Arc<Store>>(cx); |
| 190 | let name = path_param::<Title>(cx).to_owned(); |
| 191 | let key = title_key(&name); |
| 192 | if let Some(note) = store.note_by_title_key(&key).await.map_err(topcoat::Error::from_anyhow)? { |
| 193 | return Err(see_other(format!("/notes/{}", note.id)).into()); |
| 194 | } |
| 195 | |
| 196 | let lang = i18n::lang(cx); |
| 197 | let heading = t(lang, Msg::NoNoteNamed).replace("{title}", &name); |
| 198 | let create = t(lang, Msg::CreateNote); |
| 199 | Ok(view! { |
| 200 | <div class="mx-auto flex w-full max-w-md flex-col gap-4 px-4 py-16 lg:px-8"> |
| 201 | <p class="text-base">(heading)</p> |
| 202 | <form method="post" action="/notes/quick" class="flex"> |
| 203 | <input type="hidden" name="title" value=(name)> |
| 204 | <input type="hidden" name="go" value="1"> |
| 205 | button( |
| 206 | variant: ButtonVariant::Outline, |
| 207 | size: ButtonSize::Md, |
| 208 | attrs: attributes! { type="submit" }, |
| 209 | (create) |
| 210 | ) |
| 211 | </form> |
| 212 | </div> |
| 213 | }) |
| 214 | } |