forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

palette.rs533 lines, 19.5 KiBHistoryRawDownload
1//! The command palette: the Ctrl/Cmd+K dialog that the layout renders, and `GET /palette`,
2//! the results fragment the dialog fetches as the user types.
3//!
4//! Commands, notes, and notebooks share one `role="listbox"`. Links are `<a>` elements.
5//! Actions that stay on the page (theme, new notebook) and form posts are `<button>`s that
6//! the inline script runs. The shortcut itself is handled by `SHELL_SCRIPT` in `shell.rs`,
7//! which calls `window.openPalette`.
8
9use std::collections::HashSet;
10use std::sync::Arc;
11
12use topcoat::{
13 Result,
14 context::{Cx, app_context},
15 router::{query_params, route},
16 view::{Unescaped, View, ViewExt, ViewHandle, component, view},
17};
18
19use crate::app::shell;
20use crate::components::badge::{BadgeVariant, badge};
21use crate::components::kbd::{kbd, kbd_group};
22use crate::i18n::{self, Lang, Msg, t};
23use crate::scheme::ALL as SCHEMES;
24use crate::store::{ListFilter, Notebook, NoteMeta, Store};
25
26/// Most notes, and most notebooks, listed in one result set.
27const LIMIT: usize = 8;
28/// How long the palette reads long notes for full-text hits; title hits come anyway.
29const PALETTE_BUDGET: std::time::Duration = std::time::Duration::from_millis(250);
30
31/// Classes of the dialog. It is hidden until `showModal()`, then fades in.
32const DIALOG: &str = "m-0 mx-auto top-[15vh] bottom-auto h-auto w-full max-w-none overflow-visible border-0 bg-transparent p-0 text-popover-foreground sm:w-[560px] backdrop:bg-black/40 opacity-0 open:opacity-100 starting:open:opacity-0 transition-[opacity,display] transition-discrete duration-150 ease-out motion-reduce:transition-none";
33/// Classes of the panel inside the dialog.
34const PANEL: &str = "flex flex-col overflow-hidden border border-border bg-popover shadow-float sm:rounded-float";
35/// Classes of one result row.
36const OPTION: &str = "flex min-h-9 w-full items-center gap-3 rounded-control px-3 py-1.5 text-left text-sm transition-colors hover:bg-foreground/5";
37
38/// Picks the text for `lang`. Every string in the palette goes through here with both
39/// languages, so a missing Turkish text does not compile.
40fn pick(lang: Lang, en: &'static str, tr: &'static str) -> &'static str {
41 match lang {
42 Lang::En => en,
43 Lang::Tr => tr,
44 }
45}
46
47/// The `q` parameter of the palette fragment.
48#[query_params(error = bad_request)]
49pub struct PaletteQuery {
50 pub q: Option<String>,
51}
52
53/// One row of the palette.
54pub struct Item {
55 label: String,
56 /// A secondary line, such as the search snippet of a note.
57 detail: Option<String>,
58 /// The notebook name of a note.
59 notebook: Option<String>,
60 /// A shortcut shown as a keycap, such as "N".
61 keycap: Option<&'static str>,
62 /// Set for links, which render as `<a href>`.
63 href: Option<String>,
64 /// For buttons: "post", "theme", "new-notebook", or "scheme".
65 action: &'static str,
66 /// For "post": the URL the script submits a form to.
67 url: &'static str,
68 /// For "post": the hidden form fields, as a JSON object. For "scheme": the scheme id.
69 fields: &'static str,
70}
71
72impl Item {
73 fn link(label: impl Into<String>, href: impl Into<String>) -> Self {
74 Self {
75 label: label.into(),
76 detail: None,
77 notebook: None,
78 keycap: None,
79 href: Some(href.into()),
80 action: "",
81 url: "",
82 fields: "",
83 }
84 }
85
86 fn action(label: impl Into<String>, action: &'static str) -> Self {
87 Self {
88 action,
89 href: None,
90 ..Self::link(label, "")
91 }
92 }
93
94 fn post(label: impl Into<String>, url: &'static str, fields: &'static str, keycap: Option<&'static str>) -> Self {
95 Self {
96 action: "post",
97 url,
98 fields,
99 keycap,
100 href: None,
101 ..Self::link(label, "")
102 }
103 }
104}
105
106/// The commands, in both languages. Labels are matched against the query.
107fn commands(lang: Lang) -> Vec<Item> {
108 vec![
109 Item::post(pick(lang, "New note", "Yeni not"), "/notes", "{}", Some("N")),
110 Item::action(pick(lang, "New notebook", "Yeni defter"), "new-notebook"),
111 Item::link(pick(lang, "Go to All notes", "Tüm notlara git"), "/"),
112 Item::link(pick(lang, "Go to Unfiled", "Dosyalanmamışlara git"), "/unfiled"),
113 Item::link(pick(lang, "Go to Trash", "Çöp kutusuna git"), "/trash"),
114 Item::link(t(lang, Msg::ExportAll), "/export.zip"),
115 Item::link(t(lang, Msg::ImportMarkdown), "/import"),
116 Item::action(pick(lang, "Toggle theme", "Temayı değiştir"), "theme"),
117 Item::post(pick(lang, "Switch to English", "İngilizceye geç"), "/lang", r#"{"lang":"en"}"#, None),
118 Item::post(pick(lang, "Switch to Türkçe", "Türkçeye geç"), "/lang", r#"{"lang":"tr"}"#, None),
119 ]
120}
121
122/// One command per color scheme, named "Color scheme: <Name>" (the name is not translated).
123fn scheme_commands(lang: Lang) -> Vec<Item> {
124 let prefix = t(lang, Msg::ColorScheme);
125 SCHEMES
126 .into_iter()
127 .map(|scheme| Item {
128 action: "scheme",
129 href: None,
130 fields: scheme.id(),
131 ..Item::link(format!("{prefix}: {}", scheme.name()), "")
132 })
133 .collect()
134}
135
136/// A note row. `snippet` is the search excerpt, if this is a search result.
137fn note_item(lang: Lang, note: &NoteMeta, notebooks: &[Notebook], snippet: Option<&str>) -> Item {
138 let detail = snippet
139 .map(|s| s.split_whitespace().collect::<Vec<_>>().join(" "))
140 .filter(|s| !s.is_empty());
141 Item {
142 detail,
143 notebook: shell::notebook_name(notebooks, note.notebook_id.as_deref()),
144 ..Item::link(shell::title_of(lang, &note.title), format!("/notes/{}", note.id))
145 }
146}
147
148/// GET /palette?q=...: the palette's results as an HTML fragment, without the page layout.
149/// An empty query lists the commands, the 8 most recently updated notes, and all notebooks
150/// (up to 8). A query lists the matching commands, the search results, and matching notebooks.
151#[route(GET)]
152async fn palette_results(cx: &Cx) -> Result<ViewHandle> {
153 let store = app_context::<Arc<Store>>(cx);
154 let lang = i18n::lang(cx);
155 let query = query_params::<PaletteQuery>(cx)?;
156 let q = query.q.as_deref().unwrap_or("").trim().to_owned();
157 let needle = q.to_lowercase();
158
159 let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?;
160 let cmds: Vec<Item> = commands(lang)
161 .into_iter()
162 .chain(scheme_commands(lang))
163 .filter(|c| c.label.to_lowercase().contains(&needle))
164 .collect();
165 let notes: Vec<Item> = if q.is_empty() {
166 let recent = store
167 .list_notes_page(ListFilter::All, LIMIT, 0)
168 .await
169 .map_err(topcoat::Error::from_anyhow)?;
170 recent
171 .iter()
172 .map(|n| note_item(lang, n, &notebooks, None))
173 .collect()
174 } else {
175 // Full-text hits match whole words; title hits also match inside a word ("ro" finds
176 // "Q4 roadmap"). Full-text hits come first, and a note listed once is not repeated.
177 let hits = match crate::matcher::Matcher::simple(&q) {
178 Some(matcher) => store
179 .search(&matcher, LIMIT, Some(PALETTE_BUDGET))
180 .await
181 .map_err(topcoat::Error::from_anyhow)?
182 .hits,
183 None => Vec::new(),
184 };
185 let mut seen: HashSet<String> = hits.iter().map(|h| h.note.id.clone()).collect();
186 let mut items: Vec<Item> = hits
187 .iter()
188 .map(|h| note_item(lang, &h.note, &notebooks, Some(&h.snippet)))
189 .collect();
190 let titles = store
191 .search_titles(&q, LIMIT)
192 .await
193 .map_err(topcoat::Error::from_anyhow)?;
194 for note in titles.iter().filter(|n| seen.insert(n.id.clone())) {
195 items.push(note_item(lang, note, &notebooks, None));
196 }
197 items.truncate(LIMIT);
198 items
199 };
200 let books: Vec<Item> = notebooks
201 .iter()
202 .filter(|nb| nb.name.to_lowercase().contains(&needle))
203 .take(LIMIT)
204 .map(|nb| Item::link(nb.name.clone(), format!("/notebooks/{}", nb.id)))
205 .collect();
206
207 let empty = cmds.is_empty() && notes.is_empty() && books.is_empty();
208 let no_results = pick(lang, "No results", "Sonuç yok");
209 let results_label = pick(lang, "Results", "Sonuçlar");
210
211 let fragment = view! {
212 <div id="palette-list" role="listbox" aria-label=(results_label)>
213 if !cmds.is_empty() {
214 palette_group(
215 id: "palette-h-commands".to_owned(),
216 title: pick(lang, "Commands", "Komutlar").to_owned(),
217 items: cmds,
218 )
219 }
220 if !notes.is_empty() {
221 palette_group(
222 id: "palette-h-notes".to_owned(),
223 title: pick(lang, "Notes", "Notlar").to_owned(),
224 items: notes,
225 )
226 }
227 if !books.is_empty() {
228 palette_group(
229 id: "palette-h-notebooks".to_owned(),
230 title: pick(lang, "Notebooks", "Defterler").to_owned(),
231 items: books,
232 )
233 }
234 </div>
235 if empty {
236 <p class="px-3 py-8 text-center text-sm text-muted-foreground">(no_results)</p>
237 }
238 };
239 Ok(fragment.single().await?)
240}
241
242/// A labelled group of options inside the listbox.
243#[component]
244async fn palette_group(id: String, title: String, items: Vec<Item>) -> Result<impl View> {
245 Ok(view! {
246 <div role="group" aria-labelledby=(id.clone()) class="py-1">
247 <p id=(id) class="section-label px-3 pt-2 pb-1">(title)</p>
248 for item in items {
249 palette_option(item: item)
250 }
251 </div>
252 })
253}
254
255/// One option: a link when it has an `href`, otherwise a button the script runs.
256#[component]
257async fn palette_option(item: Item) -> Result<impl View> {
258 let Item {
259 label,
260 detail,
261 notebook,
262 keycap,
263 href,
264 action,
265 url,
266 fields,
267 } = item;
268 Ok(view! {
269 if let Some(href) = href {
270 <a href=(href) role="option" aria-selected="false" class=(OPTION)>
271 option_body(label: label, detail: detail, notebook: notebook, keycap: keycap)
272 </a>
273 } else {
274 <button
275 type="button"
276 role="option"
277 aria-selected="false"
278 class=(OPTION)
279 data-action=(action)
280 data-url=(url)
281 data-fields=(fields)
282 >
283 option_body(label: label, detail: detail, notebook: notebook, keycap: keycap)
284 </button>
285 }
286 })
287}
288
289/// The text and badges inside an option.
290#[component]
291async fn option_body(
292 label: String,
293 detail: Option<String>,
294 notebook: Option<String>,
295 keycap: Option<&'static str>,
296) -> Result<impl View> {
297 Ok(view! {
298 <span class="min-w-0 flex-1">
299 <span class="block truncate font-medium">(label)</span>
300 if let Some(text) = detail {
301 <span class="block truncate text-xs text-muted-foreground">(text)</span>
302 }
303 </span>
304 if let Some(name) = notebook {
305 badge(variant: BadgeVariant::Secondary, (name))
306 }
307 if let Some(key) = keycap {
308 <span class="ml-auto">kbd((key))</span>
309 }
310 })
311}
312
313/// The palette dialog, rendered once in the layout. It stays closed until the shortcut
314/// (or `window.openPalette`) opens it.
315#[component]
316pub async fn palette_dialog(lang: Lang) -> Result<impl View> {
317 let dialog_label = pick(lang, "Command palette", "Komut paleti");
318 let placeholder = pick(lang, "Search notes or type a command…", "Not ara veya komut yaz…");
319 let nav = pick(lang, "navigate", "gezin");
320 let open = pick(lang, "open", "aç");
321 let close = pick(lang, "close", "kapat");
322 let in_editor = pick(lang, "in editor", "editörde");
323
324 Ok(view! {
325 <dialog id="palette" aria-label=(dialog_label) class=(DIALOG)>
326 <div class=(PANEL)>
327 <div class="flex items-center gap-2 border-b border-border px-3">
328 <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">
329 <circle cx="11" cy="11" r="7"></circle>
330 <path d="m20 20-3.5-3.5"></path>
331 </svg>
332 <input
333 id="palette-input"
334 type="text"
335 role="combobox"
336 aria-expanded="true"
337 aria-controls="palette-list"
338 aria-autocomplete="list"
339 placeholder=(placeholder)
340 autocomplete="off"
341 spellcheck="false"
342 class="h-12 min-w-0 flex-1 bg-transparent text-base placeholder:text-muted-foreground outline-none"
343 >
344 kbd("Esc")
345 </div>
346 <div id="palette-results" class="max-h-[60vh] overflow-y-auto p-1"></div>
347 <div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 border-t border-border px-3 py-2 font-mono text-[11px] text-muted-foreground">
348 <div class="flex items-center gap-3">
349 <span class="inline-flex items-center gap-1">kbd("↑") kbd("↓")</span>
350 <span>(nav)</span>
351 <span class="inline-flex items-center gap-1">kbd("↵")</span>
352 <span>(open)</span>
353 <span class="inline-flex items-center gap-1">kbd("Esc")</span>
354 <span>(close)</span>
355 </div>
356 <div class="flex items-center gap-2">
357 kbd_group(kbd("Ctrl") kbd("Shift") kbd("K"))
358 <span>(in_editor)</span>
359 </div>
360 </div>
361 </div>
362 </dialog>
363 <script>(Unescaped::new_unchecked(PALETTE_SCRIPT))</script>
364 })
365}
366
367/// Palette behaviour. Defines `window.openPalette` (called by the shortcut in `shell.rs`).
368/// Results load on open and 120ms after each keystroke; a new request aborts the last one.
369/// Up and Down move the highlight (`aria-activedescendant`), Enter runs it, and Esc closes
370/// the dialog natively. A click on the backdrop closes it. Closing returns focus to the
371/// element that was focused before.
372const PALETTE_SCRIPT: &str = r#"
373(function () {
374 var dialog = document.getElementById('palette');
375 if (!dialog) return;
376 var input = document.getElementById('palette-input');
377 var results = document.getElementById('palette-results');
378 var desktop = window.matchMedia('(min-width: 1024px)');
379 var opener = null;
380 var active = -1;
381 var timer = null;
382 var controller = null;
383
384 function options() {
385 return Array.prototype.slice.call(results.querySelectorAll('[role="option"]'));
386 }
387 function setActive(index) {
388 var list = options();
389 if (list.length === 0) {
390 active = -1;
391 input.removeAttribute('aria-activedescendant');
392 return;
393 }
394 if (index < 0) index = list.length - 1;
395 if (index >= list.length) index = 0;
396 list.forEach(function (opt, i) {
397 var on = i === index;
398 opt.setAttribute('aria-selected', on ? 'true' : 'false');
399 opt.classList.toggle('marker', on);
400 });
401 active = index;
402 input.setAttribute('aria-activedescendant', list[index].id);
403 list[index].scrollIntoView({ block: 'nearest' });
404 }
405 function assignIds() {
406 options().forEach(function (opt, i) { opt.id = 'palette-opt-' + i; });
407 }
408 function load(q) {
409 if (controller) controller.abort();
410 controller = new AbortController();
411 var signal = controller.signal;
412 fetch('/palette?q=' + encodeURIComponent(q), {
413 headers: { Accept: 'text/html' },
414 cache: 'no-store',
415 signal: signal
416 })
417 .then(function (res) {
418 if (!res.ok) throw new Error('palette ' + res.status);
419 return res.text();
420 })
421 .then(function (html) {
422 if (signal.aborted) return;
423 results.innerHTML = html;
424 assignIds();
425 setActive(0);
426 })
427 .catch(function () { /* aborted or failed: keep the last results */ });
428 }
429 function newNotebook() {
430 if (desktop.matches) {
431 document.documentElement.dataset.sidebar = 'expanded';
432 try { localStorage.setItem('sidebar', 'expanded'); } catch (err) {}
433 } else {
434 var toggle = document.getElementById('drawer-open');
435 if (toggle) toggle.click();
436 }
437 var field = document.querySelector('#sidebar input[name="name"]');
438 if (field) setTimeout(function () { field.focus(); }, 0);
439 }
440 function post(url, json) {
441 var fields = JSON.parse(json || '{}');
442 if (url === '/notes') {
443 var nb = document.querySelector('#new-note-form input[name="notebook_id"]');
444 fields.notebook_id = nb ? nb.value : '';
445 }
446 if (url === '/lang') fields.back = location.pathname + location.search;
447 var form = document.createElement('form');
448 form.method = 'post';
449 form.action = url;
450 Object.keys(fields).forEach(function (name) {
451 var field = document.createElement('input');
452 field.type = 'hidden';
453 field.name = name;
454 field.value = fields[name];
455 form.appendChild(field);
456 });
457 document.body.appendChild(form);
458 form.submit();
459 }
460 function run(opt) {
461 var action = opt.getAttribute('data-action');
462 if (action === 'theme') {
463 if (typeof window.cycleTheme === 'function') window.cycleTheme();
464 dialog.close();
465 } else if (action === 'scheme') {
466 if (typeof window.setScheme === 'function') window.setScheme(opt.getAttribute('data-fields'));
467 dialog.close();
468 } else if (action === 'new-notebook') {
469 opener = null;
470 dialog.close();
471 newNotebook();
472 } else if (action === 'post') {
473 opener = null;
474 post(opt.getAttribute('data-url'), opt.getAttribute('data-fields'));
475 }
476 }
477
478 window.openPalette = function () {
479 if (dialog.open) {
480 input.focus();
481 return;
482 }
483 opener = document.activeElement;
484 input.value = '';
485 dialog.showModal();
486 input.focus();
487 load('');
488 };
489
490 input.addEventListener('input', function () {
491 clearTimeout(timer);
492 timer = setTimeout(function () { load(input.value.trim()); }, 120);
493 });
494 input.addEventListener('keydown', function (e) {
495 if (e.isComposing) return;
496 if (e.key === 'ArrowDown') {
497 e.preventDefault();
498 setActive(active + 1);
499 } else if (e.key === 'ArrowUp') {
500 e.preventDefault();
501 setActive(active - 1);
502 } else if (e.key === 'Enter') {
503 var opt = options()[active];
504 if (opt) {
505 e.preventDefault();
506 opt.click();
507 }
508 }
509 });
510 results.addEventListener('mousemove', function (e) {
511 var opt = e.target.closest('[role="option"]');
512 if (!opt) return;
513 var i = options().indexOf(opt);
514 if (i !== active) setActive(i);
515 });
516 results.addEventListener('click', function (e) {
517 var opt = e.target.closest('[role="option"]');
518 if (!opt || opt.tagName === 'A') return;
519 e.preventDefault();
520 run(opt);
521 });
522 dialog.addEventListener('click', function (e) {
523 if (e.target === dialog) dialog.close();
524 });
525 dialog.addEventListener('close', function () {
526 clearTimeout(timer);
527 if (controller) controller.abort();
528 var back = opener;
529 opener = null;
530 if (back && back.isConnected && typeof back.focus === 'function') back.focus();
531 });
532})();
533"#;