-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
105 lines (81 loc) · 2.36 KB
/
script.js
File metadata and controls
105 lines (81 loc) · 2.36 KB
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
const app = document.querySelector("#quotes-app");
const title = document.querySelector("#page-title");
const count = document.querySelector("#quote-count");
async function loadQuotes() {
try {
const response = await fetch("./README.md", { cache: "no-store" });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const markdown = await response.text();
const { heading, quotes } = parseMarkdown(markdown);
if (heading) {
title.textContent = heading;
document.title = heading;
}
renderQuotes(quotes);
} catch (error) {
if (count) {
count.textContent = "Fehler beim Laden";
}
app.innerHTML = `<p class="status">Konnte <code>README.md</code> nicht laden. Starte die Seite über einen lokalen Server, damit <code>fetch()</code> funktioniert.</p>`;
console.error(error);
}
}
function parseMarkdown(markdown) {
const lines = markdown.split(/\r?\n/);
const quotes = [];
let heading = "";
let currentQuote = [];
const flushQuote = () => {
if (currentQuote.length === 0) {
return;
}
quotes.push(currentQuote.join(" ").trim());
currentQuote = [];
};
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line) {
flushQuote();
continue;
}
if (!heading && line.startsWith("# ")) {
heading = line.slice(2).trim();
continue;
}
if (line.startsWith(">")) {
currentQuote.push(line.replace(/^>\s?/, ""));
continue;
}
flushQuote();
}
flushQuote();
return { heading, quotes };
}
function renderQuotes(quotes) {
if (quotes.length === 0) {
if (count) {
count.textContent = "0 Zitate";
}
app.innerHTML = `<p class="status">Keine Zitate gefunden. Füge in <code>README.md</code> Zeilen mit <code>></code> hinzu.</p>`;
return;
}
const orderedQuotes = [...quotes].reverse();
if (count) {
count.textContent = `${orderedQuotes.length} Zitate`;
}
app.replaceChildren(
...orderedQuotes.map((quote, index) => {
const card = document.createElement("article");
card.className = "quote-card";
card.style.animationDelay = `${index * 70}ms`;
const paragraph = document.createElement("p");
paragraph.className = "quote-text";
paragraph.textContent = quote;
card.append(paragraph);
return card;
}),
);
}
loadQuotes();