forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksJavaScript3.6 MiBe100df4Tahinli1 month ago1 commit

shell.rs930 lines, 44.7 KiBHistoryRawDownload
1//! The app shell pieces shared by every page: the head scripts and styles, the sidebar,
2//! the toast region, the note rows, and the "New note" form.
3
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use topcoat::{
7 Result,
8 view::{Child, View, attributes, component, view},
9};
10
11use crate::components::button::{ButtonSize, ButtonVariant, button};
12use crate::components::dropdown_menu::{
13 dropdown_menu, dropdown_menu_content, dropdown_menu_item, dropdown_menu_label,
14 dropdown_menu_separator,
15 dropdown_menu_sub, dropdown_menu_sub_content, dropdown_menu_sub_trigger, dropdown_menu_trigger,
16};
17use crate::components::floating::{FloatingAlign, FloatingSide};
18use crate::components::input::input;
19use crate::components::kbd::{kbd, kbd_group};
20use crate::components::segmented::{SEGMENT_ICON, TRACK};
21use crate::i18n::{Lang, Msg, t};
22use crate::scheme::{ALL as SCHEMES, Scheme};
23use crate::store::Notebook;
24
25/// Runs before first paint. It applies the theme (light, dark, or system, stored in
26/// localStorage as "theme") and the sidebar state ("sidebar"). The sidebar theme buttons
27/// (`data-theme-set`) set the theme on click and keep `aria-pressed` in step with it.
28/// `window.cycleTheme` steps through light, dark, and system for the command palette.
29/// `html.no-anim` turns transitions off until the first frame, so a restored sidebar
30/// state does not animate on load.
31pub const THEME_SCRIPT: &str = r#"
32(function () {
33 var root = document.documentElement;
34 var order = ['light', 'dark', 'system'];
35 var mq = window.matchMedia('(prefers-color-scheme: dark)');
36 root.classList.add('no-anim');
37 function read(key, valid, fallback) {
38 try {
39 var v = localStorage.getItem(key);
40 return valid.indexOf(v) >= 0 ? v : fallback;
41 } catch (e) {
42 return fallback;
43 }
44 }
45 function syncThemeButtons() {
46 var pref = root.dataset.theme;
47 document.querySelectorAll('[data-theme-set]').forEach(function (btn) {
48 btn.setAttribute('aria-pressed', btn.dataset.themeSet === pref ? 'true' : 'false');
49 });
50 }
51 function applyTheme(pref) {
52 root.dataset.theme = pref;
53 root.classList.toggle('dark', pref === 'dark' || (pref === 'system' && mq.matches));
54 syncThemeButtons();
55 }
56 function setTheme(pref) {
57 try { localStorage.setItem('theme', pref); } catch (e) {}
58 applyTheme(pref);
59 }
60 applyTheme(read('theme', order, 'system'));
61 mq.addEventListener('change', function () {
62 if (read('theme', order, 'system') === 'system') applyTheme('system');
63 });
64 window.cycleTheme = function () {
65 setTheme(order[(order.indexOf(read('theme', order, 'system')) + 1) % order.length]);
66 };
67 window.syncThemeButtons = syncThemeButtons;
68 document.addEventListener('click', function (e) {
69 var btn = e.target.closest && e.target.closest('[data-theme-set]');
70 if (btn) setTheme(btn.dataset.themeSet);
71 });
72 root.dataset.sidebar = read('sidebar', ['collapsed', 'expanded'], 'expanded');
73 requestAnimationFrame(function () {
74 requestAnimationFrame(function () { root.classList.remove('no-anim'); });
75 });
76})();
77"#;
78
79/// Shell styles that depend on the viewport or on `data-*` state. Below 1024px the sidebar
80/// is an off-canvas drawer that slides in and out with a fading backdrop; it stays
81/// `visibility: hidden` (and `inert`, set by the script) until the slide-out ends. At
82/// 1024px and up the sidebar collapses by animating its width to 0, with its fixed-width
83/// body fading. `html.no-anim` suppresses transitions on the first frame. Reduced motion
84/// disables all of it. Also: touch target sizes and cross-document view transitions.
85pub const SHELL_STYLE: &str = r#"
86@view-transition { navigation: auto; }
87#sidebar {
88 position: fixed; top: 0; bottom: 0; left: 0; z-index: 40;
89 width: 240px; max-width: 85vw; height: 100dvh;
90 transform: translateX(-100%); visibility: hidden;
91 transition: transform 220ms cubic-bezier(.2,.8,.2,1), visibility 0s linear 220ms;
92}
93#sidebar[data-open="true"] {
94 transform: none; visibility: visible;
95 transition: transform 220ms cubic-bezier(.2,.8,.2,1), visibility 0s;
96}
97#drawer-backdrop {
98 position: fixed; inset: 0; z-index: 30;
99 background: color-mix(in srgb, var(--foreground) 30%, transparent);
100 opacity: 0; visibility: hidden;
101 transition: opacity 220ms ease, visibility 0s linear 220ms;
102}
103#drawer-backdrop[data-open="true"] {
104 opacity: 1; visibility: visible;
105 transition: opacity 220ms ease, visibility 0s;
106}
107#sidebar-expand { display: none; }
108html.no-anim, html.no-anim *, html.no-anim *::before, html.no-anim *::after {
109 transition: none !important;
110}
111@media (min-width: 1024px) {
112 #sidebar {
113 position: static; z-index: auto; max-width: none; height: auto; flex-shrink: 0;
114 width: 240px; transform: none; visibility: visible;
115 transition:
116 width 200ms cubic-bezier(.2,.8,.2,1),
117 border-right-width 200ms cubic-bezier(.2,.8,.2,1),
118 visibility 200ms linear;
119 }
120 #sidebar > .sidebar-body { transition: opacity 150ms ease; }
121 html[data-sidebar="collapsed"] #sidebar { width: 0; border-right-width: 0; visibility: hidden; }
122 html[data-sidebar="collapsed"] #sidebar > .sidebar-body { opacity: 0; }
123 html[data-sidebar="collapsed"] #sidebar-expand { display: inline-flex; }
124 /* The list pane header reserves room for the floating expand button (12px inset, 32px wide, 8px gap). */
125 .sidebar-lead { transition: padding-left 200ms cubic-bezier(.2,.8,.2,1); }
126 html[data-sidebar="collapsed"] .sidebar-lead { padding-left: 3.25rem; }
127 #drawer-backdrop { display: none; }
128}
129@media (max-width: 1023px) {
130 #sidebar a, #sidebar button, #sidebar input, #sidebar-expand, #drawer-open, [data-close-drawer] { min-height: 40px; }
131 input, select, textarea { font-size: 16px; }
132}
133@media (prefers-reduced-motion: reduce) {
134 #sidebar, #sidebar[data-open="true"], #sidebar > .sidebar-body, .sidebar-lead, #drawer-backdrop, #drawer-backdrop[data-open="true"] {
135 transition: none !important;
136 }
137}
138"#;
139
140/// Global keyboard shortcuts and the small interactions of the shell: the mobile drawer
141/// (opened from the top bar, closed by Esc, the backdrop, or its close button), sidebar
142/// collapse, and toasts that hide after six seconds.
143///
144/// Shortcuts: Ctrl/Cmd+K opens the command palette (`window.openPalette`, Ctrl/Cmd+Shift+K
145/// inside the editor), otherwise focuses the search box. "/" focuses search and "n" submits the New note form, both only when no
146/// field is being typed in.
147pub const SHELL_SCRIPT: &str = r#"
148(function () {
149 var root = document.documentElement;
150 // Server renders times in UTC; show them in the viewer's own time zone.
151 var fmt = new Intl.DateTimeFormat(root.lang || undefined, { dateStyle: 'medium', timeStyle: 'short' });
152 document.querySelectorAll('time[data-ms]').forEach(function (el) {
153 el.textContent = fmt.format(new Date(Number(el.dataset.ms)));
154 });
155 var sidebar = document.getElementById('sidebar');
156 var backdrop = document.getElementById('drawer-backdrop');
157 var openBtn = document.getElementById('drawer-open');
158 var collapseBtn = document.getElementById('sidebar-collapse');
159 var expandBtn = document.getElementById('sidebar-expand');
160 var desktop = window.matchMedia('(min-width: 1024px)');
161 var opener = null;
162
163 function isOpen() { return sidebar.dataset.open === 'true'; }
164 function syncInert() { sidebar.inert = !desktop.matches && !isOpen(); }
165 function setDrawer(open) {
166 if (open === isOpen()) return;
167 if (open) opener = document.activeElement;
168 sidebar.dataset.open = open ? 'true' : 'false';
169 backdrop.dataset.open = open ? 'true' : 'false';
170 openBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
171 syncInert();
172 // The drawer is still sliding in when focus moves, so keep the page from scrolling.
173 if (open) {
174 var first = sidebar.querySelector('[data-close-drawer]');
175 if (first) first.focus({ preventScroll: true });
176 } else if (opener && !desktop.matches) {
177 opener.focus({ preventScroll: true });
178 }
179 }
180 function isCollapsed() { return root.dataset.sidebar === 'collapsed'; }
181 function setCollapsed(collapsed) {
182 root.dataset.sidebar = collapsed ? 'collapsed' : 'expanded';
183 try { localStorage.setItem('sidebar', root.dataset.sidebar); } catch (e) {}
184 }
185 function focusSearch() {
186 if (desktop.matches && isCollapsed()) setCollapsed(false);
187 if (!desktop.matches && !isOpen()) setDrawer(true);
188 var input = document.getElementById('search-input');
189 if (input) { input.focus(); input.select(); }
190 }
191
192 // Live search: results replace the page content as you type, without a reload. An
193 // empty box shows every note again. Enter still submits the form as a fallback.
194 var searchBox = document.getElementById('search-input');
195 if (searchBox && window.fetch && window.DOMParser) {
196 var searchTimer = 0;
197 var searchCtl = null;
198 var searchSeq = 0;
199 // Search filters (match case, whole word, exact phrase, regex). The results page's
200 // URL says which are on; elsewhere the last choice is remembered.
201 var OPTS = ['case', 'word', 'exact', 're'];
202 var opts = {};
203 var params = new URLSearchParams(location.search);
204 var saved = {};
205 try { saved = JSON.parse(localStorage.getItem('search-opts') || '{}'); } catch (e) {}
206 OPTS.forEach(function (k) {
207 opts[k] = location.pathname === '/search' ? params.get(k) === '1' : !!saved[k];
208 });
209 // The filter menu's checkboxes and the dot on its button follow `opts`.
210 var syncOpts = function () {
211 var any = false;
212 document.querySelectorAll('[data-search-opt]').forEach(function (el) {
213 el.setAttribute('aria-checked', opts[el.dataset.searchOpt] ? 'true' : 'false');
214 });
215 OPTS.forEach(function (k) { if (opts[k]) any = true; });
216 var btn = document.getElementById('search-filter-button');
217 if (btn) btn.toggleAttribute('data-active', any);
218 };
219 syncOpts();
220 var runSearch = function () {
221 var q = searchBox.value.trim();
222 var url = '/';
223 if (q) {
224 url = '/search?q=' + encodeURIComponent(q);
225 OPTS.forEach(function (k) { if (opts[k]) url += '&' + k + '=1'; });
226 }
227 if (searchCtl) searchCtl.abort();
228 searchCtl = new AbortController();
229 var seq = ++searchSeq;
230 fetch(url, { signal: searchCtl.signal, headers: { accept: 'text/html' } })
231 .then(function (res) { return res.text(); })
232 .then(function (html) {
233 if (seq !== searchSeq) return;
234 var doc = new DOMParser().parseFromString(html, 'text/html');
235 var next = doc.getElementById('main');
236 var main = document.getElementById('main');
237 if (!next || !main) return;
238 window.dispatchEvent(new Event('note:detach'));
239 main.innerHTML = next.innerHTML;
240 document.title = doc.title;
241 main.querySelectorAll('time[data-ms]').forEach(function (el) {
242 el.textContent = fmt.format(new Date(Number(el.dataset.ms)));
243 });
244 // Keep the sidebar's current section in step with the page.
245 // Links pair up by position; the sidebar has the same links on every page.
246 var twins = doc.querySelectorAll('#sidebar a[href]');
247 document.querySelectorAll('#sidebar a[href]').forEach(function (a, i) {
248 var twin = twins[i];
249 if (!twin || twin.getAttribute('href') !== a.getAttribute('href')) return;
250 a.className = twin.className;
251 if (twin.hasAttribute('aria-current')) a.setAttribute('aria-current', twin.getAttribute('aria-current'));
252 else a.removeAttribute('aria-current');
253 });
254 // The first keystroke from another page adds a history entry; later ones
255 // replace it, so Back leaves search in one step.
256 var onResults = location.pathname === '/search' || history.state === 'live-search';
257 history[onResults ? 'replaceState' : 'pushState']('live-search', '', url);
258 })
259 .catch(function () {});
260 };
261 searchBox.addEventListener('input', function () {
262 clearTimeout(searchTimer);
263 searchTimer = setTimeout(runSearch, 150);
264 });
265 var flip = function (key) {
266 opts[key] = !opts[key];
267 try { localStorage.setItem('search-opts', JSON.stringify(opts)); } catch (e) {}
268 syncOpts();
269 clearTimeout(searchTimer);
270 if (searchBox.value.trim()) runSearch();
271 };
272 document.addEventListener('click', function (e) {
273 var btn = e.target.closest && e.target.closest('[data-search-opt]');
274 if (!btn) return;
275 e.preventDefault();
276 flip(btn.dataset.searchOpt);
277 });
278 // Alt+C / W / E / R toggle the filters from the search box, as in code editors.
279 searchBox.addEventListener('keydown', function (e) {
280 if (!e.altKey || e.ctrlKey || e.metaKey) return;
281 var key = { KeyC: 'case', KeyW: 'word', KeyE: 'exact', KeyR: 're' }[e.code];
282 if (!key) return;
283 e.preventDefault();
284 flip(key);
285 });
286 window.addEventListener('popstate', function () { location.reload(); });
287 }
288
289 openBtn.addEventListener('click', function () { setDrawer(!isOpen()); });
290 backdrop.addEventListener('click', function () { setDrawer(false); });
291 document.querySelectorAll('[data-close-drawer]').forEach(function (btn) {
292 btn.addEventListener('click', function () { setDrawer(false); });
293 });
294 if (collapseBtn) {
295 collapseBtn.addEventListener('click', function () {
296 setCollapsed(true);
297 if (expandBtn) expandBtn.focus();
298 });
299 }
300 if (expandBtn) {
301 expandBtn.addEventListener('click', function () {
302 setCollapsed(false);
303 if (collapseBtn) collapseBtn.focus();
304 });
305 }
306 desktop.addEventListener('change', function () {
307 if (desktop.matches) {
308 sidebar.dataset.open = 'false';
309 backdrop.dataset.open = 'false';
310 openBtn.setAttribute('aria-expanded', 'false');
311 }
312 syncInert();
313 });
314 syncInert();
315 if (typeof window.syncThemeButtons === 'function') window.syncThemeButtons();
316
317 document.addEventListener('keydown', function (e) {
318 if (e.key === 'Escape' && isOpen()) {
319 e.preventDefault();
320 setDrawer(false);
321 return;
322 }
323 var el = document.activeElement;
324 var typing = !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
325 var mod = e.ctrlKey || e.metaKey;
326 if (mod && !e.altKey && e.key.toLowerCase() === 'k') {
327 // In the editor, Mod-K is the link shortcut; the palette takes Mod-Shift-K there.
328 if (el && el.closest && el.closest('.ProseMirror') && !e.shiftKey) return;
329 e.preventDefault();
330 if (typeof window.openPalette === 'function') {
331 window.openPalette();
332 } else {
333 var palette = document.getElementById('palette');
334 if (palette) {
335 if (typeof palette.showModal === 'function') palette.showModal();
336 else palette.hidden = false;
337 } else {
338 focusSearch();
339 }
340 }
341 return;
342 }
343 if (typing || mod || e.altKey) return;
344 if (e.key === '/') {
345 e.preventDefault();
346 focusSearch();
347 } else if (e.key === 'n' || e.key === 'N') {
348 var form = document.getElementById('new-note-form');
349 if (form) {
350 e.preventDefault();
351 form.requestSubmit();
352 }
353 }
354 });
355
356 // Color scheme. The server puts data-scheme on <html> from the cookie. Choosing a scheme
357 // (picker or palette) applies it at once and saves it with a POST to /scheme. Hovering or
358 // focusing a picker row previews that scheme; closing the menu without a choice restores
359 // the saved one. `window.setScheme` is shared with the command palette.
360 var committed = root.dataset.scheme;
361 var schemeMenu = document.getElementById('scheme-menu');
362 function syncScheme() {
363 var id = root.dataset.scheme;
364 document.querySelectorAll('[data-scheme-current]').forEach(function (el) {
365 el.hidden = el.dataset.schemeCurrent !== id;
366 });
367 document.querySelectorAll('[data-scheme-choice]').forEach(function (el) {
368 el.setAttribute('aria-checked', el.dataset.schemeChoice === committed ? 'true' : 'false');
369 });
370 }
371 function preview(id) {
372 root.dataset.scheme = id;
373 syncScheme();
374 }
375 window.setScheme = function (id) {
376 committed = id;
377 preview(id);
378 fetch('/scheme', {
379 method: 'POST',
380 credentials: 'same-origin',
381 redirect: 'manual',
382 body: new URLSearchParams({ scheme: id, back: location.pathname + location.search })
383 }).catch(function () {});
384 };
385 function rowScheme(e) {
386 var item = e.target.closest && e.target.closest('[data-scheme-choice]');
387 if (item) preview(item.dataset.schemeChoice);
388 }
389 if (schemeMenu) {
390 schemeMenu.addEventListener('pointerover', rowScheme);
391 schemeMenu.addEventListener('focusin', rowScheme);
392 schemeMenu.addEventListener('toggle', function (e) {
393 if (e.newState === 'closed') preview(committed);
394 });
395 }
396 document.addEventListener('submit', function (e) {
397 var form = e.target;
398 var field = form.matches && form.matches('[data-scheme-form]') && form.querySelector('input[name="scheme"]');
399 if (!field) return;
400 e.preventDefault();
401 window.setScheme(field.value);
402 if (schemeMenu && schemeMenu.matches(':popover-open')) schemeMenu.hidePopover();
403 });
404 syncScheme();
405
406 document.querySelectorAll('#toasts [data-toast]').forEach(function (toast) {
407 var timer = setTimeout(function () { toast.remove(); }, 6000);
408 var dismiss = toast.querySelector('[data-dismiss]');
409 if (dismiss) {
410 dismiss.addEventListener('click', function () {
411 clearTimeout(timer);
412 toast.remove();
413 });
414 }
415 });
416})();
417"#;
418
419pub fn now_millis() -> i64 {
420 SystemTime::now()
421 .duration_since(UNIX_EPOCH)
422 .map(|d| d.as_millis() as i64)
423 .unwrap_or(0)
424}
425
426/// The note title, or "Untitled" in `lang` when it is blank.
427pub fn title_of(lang: Lang, title: &str) -> String {
428 if title.trim().is_empty() {
429 t(lang, Msg::Untitled).to_owned()
430 } else {
431 title.trim().to_owned()
432 }
433}
434
435/// The name of the notebook with `id`, if it exists.
436pub fn notebook_name(notebooks: &[Notebook], id: Option<&str>) -> Option<String> {
437 let id = id?;
438 notebooks.iter().find(|nb| nb.id == id).map(|nb| nb.name.clone())
439}
440
441/// Where the user is, as far as the sidebar is concerned.
442#[derive(Clone, PartialEq, Eq)]
443pub enum Section {
444 All,
445 Unfiled,
446 Trash,
447 Notebook(String),
448 /// A page that has no sidebar entry, such as search.
449 Other,
450}
451
452/// A notebook entry in the sidebar.
453pub struct Shelf {
454 pub id: String,
455 pub name: String,
456 pub count: usize,
457}
458
459/// Everything the sidebar shows. Counts exclude trashed notes, except `trash`.
460pub struct SidebarData {
461 pub all: usize,
462 pub unfiled: usize,
463 pub trash: usize,
464 pub notebooks: Vec<Shelf>,
465 pub section: Section,
466 /// The notebook a new note is created in. Empty for none.
467 pub current_notebook: String,
468 /// The search text, shown in the search box.
469 pub query: String,
470 /// Path and query to return to after a language change.
471 pub back: String,
472 /// The color scheme in effect, for the picker's button and checkmarks.
473 pub scheme: Scheme,
474}
475
476const NAV_ITEM: &str = "flex h-9 min-w-0 items-center gap-2 rounded-control px-2 text-sm transition-colors";
477const NAV_IDLE: &str = "text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground";
478const NAV_ACTIVE: &str = "marker font-medium";
479const NAV_COUNT: &str = "ml-auto font-mono text-xs tabular-nums text-muted-foreground";
480
481/// One sidebar row: a link with an optional count. The active row gets the marker swipe
482/// and `aria-current="page"`.
483#[component]
484async fn nav_item(href: String, label: String, count: usize, active: bool) -> Result<impl View> {
485 let class = if active {
486 format!("{NAV_ITEM} {NAV_ACTIVE}")
487 } else {
488 format!("{NAV_ITEM} {NAV_IDLE}")
489 };
490 let current = if active { "page" } else { "false" };
491 Ok(view! {
492 <a href=(href) class=(class) aria-current=(current)>
493 <span class="min-w-0 truncate">(label)</span>
494 <span class=(NAV_COUNT)>(count)</span>
495 </a>
496 })
497}
498
499/// Three dots showing a scheme's sidebar, accent, and active row colors. The light and
500/// dark colors go in as custom properties; `.dark` picks the dark one (see `styles.css`).
501#[component]
502async fn scheme_dots(scheme: Scheme) -> Result<impl View> {
503 let dots: Vec<String> = scheme
504 .dots()
505 .iter()
506 .map(|(light, dark)| format!("--dot-light:{light};--dot-dark:{dark}"))
507 .collect();
508 Ok(view! {
509 <span class="scheme-dots" aria-hidden="true">
510 for style in dots {
511 <span class="scheme-dot" style=(style)></span>
512 }
513 </span>
514 })
515}
516
517/// The picker's button label: the scheme's name and dots. Every scheme has a label, and
518/// the script shows the one for the current (or previewed) scheme.
519#[component]
520async fn scheme_label(scheme: Scheme, current: Scheme) -> Result<impl View> {
521 Ok(view! {
522 if scheme == current {
523 <span class="flex min-w-0 flex-1 items-center gap-2" data-scheme-current=(scheme.id())>
524 scheme_dots(scheme: scheme)
525 <span class="min-w-0 truncate">(scheme.name())</span>
526 </span>
527 } else {
528 <span class="flex min-w-0 flex-1 items-center gap-2" data-scheme-current=(scheme.id()) hidden="">
529 scheme_dots(scheme: scheme)
530 <span class="min-w-0 truncate">(scheme.name())</span>
531 </span>
532 }
533 })
534}
535
536/// Every scheme's label in the picker button. Only the current one is shown; the script
537/// moves the `hidden` attribute when the scheme changes or is previewed.
538#[component]
539async fn scheme_names(current: Scheme) -> Result<impl View> {
540 Ok(view! {
541 for s in SCHEMES {
542 scheme_label(scheme: s, current: current)
543 }
544 })
545}
546
547/// One row per scheme in the picker's menu. Each row is a form that posts the choice to
548/// `/scheme`; the script intercepts it and applies the scheme without a reload.
549#[component]
550async fn scheme_items(current: Scheme, back: String) -> Result<impl View> {
551 let rows: Vec<(Scheme, &'static str)> = SCHEMES
552 .into_iter()
553 .map(|s| (s, if s == current { "true" } else { "false" }))
554 .collect();
555 Ok(view! {
556 for (scheme, checked) in rows {
557 <form method="post" action="/scheme" class="contents" data-scheme-form=(true)>
558 <input type="hidden" name="scheme" value=(scheme.id())>
559 <input type="hidden" name="back" value=(back.clone())>
560 dropdown_menu_item(
561 attrs: attributes! {
562 type="submit"
563 role="menuitemradio"
564 aria-checked=(checked)
565 data-scheme-choice=(scheme.id())
566 class="justify-start"
567 },
568 scheme_dots(scheme: scheme)
569 <span class="min-w-0 flex-1 truncate">(scheme.name())</span>
570 <svg class="scheme-check size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
571 <path d="M20 6 9 17l-5-5"></path>
572 </svg>
573 )
574 </form>
575 }
576 })
577}
578
579/// The round initials badge of the profile button.
580const 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)]";
581/// A link row in a menu, with an icon, matching `dropdown_menu_item`.
582const 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";
583
584/// The sidebar: app name, search, New note, the notes and trash list, notebooks with
585/// a new-notebook form, and the theme and language controls. It is a `<nav>` landmark.
586/// Below 1024px it is an off-canvas drawer; above, it can be collapsed.
587#[component]
588pub async fn sidebar(lang: Lang, data: SidebarData) -> Result<impl View> {
589 let SidebarData {
590 all,
591 unfiled,
592 trash,
593 notebooks,
594 section,
595 current_notebook,
596 query,
597 back,
598 scheme,
599 } = data;
600 let is_all = section == Section::All;
601 let is_unfiled = section == Section::Unfiled;
602 let is_trash = section == Section::Trash;
603 let shelves: Vec<(String, String, usize, bool)> = notebooks
604 .into_iter()
605 .map(|shelf| {
606 let active = section == Section::Notebook(shelf.id.clone());
607 (format!("/notebooks/{}", shelf.id), shelf.name, shelf.count, active)
608 })
609 .collect();
610 let en_pressed = if lang == Lang::En { "true" } else { "false" };
611 let tr_pressed = if lang == Lang::Tr { "true" } else { "false" };
612 let app = t(lang, Msg::AppName);
613 let theme_group = t(lang, Msg::Theme);
614 let theme_light = t(lang, Msg::ThemeLight);
615 let theme_system = t(lang, Msg::ThemeSystem);
616 let theme_dark = t(lang, Msg::ThemeDark);
617 let lang_group = t(lang, Msg::Language);
618 let export_all = t(lang, Msg::ExportAll);
619 let import_md = t(lang, Msg::ImportMarkdown);
620 let color_scheme = t(lang, Msg::ColorScheme);
621 let search_filters = t(lang, Msg::SearchOptions);
622 let filters = [
623 ("case", t(lang, Msg::MatchCase), "Alt+C"),
624 ("word", t(lang, Msg::WholeWord), "Alt+W"),
625 ("exact", t(lang, Msg::ExactPhrase), "Alt+E"),
626 ("re", t(lang, Msg::RegexSearch), "Alt+R"),
627 ];
628 let account_menu = t(lang, Msg::AccountMenu);
629 let guest = t(lang, Msg::GuestName);
630 let guest_sub = t(lang, Msg::GuestSubtitle);
631 let initials = &guest[..guest.chars().next().map_or(0, char::len_utf8)];
632 let lang_code = lang.code().to_uppercase();
633
634 // The nav is the animated box (width on desktop, slide on mobile). The body inside
635 // has a fixed width so its contents never reflow while the box animates.
636 Ok(view! {
637 <nav
638 id="sidebar"
639 aria-label=(t(lang, Msg::MainNavigation))
640 class="flex min-h-0 overflow-hidden border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
641 >
642 <div class="sidebar-body flex min-h-0 w-[240px] shrink-0 flex-col gap-3 p-3">
643 <div class="flex h-9 items-center justify-between gap-2 pl-2">
644 <a href="/" class="text-base font-semibold tracking-tight">(app)</a>
645 <button
646 id="sidebar-collapse"
647 type="button"
648 aria-controls="sidebar"
649 aria-label=(t(lang, Msg::HideSidebar))
650 class="hidden size-8 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-foreground/8 hover:text-foreground active:bg-foreground/12 lg:inline-flex"
651 >
652 <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">
653 <rect x="3" y="3" width="18" height="18" rx="2"></rect>
654 <path d="M9 3v18"></path>
655 </svg>
656 </button>
657 <button
658 type="button"
659 data-close-drawer=(true)
660 aria-label=(t(lang, Msg::CloseMenu))
661 class="inline-flex size-10 items-center justify-center rounded-control text-foreground transition-colors hover:bg-sidebar-accent lg:hidden"
662 >
663 <svg class="size-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
664 <path d="M18 6 6 18M6 6l12 12"></path>
665 </svg>
666 </button>
667 </div>
668
669 <form method="get" action="/search" role="search" class="relative">
670 input(attrs: attributes! {
671 type="search"
672 name="q"
673 id="search-input"
674 value=(query)
675 placeholder=(t(lang, Msg::SearchPlaceholder))
676 aria-label=(t(lang, Msg::SearchLabel))
677 autocomplete="off"
678 class="h-8 pr-[6.25rem]"
679 })
680 <span class="search-hint pointer-events-none absolute top-1/2 right-8 -translate-y-1/2" aria-hidden="true">
681 kbd_group(kbd("Ctrl") kbd("K"))
682 </span>
683 // Search filters: a checkbox menu behind a filter icon, as in mail and
684 // issue trackers. A dot on the icon says some filter is on.
685 dropdown_menu(
686 dropdown_menu_trigger(
687 target: "search-filters",
688 attrs: attributes! {
689 id="search-filter-button"
690 aria-label=(search_filters)
691 title=(search_filters)
692 class="group/filter absolute top-1/2 right-1 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-[5px] text-muted-foreground transition-colors hover:bg-foreground/8 hover:text-foreground data-active:text-foreground"
693 },
694 <svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
695 <path d="M3 6h18M7 12h10M10 18h4"></path>
696 </svg>
697 <span class="absolute top-0.5 right-0.5 hidden size-1.5 rounded-full bg-[var(--ring)] group-data-active/filter:block"></span>
698 )
699 dropdown_menu_content(
700 id: "search-filters",
701 align: FloatingAlign::End,
702 attrs: attributes! { role="menu" aria-label=(search_filters) class="w-60" },
703 dropdown_menu_label((search_filters))
704 for (key, label, keys) in filters {
705 dropdown_menu_item(
706 attrs: attributes! {
707 role="menuitemcheckbox"
708 aria-checked="false"
709 data-search-opt=(key)
710 },
711 <span class="filter-box">
712 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"></path></svg>
713 </span>
714 <span class="min-w-0 flex-1 truncate">(label)</span>
715 <span class="font-mono text-[11px] text-muted-foreground">(keys)</span>
716 )
717 }
718 )
719 )
720 </form>
721
722 <form id="new-note-form" method="post" action="/notes">
723 <input type="hidden" name="notebook_id" value=(current_notebook)>
724 button(
725 variant: ButtonVariant::Primary,
726 size: ButtonSize::Md,
727 attrs: attributes! { type="submit" class="w-full justify-between" },
728 keycap: Child::new(view! { kbd("N") }),
729 (t(lang, Msg::NewNote))
730 )
731 </form>
732
733 <ul class="flex flex-col gap-0.5">
734 <li>
735 nav_item(href: "/".to_owned(), label: t(lang, Msg::AllNotes).to_owned(), count: all, active: is_all)
736 </li>
737 <li>
738 nav_item(href: "/unfiled".to_owned(), label: t(lang, Msg::Unfiled).to_owned(), count: unfiled, active: is_unfiled)
739 </li>
740 <li>
741 nav_item(href: "/trash".to_owned(), label: t(lang, Msg::Trash).to_owned(), count: trash, active: is_trash)
742 </li>
743 </ul>
744
745 <div class="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto">
746 <p class="section-label px-2 pt-2 pb-1">(t(lang, Msg::Notebooks))</p>
747 <ul class="flex flex-col gap-0.5">
748 for (href, name, count, active) in shelves {
749 <li>
750 nav_item(href: href, label: name, count: count, active: active)
751 </li>
752 }
753 </ul>
754 <form method="post" action="/notebooks" class="mt-2 flex items-center gap-1.5 px-1">
755 input(attrs: attributes! {
756 type="text"
757 name="name"
758 maxlength="120"
759 placeholder=(t(lang, Msg::NewNotebook))
760 aria-label=(t(lang, Msg::NewNotebookLabel))
761 autocomplete="off"
762 class="min-w-0 flex-1"
763 })
764 button(
765 variant: ButtonVariant::Secondary,
766 size: ButtonSize::Sm,
767 attrs: attributes! { type="submit" },
768 (t(lang, Msg::Add))
769 )
770 </form>
771 </div>
772
773 // Profile button: everything that isn't navigation lives in its menu.
774 <div class="border-t border-sidebar-border pt-2">
775 dropdown_menu(
776 dropdown_menu_trigger(
777 target: "account-menu",
778 attrs: attributes! {
779 aria-label=(account_menu)
780 class="flex w-full min-w-0 items-center gap-2.5 rounded-control p-1.5 text-left transition-colors hover:bg-sidebar-accent group-has-[:popover-open]/dropdown-menu:bg-sidebar-accent"
781 },
782 <span class=(AVATAR)>(initials)</span>
783 <span class="flex min-w-0 flex-1 flex-col">
784 <span class="truncate text-sm font-medium text-sidebar-foreground">(guest)</span>
785 <span class="truncate text-xs text-muted-foreground">(guest_sub)</span>
786 </span>
787 <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"></path></svg>
788 )
789 dropdown_menu_content(
790 id: "account-menu",
791 side: FloatingSide::Right,
792 align: FloatingAlign::End,
793 attrs: attributes! { role="menu" aria-label=(account_menu) class="w-64" },
794 <div class="flex items-center gap-2.5 rounded-md bg-foreground/4 p-2">
795 <span class=(AVATAR)>(initials)</span>
796 <span class="flex min-w-0 flex-col">
797 <span class="truncate text-sm font-medium">(guest)</span>
798 <span class="truncate text-xs text-muted-foreground">(guest_sub)</span>
799 </span>
800 </div>
801 dropdown_menu_separator()
802 <a href="/import" role="menuitem" class=(MENU_ROW)>
803 <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><path d="m17 8-5-5-5 5"></path><path d="M12 3v12"></path></svg>
804 <span class="min-w-0 flex-1 truncate">(import_md)</span>
805 </a>
806 <a href="/export.zip" role="menuitem" class=(MENU_ROW)>
807 <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><path d="m7 10 5 5 5-5"></path><path d="M12 15V3"></path></svg>
808 <span class="min-w-0 flex-1 truncate">(export_all)</span>
809 </a>
810 dropdown_menu_separator()
811 dropdown_menu_sub(
812 dropdown_menu_sub_trigger(
813 target: "scheme-menu",
814 attrs: attributes! { role="menuitem" aria-haspopup="menu" },
815 <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="13.5" cy="6.5" r="1.5"></circle><circle cx="17.5" cy="10.5" r="1.5"></circle><circle cx="8.5" cy="7.5" r="1.5"></circle><circle cx="6.5" cy="12.5" r="1.5"></circle><path d="M12 2a10 10 0 0 0 0 20 2 2 0 0 0 2-2v-.5a2 2 0 0 1 2-2h1.5A4.5 4.5 0 0 0 22 13 10 10 0 0 0 12 2Z"></path></svg>
816 <span class="min-w-0 flex-1 truncate">(color_scheme)</span>
817 <span class="flex max-w-24 min-w-0 items-center text-xs text-muted-foreground">
818 scheme_names(current: scheme)
819 </span>
820 )
821 dropdown_menu_sub_content(
822 id: "scheme-menu",
823 attrs: attributes! { role="menu" aria-label=(color_scheme) class="w-56" },
824 scheme_items(current: scheme, back: back.clone())
825 )
826 )
827 dropdown_menu_sub(
828 dropdown_menu_sub_trigger(
829 target: "lang-menu",
830 attrs: attributes! { role="menuitem" aria-haspopup="menu" },
831 <svg class="size-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"></circle><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10Z"></path></svg>
832 <span class="min-w-0 flex-1 truncate">(lang_group)</span>
833 <span class="font-mono text-xs text-muted-foreground">(lang_code)</span>
834 )
835 dropdown_menu_sub_content(
836 id: "lang-menu",
837 attrs: attributes! { role="menu" aria-label=(lang_group) class="w-44" },
838 <form method="post" action="/lang" class="contents">
839 <input type="hidden" name="lang" value="en">
840 <input type="hidden" name="back" value=(back.clone())>
841 dropdown_menu_item(
842 attrs: attributes! { type="submit" role="menuitemradio" aria-checked=(en_pressed) lang="en" },
843 <span class="min-w-0 flex-1">(t(lang, Msg::LanguageEnglish))</span>
844 <svg class="scheme-check size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"></path></svg>
845 )
846 </form>
847 <form method="post" action="/lang" class="contents">
848 <input type="hidden" name="lang" value="tr">
849 <input type="hidden" name="back" value=(back.clone())>
850 dropdown_menu_item(
851 attrs: attributes! { type="submit" role="menuitemradio" aria-checked=(tr_pressed) lang="tr" },
852 <span class="min-w-0 flex-1">(t(lang, Msg::LanguageTurkish))</span>
853 <svg class="scheme-check size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"></path></svg>
854 )
855 </form>
856 )
857 )
858 dropdown_menu_separator()
859 <div class="flex items-center justify-between gap-2 px-2 py-1">
860 <span class="text-sm font-semibold tracking-tight">(app)</span>
861 <div role="group" aria-label=(theme_group) class=(TRACK)>
862 <button type="button" data-theme-set="light" aria-label=(theme_light) title=(theme_light) aria-pressed="false" class=(SEGMENT_ICON)>
863 <svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
864 <circle cx="12" cy="12" r="4"></circle>
865 <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"></path>
866 </svg>
867 </button>
868 <button type="button" data-theme-set="system" aria-label=(theme_system) title=(theme_system) aria-pressed="false" class=(SEGMENT_ICON)>
869 <svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
870 <rect x="2" y="3" width="20" height="14" rx="2"></rect>
871 <path d="M8 21h8M12 17v4"></path>
872 </svg>
873 </button>
874 <button type="button" data-theme-set="dark" aria-label=(theme_dark) title=(theme_dark) aria-pressed="false" class=(SEGMENT_ICON)>
875 <svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
876 <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"></path>
877 </svg>
878 </button>
879 </div>
880 </div>
881 )
882 )
883 </div>
884 </div>
885 </nav>
886 })
887}
888
889/// The toast region: a polite live region in the bottom-right corner. `message` is the
890/// localized text; `undo` is the note id to restore, shown as an Undo button.
891#[component]
892pub async fn toast_region(lang: Lang, message: Option<&'static str>, undo: Option<String>) -> Result<impl View> {
893 Ok(view! {
894 <div
895 id="toasts"
896 role="status"
897 aria-live="polite"
898 class="pointer-events-none fixed inset-x-0 bottom-0 z-50 flex flex-col items-end gap-2 p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pr-[max(1rem,env(safe-area-inset-right))]"
899 >
900 if let Some(text) = message {
901 <div
902 data-toast=(true)
903 class="pointer-events-auto flex max-w-sm items-center gap-2 rounded-float border border-border bg-popover px-3 py-2 text-sm text-popover-foreground shadow-float"
904 >
905 <span class="min-w-0 flex-1">(text)</span>
906 if let Some(id) = undo {
907 <form method="post" action=(format!("/notes/{id}/restore"))>
908 button(
909 variant: ButtonVariant::Ghost,
910 size: ButtonSize::Sm,
911 attrs: attributes! { type="submit" },
912 (t(lang, Msg::Undo))
913 )
914 </form>
915 }
916 <button
917 type="button"
918 data-dismiss=(true)
919 aria-label=(t(lang, Msg::Dismiss))
920 class="inline-flex size-8 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground"
921 >
922 <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">
923 <path d="M18 6 6 18M6 6l12 12"></path>
924 </svg>
925 </button>
926 </div>
927 }
928 </div>
929 })
930}