summaryrefslogtreecommitdiff
path: root/static/js/controllers/comments_controller.js
blob: 683f5ca781be3f6252e57113ba18d9d140e9098e (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
import { BaseController } from "./base_controller.js";
import { Paginator } from "../paginator.js";

export class CommentsController extends BaseController {
  constructor(replies_controller) {
		super();
		this.replies_controller = replies_controller;
		this.comments_node = document.getElementById("comments-thread");
		this.paginator = new Paginator(this.comments_server_host, "/api/comments", this.post);
		this.renderForm();
		this.renderComments();
  }

  renderForm() {
		this.get("/api/comments/new").then((value) => {
	    const form = value?.getElementById("comment-form");

	    if(form != null) {
				this.comments_node.appendChild(form);
				this.form_element = document.getElementById("comment-form");
				this.form_element.addEventListener("submit", this.submit.bind(this));
	    }
		});
  }

  renderComments() {
		this.get(`/api/comments?path=${this.post}`).then((value) => {
	  	const comments = value?.getElementById("comment-section");

	  	if(comments != null) {
				this.comments_node.appendChild(comments);
				this.replies_controller.init();
				this.paginator.populatePageAnchors();
	  	}
		});
  }

  renderSubmitResponse(response_document) {
		const new_comments = this.htmlFromResponse(response_document).getElementById("comment-section");
		const comments = document.getElementById("comment-section");
		comments.replaceWith(new_comments);
  }

  async submit(event) {
		var form = new FormData(event.target);
		form.append("domain", `${window.location.protocol}//${window.location.host}`);

		super.submit(event, `${this.comments_server_host}/api/comments?path=${this.post}`, form);
  }
 }