summaryrefslogtreecommitdiff
path: root/client/simple/src/js/main/keyboard.ts
blob: b5e5d4edc7623e7941d29510fc79e58c94fe7643 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// SPDX-License-Identifier: AGPL-3.0-or-later

import { assertElement, listen, mutable, settings } from "../core/toolkit.ts";

export type KeyBindingLayout = "default" | "vim";

type KeyBinding = {
  key: string;
  fun: (event: KeyboardEvent) => void;
  des: string;
  cat: string;
};

type HighlightResultElement = "down" | "up" | "visible" | "bottom" | "top";

/* common base for layouts */
const baseKeyBinding: Record<string, KeyBinding> = {
  Escape: {
    key: "ESC",
    fun: (event: KeyboardEvent) => removeFocus(event),
    des: "remove focus from the focused input",
    cat: "Control"
  },
  c: {
    key: "c",
    fun: () => copyURLToClipboard(),
    des: "copy url of the selected result to the clipboard",
    cat: "Results"
  },
  h: {
    key: "h",
    fun: () => toggleHelp(keyBindings),
    des: "toggle help window",
    cat: "Other"
  },
  i: {
    key: "i",
    fun: () => searchInputFocus(),
    des: "focus on the search input",
    cat: "Control"
  },
  n: {
    key: "n",
    fun: () => GoToNextPage(),
    des: "go to next page",
    cat: "Results"
  },
  o: {
    key: "o",
    fun: () => openResult(false),
    des: "open search result",
    cat: "Results"
  },
  p: {
    key: "p",
    fun: () => GoToPreviousPage(),
    des: "go to previous page",
    cat: "Results"
  },
  r: {
    key: "r",
    fun: () => reloadPage(),
    des: "reload page from the server",
    cat: "Control"
  },
  t: {
    key: "t",
    fun: () => openResult(true),
    des: "open the result in a new tab",
    cat: "Results"
  }
};

const keyBindingLayouts: Record<KeyBindingLayout, Record<string, KeyBinding>> = {
  // SearXNG layout
  default: {
    ArrowLeft: {
      key: "←",
      fun: () => highlightResult("up")(),
      des: "select previous search result",
      cat: "Results"
    },
    ArrowRight: {
      key: "→",
      fun: () => highlightResult("down")(),
      des: "select next search result",
      cat: "Results"
    },
    ...baseKeyBinding
  },

  // Vim-like keyboard layout
  vim: {
    b: {
      key: "b",
      fun: () => scrollPage(-window.innerHeight),
      des: "scroll one page up",
      cat: "Navigation"
    },
    d: {
      key: "d",
      fun: () => scrollPage(window.innerHeight / 2),
      des: "scroll half a page down",
      cat: "Navigation"
    },
    f: {
      key: "f",
      fun: () => scrollPage(window.innerHeight),
      des: "scroll one page down",
      cat: "Navigation"
    },
    g: {
      key: "g",
      fun: () => scrollPageTo(-document.body.scrollHeight, "top"),
      des: "scroll to the top of the page",
      cat: "Navigation"
    },
    j: {
      key: "j",
      fun: () => highlightResult("down")(),
      des: "select next search result",
      cat: "Results"
    },
    k: {
      key: "k",
      fun: () => highlightResult("up")(),
      des: "select previous search result",
      cat: "Results"
    },
    u: {
      key: "u",
      fun: () => scrollPage(-window.innerHeight / 2),
      des: "scroll half a page up",
      cat: "Navigation"
    },
    v: {
      key: "v",
      fun: () => scrollPageTo(document.body.scrollHeight, "bottom"),
      des: "scroll to the bottom of the page",
      cat: "Navigation"
    },
    y: {
      key: "y",
      fun: () => copyURLToClipboard(),
      des: "copy url of the selected result to the clipboard",
      cat: "Results"
    },
    ...baseKeyBinding
  }
};

const keyBindings: Record<string, KeyBinding> =
  settings.hotkeys && settings.hotkeys in keyBindingLayouts
    ? keyBindingLayouts[settings.hotkeys]
    : keyBindingLayouts.default;

const isElementInDetail = (element?: HTMLElement): boolean => {
  const ancestor = element?.closest(".detail, .result");
  return ancestor?.classList.contains("detail") ?? false;
};

const getResultElement = (element?: HTMLElement): HTMLElement | undefined => {
  return element?.closest(".result") ?? undefined;
};

