aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/render/ChapterVote.tsx
blob: 1a3f8999fd1d3c96bde06218f3c76d0ad7539471 (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
import * as React from "react";
import * as ReactDOM from "react-dom";
import ChapterVoteComponent, { ChapterVoteState } from "../components/ChapterVoteComponent";
import { VoteResponse } from "../messageTypes";
import { Category, SegmentUUID, SponsorTime } from "../types";

export class ChapterVote {
    container: HTMLElement;
    ref: React.RefObject<ChapterVoteComponent>;

    unsavedState: ChapterVoteState;

    mutationObserver?: MutationObserver;
    
    constructor(vote: (type: number, UUID: SegmentUUID, category?: Category) => Promise<VoteResponse>) {
        this.ref = React.createRef();

        this.container = document.createElement('span');
        this.container.id = "chapterVote";
        this.container.style.height = "100%";

        ReactDOM.render(
            <ChapterVoteComponent ref={this.ref} vote={vote} />,
            this.container
        );
    }

    getContainer(): HTMLElement {
        return this.container;
    }

    close(): void {
        ReactDOM.unmountComponentAtNode(this.container);
        this.container.remove();
    }

    setVisibility(show: boolean): void {
        const newState = {
            show,
            ...(!show ? { segment: null } : {})
        };

        if (this.ref.current) {
            this.ref.current?.setState(newState);
        } else {
            this.unsavedState = newState;
        }
    }

    async setSegment(segment: SponsorTime): Promise<void> {
        if (this.ref.current?.state?.segment !== segment) {
            const newState = {
                segment,
                show: true
            };

            if (this.ref.current) {
                this.ref.current?.setState(newState);
            } else {
                this.unsavedState = newState;
            }
        }
    }
}