summaryrefslogtreecommitdiff
path: root/client/simple/src/js/core/toolkit.ts
blob: d80167aa59eb130115d665ecbc325cf5b102d1d4 (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
// SPDX-License-Identifier: AGPL-3.0-or-later

import type { KeyBindingLayout } from "../main/keyboard.ts";

// synced with searx/webapp.py get_client_settings
type Settings = {
  advanced_search?: boolean;
  autocomplete?: string;
  autocomplete_min?: number;
  doi_resolver?: string;
  favicon_resolver?: string;
  hotkeys?: KeyBindingLayout;
  infinite_scroll?: boolean;
  method?: "GET" | "POST";
  query_in_title?: boolean;
  results_on_new_tab?: boolean;
  safesearch?: 0 | 1 | 2;
  search_on_category_select?: boolean;
  theme?: string;
  theme_static_path?: string;
  translations?: Record<string, string>;
  url_formatting?: "pretty" | "full" | "host";
};

type HTTPOptions = {
  body?: BodyInit;
  timeout?: number;
};

type ReadyOptions = {
  // all values must be truthy for the callback to be executed
  on?: (boolean | undefined)[];
};

type AssertElement = (element?: HTMLElement | null) => asserts element is HTMLElement;

export type EndpointsKeys = keyof typeof Endpoints;

export const Endpoints = {
  index: "index",
  results: "results",
  preferences: "preferences",
  unknown: "unknown"
} as const;

export const mutable = {
  closeDetail: undefined as (() => void) | undefined,
  scrollPageToSelected: undefined as (() => void) | undefined,
  selectImage: undefined as ((resultElement: HTMLElement) => void) | undefined,
  selectNext: undefined as ((openDetailView?: boolean) => void) | undefined,
  selectPrevious: undefined as ((openDetailView?: boolean) => void) | undefined
};

const getEndpoint = (): EndpointsKeys => {
  const metaEndpoint = document.querySelector('meta[name="endpoint"]')?.getAttribute("content");

  if (metaEndpoint && metaEndpoint in Endpoints) {
    return metaEndpoint as EndpointsKeys;
  }

  return Endpoints.unknown;
};

const getSettings = (): Settings => {
  const settings = document.querySelector("script[client_settings]")?.getAttribute("client_settings");
  if (!settings) return {};

  try {
    return JSON.parse(atob(settings));
  } catch (error) {
    console.error("Failed to load client_settings:", error);
    return {};
  }
};

export const assertElement: AssertElement = (element?: HTMLElement | null): asserts element is HTMLElement => {
  if (!element) {
    throw new Error("Bad assertion: DOM element not found");
  }
};

export const http = async (method: string, url: string | URL, options?: HTTPOptions): Promise<Response> => {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), options?.timeout ?? 30_000);

  const res = await fetch(url, {
    body: options?.body,
    method: method,
    signal: controller.signal
  }).finally(() => clearTimeout(timeoutId));
  if (!res.ok) {
    throw new Error(res.statusText);
  }

  return res;
};

export const listen = <K extends keyof DocumentEventMap, E extends HTMLElement>(
  type: string | K,
  target: string | Document | E,
  listener: (this: E, event: DocumentEventMap[K]) => void | Promise<void>,
  options?: AddEventListenerOptions
): void => {
  if (typeof target !== "string") {
    target.addEventListener(type, listener as EventListener, options);
    return;
  }

  document.addEventListener(
    type,
    (event: Event) => {
      for (const node of event.composedPath()) {
        if (node instanceof HTMLElement && node.matches(target)) {
          try {
            listener.call(node as E, event as DocumentEventMap[K]);
          } catch (error) {
            console.error(error);
          }
          break;
        }
      }
    },
    options
  );
};

export const ready = (callback: () => void, options?: ReadyOptions): void => {
  for (const condition of options?.on ?? []) {
    if (!condition) {
      return;
    }
  }

  if (document.readyState !== "loading") {
    callback();
  } else {
    listen("DOMContentLoaded", document, callback, { once: true });
  }
};

export const endpoint: EndpointsKeys = getEndpoint();
export const settings: Settings = getSettings();