~sirn/fanboi2

ref: 5b482cfc1bfb0bb1e89715cb57c7bac864391768 fanboi2/assets/app/javascripts/components/topic_reloader.ts -rw-r--r-- 1.8 KiB
5b482cfcKridsada Thanabulpong 0.30.0 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
61
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}-/`
              )
          );
        }
    }
}