summaryrefslogtreecommitdiff
path: root/public/js/writing_create.js
blob: dc737f8efef775ee1cb0d92b44705ee672bb7c89 (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
let dom = {};
let editorHistory = [];

document.addEventListener('DOMContentLoaded', () => {
    if (typeof marked === 'undefined') {
        console.error("marked lib not loaded");
        return;
    }

    initDOM();

    marked.use({ breaks: true });

    dom.inputText.addEventListener('input', () => {
        dom.contentPreview.innerHTML = marked.parse(dom.inputText.value);
    });

    // Restore autosaved draft
    const restoredContent = localStorage.getItem('writing_draft_content');
    if (restoredContent !== null) {
        const expiration = parseInt(localStorage.getItem('writing_draft_expiration') || '0');
        if (expiration < Date.now()) {
            localStorage.removeItem('writing_draft_content');
            localStorage.removeItem('writing_draft_expiration');
        } else {
            dom.inputText.value = restoredContent;
            dom.contentPreview.innerHTML = marked.parse(dom.inputText.value);
        }
    }

    // Periodically save contents to localStorage to prevent data loss
    setInterval(() => {
        localStorage.setItem('writing_draft_content', dom.inputText.value);
        localStorage.setItem('writing_draft_expiration', Date.now() + 1000 * 3600 * 96);
    }, 5000);

    // Clear draft on successful submit
    document.getElementById('writing-form')?.addEventListener('submit', () => {
        localStorage.removeItem('writing_draft_content');
        localStorage.removeItem('writing_draft_expiration');
    });
});

function initDOM() {
    dom.inputText       = document.getElementById('input_content');
    dom.contentPreview  = document.getElementById('content_preview');
    dom.findStr         = document.getElementById('input_findstr');
    dom.replaceStr      = document.getElementById('input_replacestr');
    dom.btnReplace      = document.getElementById('button_replace');
    dom.btnUndo         = document.getElementById('button_undo');
    dom.toggleMultiline = document.getElementById('input_multiline');

    dom.btnReplace.addEventListener('click', performReplace);
    dom.btnUndo.addEventListener('click', () => {
        if (editorHistory.length > 0) {
            dom.inputText.value = editorHistory.pop();
            dom.contentPreview.innerHTML = marked.parse(dom.inputText.value);
        }
    });
}

function performReplace() {
    // Save current state for undo
    editorHistory.push(dom.inputText.value);

    const flags = dom.toggleMultiline.checked ? 'gm' : 'g';
    const regex = new RegExp(dom.findStr.value, flags);
    dom.inputText.value = dom.inputText.value.replace(regex, dom.replaceStr.value);
    dom.contentPreview.innerHTML = marked.parse(dom.inputText.value);
};