Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Mastodon comments feature. Fixes #157 #158

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions code/purify.min.js

Large diffs are not rendered by default.

112 changes: 112 additions & 0 deletions www/assets/css/comments.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* ╭───────────────────────────────────────────────────────────────╮
* │ Comments │
* ╰───────────────────────────────────────────────────────────────╯
**/

#comments-wrapper {
margin: 1.5em 0;
padding: 0 var(25px);
}

.comment {
display: grid;
column-gap: 1rem;
grid-template-areas: "avatar name" "avatar time" "avatar post" "...... interactions";
grid-template-columns: min-content;
justify-items: start;
margin: 0 auto 0 -1em;
padding: .5em;
}

.comment.comment-reply {
margin: 0 auto 0 1em;
}

.comment .avatar-link {
grid-area: avatar;
height: 4rem;
position: relative;
width: 4rem;
}

.comment .avatar-link .avatar {
height: 100%;
width: 100%;
}

.comment .author {
align-items: center;
display: flex;
font-weight: 700;
gap: .5em;
grid-area: name;
}

.comment .author .instance {
background-color: var(--bg-accent);
color: var(--fg-accent);
border-radius: 9999px;
font-size: smaller;
font-weight: 400;
padding: .25em .75em;
}

.comment .author .instance:hover {
opacity: .8;
text-decoration: none;
}

.comment time {
grid-area: time;
line-height: 3.5rem;
}

.comment main {
grid-area: post;
}

.comment main p:first-child {
margin-top: .25em;
}

.comment main p:last-child {
margin-bottom: 0;
}

.comment footer {
grid-area: interactions;
border: none;
margin-top: 1em;
}

.comment footer .faves {
color: inheritE
}

.comment footer .faves:hover {
opacity: .8;
text-decoration: none;
}

.comment footer .faves::before {
color: red;
content: "♥";
font-size: 1rem;
margin-inline-end: .25em;
}

.comment .emoji {
display: inline;
height: 1.25em;
vertical-align: middle;
width: 1.25em;
}

.comment .invisible {
display: none;
}

.comment .ellipsis::after {
content: "…";
}
2 changes: 1 addition & 1 deletion www/assets/css/theme.css
Original file line number Diff line number Diff line change
Expand Up @@ -377,4 +377,4 @@ code { /* character, digrams, trigrams */
header + nav li:has(.active) a.active {
color: var(--fg-banner);
}
}
}
4 changes: 4 additions & 0 deletions www/content/articles/bienvenue.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ title = "Bienvenue chez les Ergonautes !"
date = 2024-03-18T22:01:23+01:00
author = "nuclear_squid"
tags = ["communauté"]
[comments]
host = "mastodon.social"
username = "fabi1cazenave"
id = 112124416010685631
+++

Après plus de quatre ans de travail et avec une version 1.0 en approche, il
Expand Down
4 changes: 4 additions & 0 deletions www/layouts/_default/single.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@
</p>
{{- end -}}

{{ with .Params.comments }}
{{ partial "comments.html" . }}
{{ end }}

{{ end }}
193 changes: 193 additions & 0 deletions www/layouts/partials/comments.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
{{- with resources.Get "css/comments.css" }}
{{- if eq hugo.Environment "development" }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{- else }}
{{- with . | minify | fingerprint }}
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
{{- end }}
{{- end }}
{{- end }}

{{- with resources.Get "js/purify.min.js" }}
{{- if eq hugo.Environment "development" }}
<script src="{{ relURL .RelPermalink }}" type="text/javascript"></script>
{{- else }}
{{- with . | minify | fingerprint }}
<script src="{{ relURL .RelPermalink }}" integrity="{{- .Data.Integrity }}" crossorigin="anonymous" type="text/javascript"></script>
{{- end }}
{{- end }}
{{- end }}

<section id="comments" class="article-content">
<h2>Commentaires</h2>
<p>Avec un compte sur le Fediverse ou Mastodon, vous pouvez répondre à ce <a
href="https://{{ .host }}/@{{ .username }}/{{ .id }}">post</a>. Mastodon étant décentralisé, vous pouvez utiliser
votre compte existant hébergé sur un autre serveur Mastodon ou une plateforme compatible si vous n'avez pas de
compte sur celui-ci.</p>

<p id="mastodon-comments-list"><button id="load-comment">Charger les commentaires</button></p>
<div id="comments-wrapper">
<noscript>
<p>Charger les commentaires nécessite JavaScript. Essayez d'activer Javascript et rechargez la page, ou visitez <a
href="https://{{ .host }}/@{{ .username }}/{{ .id }}">le post original</a> sur Mastodon.</p>
</noscript>
</div>
<noscript>Vous devez activer Javascript pour voir les commentaires.</noscript>
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This noscript tag is redundant, the one above is more detailed

<script type="text/javascript">
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moving the code to fetch the comments to a separate layout partial is a step in the right direction, but I would greatly prefer if this was in it’s own js file in ergol/code/comments.js.

You can use Hugo’s js.Build with a params dict to pass in values from the front matter to the js script.

Copy link
Author

@ClemABT ClemABT Apr 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was not able to pass Hugo variables to a separate js file, thanks for the tip, I will have a look

