Skip to content

Instantly share code, notes, and snippets.

@johanbove
Last active June 25, 2021 10:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save johanbove/c0707468d1828df9fbc8c64d0cff20b6 to your computer and use it in GitHub Desktop.
A one file Twtxt txt to HTML parser using markdown
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="none" />
<title>Twttxt</title>
<style>
body {
font-size: 16px;
}
time {
color: slateblue;
font-size: smaller;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
li {
padding: 0;
margin: 1rem;
display: flex;
}
p {
margin: 0;
}
.meta {
flex: 0 0 150px;
}
.message {
flex: 2;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</head>
<body>
<template id="a-tweet">
<li class="tweet">
<div class="meta">
<time class="timestamp"></time>
</div>
<div class="message"></div>
</li>
</template>
<h1>Twtxt Feed</h1>
<ul id="theTweets"></ul>
<script>
const parseData = function (data) {
const lines = data.split("\n");
const numLines = lines.length;
const tweets = [];
console.debug(`Retrieved ${numLines} lines...`);
const theTweets = document.getElementById("theTweets");
// Reverse the order without using Array.reverse()
for (let i = numLines - 1; i >= 0; i--) {
let line = lines[i];
let tweet;
// Exclude comments
if (
!line.length ||
line.indexOf("#") === 0 ||
line.indexOf("// follow") !== -1
) {
// start of e.g. time section, handled in nex loop
continue;
} else {
tweet = line.split("\t");
tweets.push(tweet);
let msg = tweet[1];
let timestamp = tweet[0];
let timestampDate = new Date(timestamp);
let tpl = document
.getElementById("a-tweet")
.content.cloneNode(true);
let timestampTpl = tpl.querySelector(".timestamp");
timestampTpl.innerText = timestampDate.toLocaleString();
timestampTpl.setAttribute("datetime", timestamp);
tpl.querySelector(".message").innerHTML = marked(msg);
theTweets.appendChild(tpl);
}
}
console.debug(`${tweets.length} tweets parsed.`);
};
const url = "./twtxt.txt";
const xhrDoc = new XMLHttpRequest();
xhrDoc.open("GET", url);
xhrDoc.onreadystatechange = function () {
console.debug("onreadystatechange", this);
if (this.readyState === 4) {
if (this.status === 200) {
const data = this.response;
parseData(data);
} else {
console.error(
`An error occured getting the data! readyState: ${this.readyState} status: ${this.status}.`
);
}
}
};
xhrDoc.send();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment