~sirn/fanboi2

ref: 5b482cfc1bfb0bb1e89715cb57c7bac864391768 fanboi2/assets/app/javascripts/components/topic_inline_reply.ts -rw-r--r-- 1.9 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
import {create, h} from 'virtual-dom';

import {SingletonComponent} from './base';
import {ResourceError} from '../utils/errors';
import {dispatchCustomEvent} from '../utils/elements';
import {attachErrors, detachErrors, serializeForm} from '../utils/forms';
import {LoadingState} from '../utils/loading';


export class TopicInlineReply extends SingletonComponent {
    public targetSelector = '[data-topic-inline-reply]';

    protected bindOne($target: Element) {
        let $form = $target;

        if ($form instanceof HTMLFormElement) {
            let $button = $target.querySelector('button');
            let loadingState = new LoadingState();

            $form.addEventListener('submit', (e: Event): void => {
                e.preventDefault();
                loadingState.bind(() => {
                    return new Promise((resolve) => {
                        if ($form instanceof HTMLFormElement) {
                            dispatchCustomEvent($form, 'newPost', {
                                params: serializeForm($form),
                                callback: () => {
                                    if ($form instanceof HTMLFormElement) {
                                        detachErrors($form);
                                        $form.reset();
                                        resolve();
                                    }
                                },
                                errorCallback: (error: ResourceError) => {
                                    if ($form instanceof HTMLFormElement) {
                                        detachErrors($form);
                                        attachErrors($form, error);
                                        resolve();
                                    }
                                }
                            });
                        }
                    });
                }, $button);
            });
        }
    }
}