Skip to content

web search done right

[WIP] Implemented `keybind` module to handle keyboard shortcuts (#186)

Wesley Applercc612c5b8db0
diff --git a/frontend/src/lib/components/Searchbar.svelte b/frontend/src/lib/components/Searchbar.svelte
index 422d8a44..302c07b9 100644
--- a/frontend/src/lib/components/Searchbar.svelte
+++ b/frontend/src/lib/components/Searchbar.svelte
@@ -1,3 +1,5 @@
+<svelte:options accessors />
+
<script lang="ts">
import MagnifyingGlass from '~icons/heroicons/magnifying-glass';
import Button from '$lib/components/Button.svelte';
@@ -77,6 +79,19 @@
let suggestionsDiv: HTMLDivElement | undefined;
let hasFocus = autofocus;
+
+ let formElem: HTMLFormElement;
+ let inputElem: HTMLInputElement;
+ export const getInputElem = () => inputElem;
+ export const getForm = () => formElem;
+ export const select = () => inputElem.select();
+ export const userQuery = () => lastRealQuery;
+ export const search = (q: string) => {
+ if (formElem && inputElem) {
+ inputElem.value = q;
+ formElem.submit();
+ }
+ };
</script>
<form
@@ -84,6 +99,7 @@
class="flex w-full justify-center"
id="searchbar-form"
method={$postSearchStore ? 'POST' : 'GET'}
+ bind:this={formElem}
>
<input type="hidden" value={$safeSearchStore ? 'true' : 'false'} name="ss" />
<input type="hidden" value={$compressedRanked} name="sr" id="host_rankingsUuid" />
@@ -124,6 +140,7 @@
}}
bind:value={query}
on:keydown={onKeydown}
+ bind:this={inputElem}
/>
<div class="h-full py-0.5 pr-0.5">
<Button _class="py-0 h-full" type="submit">search</Button>
diff --git a/frontend/src/lib/keybind.ts b/frontend/src/lib/keybind.ts
new file mode 100644
index 00000000..5a180c56
--- /dev/null
+++ b/frontend/src/lib/keybind.ts
@@ -0,0 +1,230 @@
+import { match } from 'ts-pattern';
+import Result from '../routes/search/Result.svelte';
+import type Searchbar from './components/Searchbar.svelte';
+import type SpellCorrection from '../routes/search/SpellCorrection.svelte';
+
+export const Keys = [
+ 'j',
+ 'd',
+ 'k',
+ 'h',
+ 'v',
+ 't',
+ 'm',
+ 'l',
+ 'o',
+ 's',
+ "'",
+ '/',
+ 'Control',
+ 'Enter',
+ 'ArrowUp',
+ 'ArrowDown',
+ 'Escape',
+];
+export type Key = (typeof Keys)[number];
+
+// The type used to declare the key downs that will trigger the callback
+export interface KeybindCallback {
+ key: Key;
+ callback: (context: Refs) => void;
+ shift?: boolean;
+ ctrl?: boolean;
+ alt?: boolean;
+}
+
+/**
+ * Used to create and interface with key bindings
+ */
+export class Keybind {
+ // All of the keybindings to their callbacks
+ public bindings: KeybindCallback[];
+ private bindingEntries: Key[];
+
+ /**
+ * Constructor
+ *
+ * @param bindings An array of {@link KeybindCallback}s to be evaluated and utilized with {@link Keybind:onKeyDown}.
+ */
+ constructor(bindings: KeybindCallback[]) {
+ this.bindings = bindings;
+ this.bindingEntries = this.bindings.map((x) => x.key);
+ }
+
+ /**
+ * Attempt to convert a string to a {@link Key}
+ *
+ * @param str - The string to attempt to convert
+ * @returns undefined if unable to convert, otherwise corresponding {@link Key}
+ */
+ private keyFromString(str: string): Key | undefined {
+ return Keys.find((key) => key === str);
+ }
+
+ /**
+ * Handler for `keydown` events
+ *
+ * @remarks
+ * Requires a wrapper function to pass in `useKeyboardShortcuts` boolean store.
+ *
+ * Will run the given callback if all requirements are met from an item in the
+ * previously given {@link KeybindCallback} array.
+ *
+ * @param e - The `keydown` event of `KeyboardEvent` type
+ * @param useKeyboardShortcuts - A boolean of the user's `useKeyboardShortcuts` preference
+ */
+ onKeyDown(e: KeyboardEvent, useKeyboardShortcuts: boolean, context: Refs) {
+ if (!useKeyboardShortcuts) return;
+
+ const key = this.keyFromString(e.key);
+
+ if (!(key && this.bindingEntries.includes(key))) return;
+
+ // Conditionals to be able to later compare to a potentially undefined binding.shift/.al/.ctrl
+ const shift = e.shiftKey ? true : undefined;
+ const ctrl = e.ctrlKey ? true : undefined;
+ const alt = e.altKey ? true : undefined;
+
+ const binding = this.bindings.find((binding) => binding.key === key);
+ if (binding && binding.alt == alt && binding.shift == shift && binding.ctrl == ctrl) {
+ e.preventDefault();
+ binding.callback(context);
+ }
+ }
+}
+
+/*
+Search callbacks
+*/
+
+export type Refs = {
+ results?: Result[];
+ searchbar?: Searchbar;
+ spellCorrection?: SpellCorrection;
+};
+
+type Direction = 'up' | 'down';
+
+/**
+ * Utilized to bring the next/previous result into focus
+ *
+ * @remarks
+ * Utilizes the element that is currently in focus and the given
+ * direction to determine where and how to traverse the array of
+ * results. Moves a single result per call.
+ *
+ * @param direction - How to maneuver through the result list (up/down), indicated by {@link Direction}
+ */
+const navigateResults = (direction: Direction, context: Refs) => {
+ if (!context.results || context.results.length === 0) return;
+ const results = context.results;
+
+ let newIndex = 0;
+ const currentResultIndex = results.findIndex((result) => result?.hasFocus());
+
+ if (currentResultIndex > -1) {
+ newIndex =
+ currentResultIndex +
+ match(direction)
+ .with('up', () => -1)
+ .with('down', () => 1)
+ .exhaustive();
+
+ if (newIndex < 0 || newIndex >= results.length) {
+ newIndex = currentResultIndex;
+ }
+ }
+
+ if (newIndex < results.length && results[newIndex]) {
+ results[newIndex].getMainResultLink()?.focus();
+ }
+};
+
+const focusNextResult = (context: Refs) => navigateResults('down', context);
+const focusPrevResult = (context: Refs) => navigateResults('up', context);
+const focusMainResult = (context: Refs) => {
+ if (!context.results || context.results.length == 0) return;
+ if (context.results[0]) context.results[0].getMainResultLink()?.focus();
+};
+
+const selectSearchBar = (context: Refs) => {
+ scrollToTop(context);
+
+ if (context.searchbar) {
+ context.searchbar.select();
+ }
+};
+
+/**
+ * Scroll to the top of the window and reset focus
+ */
+const scrollToTop = (context: Refs) => {
+ window.scrollTo({ top: 0, behavior: 'smooth' });
+
+ if (!context.results) return;
+
+ const focusedResult: Result | undefined = context.results.find((result) => result.hasFocus());
+ focusedResult?.clearFocus();
+};
+
+/**
+ * Redirect to the currently focused result
+ */
+const openResult = (context: Refs) => {
+ if (!context.results) return;
+
+ const focusedResult: Result | undefined = context.results.find((result) => result.hasFocus());
+ focusedResult?.getMainResultLink()?.open();
+};
+
+/**
+ * Open the currently focused result in a new tab
+ *
+ * @remarks
+ * Requires pop-ups to be allowed for the window
+ */
+const openResultInNewTab = (context: Refs) => {
+ if (!context.results) return;
+ const focusedResult: Result | undefined = context.results.find((result) => result.hasFocus());
+ focusedResult?.getMainResultLink()?.openInNewTab();
+};
+
+/**
+ * Do a domain search using the domain of the currently focused result
+ */
+const domainSearch = (context: Refs) => {
+ if (!context.results || !context.searchbar) return;
+
+ const focusedResult: Result | undefined = context.results.find((result) => result.hasFocus());
+ if (!focusedResult) return;
+
+ const query = context.searchbar.userQuery();
+ const domain = focusedResult.getMainResultLink()?.getUrl().hostname;
+ const domainQuery = `site:${domain}`;
+
+ // Only run the domain query if it isn't already in the query
+ if (!query.includes(domainQuery)) context.searchbar.search(`${query} ${domainQuery}`);
+};
+
+const openSpellCorrection = (context: Refs) => {
+ if (context.spellCorrection) context.spellCorrection.open();
+};
+
+const clearFocus = (context: Refs) => {
+ const focusedResult: Result | undefined = context.results?.find((result) => result.hasFocus());
+ focusedResult?.clearFocus();
+};
+
+// Packaged callbacks to keep imports clean
+export const searchCb = {
+ focusNextResult,
+ focusPrevResult,
+ focusMainResult,
+ selectSearchBar,
+ scrollToTop,
+ openResult,
+ openResultInNewTab,
+ domainSearch,
+ openSpellCorrection,
+ clearFocus,
+};
diff --git a/frontend/src/lib/stores.ts b/frontend/src/lib/stores.ts
index 07b4a3fa..7246703c 100644
--- a/frontend/src/lib/stores.ts
+++ b/frontend/src/lib/stores.ts
@@ -76,6 +76,9 @@ export const markPagesWithAdsStore = writableLocalStorage<boolean>(MARK_PAGES_WI
const RESULTS_IN_NEW_TAB_KEY = 'resultsInNewTab';
export const resultsInNewTab = writableLocalStorage<boolean>(RESULTS_IN_NEW_TAB_KEY, false);
+const USE_KEYBOARD_SHORTCUTS = 'useKeyboardShortcuts';
+export const useKeyboardShortcuts = writableLocalStorage<boolean>(USE_KEYBOARD_SHORTCUTS, true);
+
const MARK_PAGES_WITH_PAYWALL_KEY = 'markPagesWithPaywall';
export const markPagesWithPaywallStore = writableLocalStorage<boolean>(
MARK_PAGES_WITH_PAYWALL_KEY,
diff --git a/frontend/src/routes/search/+page.svelte b/frontend/src/routes/search/+page.svelte
index 6e9e6d46..ba6347bc 100644
--- a/frontend/src/routes/search/+page.svelte
+++ b/frontend/src/routes/search/+page.svelte
@@ -3,12 +3,15 @@
import Searchbar from '$lib/components/Searchbar.svelte';
import type { PageData } from './$types';
import RegionSelect from '$lib/components/RegionSelect.svelte';
- import { searchQueryStore } from '$lib/stores';
+ import { searchQueryStore, useKeyboardShortcuts } from '$lib/stores';
import { page } from '$app/stores';
import { updateQueryId } from '$lib/improvements';
import { browser } from '$app/environment';
import Serp from './Serp.svelte';
+ import Result from './Result.svelte';
import { search } from '$lib/search';
+ import { Keybind, searchCb, type Refs } from '$lib/keybind';
+ import SpellCorrection from './SpellCorrection.svelte';
export let data: PageData;
$: results = data.results;
@@ -35,6 +38,8 @@
}
}
+ let serp: Serp | undefined = undefined;
+
const clientSearch = async () => {
if (!browser) return;
@@ -61,8 +66,45 @@
if (browser && results && results.type == 'websites')
updateQueryId({ query, webpages: results.webpages });
}
+
+ let resultElems: Result[] = [];
+ let spellCorrectElem: SpellCorrection | undefined = undefined;
+ let searchbarElem: Searchbar | undefined = undefined;
+
+ let context: Refs;
+ $: context = {
+ results: serp?.resultElems,
+ searchbar: searchbarElem,
+ spellCorrection: serp?.spellCorrectElem,
+ };
+
+ let keybind = new Keybind([
+ { key: 'j', callback: searchCb.focusNextResult },
+ { key: 'ArrowDown', callback: searchCb.focusNextResult },
+ { key: 'k', callback: searchCb.focusPrevResult },
+ { key: 'ArrowUp', callback: searchCb.focusPrevResult },
+ { key: 'h', callback: searchCb.selectSearchBar },
+ { key: '/', callback: searchCb.selectSearchBar },
+ { key: 'v', callback: searchCb.openResultInNewTab },
+ { key: "'", callback: searchCb.openResultInNewTab },
+ { key: 't', callback: searchCb.scrollToTop },
+ { key: 'd', callback: searchCb.domainSearch },
+ { key: 'l', callback: searchCb.openResult },
+ { key: 'o', callback: searchCb.openResult },
+ { key: 'm', callback: searchCb.focusMainResult },
+ { key: 's', callback: searchCb.openSpellCorrection },
+ { key: 'Escape', callback: searchCb.clearFocus },
+ ]);
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.target != searchbarElem?.getInputElem()) {
+ keybind.onKeyDown(event, $useKeyboardShortcuts, context);
+ }
+ };
</script>
+<svelte:window on:keydown={onKeyDown} />
+
{#if !serverSearch}
<noscript>
<meta http-equiv="refresh" content="0;url=/search?{encodedQueryForRedirect}" />
@@ -80,7 +122,7 @@
>
<div class="flex max-w-2xl flex-col space-y-1">
<div class="w-full">
- <Searchbar {query} />
+ <Searchbar {query} bind:this={searchbarElem} />
</div>
<div class="mx-auto flex w-full justify-end sm:justify-between">
<div class="hidden h-full flex-col space-x-2 text-xs text-neutral sm:flex">
@@ -112,6 +154,9 @@
{prevPageSearchParams}
{nextPageSearchParams}
currentPage={data.params.currentPage}
+ {resultElems}
+ {spellCorrectElem}
+ bind:this={serp}
/>
{:else}
{#await clientSearch() then results}
@@ -122,6 +167,9 @@
{prevPageSearchParams}
{nextPageSearchParams}
currentPage={data.params.currentPage}
+ {resultElems}
+ {spellCorrectElem}
+ bind:this={serp}
/>
{/if}
{/await}
diff --git a/frontend/src/routes/search/Result.svelte b/frontend/src/routes/search/Result.svelte
index f1a47f16..6de5fe62 100644
--- a/frontend/src/routes/search/Result.svelte
+++ b/frontend/src/routes/search/Result.svelte
@@ -1,3 +1,5 @@
+<svelte:options accessors />
+
<script lang="ts">
import AdjustVertical from '~icons/heroicons/adjustments-vertical';
import type { DisplayedWebpage } from '$lib/api';
@@ -22,9 +24,18 @@
let button: HTMLButtonElement;
const dispatch = createEventDispatcher<{ modal: HTMLButtonElement }>();
+
+ let mainDiv: HTMLElement | undefined = undefined;
+ export const getMainDiv = () => mainDiv;
+
+ let mainResultLink: ResultLink | undefined = undefined;
+ export const getMainResultLink = () => mainResultLink;
+
+ export const hasFocus = () => mainResultLink?.hasFocus();
+ export const clearFocus = () => mainResultLink?.clearFocus();
</script>
-<div class="result flex min-w-0 grow flex-col space-y-0.5">
+<div class="flex min-w-0 grow flex-col space-y-0.5" bind:this={mainDiv}>
<div class="flex min-w-0">
<div class="flex min-w-0 grow flex-col space-y-0.5">
<div class="flex items-center text-sm">
@@ -41,6 +52,7 @@
title={webpage.title}
href={webpage.url}
{resultIndex}
+ bind:this={mainResultLink}
>
{webpage.title}
</ResultLink>
diff --git a/frontend/src/routes/search/ResultLink.svelte b/frontend/src/routes/search/ResultLink.svelte
index 5ce08668..125ba4f0 100644
--- a/frontend/src/routes/search/ResultLink.svelte
+++ b/frontend/src/routes/search/ResultLink.svelte
@@ -8,6 +8,27 @@
export let _class: string = '';
export let title: string | null = null;
export let resultIndex: number | null = null;
+
+ let link: HTMLAnchorElement;
+ export const focus = () => {
+ link.focus();
+ };
+ export const clearFocus = () => {
+ link.blur();
+ };
+ export const open = () => {
+ link.click();
+ };
+ export const openInCurrentTab = () => {
+ window.location.href = link.href;
+ };
+ export const openInNewTab = () => {
+ window.open(link.href, '_blank', 'noopener');
+ };
+
+ export const hasFocus = () => document.activeElement == link;
+
+ export const getUrl = () => new URL(link.href);
</script>
{#if resultIndex != null}
@@ -18,6 +39,7 @@
use:improvements={resultIndex}
target={$resultsInNewTab ? '_blank' : null}
rel={$resultsInNewTab ? 'noopener' : null}
+ bind:this={link}
>
<slot />
</a>
@@ -28,6 +50,7 @@
{title}
target={$resultsInNewTab ? '_blank' : null}
rel={$resultsInNewTab ? 'noopener' : null}
+ bind:this={link}
>
<slot />
</a>
diff --git a/frontend/src/routes/search/Serp.svelte b/frontend/src/routes/search/Serp.svelte
index 40f2135b..ab0816e1 100644
--- a/frontend/src/routes/search/Serp.svelte
+++ b/frontend/src/routes/search/Serp.svelte
@@ -1,3 +1,5 @@
+<svelte:options accessors />
+
<script lang="ts">
import { type DisplayedWebpage } from '$lib/api';
import type { SearchResults } from '$lib/search';
@@ -12,12 +14,15 @@
import ChevronLeft from '~icons/heroicons/chevron-left-20-solid';
import ChevronRight from '~icons/heroicons/chevron-right-20-solid';
import { flip } from 'svelte/animate';
+ import SpellCorrection from './SpellCorrection.svelte';
export let results: SearchResults;
export let query: string;
export let nextPageSearchParams: URLSearchParams | null;
export let prevPageSearchParams: URLSearchParams | null;
export let currentPage: number;
+ export let spellCorrectElem: SpellCorrection | undefined;
+ export let resultElems: Result[];
let modal: { top: number; left: number; site: DisplayedWebpage } | undefined;
@@ -64,20 +69,7 @@
{#if results.type == 'websites'}
<div class="col-start-1 flex min-w-0 max-w-2xl flex-col space-y-5">
{#if results.spellCorrection}
- <div>
- <div>
- Did you mean:{' '}
- <a class="font-medium" href="/search?q={encodeURIComponent(results.spellCorrection.raw)}"
- >{#each results.spellCorrection.highlighted as frag}
- {#if frag.kind == 'highlighted'}
- <b><i>{frag.text}</i></b>
- {:else}
- {frag.text}
- {/if}
- {/each}</a
- >
- </div>
- </div>
+ <SpellCorrection spellCorrection={results.spellCorrection} bind:this={spellCorrectElem} />
{/if}
{#if results.widget}
@@ -88,7 +80,12 @@
<div class="grid w-full grid-cols-1 space-y-10 place-self-start">
{#each results.webpages as webpage, resultIndex (`${query}-${webpage.url}`)}
<div animate:flip={{ duration: 150 }}>
- <Result {webpage} {resultIndex} on:modal={openSearchModal(webpage)} />
+ <Result
+ bind:this={resultElems[resultIndex]}
+ {webpage}
+ {resultIndex}
+ on:modal={openSearchModal(webpage)}
+ />
</div>
{/each}
{#if results.discussions}
diff --git a/frontend/src/routes/search/SpellCorrection.svelte b/frontend/src/routes/search/SpellCorrection.svelte
new file mode 100644
index 00000000..49cccba7
--- /dev/null
+++ b/frontend/src/routes/search/SpellCorrection.svelte
@@ -0,0 +1,28 @@
+<script lang="ts">
+ import type { HighlightedSpellCorrection } from '$lib/api';
+
+ export let spellCorrection: HighlightedSpellCorrection;
+
+ let link: HTMLAnchorElement;
+ export const open = () => {
+ link.click();
+ };
+ export const hasFocus = () => document.activeElement == link;
+</script>
+
+<div>
+ Did you mean:{' '}
+ <a
+ class="font-medium"
+ href="/search?q={encodeURIComponent(spellCorrection.raw)}"
+ bind:this={link}
+ >
+ {#each spellCorrection.highlighted as frag}
+ {#if frag.kind == 'highlighted'}
+ <b><i>{frag.text}</i></b>
+ {:else}
+ {frag.text}
+ {/if}
+ {/each}
+ </a>
+</div>
diff --git a/frontend/src/routes/settings/+page.svelte b/frontend/src/routes/settings/+page.svelte
index 4bbd6b93..c1e71994 100644
--- a/frontend/src/routes/settings/+page.svelte
+++ b/frontend/src/routes/settings/+page.svelte
@@ -5,6 +5,7 @@
import MarkPagesWithAdsSelect from './MarkPagesWithAdsSelect.svelte';
import MarkPagesWithPaywallSelect from './MarkPagesWithPaywallSelect.svelte';
import ResultsInNewTabs from './ResultsInNewTabs.svelte';
+ import UseKeyboardShortcuts from './UseKeyboardShortcuts.svelte';
const settings = [
{
@@ -38,6 +39,11 @@
description: 'Keep the search results window open and have links open in new tabs',
type: 'results-in-new-tabs',
},
+ {
+ title: 'Keyboard shortcuts',
+ description: 'Enables the use of keyboard shortcuts on the site',
+ type: 'use-keeb-shortcuts',
+ },
] as const;
</script>
@@ -65,6 +71,8 @@
<MarkPagesWithPaywallSelect />
{:else if setting.type == 'results-in-new-tabs'}
<ResultsInNewTabs />
+ {:else if setting.type == 'use-keeb-shortcuts'}
+ <UseKeyboardShortcuts />
{/if}
</div>
</div>
diff --git a/frontend/src/routes/settings/UseKeyboardShortcuts.svelte b/frontend/src/routes/settings/UseKeyboardShortcuts.svelte
new file mode 100644
index 00000000..3030a5fa
--- /dev/null
+++ b/frontend/src/routes/settings/UseKeyboardShortcuts.svelte
@@ -0,0 +1,6 @@
+<script lang="ts">
+ import { useKeyboardShortcuts } from '$lib/stores';
+ import RadioSelect from './RadioSelect.svelte';
+</script>
+
+<RadioSelect store={useKeyboardShortcuts} prefix="use-keeb-shortcuts" />