πŸ“’ Actions Speak Louder Than Words!

Webmentions and Hugo

Posted: Aug 28, 2021 | Reading time: 9 min
⚠️ Warning: This post is over a year old, the information may be out of date.
πŸ“’ I’ve moved to a new website. Please visit me at https://journal.robbi.my !
post

ToC

As mentioned previously, now I implemented WebMention on this website (Hugo) since I still think some people don’t like email but most people have social media such as Twitter, Mastodon, Facebook or owning a blog. Now with webmention you can just use you own blog or social media to leave a comment or react on my posts.

It’s a really basic implementation using webmention.io and PlaidWeb/webmention.js and maybe this is poorman implementation because it client side rendered. If you turn-off javascript, you will not be able to see Webmentions interaction when browsing here. Sorry about that…

Anyway.. implementation was super easy (trust me), the webmention approach on Jamie Tanna (jvt.me) website are my inspiration. I really like using spoiler/summary because it stay hidden by default. It much cleaner and formatted.

Let me show you how I able to integrate webmention on my website…


layouts/partials/webmention.html

Create a partial template, it better named it as webmention.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
{ $url := printf "%s" .Permalink }}
<div class="webmentions">
	<details>
		<summary class="text-center padding-bottom-04rem">(Webmentions)</summary>
		<p class="text-center">Below you can find the interactions that this page has had using Indieweb. Which means, you can mentioned this URL on any website that support <a href="http://indieweb.org/webmention">WebMention</a>. Have you written a <a href="https://indieweb.org/responses">response</a> to this post? Let me know the URL:</p>
		<div class="manual-webmention text-center">
			<form id="manual-webmention" action="https://webmention.io/robbinespu.gitlab.io/webmention" method="post">
				<input type="url" name="source" value="" />
				<input type="hidden" name="target" value="{{ $url }}" />
				<input type="submit" name="submit" value="Send" />
			</form>
			<p><small>Do you not have a website set up with WebMention capabilities? You can use <a href="https://commentpara.de/">Comment Parade</a>.</small></p>
		</div>
		<div id="webmentions">
			<noscript>
				This site uses client-side JavaScript to render the webmentions, rather than them being rendered server-side. If you do not wish to enable JavaScript, that's fair enough, but you won't be able to automatically see what Webmentions I've received - sorry!
			</noscript>
		</div>
	</details>
</div>

See my code above? change action value to your own webmention.io username

HTML head

Open your main html file for HTML head and paste code above before </head> closing tag

<!-- webmention -->
<link rel="webmention" href="https://webmention.io/robbinespu.gitlab.io/webmention" />
<link rel="pingback" href="https://webmention.io/robbinespu.gitlab.io/xmlrpc" />

Like I mentioned previously, change href value based your own webmention.io username.

static/js/webmention.js

now add webmention.js on your theme static directory

/* webmention.js
Simple thing for embedding webmentions from webmention.io into a page, client-side.
(c)2018 fluffy (http://beesbuzz.biz)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
GitHub repo (for latest released versions, issue tracking, etc.):
    http://github.com/PlaidWeb/webmention.js
Basic usage:
<script src="/path/to/webmention.js" data-param="val" ... async />
<div id="webmentions"></div>
Allowed parameters:
    page-url:
        The base URL to use for this page. Defaults to window.location
    add-urls:
        Additional URLs to check, separated by |s
    id:
        The HTML ID for the object to fill in with the webmention data.
        Defaults to "webmentions"
    wordcount:
        The maximum number of words to render in reply mentions.
    max-webmentions:
        The maximum number of mentions to retrieve. Defaults to 30.
    prevent-spoofing:
        By default, Webmentions render using the mf2 'url' element, which plays
        nicely with webmention bridges (such as brid.gy and telegraph)
        but allows certain spoofing attacks. If you would like to prevent
        spoofing, set this to 1.
    sort-by:
        What to order the responses by; defaults to 'published'. See
        https://github.com/aaronpk/webmention.io#api
    sort-dir:
        The order to sort the responses by; defaults to 'up' (i.e. oldest
        first). See https://github.com/aaronpk/webmention.io#api
A more detailed example:
<script src="/path/to/webmention.js"
    data-id="webmentionContainer"
    data-wordcount="30"
    data-prevent-spoofing="1"
    />
*/


