From 1c2af548d8020f9e19aa96bff085f56ca9876817 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Jaenisch?= Date: Thu, 8 Apr 2021 21:27:40 +0200 Subject: [PATCH] Rewrite data fetch using async/await. Refs #25 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: AndrΓ© Jaenisch --- static/webmention.js | 104 +++++++++++++++++++-------------------- static/webmention.min.js | 2 +- 2 files changed, 51 insertions(+), 55 deletions(-) diff --git a/static/webmention.js b/static/webmention.js index 73c2881..d4c35ac 100644 --- a/static/webmention.js +++ b/static/webmention.js @@ -368,25 +368,20 @@ A more detailed example: * Fetch the stored data. * * @param {string} url - * @param {*} callback + * @returns {Promise} */ - function getData(url, callback) { - 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) { + async function getData(url) { + try { + const response = await window.fetch(url); + if (response.status >= 200 && response.status < 300) { return response.json(); - }) - .then(callback) - .catch(function(error) { - console.error("Request failed", error); - }); + } else { + return Promise.reject(new Error(response.statusText)); + } + } catch(error) { + console.error("Request failed", error); + return Promise.reject(error); + } } /** @@ -418,47 +413,48 @@ A more detailed example: apiURL += `&target[]=${encodeURIComponent('http:' + path)}&target[]=${encodeURIComponent('https:' + path)}`; }); - getData(apiURL, function(/** @type {WebmentionResponse} */json) { - /** @type {Array} */ - let comments = []; - /** @type {Array} */ - const collects = []; - - if (commentsAreReactions) { - comments = collects; - } + getData(apiURL) + .then(function(/** @type {WebmentionResponse} */json) { + /** @type {Array} */ + let comments = []; + /** @type {Array} */ + const collects = []; - /** @type {Record>} */ - const mapping = { - "in-reply-to": comments, - "like-of": collects, - "repost-of": collects, - "bookmark-of": collects, - "mention-of": comments, - "rsvp": comments - }; - - json.children.forEach(function(child) { - // This seem to push the reaction into either comments or collects - const store = mapping[child['wm-property']]; - if (store) { - store.push(child); + if (commentsAreReactions) { + comments = collects; } - }); - // format the comment-type things - let formattedComments = ''; - if (comments.length > 0 && comments !== collects) { - formattedComments = formatComments(dedupe(comments)); - } + /** @type {Record>} */ + const mapping = { + "in-reply-to": comments, + "like-of": collects, + "repost-of": collects, + "bookmark-of": collects, + "mention-of": comments, + "rsvp": comments + }; + + json.children.forEach(function(child) { + // This seem to push the reaction into either comments or collects + const store = mapping[child['wm-property']]; + if (store) { + store.push(child); + } + }); + + // format the comment-type things + let formattedComments = ''; + if (comments.length > 0 && comments !== collects) { + formattedComments = formatComments(dedupe(comments)); + } - // format the other reactions - let reactions = ''; - if (collects.length > 0) { - reactions = formatReactions(dedupe(collects)); - } + // format the other reactions + let reactions = ''; + if (collects.length > 0) { + reactions = formatReactions(dedupe(collects)); + } - container.innerHTML = `${formattedComments}${reactions}`; - }); + container.innerHTML = `${formattedComments}${reactions}`; + }); }); }()); diff --git a/static/webmention.min.js b/static/webmention.min.js index 0f7d5d6..f363b4d 100644 --- a/static/webmention.min.js +++ b/static/webmention.min.js @@ -1 +1 @@ -!function(){"use strict";window.i18next=window.i18next||{t:function(n){return n}};const n=window.i18next.t.bind(window.i18next);function t(n,t){return document.currentScript.getAttribute("data-"+n)||t}const e=t("page-url",window.location.href.replace(/#.*$/,"")),o=t("add-urls",void 0),r=t("id","webmentions"),s=t("wordcount"),i=t("max-webmentions",30),c=t("prevent-spoofing")?"wm-source":"url",l=t("sort-by","published"),a=t("sort-dir","up"),u=t("comments-are-reactions"),p={"in-reply-to":n("replied"),"like-of":n("liked"),"repost-of":n("reposted"),"bookmark-of":n("bookmarked"),"mention-of":n("mentioned"),rsvp:n("RSVPed"),"follow-of":n("followed")},f={"in-reply-to":"πŸ’¬","like-of":"❀️","repost-of":"πŸ”„","bookmark-of":"⭐️","mention-of":"πŸ’¬",rsvp:"πŸ“…","follow-of":"🐜"},m={yes:"βœ…",no:"❌",interested:"πŸ’‘",maybe:"πŸ’­"};function d(n){return n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function h(t,e){const o=d(t.author?.name??t.url.split("/")[2]);let r=p[t["wm-property"]]||n("reacted");!e&&t.content&&t.content.text&&(r+=": "+g(t));let s="";t.author&&t.author.photo&&(s=`\n \n `);let i="";return t.rsvp&&m[t.rsvp]&&(i=`${m[t.rsvp]}`),`\n \n ${s}\n ${f[t["wm-property"]]||"πŸ’₯"}\n ${i}\n \n `}function w(n){return n.substr(n.indexOf("//"))}function $(n){const t=[],e={};return n.forEach((function(n){const o=w(n.url);e[o]||(t.push(n),e[o]=!0)})),t}function g(n){let t=d(n.content.text);if(s){let n=t.replace(/\s+/g," ").split(" ",s+1);n.length>s&&(n[s-1]+="…",n=n.slice(0,s),t=n.join(" "))}return t}window.addEventListener("load",(function(){const t=document.getElementById(r);if(!t)return;const s=[w(e)];o&&o.split("|").forEach((function(n){s.push(w(n))}));let p=`https://webmention.io/api/mentions.jf2?per-page=${i}&sort-by=${l}&sort-dir=${a}`;var f,m;s.forEach((function(n){p+=`&target[]=${encodeURIComponent("http:"+n)}&target[]=${encodeURIComponent("https:"+n)}`})),f=p,m=function(e){let o=[];const r=[];u&&(o=r);const s={"in-reply-to":o,"like-of":r,"repost-of":r,"bookmark-of":r,"mention-of":o,rsvp:o};e.children.forEach((function(n){const t=s[n["wm-property"]];t&&t.push(n)}));let i="";o.length>0&&o!==r&&(i=function(t){return`\n

