summary refs log tree commit diff
path: root/pages/main/page.js
blob: 7061c94dd29e537c199a5947385d15ab1c0cd501 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import { shiftHeld } from "../../lib/key.js"
import html from "../../lib/htmlbuilder.js"
import markdwonits from "https://cdn.jsdelivr.net/npm/[email protected]/+esm"
import { openPopup } from "../../lib/popups.js";

// NOTE: do NOT use prettier, it fucks up the spacing for htmlbuilder

window.html = html // debug

let attachments = []

async function addAttachmentFromUrl(url) {
    const resp = await fetch(url);
    if (!resp || !resp.ok) throw new Error("attachment invalid");
    attachments.push({
        type: resp.headers.get('content-type') ?? 'unknown',
        blob: await resp.blob(),
        url
    })
}

function blobToDataURL(blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function(ev) {resolve(ev.target.result);}
        reader.onerror = reject
        reader.readAsDataURL(blob);
    })
}

async function attachmentPreview(attachment) {
    switch (attachment.type.split('/')[0]) {
        case 'image':
            return html('img').attr('src', await blobToDataURL(attachment.blob))
    
        default:
            return html('span').txt('file')
    }
}

// TODO: add catbox integration
function addAttachment() {
    const input = document.createElement('input');
    input.type = 'file';

    input.onchange = async e => {
        const file = e.target.files[0]; 
    
        const reader = new FileReader();
        reader.readAsText(file,'UTF-8');
    
        reader.onload = readerEvent => {
            const content = readerEvent.target.result;

        }
    }

    input.click();
}

const md = markdwonits({
    highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
            try {
                return hljs.highlight(str, { language: lang }).value;
            } catch (__) {}
        }
    
        return ''; // use external default escaping
    },
    breaks: true,
    linkify: true,
    typographer: true,
})

async function fetchJSON(url, opts) {
    let resp = await fetch(url, opts);
    return await resp.json()
}

function buildUserPopup(userData) {
    return html('div')
        .child('pre')
            .text(JSON.stringify(userData))
            .up()
}

function scrollToBottomOfElement(element) {
    element.scrollTo(0, element.scrollHeight);
}

let handleNewPost;

function deHTML(t) {
    t = t.replaceAll("<", "&lt;")
    t = t.replaceAll("&", "&gt;")
    return t
}

function getUsernameHTML(msg) {
    return msg.author.display_name ? `${deHTML(msg.author.display_name)} (<code>@${deHTML(msg.author.username)}</code>)`: deHTML(r.author.username)
}

