forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

note_id.rs557 lines, 22.6 KiBHistoryRawDownload
1use std::sync::Arc;
2
3use serde::Deserialize;
4use topcoat::{
5 Result,
6 context::{Cx, app_context},
7 router::{
8 content::Form,
9 error::{RouterErrorExt, SeeOther, bad_request, see_other},
10 header, module_param, page, path_param, route,
11 },
12 view::{Child, Unescaped, View, attributes, view},
13};
14
15use crate::app::pane::{self, MENU_LINK, Mobile};
16use crate::app::shell;
17use crate::components::button::{ButtonSize, ButtonVariant, button, button_variants};
18use crate::components::dropdown_menu::{
19 dropdown_menu, dropdown_menu_content, dropdown_menu_item, dropdown_menu_label,
20 dropdown_menu_separator, dropdown_menu_sub, dropdown_menu_sub_content,
21 dropdown_menu_sub_trigger, dropdown_menu_trigger,
22};
23use crate::components::floating::{FloatingAlign, FloatingSide};
24use crate::components::input::input as text_input;
25use crate::editor_assets::EditorAssets;
26use crate::export::html_page;
27use crate::hub::Hub;
28use crate::i18n::{self, Msg, t};
29use crate::store::{ListFilter, NoteMeta, Notebook, Store};
30
31mod history;
32mod ws;
33
34module_param!(note_id);
35
36/// Most notebooks listed in the "Move to" menu. One form per notebook makes the page huge
37/// with thousands of notebooks; the others are moved to by name.
38const MOVE_TARGETS: usize = 30;
39
40/// How much of a note's imported markdown is previewed while its doc is built.
41const PREVIEW_MARKDOWN_BYTES: usize = 64 * 1024;
42
43#[derive(Deserialize)]
44struct MoveNote {
45 /// Empty means "no notebook".
46 #[serde(default)]
47 notebook_id: String,
48 /// Typed name of the target notebook, from the "Move to" menu's name field.
49 #[serde(default)]
50 notebook_name: String,
51}
52
53/// One note in the "Linked from" list of a note.
54struct LinkRow {
55 href: String,
56 title: String,
57 /// Empty when the note is not in a notebook.
58 notebook: String,
59}
60
61/// One entry of the "Move to" menu.
62#[derive(Clone)]
63struct MoveTarget {
64 id: String,
65 name: String,
66 current: bool,
67}
68
69/// Where the note's list goes: the notebook's notes, or every note when it has no
70/// notebook. Returns the list's title, the notes it selects, and the list's URL.
71fn context_list(
72 lang: i18n::Lang,
73 meta: &NoteMeta,
74 notebooks: &[Notebook],
75) -> (String, ListFilter, String, bool) {
76 match shell::notebook_name(notebooks, meta.notebook_id.as_deref()) {
77 Some(name) => {
78 let nb = meta.notebook_id.clone().unwrap_or_default();
79 (name, ListFilter::Notebook(nb.clone()), format!("/notebooks/{nb}"), false)
80 }
81 None => (
82 t(lang, Msg::AllNotes).to_owned(),
83 ListFilter::All,
84 "/".to_owned(),
85 true,
86 ),
87 }
88}
89
90/// GET /notes/{note_id}: the note's editor beside the list it belongs to. A trashed note
91/// shows a banner with Restore and no editor.
92#[page]
93async fn note(cx: &Cx) -> Result<impl View> {
94 let store = app_context::<Arc<Store>>(cx);
95 let editor: &Option<EditorAssets> = app_context::<Arc<Option<EditorAssets>>>(cx);
96 let id = path_param::<NoteId>(cx).to_owned();
97 let meta = store
98 .get_note(&id)
99 .await
100 .map_err(topcoat::Error::from_anyhow)?
101 .ok_or_not_found()?;
102 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
103 let lang = crate::i18n::lang(cx);
104
105 let title = shell::title_of(lang, &meta.title);
106 let trashed = meta.trashed_at.is_some();
107 let prerender = if trashed {
108 String::new()
109 } else if let Some(head) = store.pending_head(&id, PREVIEW_MARKDOWN_BYTES).await.map_err(topcoat::Error::from_anyhow)? {
110 // The doc is still being built from an import: preview the markdown's start.
111 tokio::task::spawn_blocking(move || crate::import::preview_markdown(&head))
112 .await
113 .map_err(|e| topcoat::Error::from_anyhow(e.into()))?
114 } else {
115 let hub = app_context::<Arc<Hub>>(cx);
116 let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
117 room.editor_html().await
118 };
119 let backlinks = if trashed {
120 Vec::new()
121 } else {
122 store
123 .backlinks(&id, &meta.title)
124 .await
125 .map_err(topcoat::Error::from_anyhow)?
126 };
127 let linked_rows: Vec<LinkRow> = backlinks
128 .iter()
129 .map(|note| LinkRow {
130 href: format!("/notes/{}", note.id),
131 title: shell::title_of(lang, &note.title),
132 notebook: shell::notebook_name(&notebooks, note.notebook_id.as_deref())
133 .unwrap_or_default(),
134 })
135 .collect();
136 let current_nb = meta.notebook_id.clone().unwrap_or_default();
137 let crumb_nb = shell::notebook_name(&notebooks, meta.notebook_id.as_deref());
138 let crumb_label = crumb_nb
139 .clone()
140 .unwrap_or_else(|| t(lang, Msg::Unfiled).to_owned());
141 let crumb_href = match &meta.notebook_id {
142 Some(nb) => format!("/notebooks/{nb}"),
143 None => "/unfiled".to_owned(),
144 };
145
146 let (list_title, list_filter, list_href, show_notebook) =
147 context_list(lang, &meta, &notebooks);
148 // Only the first page of the list is read. The open note is in it when it is near the top.
149 let page = pane::load_page(cx, store, list_filter)
150 .await
151 .map_err(topcoat::Error::from_anyhow)?;
152 let groups = pane::groups(
153 lang,
154 &page.notes,
155 &notebooks,
156 &page.previews,
157 Some(id.as_str()),
158 show_notebook,
159 );
160 let spec = pane::ListSpec {
161 title: list_title,
162 heading: false,
163 count: page.total,
164 notebook_id: current_nb.clone(),
165 groups,
166 empty: t(lang, Msg::NoNotesYet),
167 more: page.more,
168 };
169 let list = pane::list_pane(cx, lang, spec, Child::new(()));
170
171 let mut moves: Vec<MoveTarget> = std::iter::once(MoveTarget {
172 id: String::new(),
173 name: t(lang, Msg::Unfiled).to_owned(),
174 current: current_nb.is_empty(),
175 })
176 .chain(notebooks.iter().take(MOVE_TARGETS).map(|nb| MoveTarget {
177 id: nb.id.clone(),
178 name: nb.name.clone(),
179 current: nb.id == current_nb,
180 }))
181 .collect();
182 // The note's own notebook stays listed even when it is past the first MOVE_TARGETS.
183 if !current_nb.is_empty() && !moves.iter().any(|m| m.current) {
184 if let Some(nb) = notebooks.iter().find(|nb| nb.id == current_nb) {
185 moves.push(MoveTarget {
186 id: nb.id.clone(),
187 name: nb.name.clone(),
188 current: true,
189 });
190 }
191 }
192 let hidden = notebooks.len() + 1 - moves.len();
193 let by_name_label = t(lang, Msg::NotebookByName);
194 let already_here = t(lang, Msg::AlreadyHere);
195 let move_reason = if trashed {
196 t(lang, Msg::RestoreFirst)
197 } else {
198 ""
199 };
200 let trash_reason = if trashed {
201 t(lang, Msg::AlreadyInTrash)
202 } else {
203 ""
204 };
205 let move_action = format!("/notes/{id}/move");
206 let trash_action = format!("/notes/{id}/trash");
207 let restore_action = format!("/notes/{id}/restore");
208 let export_href = format!("/notes/{id}/export.md");
209 let export_html_href = format!("/notes/{id}/export.html");
210 let print_href = format!("/notes/{id}/print");
211 let history_href = format!("/notes/{id}/history");
212 let history_label = t(lang, Msg::VersionHistory);
213 let export_html_label = t(lang, Msg::ExportHtml);
214 let export_pdf = t(lang, Msg::ExportPdf);
215 let back_label = t(lang, Msg::BackToList);
216 let in_trash = t(lang, Msg::InTrash);
217 let restore = t(lang, Msg::Restore);
218 let breadcrumb = t(lang, Msg::Breadcrumb);
219 let move_to_notebook = t(lang, Msg::MoveToNotebook);
220 let export_as = t(lang, Msg::ExportAs);
221 let export_md = t(lang, Msg::ExportMarkdown);
222 let trash_label = t(lang, Msg::MoveToTrash);
223 let note_actions = t(lang, Msg::NoteActions);
224 let linked_label = t(lang, Msg::LinkedFrom);
225
226 // The one actions menu, at every width: move, export, trash.
227 let actions = Child::new(view! {
228 dropdown_menu(
229 dropdown_menu_trigger(
230 target: "note-actions-menu",
231 attrs: attributes! {
232 class=(button_variants(ButtonVariant::Outline, ButtonSize::Icon))
233 aria-label=(note_actions)
234 },
235 <svg class="size-4" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
236 <circle cx="5" cy="12" r="1.75"></circle>
237 <circle cx="12" cy="12" r="1.75"></circle>
238 <circle cx="19" cy="12" r="1.75"></circle>
239 </svg>
240 )
241 dropdown_menu_content(
242 id: "note-actions-menu",
243 align: FloatingAlign::End,
244 dropdown_menu_label((move_to_notebook))
245 for target in moves {
246 <form method="post" action=(move_action.clone())>
247 <input type="hidden" name="notebook_id" value=(target.id)>
248 dropdown_menu_item(
249 attrs: attributes! {
250 type="submit"
251 disabled=(trashed || target.current)
252 title=(if trashed { move_reason } else if target.current { already_here } else { "" })
253 },
254 (target.name)
255 )
256 </form>
257 }
258 if hidden > 0 {
259 <form method="post" action=(move_action.clone())>
260 text_input(attrs: attributes! {
261 type="text"
262 name="notebook_name"
263 placeholder=(by_name_label)
264 aria-label=(by_name_label)
265 required=(true)
266 autocomplete="off"
267 maxlength="120"
268 disabled=(trashed)
269 onclick="event.stopPropagation()"
270 onkeydown="if (event.key !== 'Escape') event.stopPropagation()"
271 class="h-8 text-sm"
272 })
273 </form>
274 }
275 dropdown_menu_separator()
276 if !trashed {
277 <a href=(history_href) class=(MENU_LINK)>(history_label)</a>
278 }
279 dropdown_menu_sub(
280 dropdown_menu_sub_trigger(target: "note-export-menu", (export_as))
281 dropdown_menu_sub_content(
282 id: "note-export-menu",
283 side: FloatingSide::Left,
284 <a href=(export_href) class=(MENU_LINK)>(export_md)</a>
285 <a href=(export_html_href) class=(MENU_LINK)>(export_html_label)</a>
286 <a href=(print_href) target="_blank" rel="noopener" class=(MENU_LINK)>(export_pdf)</a>
287 )
288 )
289 dropdown_menu_separator()
290 <form method="post" action=(trash_action)>
291 dropdown_menu_item(
292 attrs: attributes! {
293 type="submit"
294 class="text-destructive"
295 disabled=(trashed)
296 title=(trash_reason)
297 },
298 (trash_label)
299 )
300 </form>
301 )
302 )
303 });
304
305 let detail = Child::new(view! {
306 <div class="flex min-h-0 min-w-0 flex-1 flex-col">
307 <header id="note-header" class="sticky top-0 z-10 flex h-11 shrink-0 items-center gap-2 border-b border-border bg-background px-3">
308 <a
309 href=(list_href)
310 aria-label=(back_label)
311 class="inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground lg:hidden"
312 >
313 <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
314 <path d="m15 18-6-6 6-6"></path>
315 </svg>
316 </a>
317 <nav aria-label=(breadcrumb) class="note-crumb flex min-w-[8rem] flex-1 items-center gap-2 text-sm text-muted-foreground">
318 <a href=(crumb_href) class="note-crumb-notebook min-w-0 truncate hover:text-foreground">(crumb_label)</a>
319 <span class="note-crumb-notebook" aria-hidden="true">"›"</span>
320 <h1 class="min-w-0 truncate text-sm font-medium text-foreground">(title.clone())</h1>
321 </nav>
322 if !trashed {
323 <span class="h-4 w-px shrink-0 bg-border" aria-hidden="true"></span>
324 <div id="editor-toolbar" class="flex shrink-0 items-center"></div>
325 }
326 <div class="ml-auto flex shrink-0 items-center gap-2">
327 if !trashed {
328 <span id="sync-slot" class="flex shrink-0 items-center"></span>
329 }
330 (actions)
331 </div>
332 </header>
333 if trashed {
334 <div role="status" class="flex flex-wrap items-center gap-3 border-b border-border px-4 py-3 text-sm">
335 <p class="min-w-0 flex-1">(in_trash)</p>
336 <form method="post" action=(restore_action)>
337 button(
338 variant: ButtonVariant::Outline,
339 size: ButtonSize::Sm,
340 attrs: attributes! { type="submit" },
341 (restore)
342 )
343 </form>
344 </div>
345 } else {
346 <div id="editor" class="min-h-0 w-full flex-1" data-note-id=(id.clone()) data-note-title=(title)>
347 <div class="ProseMirror" contenteditable="false" translate="no">(Unescaped::new_unchecked(prerender.clone()))</div>
348 </div>
349 <script type="application/json" id="editor-strings">(Unescaped::new_unchecked(i18n::editor_strings_json(lang)))</script>
350 if let Some(assets) = editor {
351 <link rel="modulepreload" href=(format!("/{}", assets.js))>
352 <link rel="preload" href=(format!("/{}", assets.wasm)) as="fetch" type="application/wasm" crossorigin="anonymous">
353 <script type="module" src=(format!("/{}", assets.js))></script>
354 }
355 if !linked_rows.is_empty() {
356 <section aria-labelledby="linked-from" class="mx-auto w-full max-w-[calc(68ch+48px)] shrink-0 border-t border-border px-6 pt-4 pb-8">
357 <h2 id="linked-from" class="text-xs font-medium text-muted-foreground">(linked_label)</h2>
358 <ul class="mt-2 flex max-h-48 flex-col gap-1 overflow-y-auto">
359 for row in linked_rows {
360 <li>
361 <a href=(row.href) class="flex min-w-0 items-baseline gap-2 rounded-control px-2 py-1.5 text-sm transition-colors hover:bg-foreground/5">
362 <span class="min-w-0 truncate">(row.title)</span>
363 if !row.notebook.is_empty() {
364 <span class="shrink-0 text-xs text-muted-foreground">(row.notebook)</span>
365 }
366 </a>
367 </li>
368 }
369 </ul>
370 </section>
371 }
372 }
373 </div>
374 });
375 Ok(pane::split(cx, Mobile::Detail, Child::new(list), detail))
376}
377
378/// POST /notes/{note_id}/move: moves the note into a notebook, or unfiles it.
379#[route(POST "./move")]
380async fn move_note(cx: &Cx, Form(input): Form<MoveNote>) -> Result<SeeOther> {
381 let store = app_context::<Arc<Store>>(cx);
382 let id = path_param::<NoteId>(cx).to_owned();
383 let meta = store
384 .get_note(&id)
385 .await
386 .map_err(topcoat::Error::from_anyhow)?
387 .ok_or_not_found()?;
388 if meta.trashed_at.is_some() {
389 return Err(bad_request("the note is in the trash; restore it first").into());
390 }
391 let typed = input.notebook_name.trim();
392 let picked = if typed.is_empty() {
393 None
394 } else {
395 let wanted = typed.to_lowercase();
396 let nb_id = store
397 .list_notebooks()
398 .await
399 .map_err(topcoat::Error::from_anyhow)?
400 .iter()
401 .find(|nb| nb.name.trim().to_lowercase() == wanted)
402 .map(|nb| nb.id.clone());
403 let Some(nb_id) = nb_id else {
404 return Err(bad_request(t(i18n::lang(cx), Msg::NoSuchNotebook)).into());
405 };
406 Some(nb_id)
407 };
408 let target = picked.as_deref().unwrap_or(input.notebook_id.trim());
409 let target = if target.is_empty() {
410 None
411 } else {
412 let exists = store
413 .get_notebook(target)
414 .await
415 .map_err(topcoat::Error::from_anyhow)?
416 .is_some();
417 if !exists {
418 return Err(bad_request("unknown notebook").into());
419 }
420 Some(target)
421 };
422 store
423 .move_note(&id, target)
424 .await
425 .map_err(topcoat::Error::from_anyhow)?;
426 Ok(see_other(format!("/notes/{id}?toast=moved")))
427}
428
429/// POST /notes/{note_id}/trash: moves the note to the trash and returns to its list, with
430/// an Undo toast.
431#[route(POST "./trash")]
432async fn trash_note(cx: &Cx) -> Result<SeeOther> {
433 let store = app_context::<Arc<Store>>(cx);
434 let id = path_param::<NoteId>(cx).to_owned();
435 let meta = store
436 .get_note(&id)
437 .await
438 .map_err(topcoat::Error::from_anyhow)?
439 .ok_or_not_found()?;
440 store.trash_note(&id).await.map_err(topcoat::Error::from_anyhow)?;
441 let back = match meta.notebook_id {
442 Some(nb) => format!("/notebooks/{nb}"),
443 None => "/".to_owned(),
444 };
445 Ok(see_other(format!("{back}?toast=trashed&undo={id}")))
446}
447
448/// POST /notes/{note_id}/restore: takes the note out of the trash and opens it.
449#[route(POST "./restore")]
450async fn restore_note(cx: &Cx) -> Result<SeeOther> {
451 let store = app_context::<Arc<Store>>(cx);
452 let id = path_param::<NoteId>(cx).to_owned();
453 store.get_note(&id).await.map_err(topcoat::Error::from_anyhow)?.ok_or_not_found()?;
454 store.restore_note(&id).await.map_err(topcoat::Error::from_anyhow)?;
455 Ok(see_other(format!("/notes/{id}?toast=restored")))
456}
457
458/// ASCII-only file name stem from a note title. Falls back to "note".
459/// The note title as a safe file name, without extension.
460fn file_stem(title: &str) -> String {
461 crate::app::export_all::sanitize(title)
462}
463
464/// `Content-Disposition` for a download: an ASCII `filename` for old clients and the
465/// real title as UTF-8 in `filename*`.
466fn attachment(stem: &str, ext: &str) -> String {
467 let ascii: String = stem
468 .chars()
469 .map(|c| match c {
470 'ı' | 'İ' => 'i',
471 'ş' | 'Ş' => 's',
472 'ğ' | 'Ğ' => 'g',
473 'ü' | 'Ü' => 'u',
474 'ö' | 'Ö' => 'o',
475 'ç' | 'Ç' => 'c',
476 c if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' => c,
477 _ => '-',
478 })
479 .collect();
480 let ascii = ascii.trim_matches('-');
481 let ascii = if ascii.is_empty() { "note" } else { ascii };
482 let encoded: String = format!("{stem}.{ext}")
483 .bytes()
484 .map(|b| match b {
485 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
486 _ => format!("%{b:02X}"),
487 })
488 .collect();
489 format!("attachment; filename=\"{ascii}.{ext}\"; filename*=UTF-8''{encoded}")
490}
491
492/// Standalone HTML of the live note, and the file name stem to save it under.
493async fn note_page(cx: &Cx, print: bool) -> Result<(String, String)> {
494 let store = app_context::<Arc<Store>>(cx);
495 let hub = app_context::<Arc<Hub>>(cx);
496 let id = path_param::<NoteId>(cx).to_owned();
497 let meta = store
498 .get_note(&id)
499 .await
500 .map_err(topcoat::Error::from_anyhow)?
501 .ok_or_not_found()?;
502 let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
503 let body = room.html().await.map_err(topcoat::Error::from_anyhow)?;
504 let lang = i18n::lang(cx);
505 let title = shell::title_of(lang, &meta.title);
506 let page = html_page(&title, &body, lang.code(), print);
507 Ok((file_stem(&title), page))
508}
509
510/// GET /notes/{note_id}/export.md: markdown of the live document.
511#[route(GET "./export.md")]
512async fn export_markdown(cx: &Cx) -> Result<([(&'static str, String); 2], String)> {
513 let store = app_context::<Arc<Store>>(cx);
514 let hub = app_context::<Arc<Hub>>(cx);
515 let id = path_param::<NoteId>(cx).to_owned();
516 let meta = store
517 .get_note(&id)
518 .await
519 .map_err(topcoat::Error::from_anyhow)?
520 .ok_or_not_found()?;
521 let markdown = match store.pending_markdown(&id).await.map_err(topcoat::Error::from_anyhow)? {
522 Some(markdown) => markdown,
523 None => {
524 let room = hub.room(store, &id).await.map_err(topcoat::Error::from_anyhow)?;
525 room.markdown_with(store).await.map_err(topcoat::Error::from_anyhow)?
526 }
527 };
528 let stem = file_stem(&shell::title_of(i18n::lang(cx), &meta.title));
529 Ok((
530 [
531 (header::CONTENT_TYPE.as_str(), "text/markdown; charset=utf-8".to_owned()),
532 (header::CONTENT_DISPOSITION.as_str(), attachment(&stem, "md")),
533 ],
534 markdown,
535 ))
536}
537
538/// GET /notes/{note_id}/export.html: standalone HTML file of the live document.
539#[route(GET "./export.html")]
540async fn export_html(cx: &Cx) -> Result<([(&'static str, String); 2], String)> {
541 let (stem, page) = note_page(cx, false).await?;
542 Ok((
543 [
544 (header::CONTENT_TYPE.as_str(), "text/html; charset=utf-8".to_owned()),
545 (header::CONTENT_DISPOSITION.as_str(), attachment(&stem, "html")),
546 ],
547 page,
548 ))
549}
550
551/// GET /notes/{note_id}/print: the same HTML, shown inline. It opens the print dialog,
552/// where "Save as PDF" makes the PDF.
553#[route(GET "./print")]
554async fn print_note(cx: &Cx) -> Result<([(&'static str, &'static str); 1], String)> {
555 let (_, page) = note_page(cx, true).await?;
556 Ok(([(header::CONTENT_TYPE.as_str(), "text/html; charset=utf-8")], page))
557}