forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

notes.rs214 lines, 7.0 KiBHistoryRawDownload
1use std::sync::Arc;
2
3use serde::{Deserialize, Serialize};
4use 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
15use crate::components::button::{ButtonSize, ButtonVariant, button};
16use crate::export;
17use crate::i18n::{self, Msg, t};
18use crate::import::{markdown_to_doc, markdown_to_update};
19use crate::store::{ListFilter, Store, title_key};
20
21mod note_id;
22
23path_param!(title);
24
25#[derive(Deserialize)]
26struct NewNote {
27 /// Empty or absent when the note is created outside any notebook.
28 #[serde(default)]
29 notebook_id: String,
30}
31
32/// POST /notes: creates an empty note (in the notebook named by the form, if any)
33/// and redirects to the editor.
34#[route(POST)]
35async 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(&note.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)]
64pub struct TitlesQuery {
65 pub q: Option<String>,
66}
67
68#[derive(Serialize)]
69struct TitleHit {
70 id: String,
71 title: String,
72}
73
74/// Most notes the link picker is answered with.
75const TITLE_HITS: usize = 8;
76/// Most title matches read before the prefix matches are put first.
77const TITLE_SEARCH_LIMIT: usize = 10_000;
78
79/// GET /notes/titles.json?q=...: up to 8 notes outside the trash whose title contains `q`
80/// (case-insensitive), prefix matches first. Without a query, the most recently updated.
81#[route(GET "./titles.json")]
82async 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 // Stable: within each group the most recently updated notes stay first.
103 notes.sort_by_key(|note| !crate::matcher::title_fold(&note.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)]
120struct QuickNote {
121 title: String,
122 /// `1` from the by-title page's button: redirect to the new note instead of answering
123 /// with its id.
124 #[serde(default)]
125 go: String,
126}
127
128/// A one-heading markdown document whose heading is `title` as literal text. Markdown
129/// syntax in the title is escaped and whitespace is collapsed.
130fn 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/// POST /notes/quick: creates an unfiled note titled `title` and answers with its id. With
148/// `go` set, it redirects to the note instead.
149#[route(POST "./quick")]
150async 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(&note.id, &update)
164 .await
165 .map_err(topcoat::Error::from_anyhow)?;
166 store
167 .set_title(&note.id, &title)
168 .await
169 .map_err(topcoat::Error::from_anyhow)?;
170 store
171 .put_text(&note.id, &title, &body)
172 .await
173 .map_err(topcoat::Error::from_anyhow)?;
174 store
175 .set_links(&note.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/// GET /notes/by-title/{title}: redirects to the note with that title (case-insensitive,
186/// outside the trash). Otherwise offers to create a note with the title.
187#[page("./by-title/{title}")]
188async 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}