export async function onload() {
    const msgArea = document.getElementById("messages");

    document.getElementById("addAttachment").onclick = async () => {
        await addAttachmentFromUrl(prompt('Attachment Url'));
        updateAttachmentUI()
    }

    handleNewPost = function handleNewPost(post) {
        console.debug('posting of the poster', post)
        let scrolledToBottom = msgArea.parentElement.scrollTopMax == msgArea.parentElement.scrollTop;
        createMessage(post.data)
        if(scrolledToBottom) scrollToBottomOfElement(msgArea.parentElement);
    }

    let replies = []

    function rednerReplyThingy() {
		let scrolledToBottom = msgArea.parentElement.scrollTopMax == msgArea.parentElement.scrollTop;
        let elem = html('div')
            .class('replies')
            .attr('id', 'replies')
            .for(replies, (r, i) => 
                html('div')
                    .class('reply')
                    .child('span')
                        .html(getUsernameHTML(r) + ": " + deHTML(String(r.content).slice(0, 50)))
                        .up()
                    .child('button')
                        .text('x')
                        .ev('click', e => {
                            replies.splice(i, 1);
                            rednerReplyThingy();
                        })
                        .up()
            );
        if(document.getElementById('repliesContainer').firstChild)
            document.getElementById('repliesContainer').firstChild.remove()
        document.getElementById('repliesContainer').prepend(elem);
		if(scrolledToBottom) scrollToBottomOfElement(msgArea.parentElement);
    }

    async function updateAttachmentUI() {
        if(attachments.length >= 3) {
            document.getElementById("addAttachment").setAttribute('disabled', true)
        } else {
            document.getElementById("addAttachment").removeAttribute('disabled')
        }
        let scrolledToBottom = msgArea.parentElement.scrollTopMax == msgArea.parentElement.scrollTop;
        const previews = [];
        for (const attachment of attachments) {
            previews.push(await attachmentPreview(attachment))
        }
        const elem = html('div')
            .class('attachments')
            .for(attachments, (attachment, i) => {
                let elem = html('div')
                    .class('attachment')
                    .child('div')
                        .class('attachment-header')
                            .child('span')
                                .txt(attachment.url.split('/')[attachment.url.split('/').length - 1])
                                .up()
                            .child('button')
                                .class('remove-attachment')
                                .txt('X')
                                .ev('click', e => {
                                    attachments.splice(i, 1);
                                    updateAttachmentUI();
                                })
                                .up()
                        .up();
                elem.appendChild(previews[i]);
                return elem
            });
        if(document.getElementById('attachmentsContainer').firstChild)
            document.getElementById('attachmentsContainer').firstChild.remove()
        document.getElementById('attachmentsContainer').prepend(elem);
        if(scrolledToBottom) scrollToBottomOfElement(msgArea.parentElement);
    }

    async function createMessage(msg) {
        const elem = html('div')
        msgArea.appendChild(elem)
        let types = [];
        for (const attachment of msg.attachments) {
            console.debug(attachment)
            const resp = await fetch(attachment.toString());
            types.push(resp.headers.get('content-type'))
        }
        elem.class('message')
            .child('div')
                .class('message-container')
                .child('img')
                    .attr('src', msg.author.avatar || '/assets/pfp_sdwl.png')
                    .class('avatar')
                    .ev('click', e => openPopup(buildUserPopup(msg.author)))
                    .up()
                .child('div')
                    .class('message-content-container')
                    .for(msg.replies, r => html('div')
                        .class('reply')
                        .html(`→ ${getUsernameHTML(r)}: ${deHTML(String(r.content).slice(0, 50))}`))
                    .child('div')
                        .class('message-header')
                        .child('span')
                            .class('username')
                            .html(getUsernameHTML(msg))
                            .up()
                        .child('div')
                            .class('action-buttons')
                            .child('button')
                                .text('reply')
                                .ev('click', e => {
                                    if(msg.length >= 3) return;
                                    replies.push(msg);
                                    rednerReplyThingy();
                                })
                                .up()
                            .up()
                        .up()
                    .child('span')
                        .class('post-content')
                        .html(md.render(msg?.content))
                    .child('div')
                        .for(msg.attachments, (a, i) => {
                            if(types[i].startsWith('image')) {
                                return html('img').class('attachment').attr('src', a)
                            } else if (types[i].startsWith('video')) {
                                return html('video')
                                    .class('attachment')
                                    .attr('controls', 1)
                                    .child('source')
                                        .attr('src', a)
                                        .attr('type', types[i])
                                        .up()
                            } else {
                                return html('a')
                                    .attr('target', '_blank')
                                    .txt(`Attachment ${i + 1} (${a})`)
                                    .attr('href', a)
                            }
                        })
                        .up()
                    .up()
                .up()
            .up()
    }
    document.getElementById("messageForm").classList.remove('disabled')
    msgArea.innerHTML = "";
    // :+1:

    msgArea.style.display = 'none'

    for (const msg of window.stores.sdlib.messages) {
        createMessage(msg)
    }
    msgArea.style.display = 'block'
    scrollToBottomOfElement(msgArea.parentElement);

    stores.sdlib.wsEvents.on("new_post", handleNewPost)

    const submitBtn = document.getElementById("send")

    submitBtn.onclick = function (event) { // using on(event) = ... instead of addEventListener("(event)", ...) because i cant be bothered to clear the event on channel change lol
        let msg = document.getElementById("messageInput").value;
        stores.sdlib.ws.send(JSON.stringify({
            command: "post",
            content: msg,
            replies: replies.map(p => p.id),
            attachments: attachments.map(a => a.url)
        }))
        replies = [];
        rednerReplyThingy()
        document.getElementById("messageInput").value = ""
    }

    document.getElementById('messageInput').addEventListener('keydown', event => {
        if (
            event.key == "Enter" &&
            !shiftHeld
        ) {
            event.preventDefault();
            if (!submitBtn.disabled) submitBtn.click();
        }
    })
}

export function onunload() {
    stores.sdlib.wsEvents.off('new_post', handleNewPost)
}