aboutsummaryrefslogtreecommitdiffstats
path: root/src/static/main.js
blob: 68d36adc24c5ee3d7184426edd6278a019ea5d4a (plain) (blame)
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
const convertButton = document.getElementById("convert-button");
const uploadButton = document.getElementById("upload-button");
const markdownInput = document.getElementById("markdown");
const imageInput = document.getElementById("image");
const mdFileInput = document.getElementById("md-file");

document.body.addEventListener("htmx:beforeRequest", (event) => {
  const elt = event.detail?.elt;
  if (!elt) {
    return;
  }

  if (elt.id === "convert-form" && convertButton) {
    convertButton.disabled = true;
    convertButton.textContent = "generating...";
  }

  if (elt.id === "upload-button" && uploadButton) {
    uploadButton.disabled = true;
    uploadButton.textContent = "uploading...";
  }
});

document.body.addEventListener("htmx:afterRequest", (event) => {
  const elt = event.detail?.elt;
  if (!elt) {
    return;
  }

  if (elt.id === "convert-form" && convertButton) {
    convertButton.disabled = false;
    convertButton.textContent = "generate pdf";
  }

  if (elt.id === "upload-button" && uploadButton) {
    uploadButton.disabled = false;
    uploadButton.textContent = "upload image";
  }
});

if (mdFileInput) {
  mdFileInput.addEventListener("change", () => {
    const file = mdFileInput.files?.[0];

    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (markdownInput) {
          markdownInput.value = /** @type {string} */ (e.target.result);
          markdownInput.readOnly = true;
        }
        if (imageInput) {
          imageInput.disabled = true;
        }
        if (uploadButton) {
          uploadButton.disabled = true;
        }
      };
      reader.readAsText(file);
    } else {
      if (markdownInput) {
        markdownInput.value = "";
        markdownInput.readOnly = false;
      }
      if (imageInput) {
        imageInput.disabled = false;
      }
      if (uploadButton) {
        uploadButton.disabled = false;
      }
    }
  });
}

document.body.addEventListener("click", (event) => {
  const target = event.target;
  if (!(target instanceof HTMLElement)) {
    return;
  }

  const button = target.closest("[data-insert-markdown]");
  if (!(button instanceof HTMLElement) || !markdownInput) {
    return;
  }

  const snippet = button.dataset.insertMarkdown;
  if (!snippet) {
    return;
  }

  const needsLeadingNewline = markdownInput.value && !markdownInput.value.endsWith("\n");
  const prefix = needsLeadingNewline ? "\n" : "";
  markdownInput.value += `${prefix}${snippet}\n`;
  markdownInput.focus();
});