//! The app shell pieces shared by every page: the head scripts and styles, the sidebar, //! the toast region, the note rows, and the "New note" form. use std::time::{SystemTime, UNIX_EPOCH}; use topcoat::{ Result, view::{Child, View, attributes, component, view}, }; use crate::components::button::{ButtonSize, ButtonVariant, button}; use crate::components::dropdown_menu::{ dropdown_menu, dropdown_menu_content, dropdown_menu_item, dropdown_menu_label, dropdown_menu_separator, dropdown_menu_sub, dropdown_menu_sub_content, dropdown_menu_sub_trigger, dropdown_menu_trigger, }; use crate::components::floating::{FloatingAlign, FloatingSide}; use crate::components::input::input; use crate::components::kbd::{kbd, kbd_group}; use crate::components::segmented::{SEGMENT_ICON, TRACK}; use crate::i18n::{Lang, Msg, t}; use crate::scheme::{ALL as SCHEMES, Scheme}; use crate::store::Notebook; /// Runs before first paint. It applies the theme (light, dark, or system, stored in /// localStorage as "theme") and the sidebar state ("sidebar"). The sidebar theme buttons /// (`data-theme-set`) set the theme on click and keep `aria-pressed` in step with it. /// `window.cycleTheme` steps through light, dark, and system for the command palette. /// `html.no-anim` turns transitions off until the first frame, so a restored sidebar /// state does not animate on load. pub const THEME_SCRIPT: &str = r#" (function () { var root = document.documentElement; var order = ['light', 'dark', 'system']; var mq = window.matchMedia('(prefers-color-scheme: dark)'); root.classList.add('no-anim'); function read(key, valid, fallback) { try { var v = localStorage.getItem(key); return valid.indexOf(v) >= 0 ? v : fallback; } catch (e) { return fallback; } } function syncThemeButtons() { var pref = root.dataset.theme; document.querySelectorAll('[data-theme-set]').forEach(function (btn) { btn.setAttribute('aria-pressed', btn.dataset.themeSet === pref ? 'true' : 'false'); }); } function applyTheme(pref) { root.dataset.theme = pref; root.classList.toggle('dark', pref === 'dark' || (pref === 'system' && mq.matches)); syncThemeButtons(); } function setTheme(pref) { try { localStorage.setItem('theme', pref); } catch (e) {} applyTheme(pref); } applyTheme(read('theme', order, 'system')); mq.addEventListener('change', function () { if (read('theme', order, 'system') === 'system') applyTheme('system'); }); window.cycleTheme = function () { setTheme(order[(order.indexOf(read('theme', order, 'system')) + 1) % order.length]); }; window.syncThemeButtons = syncThemeButtons; document.addEventListener('click', function (e) { var btn = e.target.closest && e.target.closest('[data-theme-set]'); if (btn) setTheme(btn.dataset.themeSet); }); root.dataset.sidebar = read('sidebar', ['collapsed', 'expanded'], 'expanded'); requestAnimationFrame(function () { requestAnimationFrame(function () { root.classList.remove('no-anim'); }); }); })(); "#; /// Shell styles that depend on the viewport or on `data-*` state. Below 1024px the sidebar /// is an off-canvas drawer that slides in and out with a fading backdrop; it stays /// `visibility: hidden` (and `inert`, set by the script) until the slide-out ends. At /// 1024px and up the sidebar collapses by animating its width to 0, with its fixed-width /// body fading. `html.no-anim` suppresses transitions on the first frame. Reduced motion /// disables all of it. Also: touch target sizes and cross-document view transitions. pub const SHELL_STYLE: &str = r#" @view-transition { navigation: auto; } #sidebar { position: fixed; top: 0; bottom: 0; left: 0; z-index: 40; width: 240px; max-width: 85vw; height: 100dvh; transform: translateX(-100%); visibility: hidden; transition: transform 220ms cubic-bezier(.2,.8,.2,1), visibility 0s linear 220ms; } #sidebar[data-open="true"] { transform: none; visibility: visible; transition: transform 220ms cubic-bezier(.2,.8,.2,1), visibility 0s; } #drawer-backdrop { position: fixed; inset: 0; z-index: 30; background: color-mix(in srgb, var(--foreground) 30%, transparent); opacity: 0; visibility: hidden; transition: opacity 220ms ease, visibility 0s linear 220ms; } #drawer-backdrop[data-open="true"] { opacity: 1; visibility: visible; transition: opacity 220ms ease, visibility 0s; } #sidebar-expand { display: none; } html.no-anim, html.no-anim *, html.no-anim *::before, html.no-anim *::after { transition: none !important; } @media (min-width: 1024px) { #sidebar { position: static; z-index: auto; max-width: none; height: auto; flex-shrink: 0; width: 240px; transform: none; visibility: visible; transition: width 200ms cubic-bezier(.2,.8,.2,1), border-right-width 200ms cubic-bezier(.2,.8,.2,1), visibility 200ms linear; } #sidebar > .sidebar-body { transition: opacity 150ms ease; } html[data-sidebar="collapsed"] #sidebar { width: 0; border-right-width: 0; visibility: hidden; } html[data-sidebar="collapsed"] #sidebar > .sidebar-body { opacity: 0; } html[data-sidebar="collapsed"] #sidebar-expand { display: inline-flex; } /* The list pane header reserves room for the floating expand button (12px inset, 32px wide, 8px gap). */ .sidebar-lead { transition: padding-left 200ms cubic-bezier(.2,.8,.2,1); } html[data-sidebar="collapsed"] .sidebar-lead { padding-left: 3.25rem; } #drawer-backdrop { display: none; } } @media (max-width: 1023px) { #sidebar a, #sidebar button, #sidebar input, #sidebar-expand, #drawer-open, [data-close-drawer] { min-height: 40px; } input, select, textarea { font-size: 16px; } } @media (prefers-reduced-motion: reduce) { #sidebar, #sidebar[data-open="true"], #sidebar > .sidebar-body, .sidebar-lead, #drawer-backdrop, #drawer-backdrop[data-open="true"] { transition: none !important; } } "#; /// Global keyboard shortcuts and the small interactions of the shell: the mobile drawer /// (opened from the top bar, closed by Esc, the backdrop, or its close button), sidebar /// collapse, and toasts that hide after six seconds. /// /// Shortcuts: Ctrl/Cmd+K opens the command palette (`window.openPalette`, Ctrl/Cmd+Shift+K /// inside the editor), otherwise focuses the search box. "/" focuses search and "n" submits the New note form, both only when no /// field is being typed in. pub const SHELL_SCRIPT: &str = r#" (function () { var root = document.documentElement; // Server renders times in UTC; show them in the viewer's own time zone. var fmt = new Intl.DateTimeFormat(root.lang || undefined, { dateStyle: 'medium', timeStyle: 'short' }); document.querySelectorAll('time[data-ms]').forEach(function (el) { el.textContent = fmt.format(new Date(Number(el.dataset.ms))); }); var sidebar = document.getElementById('sidebar'); var backdrop = document.getElementById('drawer-backdrop'); var openBtn = document.getElementById('drawer-open'); var collapseBtn = document.getElementById('sidebar-collapse'); var expandBtn = document.getElementById('sidebar-expand'); var desktop = window.matchMedia('(min-width: 1024px)'); var opener = null; function isOpen() { return sidebar.dataset.open === 'true'; } function syncInert() { sidebar.inert = !desktop.matches && !isOpen(); } function setDrawer(open) { if (open === isOpen()) return; if (open) opener = document.activeElement; sidebar.dataset.open = open ? 'true' : 'false'; backdrop.dataset.open = open ? 'true' : 'false'; openBtn.setAttribute('aria-expanded', open ? 'true' : 'false'); syncInert(); // The drawer is still sliding in when focus moves, so keep the page from scrolling. if (open) { var first = sidebar.querySelector('[data-close-drawer]'); if (first) first.focus({ preventScroll: true }); } else if (opener && !desktop.matches) { opener.focus({ preventScroll: true }); } } function isCollapsed() { return root.dataset.sidebar === 'collapsed'; } function setCollapsed(collapsed) { root.dataset.sidebar = collapsed ? 'collapsed' : 'expanded'; try { localStorage.setItem('sidebar', root.dataset.sidebar); } catch (e) {} } function focusSearch() { if (desktop.matches && isCollapsed()) setCollapsed(false); if (!desktop.matches && !isOpen()) setDrawer(true); var input = document.getElementById('search-input'); if (input) { input.focus(); input.select(); } } // Live search: results replace the page content as you type, without a reload. An // empty box shows every note again. Enter still submits the form as a fallback. var searchBox = document.getElementById('search-input'); if (searchBox && window.fetch && window.DOMParser) { var searchTimer = 0; var searchCtl = null; var searchSeq = 0; // Search filters (match case, whole word, exact phrase, regex). The results page's // URL says which are on; elsewhere the last choice is remembered. var OPTS = ['case', 'word', 'exact', 're']; var opts = {}; var params = new URLSearchParams(location.search); var saved = {}; try { saved = JSON.parse(localStorage.getItem('search-opts') || '{}'); } catch (e) {} OPTS.forEach(function (k) { opts[k] = location.pathname === '/search' ? params.get(k) === '1' : !!saved[k]; }); // The filter menu's checkboxes and the dot on its button follow `opts`. var syncOpts = function () { var any = false; document.querySelectorAll('[data-search-opt]').forEach(function (el) { el.setAttribute('aria-checked', opts[el.dataset.searchOpt] ? 'true' : 'false'); }); OPTS.forEach(function (k) { if (opts[k]) any = true; }); var btn = document.getElementById('search-filter-button'); if (btn) btn.toggleAttribute('data-active', any); }; syncOpts(); var runSearch = function () { var q = searchBox.value.trim(); var url = '/'; if (q) { url = '/search?q=' + encodeURIComponent(q); OPTS.forEach(function (k) { if (opts[k]) url += '&' + k + '=1'; }); } if (searchCtl) searchCtl.abort(); searchCtl = new AbortController(); var seq = ++searchSeq; fetch(url, { signal: searchCtl.signal, headers: { accept: 'text/html' } }) .then(function (res) { return res.text(); }) .then(function (html) { if (seq !== searchSeq) return; var doc = new DOMParser().parseFromString(html, 'text/html'); var next = doc.getElementById('main'); var main = document.getElementById('main'); if (!next || !main) return; window.dispatchEvent(new Event('note:detach')); main.innerHTML = next.innerHTML; document.title = doc.title; main.querySelectorAll('time[data-ms]').forEach(function (el) { el.textContent = fmt.format(new Date(Number(el.dataset.ms))); }); // Keep the sidebar's current section in step with the page. // Links pair up by position; the sidebar has the same links on every page. var twins = doc.querySelectorAll('#sidebar a[href]'); document.querySelectorAll('#sidebar a[href]').forEach(function (a, i) { var twin = twins[i]; if (!twin || twin.getAttribute('href') !== a.getAttribute('href')) return; a.className = twin.className; if (twin.hasAttribute('aria-current')) a.setAttribute('aria-current', twin.getAttribute('aria-current')); else a.removeAttribute('aria-current'); }); // The first keystroke from another page adds a history entry; later ones // replace it, so Back leaves search in one step. var onResults = location.pathname === '/search' || history.state === 'live-search'; history[onResults ? 'replaceState' : 'pushState']('live-search', '', url); }) .catch(function () {}); }; searchBox.addEventListener('input', function () { clearTimeout(searchTimer); searchTimer = setTimeout(runSearch, 150); }); var flip = function (key) { opts[key] = !opts[key]; try { localStorage.setItem('search-opts', JSON.stringify(opts)); } catch (e) {} syncOpts(); clearTimeout(searchTimer); if (searchBox.value.trim()) runSearch(); }; document.addEventListener('click', function (e) { var btn = e.target.closest && e.target.closest('[data-search-opt]'); if (!btn) return; e.preventDefault(); flip(btn.dataset.searchOpt); }); // Alt+C / W / E / R toggle the filters from the search box, as in code editors. searchBox.addEventListener('keydown', function (e) { if (!e.altKey || e.ctrlKey || e.metaKey) return; var key = { KeyC: 'case', KeyW: 'word', KeyE: 'exact', KeyR: 're' }[e.code]; if (!key) return; e.preventDefault(); flip(key); }); window.addEventListener('popstate', function () { location.reload(); }); } openBtn.addEventListener('click', function () { setDrawer(!isOpen()); }); backdrop.addEventListener('click', function () { setDrawer(false); }); document.querySelectorAll('[data-close-drawer]').forEach(function (btn) { btn.addEventListener('click', function () { setDrawer(false); }); }); if (collapseBtn) { collapseBtn.addEventListener('click', function () { setCollapsed(true); if (expandBtn) expandBtn.focus(); }); } if (expandBtn) { expandBtn.addEventListener('click', function () { setCollapsed(false); if (collapseBtn) collapseBtn.focus(); }); } desktop.addEventListener('change', function () { if (desktop.matches) { sidebar.dataset.open = 'false'; backdrop.dataset.open = 'false'; openBtn.setAttribute('aria-expanded', 'false'); } syncInert(); }); syncInert(); if (typeof window.syncThemeButtons === 'function') window.syncThemeButtons(); document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && isOpen()) { e.preventDefault(); setDrawer(false); return; } var el = document.activeElement; var typing = !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)); var mod = e.ctrlKey || e.metaKey; if (mod && !e.altKey && e.key.toLowerCase() === 'k') { // In the editor, Mod-K is the link shortcut; the palette takes Mod-Shift-K there. if (el && el.closest && el.closest('.ProseMirror') && !e.shiftKey) return; e.preventDefault(); if (typeof window.openPalette === 'function') { window.openPalette(); } else { var palette = document.getElementById('palette'); if (palette) { if (typeof palette.showModal === 'function') palette.showModal(); else palette.hidden = false; } else { focusSearch(); } } return; } if (typing || mod || e.altKey) return; if (e.key === '/') { e.preventDefault(); focusSearch(); } else if (e.key === 'n' || e.key === 'N') { var form = document.getElementById('new-note-form'); if (form) { e.preventDefault(); form.requestSubmit(); } } }); // Color scheme. The server puts data-scheme on from the cookie. Choosing a scheme // (picker or palette) applies it at once and saves it with a POST to /scheme. Hovering or // focusing a picker row previews that scheme; closing the menu without a choice restores // the saved one. `window.setScheme` is shared with the command palette. var committed = root.dataset.scheme; var schemeMenu = document.getElementById('scheme-menu'); function syncScheme() { var id = root.dataset.scheme; document.querySelectorAll('[data-scheme-current]').forEach(function (el) { el.hidden = el.dataset.schemeCurrent !== id; }); document.querySelectorAll('[data-scheme-choice]').forEach(function (el) { el.setAttribute('aria-checked', el.dataset.schemeChoice === committed ? 'true' : 'false'); }); } function preview(id) { root.dataset.scheme = id; syncScheme(); } window.setScheme = function (id) { committed = id; preview(id); fetch('/scheme', { method: 'POST', credentials: 'same-origin', redirect: 'manual', body: new URLSearchParams({ scheme: id, back: location.pathname + location.search }) }).catch(function () {}); }; function rowScheme(e) { var item = e.target.closest && e.target.closest('[data-scheme-choice]'); if (item) preview(item.dataset.schemeChoice); } if (schemeMenu) { schemeMenu.addEventListener('pointerover', rowScheme); schemeMenu.addEventListener('focusin', rowScheme); schemeMenu.addEventListener('toggle', function (e) { if (e.newState === 'closed') preview(committed); }); } document.addEventListener('submit', function (e) { var form = e.target; var field = form.matches && form.matches('[data-scheme-form]') && form.querySelector('input[name="scheme"]'); if (!field) return; e.preventDefault(); window.setScheme(field.value); if (schemeMenu && schemeMenu.matches(':popover-open')) schemeMenu.hidePopover(); }); syncScheme(); document.querySelectorAll('#toasts [data-toast]').forEach(function (toast) { var timer = setTimeout(function () { toast.remove(); }, 6000); var dismiss = toast.querySelector('[data-dismiss]'); if (dismiss) { dismiss.addEventListener('click', function () { clearTimeout(timer); toast.remove(); }); } }); })(); "#; pub fn now_millis() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_millis() as i64) .unwrap_or(0) } /// The note title, or "Untitled" in `lang` when it is blank. pub fn title_of(lang: Lang, title: &str) -> String { if title.trim().is_empty() { t(lang, Msg::Untitled).to_owned() } else { title.trim().to_owned() } } /// The name of the notebook with `id`, if it exists. pub fn notebook_name(notebooks: &[Notebook], id: Option<&str>) -> Option { let id = id?; notebooks.iter().find(|nb| nb.id == id).map(|nb| nb.name.clone()) } /// Where the user is, as far as the sidebar is concerned. #[derive(Clone, PartialEq, Eq)] pub enum Section { All, Unfiled, Trash, Notebook(String), /// A page that has no sidebar entry, such as search. Other, } /// A notebook entry in the sidebar. pub struct Shelf { pub id: String, pub name: String, pub count: usize, } /// Everything the sidebar shows. Counts exclude trashed notes, except `trash`. pub struct SidebarData { pub all: usize, pub unfiled: usize, pub trash: usize, pub notebooks: Vec, pub section: Section, /// The notebook a new note is created in. Empty for none. pub current_notebook: String, /// The search text, shown in the search box. pub query: String, /// Path and query to return to after a language change. pub back: String, /// The color scheme in effect, for the picker's button and checkmarks. pub scheme: Scheme, } const NAV_ITEM: &str = "flex h-9 min-w-0 items-center gap-2 rounded-control px-2 text-sm transition-colors"; const NAV_IDLE: &str = "text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"; const NAV_ACTIVE: &str = "marker font-medium"; const NAV_COUNT: &str = "ml-auto font-mono text-xs tabular-nums text-muted-foreground"; /// One sidebar row: a link with an optional count. The active row gets the marker swipe /// and `aria-current="page"`. #[component] async fn nav_item(href: String, label: String, count: usize, active: bool) -> Result { let class = if active { format!("{NAV_ITEM} {NAV_ACTIVE}") } else { format!("{NAV_ITEM} {NAV_IDLE}") }; let current = if active { "page" } else { "false" }; Ok(view! { (label) (count) }) } /// Three dots showing a scheme's sidebar, accent, and active row colors. The light and /// dark colors go in as custom properties; `.dark` picks the dark one (see `styles.css`). #[component] async fn scheme_dots(scheme: Scheme) -> Result { let dots: Vec = scheme .dots() .iter() .map(|(light, dark)| format!("--dot-light:{light};--dot-dark:{dark}")) .collect(); Ok(view! { }) } /// The picker's button label: the scheme's name and dots. Every scheme has a label, and /// the script shows the one for the current (or previewed) scheme. #[component] async fn scheme_label(scheme: Scheme, current: Scheme) -> Result { Ok(view! { if scheme == current { scheme_dots(scheme: scheme) (scheme.name()) } else { } }) } /// Every scheme's label in the picker button. Only the current one is shown; the script /// moves the `hidden` attribute when the scheme changes or is previewed. #[component] async fn scheme_names(current: Scheme) -> Result { Ok(view! { for s in SCHEMES { scheme_label(scheme: s, current: current) } }) } /// One row per scheme in the picker's menu. Each row is a form that posts the choice to /// `/scheme`; the script intercepts it and applies the scheme without a reload. #[component] async fn scheme_items(current: Scheme, back: String) -> Result { let rows: Vec<(Scheme, &'static str)> = SCHEMES .into_iter() .map(|s| (s, if s == current { "true" } else { "false" })) .collect(); Ok(view! { for (scheme, checked) in rows {
dropdown_menu_item( attrs: attributes! { type="submit" role="menuitemradio" aria-checked=(checked) data-scheme-choice=(scheme.id()) class="justify-start" }, scheme_dots(scheme: scheme) (scheme.name()) )
} }) } /// The round initials badge of the profile button. const AVATAR: &str = "inline-flex size-8 shrink-0 items-center justify-center rounded-full bg-[var(--active-row)] text-xs font-semibold text-[var(--active-row-foreground)]"; /// A link row in a menu, with an icon, matching `dropdown_menu_item`. const MENU_ROW: &str = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm whitespace-nowrap hover:bg-foreground/5 focus-visible:bg-foreground/5 active:bg-foreground/10"; /// The sidebar: app name, search, New note, the notes and trash list, notebooks with /// a new-notebook form, and the theme and language controls. It is a `