use std::sync::Arc; use topcoat::{ Result, asset::{AssetBundle, RouterBuilderAssetExt}, context::{Cx, app_context}, asset::asset, cookie::RouterBuilderCookieExt, font::{Font, RouterBuilderFontExt, font}, router::{ Body, BodyLimit, HeaderValue, Layer, LayerFuture, Next, Path, Router, RouterBuilderDirectoryExt, Slot, StatusCode, header, layout, module_router, page, query_params, request::uri, }, tailwind, view::{Unescaped, View, view}, }; use crate::editor_assets::{self, EditorAssets}; use crate::hub::Hub; use crate::i18n::{self, Msg, t}; use crate::media::Media; use crate::store::{ListFilter, Store}; use self::pane::{ListSpec, Mobile}; use topcoat::view::Child; use self::shell::{Section, Shelf, SidebarData, notebook_name, sidebar, title_of, toast_region}; use self::palette::palette_dialog; mod lang; mod media; mod notebooks; mod notes; mod pane; mod export_all; mod format; mod import; mod palette; mod scheme; mod search; mod shell; mod trash; mod unfiled; /// Builds the app router. `assets/` (editor.css and the hashed editor bundle from `cargo xtask editor`) is served at the /// site root; the Tailwind stylesheet comes from the Topcoat asset bundle, which must be /// built next to the executable with `topcoat asset bundle`. /// The theme's fonts, self-hosted from `fonts/` (variable weight, SIL OFL 1.1) and served /// from the asset bundle. Latin Extended covers Turkish. UI and note body use Next; /// metadata, keycaps and code use Mono. const ATKINSON_NEXT: Font = font! { "Atkinson Hyperlegible Next", @font-face { src: url(asset!("fonts/atkinson-hyperlegible-next-latin-wght.woff2")) format("woff2") tech("variations"); font-weight: 200 800; font-display: swap; unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } @font-face { src: url(asset!("fonts/atkinson-hyperlegible-next-latin-ext-wght.woff2")) format("woff2") tech("variations"); font-weight: 200 800; font-display: swap; unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; } }; const ATKINSON_MONO: Font = font! { "Atkinson Hyperlegible Mono", @font-face { src: url(asset!("fonts/atkinson-hyperlegible-mono-latin-wght.woff2")) format("woff2") tech("variations"); font-weight: 200 800; font-display: swap; unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } @font-face { src: url(asset!("fonts/atkinson-hyperlegible-mono-latin-ext-wght.woff2")) format("woff2") tech("variations"); font-weight: 200 800; font-display: swap; unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; } }; /// Caches the content-hashed editor files for a year. Their names change with their /// contents, so a cached copy never goes stale. Other files in `assets/` are untouched. struct ImmutableEditorFiles; impl Layer for ImmutableEditorFiles { fn path(&self) -> Option<&Path> { None } fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { Box::pin(async move { let mut response = next.run(cx, body).await?; let name = uri(cx).path().trim_start_matches('/'); if let Some(content_type) = editor_assets::content_type(name) { let status = response.status(); if status.is_success() || status == StatusCode::NOT_MODIFIED { let headers = response.headers_mut(); headers.insert( header::CACHE_CONTROL, HeaderValue::from_static("public, max-age=31536000, immutable"), ); headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type)); } } Ok(response) }) } } pub fn router(store: Arc, hub: Arc, media: Arc) -> Router { // Read once at startup. `None` leaves the note page without preload hints. let editor: Arc> = Arc::new(EditorAssets::load()); module_router!() .route(export_all::export_zip) .route(import::import_file) .route(media::upload_media) .route(media::serve_media) .route(media::serve_take) .route(media::recording_socket) .route(format::format_code) // Imported files arrive form-encoded, which can grow a file several times over. .layer(BodyLimit::max(128 * 1024 * 1024).at("/import/file")) .layer(ImmutableEditorFiles) .cookies() .font(ATKINSON_NEXT) .font(ATKINSON_MONO) .public_dir("./assets") .assets(AssetBundle::load().expect("asset bundle missing: run `topcoat asset bundle`")) .app_context(store) .app_context(hub) .app_context(editor) .app_context(media) .build() } /// Query parameters the shell reads on every page: the search text, the toast key, and /// the note to restore for the toast's Undo button. #[query_params(error = bad_request)] pub struct ShellQuery { pub q: Option, pub toast: Option, pub undo: Option, } /// A note id from a query string, safe to put in a URL path. fn is_note_id(id: &str) -> bool { !id.is_empty() && id.len() <= 64 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') } /// Shell around every page: head, mobile top bar, sidebar, page content, and toasts. /// The page title and the active sidebar section follow the request path. #[layout] async fn layout(cx: &Cx, slot: Slot<'_>) -> Result { let store = app_context::>(cx); let lang = i18n::lang(cx); let scheme = crate::scheme::scheme(cx); let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?; let (all_count, unfiled_count, trash_count) = store.count_notes().await.map_err(topcoat::Error::from_anyhow)?; let notebook_counts = store.notebook_counts().await.map_err(topcoat::Error::from_anyhow)?; let (q, toast_key, undo) = match query_params::(cx) { Ok(query) => (query.q.clone(), query.toast.clone(), query.undo.clone()), Err(_) => (None, None, None), }; let query = q.unwrap_or_default(); let uri = uri(cx); let back = uri .path_and_query() .map(|pq| pq.as_str().to_owned()) .unwrap_or_else(|| "/".to_owned()); let path = uri.path().to_owned(); let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); // The section highlighted in the sidebar, the notebook a new note goes to, and the // name of the page (for the title). let mut current_notebook = String::new(); let (section, page_name) = match segments.as_slice() { [] => (Section::All, t(lang, Msg::AllNotes).to_owned()), ["unfiled"] => (Section::Unfiled, t(lang, Msg::Unfiled).to_owned()), ["trash"] => (Section::Trash, t(lang, Msg::Trash).to_owned()), // An empty search shows every note, so it is "All notes". ["search", ..] if query.trim().is_empty() => (Section::All, t(lang, Msg::AllNotes).to_owned()), ["search", ..] => (Section::Other, t(lang, Msg::Search).to_owned()), ["notebooks", id, ..] => { let name = notebook_name(¬ebooks, Some(id)); if name.is_some() { current_notebook = (*id).to_owned(); } (Section::Notebook((*id).to_owned()), name.unwrap_or_default()) } ["notes", id, ..] => match store.get_note(id).await.map_err(topcoat::Error::from_anyhow)? { Some(meta) => { current_notebook = meta.notebook_id.clone().unwrap_or_default(); // The same context as the list pane: trash, the note's notebook, or unfiled. let section = if meta.trashed_at.is_some() { Section::Trash } else if let Some(nb) = &meta.notebook_id { Section::Notebook(nb.clone()) } else { Section::Unfiled }; (section, title_of(lang, &meta.title)) } None => (Section::All, String::new()), }, _ => (Section::Other, String::new()), }; let title = if page_name.is_empty() { t(lang, Msg::AppName).to_owned() } else { format!("{page_name} \u{b7} {}", t(lang, Msg::AppName)) }; let shelves: Vec = notebooks .iter() .map(|nb| Shelf { id: nb.id.clone(), name: nb.name.clone(), count: notebook_counts.get(&nb.id).copied().unwrap_or(0), }) .collect(); let toast_message = match toast_key.as_deref() { Some("trashed") => Some(t(lang, Msg::ToastTrashed)), Some("restored") => Some(t(lang, Msg::ToastRestored)), Some("notebook_created") => Some(t(lang, Msg::ToastNotebookCreated)), Some("notebook_deleted") => Some(t(lang, Msg::ToastNotebookDeleted)), Some("moved") => Some(t(lang, Msg::ToastMoved)), Some("version-restored") => Some(t(lang, Msg::ToastVersionRestored)), _ => None, }; let undo_id = match (toast_key.as_deref(), undo) { (Some("trashed"), Some(id)) if is_note_id(&id) => Some(id), _ => None, }; let sidebar_data = SidebarData { all: all_count, unfiled: unfiled_count, trash: trash_count, notebooks: shelves, section, current_notebook, query, back, scheme, }; let app_name = t(lang, Msg::AppName); let skip = t(lang, Msg::SkipToContent); let open_menu = t(lang, Msg::OpenMenu); let show_sidebar = t(lang, Msg::ShowSidebar); Ok(view! { (title) topcoat::font::link(font: ATKINSON_NEXT) topcoat::font::link(font: ATKINSON_MONO) (skip)
(app_name)
sidebar(lang: lang, data: sidebar_data)
(slot)
toast_region(lang: lang, message: toast_message, undo: undo_id) palette_dialog(lang: lang) }) } /// GET /: all notes, most recently updated first, beside the detail pane. #[page] async fn index(cx: &Cx) -> Result { all_notes(cx).await } /// Every note in the list pane, nothing open yet. Also what an empty search shows. async fn all_notes(cx: &Cx) -> Result { let store = app_context::>(cx); let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?; let page = pane::load_page(cx, store, ListFilter::All) .await .map_err(topcoat::Error::from_anyhow)?; let lang = i18n::lang(cx); let spec = ListSpec { title: t(lang, Msg::AllNotes).to_owned(), heading: true, count: page.total, notebook_id: String::new(), groups: pane::groups(lang, &page.notes, ¬ebooks, &page.previews, None, true), empty: t(lang, Msg::NoNotesYet), more: page.more, }; let list = pane::list_pane(cx, lang, spec, Child::new(())); Ok(pane::split( cx, Mobile::List, Child::new(list), Child::new(pane::empty_detail(cx, lang)), )) }