(function () {
    "use strict";

    function getCfg(key, dfl) {
        return document.currentScript.getAttribute("data-" + key) || dfl;
    }

    var refurl = getCfg('page-url',
                        window.location.href.replace(/#.*$/, ''));
    var addurls = getCfg('add-urls', undefined);
    var containerID = getCfg('data-id', "webmentions");
    var textMaxWords = getCfg('wordcount');
    var maxWebmentions = getCfg('max-webmentions', 30);
    var mentionSource = getCfg('prevent-spoofing') ? 'wm-source' : 'url';
    var sortBy = getCfg('sort-by', 'published');
    var sortDir = getCfg('sort-dir', 'up');

    var reactTitle = {
        'in-reply-to': 'replied',
        'like-of': 'liked',
        'repost-of': 'reposted',
        'bookmark-of': 'bookmarked',
        'mention-of': 'mentioned',
        'rsvp': 'RSVPed',
        'follow-of': 'followed'
    };

    var reactEmoji = {
        'in-reply-to': 'πŸ’¬',
        'like-of': '❀️',
        'repost-of': 'πŸ”„',
        'bookmark-of': '⭐️',
        'mention-of': 'πŸ’¬',
        'rsvp': 'πŸ“…',
        'follow-of': '🐜'
    };

    var rsvpEmoji = {
        'yes': 'βœ…',
        'no': '❌',
        'interested': 'πŸ’‘',
        'maybe': 'πŸ’­'
    };

    function entities(text) {
        return text.replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    function reactImage(r) {
        var who = entities((r.author && r.author.name)
                           ? r.author.name
                           : r.url.split('/')[2]);
        var response = reactTitle[r['wm-property']] || 'reacted';
        var html = '<a class="reaction" rel="nofollow ugc" title="' + who + ' ' +
            response + '" href="' + r[mentionSource] + '">';
        if (r.author && r.author.photo) {
            html += '<img src="' + entities(r.author.photo) + '">';
        }
        html += (reactEmoji[r['wm-property']] || 'πŸ’₯');
        if (r.rsvp && rsvpEmoji[r.rsvp]) {
            html += '<sub>' + rsvpEmoji[r.rsvp] + '</sub>';
        }
        html += '</a>';

        return html;
    }

    // strip the protocol off a URL
    function stripurl(url) {
        return url.substr(url.indexOf('//'));
    }

    // Deduplicate multiple mentions from the same source URL
    function dedupe(mentions) {
        var filtered = [];
        var seen = {};

        mentions.forEach(function(r) {
            // Strip off the protocol (i.e. treat http and https the same)
            var source = stripurl(r.url);
            if (!seen[source]) {
                filtered.push(r);
                seen[source] = true;
            }
        });

        return filtered;
    }

    function formatComments(comments) {
        var html = '<h2>' + comments.length + ' Response' +
            (comments.length > 1 ? 's' : '') +
            '</h2><ul class="comments">';
        comments.forEach(function(c) {
            html += '<li>';

            html += reactImage(c);

            html += ' <a class="source" rel="nofollow ugc" href="' +
                c[mentionSource] + '">';
            if (c.author && c.author.name) {
                html += entities(c.author.name);
            } else {
                html += entities(c.url.split('/')[2]);
            }
            html += '</a>: ';

            var linkclass;
            var linktext;
            if (c.name) {
                linkclass = "name";
                linktext = c.name;
            } else if (c.content && c.content.text) {
                var text = entities(c.content.text);

                if (textMaxWords) {
                    var words = text.replace(/\s+/g,' ')
                        .split(' ', textMaxWords + 1);
                    if (words.length > textMaxWords) {
                        words[textMaxWords - 1] += '&hellip;';
                        words = words.slice(0, textMaxWords);
                        text = words.join(' ');
                    }
                }

                linkclass = "text";
                linktext = text;
            } else {
                linkclass = "name";
                linktext = "(mention)";
            }

            html += '<span class="' + linkclass + '">' + linktext + '</span>';

            html += '</li>';
        });
        html += '</ul>';

        return html;
    }

    function formatReactions(reacts) {
        var html = '<h2>' + reacts.length + ' Reaction' +
            (reacts.length > 1 ? 's' : '') +
            '</h2><ul class="reacts">';

        reacts.forEach(function(r) {
            html += reactImage(r);
        });

        return html;
    }

    function getData(url, callback) {
        if (window.fetch) {
            window.fetch(url).then(function(response) {
                if (response.status >= 200 && response.status < 300) {
                    return Promise.resolve(response);
                } else {
                    return Promise.reject(new Error(response.statusText));
                }
            }).then(function(response) {
                return response.json();
            }).then(callback).catch(function(error) {
                console.error("Request failed", error);
            });
        } else {
            var oReq = new XMLHttpRequest();
            oReq.onload = function(data) {
                callback(JSON.parse(data));
            };
            oReq.onerror = funcdata-max-webmentions

    window.addEventListener("load", function () {
        var contdata-max-webmentionsainer = document.getElementById(containerID);
        if (!container) {
            // no container, so do nothing
            return;
        }

        var pages = [stripurl(refurl)];
        if (!!addurls) {
            addurls.split('|').forEach(function (url) {
                pages.push(stripurl(url));
            })
        }

        var apiURL = 'https://webmention.io/api/mentions.jf2?per-page=' +
            maxWebmentions + '&sort-by=' + sortBy + '&sort-dir=' + sortDir;

        pages.forEach(function (path) {
            apiURL += '&target[]=' + encodeURIComponent('http:' + path) +
                '&target[]=' + encodeURIComponent('https:' + path);
        });

        getData(apiURL, function(json) {
            var html = '';

            var comments = [];
            var collects = [];

            var mapping = {
                "in-reply-to": comments,
                "like-of": collects,
                "repost-of": collects,
                "bookmark-of": collects,
                "mention-of": comments,
                "rsvp": comments
            };

            json.children.forEach(function(c) {
                var store = mapping[c['wm-property']];
                if (store) {
                    store.push(c);
                }
            });

            // format the comment-type things
            if (comments.length > 0) {
                html += formatComments(dedupe(comments));
            }

            // format the other reactions
            if (collects.length > 0) {
                html += formatReactions(dedupe(collects));
            }

            container.innerHTML = html;
        });
    });

}());

You may want to customize the emoji to be displayed. The source code on PlaidWeb/webmention.js Github.

Now add this code on you HTML footer (feel free to adjust data-max-webmentions value)

<script src="/js/webmention.js" data-id="webmentions" data-page-url="{{ .Permalink }}" data-max-webmentions="100"></script>

CSS

Ok the last thing you need here is CSS to style the output. I suggest you to inspect my website and take the value there, Since it quite mess (that why I don’t like become front-end developer) but for sake of sharing, I posted here my CSS. Feel free no modify and adapt on you Hugo theme.

/* webmention */
#webmentions {
  width: 100%;
  margin: 0 auto;
  position: relative;
  z-index: 100;
  line-height: 1.2em;
}

#webmentions .comments {
    overflow-x: hidden;
    font-size: 85%;
}

#webmentions h2 {
	font-size: 1.1em;
	margin: 0 0 5px 0;
    padding: 0 0 3px 0;
	border-bottom: 1px solid #e5e9f0;
}

#webmentions .reacts img {
    margin: 3px -1ex 1px 1px;
    max-height: 3em !important;
}

#webmentions ul {
    list-style-type: none;
    margin: 0;
    padding: 4px;
}