function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
function emojify(input, emojis) {
let output = input;

emojis.forEach(emoji => {
let picture = document.createElement("picture");

let source = document.createElement("source");
source.setAttribute("srcset", escapeHtml(emoji.url));
source.setAttribute("media", "(prefers-reduced-motion: no-preference)");

let img = document.createElement("img");
img.className = "emoji";
img.setAttribute("src", escapeHtml(emoji.static_url));
img.setAttribute("alt", `:${emoji.shortcode}:`);
img.setAttribute("title", `:${emoji.shortcode}:`);
img.setAttribute("width", "20");
img.setAttribute("height", "20");

picture.appendChild(source);
picture.appendChild(img);

output = output.replace(`:${emoji.shortcode}:`, picture.outerHTML);
});

return output;
}

function loadComments() {
let commentsWrapper = document.getElementById("comments-wrapper");
document.getElementById("load-comment").innerHTML = "Chargement";
fetch('https://{{ .host }}/api/v1/statuses/{{ .id }}/context')
.then(function (response) {
return response.json();
})
.then(function (data) {
let descendants = data['descendants'];
if (
descendants &&
Array.isArray(descendants) &&
descendants.length > 0
) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should really be an early return, with a few error messages in case it gets triggered, depending on the context (like no comments yet, fetch failed…)

commentsWrapper.innerHTML = "";

descendants.forEach(function (status) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is quite a bit of code needed to properly render a comment, so it could be nice to make it a web component. If it requires too much work on your end, we can leave this as is and I’ll come back to it later, it’s not that big a deal.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how to do it properly, so I will leave it to you if you don't mind.

if (status.account.display_name.length > 0) {
status.account.display_name = escapeHtml(status.account.display_name);
status.account.display_name = emojify(status.account.display_name, status.account.emojis);
} else {
status.account.display_name = status.account.username;
};

let instance = "";
if (status.account.acct.includes("@")) {
instance = status.account.acct.split("@")[1];
} else {
instance = "{{ .host }}";
}

const isReply = status.in_reply_to_id !== "{{ .id }}";

status.content = emojify(status.content, status.emojis);

let avatarSource = document.createElement("source");
avatarSource.setAttribute("srcset", escapeHtml(status.account.avatar));
avatarSource.setAttribute("media", "(prefers-reduced-motion: no-preference)");

let avatarImg = document.createElement("img");
avatarImg.className = "avatar";
avatarImg.setAttribute("src", escapeHtml(status.account.avatar_static));
avatarImg.setAttribute("alt", `@${status.account.username}@${instance} avatar`);

let avatarPicture = document.createElement("picture");
avatarPicture.appendChild(avatarSource);
avatarPicture.appendChild(avatarImg);

let avatar = document.createElement("a");
avatar.className = "avatar-link";
avatar.setAttribute("href", status.account.url);
avatar.setAttribute("rel", "external nofollow");
avatar.setAttribute("title", `Voir le profil sur @${status.account.username}@${instance}`);
avatar.appendChild(avatarPicture);

let instanceBadge = document.createElement("a");
instanceBadge.className = "instance";
instanceBadge.setAttribute("href", status.account.url);
instanceBadge.setAttribute("title", `@${status.account.username}@${instance}`);
instanceBadge.setAttribute("rel", "external nofollow");
instanceBadge.textContent = instance;

let display = document.createElement("span");
display.className = "display";
display.setAttribute("itemprop", "author");
display.setAttribute("itemtype", "http://schema.org/Person");
display.innerHTML = status.account.display_name;

let header = document.createElement("header");
header.className = "author";
header.appendChild(display);
header.appendChild(instanceBadge);

let permalink = document.createElement("a");
permalink.setAttribute("href", status.url);
permalink.setAttribute("itemprop", "url");
permalink.setAttribute("title", `Voir le commentaire sur ${instance}`);
permalink.setAttribute("rel", "external nofollow");
permalink.textContent = new Date(status.created_at).toLocaleString('fr-FR', {
dateStyle: "long",
timeStyle: "short",
});

let timestamp = document.createElement("time");
timestamp.setAttribute("datetime", status.created_at);
timestamp.appendChild(permalink);

let main = document.createElement("main");
main.setAttribute("itemprop", "text");
main.innerHTML = status.content;

let interactions = document.createElement("footer");
if (status.favourites_count > 0) {
let faves = document.createElement("a");
faves.className = "faves";
faves.setAttribute("href", `${status.url}/favourites`);
faves.setAttribute("title", `Favoris depuis ${instance}`);
faves.textContent = status.favourites_count;

interactions.appendChild(faves);
}

let comment = document.createElement("article");
comment.id = `comment-${status.id}`;
comment.className = isReply ? "comment comment-reply" : "comment";
comment.setAttribute("itemprop", "comment");
comment.setAttribute("itemtype", "http://schema.org/Comment");
comment.appendChild(avatar);
comment.appendChild(header);
comment.appendChild(timestamp);
comment.appendChild(main);
comment.appendChild(interactions);

commentsWrapper.innerHTML += DOMPurify.sanitize(comment.outerHTML);
});
}
document.getElementById("load-comment").innerHTML = "Charger les commentaires";
});
}
document.getElementById("load-comment").addEventListener("click", loadComments);
</script>
</section>