summaryrefslogtreecommitdiff
path: root/public/assets/js/lib/views/index/threadform.js
blob: ad3c2fb07cc337bd98d1eaeb357574dd356bedd4 (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
var ThreadForm = FormView.extend({
  el: "#thread_form",

  events: {
    "keydown textarea": "keydown",
  },

  action: "/api/thread",
  method: "POST",

  initialize: function () {
    this.__super__.initialize.call(this);
    this.template = this.$(".template").html();
  },

  load: function (selected_keyword) {
    $.get(
      "/api/keywords",
      function (data) {
        var tags = {};
        data.keywords.forEach((keyword) => {
          var kw = keyword.keyword;
          var opt = document.createElement("option");
          opt.value = kw;
          opt.innerHTML = kw;
          tags[kw] = opt;
        });
        var sorted = Object.keys(tags)
          .sort()
          .map((kw) => tags[kw]);
        this.$("[name=keyword]").append(sorted);
        if (selected_keyword) {
          this.$("[name=keyword]").val(selected_keyword);
        } else {
          this.$("[name=keyword]").val("unsorted");
        }
        $("body").removeClass("loading");
      }.bind(this)
    );
  },

  keydown: function (e) {
    if ((e.ctrlKey || e.metaKey || e.altKey) && e.keyCode == 83) {
      // "s" key
      e.preventDefault();
      e.stopPropagation();
      this.save();
    }
  },

  validate: function () {
    var errors = [];
    var title = this.$("[name=title]").val();
    if (!title || !title.length) {
      errors.push("Please title your post.");
    }
    var comment = this.$("[name=comment]").val();
    var files = this.$("[name=files]").val();
    if ((!comment || !comment.length) && !files) {
      errors.push("Please enter a comment or add some files.");
    }
    return errors.length ? errors : null;
  },

  success: function (data) {
    if (data.error) {
      return alert(data.error);
    }
    window.location.href = "/details/" + data.id;
  },
});