#webmentions li {
    text-indent: -1em;
    padding-left: 1em;
}
#webmentions a.source {
  font-weight: bold;
}

#webmentions a.reaction {
    position: relative;
    text-decoration: none;
    text-shadow: 0px 0px 3px white;
    margin-right: 0;
    letter-spacing: -1ex;
    margin-right: 1ex;
    border-bottom: none;
}

#webmentions a.reaction img {
    max-height: 0em;
}

#webmentions a.reaction sub {
    font-size: 50%;
}

#webmentions .comments li {
    padding-bottom: 1em;
    margin-bottom: 1em;
    border-bottom: 1px solid #d8dee9;
}

#webmentions .comments li:last-of-type {
    border-bottom: 0;
}

#webmentions .comments li .text {
    text-decoration: none;
}

#webmentions .comments li .name {
    color: #5e81ac;
}

#webmentions:empty {
    display: none;
}

That all! Easy right? I also don’t need to store this data and rebuilt hugo to make it appear since it run as client side. Like I told you previously, the drawback is JavaScript are needed to execute and do his job in behind.

We also have prepared a form for manually send response and for any website that don’t support webmention, don’t worry because you can use commentpara.de as alternative.

I think, as long webmention.io and PlaidWeb/webmention.js are available, this implementation will stay here. Honestly, I think this is great and every SSG (Static Site Generator) should implement it 😍

Edit

Have some thoughts, discussion or feedback on this post?
IndieWeb Interactions

Below you can find the interactions that this page has had using Indieweb. Which means, you can mentioned this URL on any website that support WebMention. Have you written a response to this post? Let me know the URL:

((Do you use a website that do not set up with WebMention capabilities? You can use Comment Parade.)


Mentions, bookmarks, likes and repost