hugo-mastodon-api-comments/mastodon-api-comments.js

105 lines
3.1 KiB
JavaScript

/* globals MastodonAPI */
function fetch_mastodon_api_comments(instance, status_id)
{
const root = document.getElementById("mastodon-api-comments_" + status_id);
let api = new MastodonAPI(
{
instance: "https://" + instance,
api_user_token: ""
});
// Get the URL of the status and write the intro.
api.get("statuses/" + status_id, function(data)
{
root.appendChild(comments_intro(data.url));
});
// Get all the replies to the status and write them to the page.
api.get("statuses/" + status_id + "/context", function(data)
{
write_comments(root, data);
});
}
function comments_intro(url)
{
const p = document.createElement("p");
const a = document.createElement("a");
p.appendChild(document.createTextNode("You can "));
p.setAttribute("class", "mastodon-api-comment-intro");
a.setAttribute("href", url);
a.appendChild(
document.createTextNode("comment on this post in the Fediverse"));
p.appendChild(a);
p.appendChild(document.createTextNode("."));
return p;
}
function write_comments(root, data)
{
for (const status of data.descendants)
{
let content = status.content;
for (const emoji of status.emojis)
{
content = content.replace(
':' + emoji.shortcode + ':',
'<img style="height: 1em;" src="' + emoji.url + '">');
}
const div = document.createElement("div");
div.setAttribute("class", "mastodon-api-comment");
div.appendChild(author_html(status));
if (status.spoiler_text.length > 0)
{
div.appendChild(subject_html(status));
}
const content_p = document.createElement("p");
content_p.setAttribute("class", "mastodon-api-comment-content");
content_p.innerHTML = content;
div.appendChild(content_p);
root.appendChild(div);
}
}
function author_html(status)
{
const p = document.createElement("p");
p.setAttribute("class", "mastodon-api-comment-author");
const img = document.createElement("img");
img.setAttribute("class", "mastodon-api-comment-avatar");
img.setAttribute("src", status.account.avatar);
p.appendChild(img);
p.innerHTML += " ";
const strong = document.createElement("strong");
strong.appendChild(document.createTextNode(status.account.display_name));
p.appendChild(strong);
p.appendChild(
document.createTextNode(" (" + status.account.acct + ") wrote on "
+ get_status_time(status) + ":"));
return p;
}
function subject_html(status)
{
const p = document.createElement("p");
p.setAttribute("class", "mastodon-api-comment-subject");
const subject = document.createElement("strong");
subject.appendChild(document.createTextNode(status.spoiler_text));
p.appendChild(subject);
return p;
}
// Human readable time, YYYY-MM-DD HH:MM.
function get_status_time(status)
{
return status.created_at.substr(0, 16).replace('T', ' ');
}