aboutsummaryrefslogtreecommitdiff
path: root/static/assets/js/pages/publish.js
blob: 7349fac4f1663ff9bfe013be2a7b001d3d069525 (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
window.addEventListener("DOMContentLoaded", () => {
  const content = document.getElementById("content");
  const renderPreview = document.getElementById("renderPreview");
  marked.setOptions({
    highlight: function (code) {
      return hljs.highlightAuto(code).value;
    },
  });
  content.addEventListener("input", () => {
    renderPreview.innerHTML = marked.parse(content.value);
    renderMathInElement(renderPreview, {
      // customised options
      // • auto-render specific keys, e.g.:
      delimiters: [
        { left: "$$", right: "$$", display: true },
        { left: "$", right: "$", display: false },
        { left: "\\(", right: "\\)", display: false },
        { left: "\\[", right: "\\]", display: true },
      ],
      // • rendering keys, e.g.:
      throwOnError: false,
    });
  });
});
$(document).on("click", "#publishPost", () => {
  document.getElementById("error").classList.add("hidden");
  const content = $("#content").val();
  const title = $("#title").val();
  const publishDate = $("#publishDate").val();
  const slug = title
    .toLowerCase()
    .replace(/ /g, "-")
    .replace(/[^\w-]+/g, "");
  const tags = $("#tags").val();
  if (title === "" || publishDate === "") {
    document.getElementById("error").classList.remove("hidden");
    return;
  } else {
    // Publish post to api/blog/new
    const body = {
      title: title,
      publishDate: publishDate,
      tags: tags,
      content: content,
      shortText: marked.parse(content.substring(0, 120) + "..."),
      slug: slug,
    };
    if (window.location.href.includes(slug)) {
      // Update post
      $.ajax({
        url: `/api/blog/update/${slug}`,
        type: "PUT",
        data: body,
        success: function (data) {
          window.location.href = `/posts/${slug}`;
        },
        error: function (err) {
          console.log(err);
        },
      });
    } else {
      $.ajax({
        url: "/api/blog/new",
        type: "POST",
        data: body,
        success: (data) => {
          window.location.href = "/admin/dashboard";
        },
        error: (err) => {
          console.log(err);
        },
      });
    }
  }
});