~sirn/fanboi2

ref: a68873a108d20a6a49a1b6caf374bfb2cf6a94fe fanboi2/assets/app/javascripts/components/topic_reloader.ts -rw-r--r-- 1.9 KiB
a68873a1Kridsada Thanabulpong Coding style cleanups and setup pre-commit hooks (#42) 3 years ago
                                                                                
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
import { SingletonComponent } from "./base";
import { dispatchCustomEvent } from "../utils/elements";
import { LoadingState } from "../utils/loading";

export class TopicReloader extends SingletonComponent {
    public targetSelector = "[data-topic-reloader]";

    protected bindOne($target: Element) {
        let $topic = $target.closest("[data-topic]");
        let loadingState = new LoadingState();

        $target.addEventListener("click", (e: Event) => {
            e.preventDefault();
            loadingState.bind(() => {
                return new Promise(resolve => {
                    dispatchCustomEvent($target, "loadPosts", {
                        callback: () => {
                            resolve();
                        },
                    });
                });
            }, $target);
        });

        if ($topic) {
            $topic.addEventListener("postsLoaded", (e: CustomEvent) => {
                this.updateButtonAlt($target);
                this.refreshButtonState($target, e.detail.lastPostNumber);
                this.updateButtonAlt($target);
            });
        }
    }

    private updateButtonAlt($target: Element): void {
        let altLabel = $target.getAttribute("data-topic-reloader-label");
        let altClass = $target.getAttribute("data-topic-reloader-class");

        if (altLabel) {
            $target.innerHTML = altLabel;
        }

        if (altClass) {
            $target.className = altClass;
        }
    }

    private refreshButtonState($target: Element, lastPostNumber: number): void {
        let originalHref = $target.getAttribute("href");

        if (originalHref) {
            $target.setAttribute(
                "href",
                originalHref.replace(
                    /^(\/\w+\/\d+)\/\d+\-\/$/,
                    `$1/${lastPostNumber}-/`,
                ),
            );
        }
    }
}