const isImageResult = (resultElement?: HTMLElement): boolean => {
  return resultElement?.classList.contains("result-images") ?? false;
};

const highlightResult =
  (which: HighlightResultElement | HTMLElement) =>
  (noScroll?: boolean, keepFocus?: boolean): void => {
    let effectiveWhich = which;
    let current = document.querySelector<HTMLElement>(".result[data-vim-selected]");
    if (!current) {
      // no selection : choose the first one
      current = document.querySelector<HTMLElement>(".result");
      if (!current) {
        // no first one : there are no results
        return;
      }
      // replace up/down actions by selecting first one
      if (which === "down" || which === "up") {
        effectiveWhich = current;
      }
    }

    const results = Array.from(document.querySelectorAll<HTMLElement>(".result"));

    let next: HTMLElement | undefined;

    if (typeof effectiveWhich !== "string") {
      next = effectiveWhich;
    } else {
      switch (effectiveWhich) {
        case "visible": {
          const top = document.documentElement.scrollTop || document.body.scrollTop;
          const bot = top + document.documentElement.clientHeight;

          for (const element of results) {
            const etop = element.offsetTop;
            const ebot = etop + element.clientHeight;
            if (ebot <= bot && etop > top) {
              next = element;
              break;
            }
          }
          break;
        }
        case "down":
          next = results[results.indexOf(current) + 1] || current;
          break;
        case "up":
          next = results[results.indexOf(current) - 1] || current;
          break;
        case "bottom":
          next = results.at(-1);
          break;
        // biome-ignore lint/complexity/noUselessSwitchCase: fallthrough is intended
        case "top":
        default:
          next = results[0];
      }
    }

    if (next) {
      current.removeAttribute("data-vim-selected");
      next.setAttribute("data-vim-selected", "true");

      if (!keepFocus) {
        const link = next.querySelector<HTMLAnchorElement>("h3 a") || next.querySelector<HTMLAnchorElement>("a");
        link?.focus();
      }

      if (!noScroll) {
        mutable.scrollPageToSelected?.();
      }
    }
  };

const reloadPage = (): void => {
  document.location.reload();
};

const removeFocus = (event: KeyboardEvent): void => {
  const target = event.target as HTMLElement;
  const tagName = target?.tagName?.toLowerCase();

  if (document.activeElement && (tagName === "input" || tagName === "select" || tagName === "textarea")) {
    (document.activeElement as HTMLElement).blur();
  } else {
    mutable.closeDetail?.();
  }
};

const pageButtonClick = (css_selector: string): void => {
  const button = document.querySelector<HTMLButtonElement>(css_selector);
  if (button) {
    button.click();
  }
};

const GoToNextPage = (): void => {
  pageButtonClick('nav#pagination .next_page button[type="submit"]');
};

const GoToPreviousPage = (): void => {
  pageButtonClick('nav#pagination .previous_page button[type="submit"]');
};

mutable.scrollPageToSelected = (): void => {
  const sel = document.querySelector<HTMLElement>(".result[data-vim-selected]");
  if (!sel) return;

  const wtop = document.documentElement.scrollTop || document.body.scrollTop;
  const height = document.documentElement.clientHeight;
  const etop = sel.offsetTop;
  const ebot = etop + sel.clientHeight;
  const offset = 120;

  // first element ?
  if (!sel.previousElementSibling && ebot < height) {
    // set to the top of page if the first element
    // is fully included in the viewport
    window.scroll(window.scrollX, 0);
    return;
  }

  if (wtop > etop - offset) {
    window.scroll(window.scrollX, etop - offset);
  } else {
    const wbot = wtop + height;
    if (wbot < ebot + offset) {
      window.scroll(window.scrollX, ebot - height + offset);
    }
  }
};

const scrollPage = (amount: number): void => {
  window.scrollBy(0, amount);
  highlightResult("visible")();
};

const scrollPageTo = (position: number, nav: HighlightResultElement): void => {
  window.scrollTo(0, position);
  highlightResult(nav)();
};

const searchInputFocus = (): void => {
  window.scrollTo(0, 0);

  const q = document.querySelector<HTMLInputElement>("#q");
  if (q) {
    q.focus();

    if (q.setSelectionRange) {
      const len = q.value.length;

      q.setSelectionRange(len, len);
    }
  }
};

const openResult = (newTab: boolean): void => {
  let link = document.querySelector<HTMLAnchorElement>(".result[data-vim-selected] h3 a");
  if (!link) {
    link = document.querySelector<HTMLAnchorElement>(".result[data-vim-selected] > a");
  }
  if (!link) return;

  const url = link.getAttribute("href");
  if (url) {
    if (newTab) {
      window.open(url);
    } else {
      window.location.href = url;
    }
  }
};

const initHelpContent = (divElement: HTMLElement, keyBindings: typeof baseKeyBinding): void => {
  const categories: Record<string, KeyBinding[]> = {};

  for (const binding of Object.values(keyBindings)) {
    const cat = binding.cat;
    categories[cat] ??= [];
    categories[cat].push(binding);
  }

  const sortedCategoryKeys = Object.keys(categories).sort(
    (a, b) => (categories[b]?.length ?? 0) - (categories[a]?.length ?? 0)
  );

  let html = '<a href="#" class="close" aria-label="close" title="close">×</a>';
  html += "<h3>How to navigate SearXNG with hotkeys</h3>";
  html += "<table>";

  for (const [i, categoryKey] of sortedCategoryKeys.entries()) {
    const bindings = categories[categoryKey];
    if (!bindings || bindings.length === 0) continue;

    const isFirst = i % 2 === 0;
    const isLast = i === sortedCategoryKeys.length - 1;

    if (isFirst) {
      html += "<tr>";
    }

    html += "<td>";
    html += `<h4>${categoryKey}</h4>`;
    html += '<ul class="list-unstyled">';

    for (const binding of bindings) {
      html += `<li><kbd>${binding.key}</kbd> ${binding.des}</li>`;
    }

    html += "</ul>";
    html += "</td>";

    if (!isFirst || isLast) {
      html += "</tr>";
    }
  }

  html += "</table>";

  divElement.innerHTML = html;
};

const toggleHelp = (keyBindings: typeof baseKeyBinding): void => {
  let helpPanel = document.querySelector<HTMLElement>("#vim-hotkeys-help");
  if (helpPanel) {
    // toggle hidden
    helpPanel.classList.toggle("invisible");
  } else {
    // first call
    helpPanel = Object.assign(document.createElement("div"), {
      id: "vim-hotkeys-help",
      className: "dialog-modal"
    });
    initHelpContent(helpPanel, keyBindings);
    const body = document.getElementsByTagName("body")[0];
    if (body) {
      body.appendChild(helpPanel);
    }
  }
};

const copyURLToClipboard = async (): Promise<void> => {
  const currentUrlElement = document.querySelector<HTMLAnchorElement>(".result[data-vim-selected] h3 a");
  assertElement(currentUrlElement);

  const url = currentUrlElement.getAttribute("href");
  if (url) {
    await navigator.clipboard.writeText(url);
  }
};

listen("click", ".result", function (this: HTMLElement, event: PointerEvent) {
  if (!isElementInDetail(event.target as HTMLElement)) {
    highlightResult(this)(true, true);

    const resultElement = getResultElement(event.target as HTMLElement);

    if (resultElement && isImageResult(resultElement)) {
      event.preventDefault();
      mutable.selectImage?.(resultElement);
    }
  }
});

// FIXME: Focus might also trigger Pointer event ^^^
listen(
  "focus",
  ".result a",
  (event: FocusEvent) => {
    if (!isElementInDetail(event.target as HTMLElement)) {
      const resultElement = getResultElement(event.target as HTMLElement);

      if (resultElement && !resultElement.hasAttribute("data-vim-selected")) {
        highlightResult(resultElement)(true);
      }

      if (resultElement && isImageResult(resultElement)) {
        event.preventDefault();
        mutable.selectImage?.(resultElement);
      }
    }
  },
  { capture: true }
);

listen("keydown", document, (event: KeyboardEvent) => {
  // check for modifiers so we don't break browser's hotkeys
  if (Object.hasOwn(keyBindings, event.key) && !event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {
    const tagName = (event.target as HTMLElement)?.tagName?.toLowerCase();

    if (event.key === "Escape") {
      keyBindings[event.key]?.fun(event);
    } else if (event.target === document.body || tagName === "a" || tagName === "button") {
      event.preventDefault();
      keyBindings[event.key]?.fun(event);
    }
  }
});

mutable.selectNext = highlightResult("down");
mutable.selectPrevious = highlightResult("up");