${n("Responses")}

\n
    ${t.map((t=>{const e=h(t,!0);let o=d(t.url.split("/")[2]);t.author&&t.author.name&&(o=d(t.author.name));const r=`${o}`;let s="name",i=`(${n("mention")})`;return t.name?(s="name",i=t.name):t.content&&t.content.text&&(s="text",i=g(t)),`
  • ${e} ${r} ${i}
  • `})).join("")}
\n `}($(o)));let l="";r.length>0&&(l=`\n

' + t('Reactions') + '

\n
    ${$(r).map((n=>h(n))).join("")}
\n `),t.innerHTML=`${i}${l}`},window.fetch(f).then((function(n){return n.status>=200&&n.status<300?Promise.resolve(n):Promise.reject(new Error(n.statusText))})).then((function(n){return n.json()})).then(m).catch((function(n){console.error("Request failed",n)}))}))}(); \ No newline at end of file +!function(){"use strict";window.i18next=window.i18next||{t:function(n){return n}};const n=window.i18next.t.bind(window.i18next);function t(n,t){return document.currentScript.getAttribute("data-"+n)||t}const e=t("page-url",window.location.href.replace(/#.*$/,"")),o=t("add-urls",void 0),r=t("id","webmentions"),s=t("wordcount"),i=t("max-webmentions",30),c=t("prevent-spoofing")?"wm-source":"url",l=t("sort-by","published"),a=t("sort-dir","up"),u=t("comments-are-reactions"),p={"in-reply-to":n("replied"),"like-of":n("liked"),"repost-of":n("reposted"),"bookmark-of":n("bookmarked"),"mention-of":n("mentioned"),rsvp:n("RSVPed"),"follow-of":n("followed")},f={"in-reply-to":"πŸ’¬","like-of":"❀️","repost-of":"πŸ”„","bookmark-of":"⭐️","mention-of":"πŸ’¬",rsvp:"πŸ“…","follow-of":"🐜"},m={yes:"βœ…",no:"❌",interested:"πŸ’‘",maybe:"πŸ’­"};function d(n){return n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function h(t,e){const o=d(t.author?.name??t.url.split("/")[2]);let r=p[t["wm-property"]]||n("reacted");!e&&t.content&&t.content.text&&(r+=": "+g(t));let s="";t.author&&t.author.photo&&(s=`\n \n `);let i="";return t.rsvp&&m[t.rsvp]&&(i=`${m[t.rsvp]}`),`\n \n ${s}\n ${f[t["wm-property"]]||"πŸ’₯"}\n ${i}\n \n `}function w(n){return n.substr(n.indexOf("//"))}function $(n){const t=[],e={};return n.forEach((function(n){const o=w(n.url);e[o]||(t.push(n),e[o]=!0)})),t}function g(n){let t=d(n.content.text);if(s){let n=t.replace(/\s+/g," ").split(" ",s+1);n.length>s&&(n[s-1]+="…",n=n.slice(0,s),t=n.join(" "))}return t}window.addEventListener("load",(function(){const t=document.getElementById(r);if(!t)return;const s=[w(e)];o&&o.split("|").forEach((function(n){s.push(w(n))}));let p=`https://webmention.io/api/mentions.jf2?per-page=${i}&sort-by=${l}&sort-dir=${a}`;s.forEach((function(n){p+=`&target[]=${encodeURIComponent("http:"+n)}&target[]=${encodeURIComponent("https:"+n)}`})),async function(n){try{const t=await window.fetch(n);return t.status>=200&&t.status<300?t.json():Promise.reject(new Error(t.statusText))}catch(n){return console.error("Request failed",n),Promise.reject(n)}}(p).then((function(e){let o=[];const r=[];u&&(o=r);const s={"in-reply-to":o,"like-of":r,"repost-of":r,"bookmark-of":r,"mention-of":o,rsvp:o};e.children.forEach((function(n){const t=s[n["wm-property"]];t&&t.push(n)}));let i="";o.length>0&&o!==r&&(i=function(t){return`\n

${n("Responses")}

\n
    ${t.map((t=>{const e=h(t,!0);let o=d(t.url.split("/")[2]);t.author&&t.author.name&&(o=d(t.author.name));const r=`${o}`;let s="name",i=`(${n("mention")})`;return t.name?(s="name",i=t.name):t.content&&t.content.text&&(s="text",i=g(t)),`
  • ${e} ${r} ${i}
  • `})).join("")}
\n `}($(o)));let l="";r.length>0&&(l=`\n

' + t('Reactions') + '

\n
    ${$(r).map((n=>h(n))).join("")}
\n `),t.innerHTML=`${i}${l}`}))}))}(); \ No newline at end of file