summaryrefslogtreecommitdiff
path: root/article.js
blob: 723d97fc0193b279541732322d7346692b3f0781 (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
function addHeader() {
    const header = document.querySelector("header");
    
    const h1 = document.createElement('h1');
    h1.textContent = document.title;
    header.appendChild(h1);
    
    const time = document.createElement('time');
    const metaDate = document.querySelector('meta[property="article:published_time"]');
    const dateString = metaDate.getAttribute('content');
    const displayDate = (new Date(dateString)).toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
        timeZone: 'UTC'
    });
    time.setAttribute('datetime', dateString);
    time.textContent = displayDate;
    header.appendChild(time);

    const hr = document.createElement('hr');
    header.appendChild(hr);
}

function addTOC() {
    const tocDiv = document.getElementById("toc");
    if (!tocDiv) return;

    const tocHeading = document.createElement("h2");
    tocHeading.textContent = "Table of Contents";
    tocDiv.appendChild(tocHeading);

    const toc = document.createElement("ul");

    document.querySelectorAll('article :is(h1, h2, h3, h4, h5, h6):not(header *, #toc *)').forEach(heading => {
        const link = document.createElement("a");
        link.href = "#" + heading.id.toLowerCase();
        link.textContent = heading.textContent;

        const li = document.createElement("li");
        li.appendChild(link);

        toc.appendChild(li);
    });

    tocDiv.appendChild(toc);
}

document.addEventListener("DOMContentLoaded", () => {
    addHeader()
    addTOC()
})