summaryrefslogtreecommitdiff
path: root/public/shell.js
blob: 9a7084672aef03902d669bd21e36ad3704dc80d1 (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
const shell = document.querySelector("[data-shell]");

if (shell) {
  const area = shell.closest("[data-scroll-area]");
  const history = shell.querySelector("#shell-history");
  const input = shell.querySelector("[data-shell-input]");
  const caret = shell.querySelector("[data-shell-caret]");
  let busy = false;

  const updateCaret = () => {
    const pos = input.selectionStart ?? input.value.length;
    caret.style.left = `calc(${pos}ch - ${input.scrollLeft}px)`;
    caret.textContent = input.value[pos] ?? "\u00a0";
    caret.style.animation = "none"; // restart the blink so the caret is solid while typing
    void caret.offsetWidth;
    caret.style.animation = "";
  };

  const snapToBottom = () => {
    area.scrollTop = area.scrollHeight;
  };

  const run = async (cmd) => {
    busy = true;
    try {
      const res = await fetch("/shell/run", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({ cmd }),
      });
      const data = await res.json();
      if (data.clear) history.replaceChildren();
      if (data.html) history.insertAdjacentHTML("beforeend", data.html);
      if (data.vars) {
        for (const [key, value] of Object.entries(data.vars)) {
          document.documentElement.style.setProperty(`--${key}`, value);
        }
      }
    } catch {
      const el = document.createElement("p");
      el.textContent = "request failed";
      history.append(el);
    } finally {
      busy = false;
      snapToBottom();
    }
  };

  input.addEventListener("keydown", (e) => {
    if (e.key !== "Enter") return;
    e.preventDefault();
    const cmd = input.value.trim();
    if (!cmd || busy) return;
    input.value = "";
    updateCaret();
    run(cmd);
  });

  for (const event of ["input", "keyup", "click", "focus"]) {
    input.addEventListener(event, updateCaret);
  }
  document.addEventListener("selectionchange", () => {
    if (document.activeElement === input) updateCaret();
  });

  area.addEventListener("click", () => {
    if (!getSelection().toString()) input.focus({ preventScroll: true });
  });

  input.focus({ preventScroll: true });
  updateCaret();
  snapToBottom();
}