aboutsummaryrefslogtreecommitdiff
path: root/static/script.js
blob: afbb66eb58c05adee9cdf991187cffe52a2e0c69 (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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/* -------------------------------------------------- */

function round_time (time, fraction) {
    let scale = 1 / fraction;
    return Math.round (time * scale) / scale;
}

function time_to_percent (time) {
    // Decimal time
    return (time.getHours() + (time.getMinutes() / 60)) * 100/24 + "%"
}

function parents_until (element, obj) {
    if (element === null) {
        return null;
    } else if (element.id == obj.id || element.classList.contains(obj.class)) {
        return element;
    } else {
        return parents_until (element.parentElement, obj);
    }
}

function decimal_time_to_string (time) {
    let hour = Math.floor(time);
    if (hour < 10) {
        hour = '0' + hour;
    }
    var minute = String((time - Math.floor(time)) * 60).padStart(2, 0);
    return "" + hour + ":" + minute;
}

let gensym_counter = 0;
function gensym (prefix) {
    gensym_counter++;
    return prefix + gensym_counter;
}

/* start and end time for calendar page */
let start_time = new Date();
let end_time = new Date();

/* dynamicly created event when dragging */
let event;

let event_start = { x: NaN, y: NaN };

function create_event_down (e) {
    event_start.x = e.clientX;
    event_start.y = e.clientY;
}

function create_event_move (e) {

    if (e.buttons != 1) return;

    /* Create event when we start moving the mouse. */
    if (! event) {
        /* Small deadzone so tiny click and drags aren't registered */
        if (abs(event_start.x - e.clientX) < 10
            && abs(event_start.y - e.clientY) < 5)
        { return; }

        /* only allow start of dragging on background */
        if (e.target != this) return;

        /* only on left click */
        if (e.buttons != 1) return;

        /* [0, 1) -- where are we in the container */
        time = round_time(24 * (e.offsetY / this.clientHeight),
                          .25)

        event = document.createElement("div");
        event.style.top = time * 100/24 + "%";
        event.dataset.time1 = time;
        event.dataset.time2 = time;

        event.className = "event generated";
        event.style.pointerEvents = "none";
        event.style.width = "calc(100% * var(--editmode))";
        event.innerText = "New Event";

        event.dataset.date = this.id;

        /* Makes all current events transparent when dragging over them.
           Without this weird stuff happens when moving over them
        */
        for (let e of this.children) {
            e.style.pointerEvents = "none";
        }

        this.appendChild(event);
    }

    time2 = event.dataset.time2 =
        round_time(24 * (e.offsetY / event.parentElement.clientHeight),
                   .25);
    time1 = event.dataset.time1;
    if (time2 > time1) {
        event.style.bottom = (24 - time2) * 100/24 + "%";
        event.style.top = time1 * 100/24 + "%";
    } else {
        event.style.top = time2 * 100/24 + "%";
        event.style.bottom = (24 - time1) * 100/24 + "%";
    }
}

function create_event_finisher (callback) {
    return function create_event_up (e) {
        if (! event) return;
        let start = min(Number(event.dataset.time1), Number(event.dataset.time2));
        let end = max(Number(event.dataset.time1), Number(event.dataset.time2));

        /* Restore pointer events for all existing events.
           Allow pointer events on our new event
        */
        for (let e of event.parentElement.children) {
            e.style.pointerEvents = "";
        }

        let localevent = event;
        event = null;

        callback (localevent, start, end);

    }
}

// for debugging
let last_xml;

async function remove_event (element) {
    console.log(element);
    let xmltext = element.getElementsByClassName("xcal")[0].innerText;
    let parser = new DOMParser();
    let xml = parser.parseFromString(xmltext, "text/xml");

    // for debugging
    last_xml = xml;

    let uid = xml.querySelector("uid").textContent.trim()

    let data = new URLSearchParams();
    data.append('uid', uid);

    let response = await fetch ( '/remove', {
        method: 'POST',
        body: data
    });

    console.log(response);
}

function time_to_date (time) {
    return [ time.getFullYear(),
             String(time.getMonth() + 1).padStart(2, '0'),
             String(time.getDate()).padStart(2, '0') ].join("-");
}

var bar_object = false
var current_cell = false

function update_current_time_bar () {
    var now = new Date()
    /* TODO
       The bar and box doesn't get cleared when we leave our time interval.
    */
    if (! (start_time <= now.getTime() && now.getTime() < end_time))
        return;

    var event_area = document.getElementById(time_to_date(now))

    if (event_area) {
        if (bar_object) {
            bar_object.parentNode.removeChild(bar_object)
        } else {
            bar_object = document.createElement("div")
            bar_object.className = "event current-time"
            bar_object.id = "bar"
        }

        bar_object.style.top = time_to_percent(now)
        event_area.append(bar_object)
    }

    /* */

    if (current_cell) {
        current_cell.style.border = "";
    }
    current_cell = document.querySelector(
        ".small-calendar time[datetime='" + time_to_date(now) + "']");
    current_cell.style.border = "1px solid black";

    /* Update [today] button */

    document.getElementById("today-button").href
        = time_to_date(new Date) + ".html";
}

function min(a, b) {
    return a < b ? a : b;
}

function max(a, b) {
    return a > b ? a : b;
}

function abs(n) {
    return n < 0 ? - n : n;
}

function setVar(str, val) {
	document.documentElement.style.setProperty("--" + str, val);
}

function close_all_popups () {
    for (let popup of document.querySelectorAll(".popup-container.visible")) {
        close_popup(popup);
    }
}

function sxml_to_xml(doc, tree) {

    if (typeof(tree) == 'string') return tree;

    let [tag, ...body] = tree;
    let node = doc.createElement(tag);
    for (const child of body) {
        node.append(sxml_to_xml(doc, child));
    }
    return node;
}

// FormData
async function create_event (date, fd) {

    let tree = ['vevent',
                ['properties',
                 ['dtstart', ['date-time', date + "T" + fd.get("dtstart") + ":00"]],
                 ['dtend', ['date-time', date + "T" + fd.get("dtend") + ":00"]],
                 ['summary', ['text', fd.get("summary")]]]]

    if (fd.get("description")) {
        tree[1].push(['description', ['text', fd.get("description")]])
    }

    let xmldoc = document.implementation.createDocument("", "", null)
    xml = sxml_to_xml(xmldoc, tree).outerHTML;

    console.log(xml);


    let data = new URLSearchParams();
    data.append("cal", "Calendar");
    data.append("data", xml);

    let response = await fetch ( '/insert', {
        method: 'POST',
        body: data
    });

    console.log(response);

    let body = await response.text();
    console.log(body);
}

window.onload = function () {
    start_time.setTime(document.querySelector("meta[name='start-time']").content * 1000)
    end_time.setTime(document.querySelector("meta[name='end-time']").content * 1000)

    update_current_time_bar()
    // once a minute for now, could probably be slowed to every 10 minutes
    window.setInterval(update_current_time_bar, 1000 * 60)

    /* Is event creation active? */
    if (true) {
        for (let c of document.getElementsByClassName("events")) {
            c.onmousedown = create_event_down;
            c.onmousemove = create_event_move;
            c.onmouseup = create_event_finisher(
                function (event, start, end) {
                    let startstr = decimal_time_to_string(start);
                    let endstr = decimal_time_to_string(end);

                    let popupElement = document
                        .getElementById("popup-template")
                        .content
                        .cloneNode(true)
                        .firstChild ;
                    let id = gensym("popup-generated-");
                    popupElement.id = id
                    document.getElementsByClassName("root")[0].appendChild(popupElement);

                    popupElement.querySelector('input[name="dtstart"]').value = startstr;
                    popupElement.querySelector('input[name="dtend"]').value = endstr;

                    let form = popupElement.querySelector("form")
                    form.addEventListener("submit", function (ev) {
                        ev.preventDefault();
                        create_event(event.dataset.date, new FormData(form));
                    });

                    open_popup(popupElement);


                    /*
                    console.log(event);

                    alert("Creating event " + startstr + " - " + endstr);
                    */
                    popupElement.querySelector('input[name="summary"]').focus();
                });
        }
    }

    for (let el of document.getElementsByClassName("event")) {
        /* Popup script replaces need for anchors to events.
           On mobile they also have the problem that they make
           the whole page scroll there.
        */
        el.parentElement.removeAttribute("href");

        /* Bind all vcomponent properties into javascript. */
        el.properties = {}
        let children = el.getElementsByTagName("properties")[0].children;

        for (let child of children) {
            let field = child.tagName;


            lst = el.properties["_slot_" + field] = []
            for (let s of el.getElementsByClassName(field)) {
                lst.push(s);
            }
            for (let s of el.querySelectorAll(field + " > :not(parameters)")) {
                lst.push(s);
                el.properties["_value_" + field] = s.innerHTML;
            }

            Object.defineProperty(
                el.properties, field,
                {
                    get: function () {
                        return this["_value_" + field];
                    },
                    set: function (value) {
                        this["_value_" + field] = value;
                        for (let slot of el.properties["_slot_" + field]) {
                            slot.innerHTML = value;
                        }
                    }
                });
        }
    }

    document.onkeydown = function (evt) {
	evt = evt || window.event;
        if (! evt.key) return;
	if (evt.key.startsWith("Esc")) {
	    close_all_popups();
	}
    }


    /* Replace backend-driven [today] link with frontend, with one that gets
    correctly set in the frontend.
    Similarly, update the go to specific date button into a link which updates
    wheneven the date form updates.
    */

    let jumpto = document.getElementsByClassName("jump-to")[0];
    let gotodatebtn = jumpto.getElementsByTagName("button")[0];
    let golink = document.createElement("a");
    golink.classList.add("btn");
    let target_href = time_to_date(new Date) + ".html";
    document.getElementById("today-button").href = target_href;
    golink.href = target_href;
    golink.innerHTML = gotodatebtn.innerHTML;
    gotodatebtn.replaceWith(golink);

    jumpto.getElementsByTagName("input")[0].onchange = function () {
        let date = time_to_date(this.valueAsDate)
        golink.href = date + ".html";
    }

    /* ---------------------------------------- */

    /*
    xml.querySelector("summary text").innerHTML = "Pastahack";
    let serializer = new XMLSerializer();
    serializer.serializeToString(xml);
    */

}

function close_popup(popup) {
    popup.classList.remove("visible");
}

function open_popup(popup) {
    popup.classList.add("visible");
}

function toggle_popup(popup) {
    popup.classList.toggle("visible");
}

function toggle_child_popup(el) {
    let popup = el.getElementsByClassName("popup-container")[0];
    toggle_popup(popup);
}