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 all 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
163 changes: 163 additions & 0 deletions code/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import * as params from '@params';

function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.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://${params.host}/api/v1/statuses/${params.id}/context`)
.then(function (response) {
return response.json();
})
.then(function (data) {
document.getElementById("load-comment").innerHTML = "Charger les commentaires";

if (data.error) {
commentsWrapper.innerHTML = "Une erreur est survenue pendant le chargement des commentaires.";
return;
}

let descendants = data['descendants'];
if (!descendants || !Array.isArray(descendants) || descendants.length <= 0) {
commentsWrapper.innerHTML = "Pas encore de commentaires.";
return;
}

commentsWrapper.innerHTML = "";

descendants.forEach(function (status) {
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 = params.host;
}

const isReply = status.in_reply_to_id !== params.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").addEventListener("click", loadComments);
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 }}
46 changes: 46 additions & 0 deletions www/layouts/partials/comments.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{{- 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>

{{- with resources.Get "js/comments.js" | js.Build (dict "params" (dict "host" .host "id" .id)) }}
{{- 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>