aboutsummaryrefslogtreecommitdiffstats
path: root/pnit-form.mjs
blob: c1fa16c87e126b7f1b9b8988c3ce3b1ed558412b (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
65
66
67
68
69
70
71
72
73
74
75
76
77
const worker = new Worker('worker.js', { type: 'module' });

export default class extends HTMLElement {
    static name = 'x-pnit-form';
    static register() {
        console.debug('Registering Element', this.name, this);
        customElements.define(this.name, this);
    }

    get form() {
        return this.querySelector('form');
    }

    get ignoreHeader() {
        return this.form.querySelector('input[name="ignore-header"]').checked;
    }

    get threshold() {
        return Number(this.form.querySelector('input[name="pni-threshold"]').value);
    }

    get files() {
        const inputs = Array.from(this.form.querySelectorAll('input[type="file"]'));
        return inputs.flatMap(inp => Array.from(inp.files));
    }

    get resultTable() {
        return document.getElementById('pnit-results');
    }

    connectedCallback() {
        console.debug('PNITForm#connectedCallback', this);

        worker.onmessage = this.handleWorkerMessage.bind(this);
        worker.onmessageerror = this.handleWorkerMessageError.bind(this);
        worker.onerror = this.handleWorkerError.bind(this);

        this.form.onchange = this.process.bind(this);
        this.form.onchange();
    }

    handleWorkerMessage(e) {
        const row = document.createElement('tr');
        e.data.forEach(v => {
            const col = document.createElement('td');
            col.innerText = v;
            row.appendChild(col);
        });
        this.resultTable.appendChild(row);
    }

    handleWorkerMessageError(e) {
        console.error('onmessageerror', e);
    }

    handleWorkerError(e) {
        console.error('onerror', e);
    }

    process() {
        console.debug('PNITForm#process', this);

        this.resultTable.innerHTML = '';

        if (isNaN(this.threshold)) {
            console.error('threshold invalid');
            return;
        }
        this.files.forEach(file => {
            worker.postMessage({
                ignoreHeader: this.ignoreHeader,
                threshold: this.threshold,
                file
            });
        });
    }
}