From 40a5d0a163c47a07f94040beaa86272e5412b018 Mon Sep 17 00:00:00 2001 From: "i.j" Date: Mon, 14 Aug 2023 10:49:52 +0000 Subject: [PATCH] Feature/link preview --- CHANGELOG | 9 +- README.md | 3 + src/mastodon-timeline.css | 52 +++- src/mastodon-timeline.js | 547 ++++++++++++++++++++-------------- src/mastodon-timeline.min.css | 2 +- src/mastodon-timeline.min.js | 2 +- 6 files changed, 390 insertions(+), 225 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 4060c2b..12d8bc3 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,8 @@ +v3.8.1 - 14/08/2023 +- Show preview card from link, photo or video URL +- Add description for the ALT attribute in images +- Improve JS comments + v3.8.0 - 04/08/2023 - Add spoiler/sensitive button for reblog content @@ -77,8 +82,8 @@ v1.5.3 - 23/05/2021 v1.5.2 - 22/05/2021 - Add avatar name -- Use id instead of css class for js selectors -- Rearrange functions in js +- Use id instead of css class for JS selectors +- Rearrange functions in JS v1.5.1 - 17/05/2021 - Add ellipses for long messages diff --git a/README.md b/README.md index c715ea2..bac9875 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,9 @@ hide_reblog: false, // Hide replies toots. Default: don't hide hide_replies: false, +// Hide preview for links. Default: don't hide +hide_preview_link: false, + // Converts Markdown symbol ">" at the beginning of a paragraph into a blockquote HTML tag (default: don't apply) markdown_blockquote: false, diff --git a/src/mastodon-timeline.css b/src/mastodon-timeline.css index d5d00c7..77df6d6 100644 --- a/src/mastodon-timeline.css +++ b/src/mastodon-timeline.css @@ -1,4 +1,4 @@ -/* Mastodon embed feed timeline v3.8.0 */ +/* Mastodon embed feed timeline v3.8.1 */ /* More info at: */ /* https://gitlab.com/idotj/mastodon-embed-feed-timeline */ @@ -40,7 +40,7 @@ html[data-theme="dark"] { text-decoration: none; color: var(--link-color); } -.mt-timeline a:hover { +.mt-timeline a:not(.toot-preview-link):hover { text-decoration: underline; } .mt-timeline::-webkit-scrollbar { @@ -78,7 +78,7 @@ html[data-theme="dark"] { /* Toot container */ .mt-toot { margin: 0.25rem; - padding: 1rem 0.5rem 2rem 4rem; + padding: 1rem 0.5rem 1.5rem 4rem; position: relative; min-height: 3.75rem; background-color: transparent; @@ -119,6 +119,7 @@ html[data-theme="dark"] { .mt-user { display: table; font-weight: 600; + margin-bottom: 1rem; } .mt-user > a { color: var(--content-text) !important; @@ -196,7 +197,7 @@ html[data-theme="dark"] { /* Medias */ .toot-media { overflow: hidden; - margin-bottom: 0.25rem; + margin-bottom: 0.5rem; } .toot-media-preview { position: relative; @@ -210,7 +211,7 @@ html[data-theme="dark"] { top: 50%; left: 50%; z-index: 1; - transform: translate(-50%, -50%); + transform: translate(-50%, -50%); } .toot-media-spoiler > img { filter: blur(2rem); @@ -239,6 +240,47 @@ html[data-theme="dark"] { text-align: center; } +/* Preview link */ +.toot-preview-link { + min-height: 4rem; + display: flex; + flex-direction: row; + + border: 1px solid var(--line-gray-color); + border-radius: 0.5rem; + color: var(--link-color); + font-size: 0.8rem; + margin: 1rem 0 0.5rem 0; + overflow: hidden; +} +.toot-preview-image { + width: 40%; + align-self: stretch; +} +.toot-preview-image img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; +} +.toot-preview-noImage { + width: 40%; + font-size: 1.5rem; + align-self: center; + text-align: center; +} +.toot-preview-content { + width: 60%; + display: flex; + align-self: center; + flex-direction: column; + padding: 0.5rem 1rem; + gap: 0.5rem; +} +.toot-preview-title { + font-weight: 600; +} + /* Spoiler button */ .spoiler-link { border-radius: 2px; diff --git a/src/mastodon-timeline.js b/src/mastodon-timeline.js index 03514c2..9f503dd 100644 --- a/src/mastodon-timeline.js +++ b/src/mastodon-timeline.js @@ -1,8 +1,13 @@ -// Mastodon embed feed timeline v3.8.0 -// More info at: -// https://gitlab.com/idotj/mastodon-embed-feed-timeline +/** + * Mastodon embed feed timeline v3.8.1 + * More info at: + * https://gitlab.com/idotj/mastodon-embed-feed-timeline + */ -// Timeline settings +/** + * Timeline settings + * Adjust these parameters to customize your timeline + */ window.addEventListener("load", () => { let mapi = new MastodonApi({ // Id of the
containing the timeline @@ -38,6 +43,9 @@ window.addEventListener("load", () => { // Hide replies toots. Default: don't hide hide_replies: false, + // Hide preview card if toot contains a link, photo or video from a URL. Default: don't hide + hide_preview_link: false, + // Converts Markdown symbol ">" at the beginning of a paragraph into a blockquote HTML tag (default: don't apply) markdown_blockquote: false, @@ -49,8 +57,13 @@ window.addEventListener("load", () => { }); }); -let MastodonApi = function (params_) { - // Endpoint access settings / default values +/** + * Set all variables with customized values or use default ones + * @param {object} params_ User customized values + * Trigger color theme function + * Trigger main function to build the timeline + */ +const MastodonApi = function (params_) { this.DEFAULT_THEME = params_.default_theme || "auto"; this.INSTANCE_URL = params_.instance_url; this.USER_ID = params_.user_id || ""; @@ -66,6 +79,10 @@ let MastodonApi = function (params_) { typeof params_.hide_reblog !== "undefined" ? params_.hide_reblog : false; this.HIDE_REPLIES = typeof params_.hide_replies !== "undefined" ? params_.hide_replies : false; + this.HIDE_PREVIEW_LINK = + typeof params_.hide_preview_link !== "undefined" + ? params_.hide_preview_link + : false; this.MARKDOWN_BLOCKQUOTE = typeof params_.markdown_blockquote !== "undefined" ? params_.markdown_blockquote @@ -73,24 +90,29 @@ let MastodonApi = function (params_) { this.TEXT_MAX_LINES = params_.text_max_lines || "0"; this.LINK_SEE_MORE = params_.link_see_more; - // Target selector this.mtBodyContainer = document.getElementById(params_.container_body_id); - // Apply selected appearance - this.applyTheme(); + this.setTheme(); - // Get the toots - this.getToots(); + this.buildTimeline(); }; -// Theme style -MastodonApi.prototype.applyTheme = function () { +/** + * Set the theme style choosen by user or browser/OS + */ +MastodonApi.prototype.setTheme = function () { + /** + * Set the theme value in the tag using the attribute "data-theme" + * @param {string} theme Type of theme to apply: dark or light + */ const setTheme = function (theme) { document.documentElement.setAttribute("data-theme", theme); }; + if (this.DEFAULT_THEME === "auto") { let systemTheme = window.matchMedia("(prefers-color-scheme: dark)"); systemTheme.matches ? setTheme("dark") : setTheme("light"); + // Update the theme if user change browser/OS preference systemTheme.addEventListener("change", (e) => { e.matches ? setTheme("dark") : setTheme("light"); }); @@ -99,8 +121,10 @@ MastodonApi.prototype.applyTheme = function () { } }; -// Listing toots function -MastodonApi.prototype.getToots = function () { +/** + * Listing toots function + */ +MastodonApi.prototype.buildTimeline = function () { let mapi = this; let requestURL = ""; @@ -131,7 +155,6 @@ MastodonApi.prototype.getToots = function () { // Empty the
container this.mtBodyContainer.innerHTML = ""; - // Add toots for (let i in jsonData) { // First filter (Public / Unlisted) if ( @@ -146,7 +169,7 @@ MastodonApi.prototype.getToots = function () { // Nothing here (Don't append toots) } else { // Format and append toots - appendToot.call(mapi, jsonData[i], i); + appendToot.call(mapi, jsonData[i], Number(i)); } } } @@ -192,197 +215,21 @@ MastodonApi.prototype.getToots = function () { this.mtBodyContainer.setAttribute("role", "none"); }); - // Inner function to add each toot content in container - let appendToot = function (status_, index) { - let avatar, user, content, url, date; - - if (status_.reblog) { - // BOOSTED toot - // Toot url - url = status_.reblog.url; - - // Boosted avatar - avatar = - '' + - '
' + - "
" + - '' + - status_.account.username + - " avatar" + - "" + - "
"; - - // User name and url - user = - '"; - - // Date - date = this.formatDate(status_.reblog.created_at); - } else { - // STANDARD toot - // Toot url - url = status_.url; - - // Avatar - avatar = - '' + - '' + - status_.account.username + - " avatar" + - "" + - ""; - - // User name and url - user = - '"; - - // Date - date = this.formatDate(status_.created_at); - } - - // Main text - let text_css = ""; - if (this.TEXT_MAX_LINES !== "0") { - text_css = "truncate"; - document.documentElement.style.setProperty( - "--text-max-lines", - this.TEXT_MAX_LINES - ); - } - - if (status_.spoiler_text !== "") { - content = - '
' + - status_.spoiler_text + - ' ' + - '
' + - this.formatTootText(status_.content) + - "
" + - "
"; - } else if ( - status_.reblog && - status_.reblog.content !== "" && - status_.reblog.spoiler_text !== "" - ) { - content = - '
' + - status_.reblog.spoiler_text + - ' ' + - '
' + - this.formatTootText(status_.reblog.content) + - "
" + - "
"; - } else if ( - status_.reblog && - status_.reblog.content !== "" && - status_.reblog.spoiler_text === "" - ) { - content = - '
' + - "
" + - this.formatTootText(status_.reblog.content) + - "
" + - "
"; - } else { - content = - '
' + - "
" + - this.formatTootText(status_.content) + - "
" + - "
"; - } - - // Media attachments - let media = ""; - if (status_.media_attachments.length > 0) { - for (let picid in status_.media_attachments) { - media = this.replaceMedias( - status_.media_attachments[picid], - status_.sensitive - ); - } - } - if (status_.reblog && status_.reblog.media_attachments.length > 0) { - for (let picid in status_.reblog.media_attachments) { - media = this.replaceMedias( - status_.reblog.media_attachments[picid], - status_.reblog.sensitive - ); - } - } - - // Poll - let poll = ""; - let pollOption = ""; - if (status_.poll) { - for (let i in status_.poll.options) { - pollOption += "
  • " + status_.poll.options[i].title + "
  • "; - } - poll = - '
    ' + "
      " + pollOption + "
    " + "
    "; - } - - // Date - let timestamp = - '
    ' + - '' + - date + - "" + - "
    "; - - // Add all to main toot container - let toot = - '
    ' + - avatar + - user + - content + - media + - poll + - timestamp + - "
    "; - - this.mtBodyContainer.insertAdjacentHTML("beforeend", toot); + /** + * Inner function to add each toot in timeline container + * @param {object} c Toot content + * @param {number} i Index of toot + */ + const appendToot = function (c, i) { + this.mtBodyContainer.insertAdjacentHTML( + "beforeend", + this.assambleToot(c, i) + ); }; // Toot interactions this.mtBodyContainer.addEventListener("click", function (e) { - // Check if clicked in a toot + // Check if toot cointainer was clicked if ( e.target.localName == "article" || e.target.offsetParent.localName == "article" || @@ -390,7 +237,7 @@ MastodonApi.prototype.getToots = function () { ) { openTootURL(e); } - // Check if clicked in Show More/Less button + // Check if Show More/Less button was clicked if ( e.target.localName == "button" && e.target.className == "spoiler-link" @@ -399,26 +246,33 @@ MastodonApi.prototype.getToots = function () { } }); this.mtBodyContainer.addEventListener("keydown", function (e) { - // Check if Enter key pressed with focus in an article + // Check if Enter key was pressed with focus in an article if (e.key === "Enter" && e.target.localName == "article") { openTootURL(e); } }); - // Open Toot in a new page avoiding any other natural link + /** + * Open toot in a new page avoiding any other natural link + * @param {event} e User interaction trigger + */ const openTootURL = function (e) { let urlToot = e.target.closest(".mt-toot").dataset.location; if ( e.target.localName !== "a" && e.target.localName !== "span" && e.target.localName !== "button" && + e.target.parentNode.className !== "toot-preview-image" && urlToot ) { window.open(urlToot, "_blank"); } }; - // Spoiler button + /** + * Spoiler button + * @param {event} e User interaction trigger + */ const toogleSpoiler = function (e) { const nextSibling = e.target.nextSibling; if (nextSibling.localName === "img") { @@ -443,7 +297,206 @@ MastodonApi.prototype.getToots = function () { }; }; -// Handle text changes made to Toots +/** + * Build toot structure + * @param {object} c Toot content + * @param {number} i Index of toot + */ +MastodonApi.prototype.assambleToot = function (c, i) { + let avatar, user, content, url, date; + + if (c.reblog) { + // BOOSTED toot + // Toot url + url = c.reblog.url; + + // Boosted avatar + avatar = + '' + + '
    ' + + "
    " + + '' + + c.account.username + + " avatar" + + "" + + "
    "; + + // User name and url + user = + '"; + + // Date + date = this.formatDate(c.reblog.created_at); + } else { + // STANDARD toot + // Toot url + url = c.url; + + // Avatar + avatar = + '' + + '' + + c.account.username + + " avatar" + + "" + + ""; + + // User name and url + user = + '"; + + // Date + date = this.formatDate(c.created_at); + } + + // Main text + let text_css = ""; + if (this.TEXT_MAX_LINES !== "0") { + text_css = "truncate"; + document.documentElement.style.setProperty( + "--text-max-lines", + this.TEXT_MAX_LINES + ); + } + + if (c.spoiler_text !== "") { + content = + '
    ' + + c.spoiler_text + + ' ' + + '
    ' + + this.formatTootText(c.content) + + "
    " + + "
    "; + } else if ( + c.reblog && + c.reblog.content !== "" && + c.reblog.spoiler_text !== "" + ) { + content = + '
    ' + + c.reblog.spoiler_text + + ' ' + + '
    ' + + this.formatTootText(c.reblog.content) + + "
    " + + "
    "; + } else if ( + c.reblog && + c.reblog.content !== "" && + c.reblog.spoiler_text === "" + ) { + content = + '
    ' + + "
    " + + this.formatTootText(c.reblog.content) + + "
    " + + "
    "; + } else { + content = + '
    ' + + "
    " + + this.formatTootText(c.content) + + "
    " + + "
    "; + } + + // Media attachments + let media = ""; + if (c.media_attachments.length > 0) { + for (let picid in c.media_attachments) { + media = this.placeMedias(c.media_attachments[picid], c.sensitive); + } + } + if (c.reblog && c.reblog.media_attachments.length > 0) { + for (let picid in c.reblog.media_attachments) { + media = this.placeMedias( + c.reblog.media_attachments[picid], + c.reblog.sensitive + ); + } + } + + // Preview link + let preview_link = ""; + if (!this.HIDE_PREVIEW_LINK && c.card) { + preview_link = this.placePreviewLink(c.card); + } + + // Poll + let poll = ""; + let pollOption = ""; + if (c.poll) { + for (let i in c.poll.options) { + pollOption += "
  • " + c.poll.options[i].title + "
  • "; + } + poll = '
    ' + "
      " + pollOption + "
    " + "
    "; + } + + // Date + const timestamp = + '
    ' + + '' + + date + + "" + + "
    "; + + // Add all to main toot container + const toot = + '
    ' + + avatar + + user + + content + + media + + preview_link + + poll + + timestamp + + "
    "; + + return toot; +}; + +/** + * Handle text changes made to toots + * @param {string} c Text content + * @returns {string} Text content modified + */ MastodonApi.prototype.formatTootText = function (c) { let content = c; @@ -464,17 +517,30 @@ MastodonApi.prototype.formatTootText = function (c) { return content; }; -// Add target="_blank" to all #hashtags and @mentions +/** + * Add target="_blank" to all #hashtags and @mentions in the toot + * @param {string} c Text content + * @returns {string} Text content modified + */ MastodonApi.prototype.addTarget2hashtagMention = function (c) { let content = c.replaceAll('rel="tag"', 'rel="tag" target="_blank"'); content = content.replaceAll( 'class="u-url mention"', 'class="u-url mention" target="_blank"' ); + return content; }; -// Find all start/end and replace them by another start/end +/** + * Find all start/end and replace them by another start/end + * @param {string} c Text content + * @param {string} initialTagOpen Start HTML tag to replace + * @param {string} initialTagClose End HTML tag to replace + * @param {string} replacedTagOpen New start HTML tag + * @param {string} replacedTagClose New end HTML tag + * @returns {string} Text in HTML format + */ MastodonApi.prototype.replaceHTMLtag = function ( c, initialTagOpen, @@ -484,14 +550,20 @@ MastodonApi.prototype.replaceHTMLtag = function ( ) { if (c.includes(initialTagOpen)) { const regex = new RegExp(initialTagOpen + "(.*?)" + initialTagClose, "gi"); + return c.replace(regex, replacedTagOpen + "$1" + replacedTagClose); } else { return c; } }; -// Place media -MastodonApi.prototype.replaceMedias = function (m, s) { +/** + * Place media + * @param {object} m Media content + * @param {boolean} s Spoiler/Sensitive status + * @returns {string} Media in HTML format + */ +MastodonApi.prototype.placeMedias = function (m, s) { let spoiler = s || false; const pic = '
    Show content' : "") + '' + + '" alt="' + + (m.description ? m.description : "") + + '" loading="lazy" />' + "
    "; return pic; }; -// Format date +/** + * Place preview link + * @param {object} c Preview link content + * @returns {string} Preview link in HTML format + */ +MastodonApi.prototype.placePreviewLink = function (c) { + let card = + '' + + (c.image + ? '
    ' + : '
    📄
    ') + + "
    " + + '
    ' + + (c.provider_name + ? '' + c.provider_name + "" + : "") + + '' + + c.title + + "" + + (c.author_name + ? 'By ' + c.author_name + "" + : "") + + "
    " + + "
    "; + + return card; +}; + +/** + * Format date + * @param {string} d Date in ISO format (YYYY-MM-DDTHH:mm:ss.sssZ) + * @returns {string} Date formated (MM DD, YYYY) + */ MastodonApi.prototype.formatDate = function (d) { const monthNames = [ "Jan", @@ -535,11 +645,16 @@ MastodonApi.prototype.formatDate = function (d) { return displayDate; }; -// Loading spinner +/** + * Loading spinner + * @param {object} e Image containing the spinner + */ const removeSpinner = function (e) { const spinnerCSS = "loading-spinner"; + // Find closest parent container (1st, 2nd or 3rd level) let spinnerContainer = e.closest("." + spinnerCSS); + if (spinnerContainer) { spinnerContainer.classList.remove(spinnerCSS); } diff --git a/src/mastodon-timeline.min.css b/src/mastodon-timeline.min.css index ea683b5..1204aee 100644 --- a/src/mastodon-timeline.min.css +++ b/src/mastodon-timeline.min.css @@ -1 +1 @@ -:root{--text-max-lines:none}:root,html[data-theme=light]{--bg-color:#fff;--bg-hover-color:#d9e1e8;--line-gray-color:#c0cdd9;--content-text:#000;--link-color:#3a3bff;--error-text-color:#8b0000}html[data-theme=dark]{--bg-color:#282c37;--bg-hover-color:#313543;--line-gray-color:#393f4f;--content-text:#fff;--link-color:#8c8dff;--error-text-color:#fe6c6c}.mt-timeline{height:100%;overflow-y:auto;position:relative;background:var(--bg-color);scrollbar-color:var(--bg-hover-color) rgba(0,0,0,.1)}.mt-timeline a,.mt-timeline a:active,.mt-timeline a:link{text-decoration:none;color:var(--link-color)}.mt-timeline a:hover{text-decoration:underline}.mt-timeline::-webkit-scrollbar{width:.75rem;height:.75rem}.mt-timeline::-webkit-scrollbar-corner{background:0 0}.mt-timeline::-webkit-scrollbar-thumb{border:0 var(--content-text);border-radius:2rem;background:var(--bg-hover-color)}.mt-timeline::-webkit-scrollbar-track{border:0 var(--content-text);border-radius:0;background:rgba(0,0,0,.1)}.mt-body{padding:1rem 1.5rem;white-space:pre-wrap;word-wrap:break-word}.mt-body .invisible{font-size:0;line-height:0;display:inline-block;width:0;height:0;position:absolute}.mt-toot{margin:.25rem;padding:1rem .5rem 2rem 4rem;position:relative;min-height:3.75rem;background-color:transparent;border-bottom:1px solid var(--line-gray-color)}.mt-toot:focus,.mt-toot:hover{cursor:pointer;background-color:var(--bg-hover-color)}.mt-toot p:last-child{margin-bottom:0}.mt-avatar{position:absolute;top:1rem;left:5px;width:3rem;height:3rem;background-repeat:no-repeat;background-position:50% 50%;background-size:contain;background-color:var(--bg-color);border-radius:5px}.mt-avatar-boosted{width:2.5rem;height:2.5rem}.mt-avatar-booster{width:1.5rem;height:1.5rem;top:1.5rem;left:1.5rem}.mt-user{display:table;font-weight:600}.mt-user>a{color:var(--content-text)!important}.toot-text{margin-bottom:.25rem;color:var(--content-text)}.toot-text .spoiler-link{display:inline-block}.toot-text .spoiler-text-hidden{display:none}.toot-text.truncate{display:-webkit-box;overflow:hidden;-webkit-line-clamp:var(--text-max-lines);-webkit-box-orient:vertical}.toot-text:not(.truncate) .ellipsis::after{content:"..."}.toot-text blockquote{border-left:4px solid var(--line-gray-color);margin-left:0;padding-left:8px}.mt-error{position:absolute;display:flex;flex-direction:column;height:calc(100% - 3.5rem);width:calc(100% - 4.5rem);justify-content:center;align-items:center;color:var(--error-text-color);padding:.75rem;text-align:center}.mt-error-icon{font-size:2rem}.mt-error-message{padding:1rem 0}.toot-poll{margin-bottom:.25rem;color:var(--content-text)}.toot-poll ul{list-style:none;padding:0;margin:0}.toot-poll ul li{font-size:.9rem;margin-bottom:.5rem}.toot-poll ul li:not(:last-child){margin-bottom:.25rem}.toot-poll ul li:before{content:"◯";padding-right:.5rem}.toot-media{overflow:hidden;margin-bottom:.25rem}.toot-media-preview{position:relative;margin-top:.25rem;height:auto;text-align:center;width:100%}.toot-media>.spoiler-link{position:absolute;top:50%;left:50%;z-index:1;transform:translate(-50%,-50%)}.toot-media-spoiler>img{filter:blur(2rem)}.toot-media-preview a{display:block;position:absolute;top:0;right:0;bottom:0;left:0}.img-ratio14_7{position:relative;padding-top:56.95%;width:100%}.img-ratio14_7>img{width:100%;height:auto;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center}.spoiler-link{border-radius:2px;background-color:var(--line-gray-color);border:0;color:var(--content-text);font-weight:700;font-size:.7rem;padding:0 .35rem;text-transform:uppercase;line-height:1.25rem;cursor:pointer;vertical-align:top}.toot-date{font-size:.75rem}.mt-body>.loading-spinner{position:absolute;width:3rem;height:3rem;margin:auto;top:calc(50% - 1.5rem);right:calc(50% - 1.5rem)}.loading-spinner{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns:svg='http://www.w3.org/2000/svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.0' viewBox='0 0 128 128' %3E%3Cg%3E%3Cpath d='M64 128A64 64 0 0 1 18.34 19.16L21.16 22a60 60 0 1 0 52.8-17.17l.62-3.95A64 64 0 0 1 64 128z' fill='%23404040'/%3E%3CanimateTransform attributeName='transform' type='rotate' from='0 64 64' to='360 64 64' dur='1000ms' repeatCount='indefinite'%3E%3C/animateTransform%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;background-position:center center;background-color:transparent;background-size:min(2.5rem,calc(100% - .5rem))}.mt-footer{margin:1rem auto 2rem auto;padding:0 2rem;text-align:center}.visually-hidden{position:absolute!important;width:1px!important;height:1px!important;padding:0!important;margin:-1px!important;overflow:hidden!important;clip:rect(0,0,0,0)!important;white-space:nowrap!important;border:0!important} \ No newline at end of file +:root{--text-max-lines:none}:root,html[data-theme=light]{--bg-color:#fff;--bg-hover-color:#d9e1e8;--line-gray-color:#c0cdd9;--content-text:#000;--link-color:#3a3bff;--error-text-color:#8b0000}html[data-theme=dark]{--bg-color:#282c37;--bg-hover-color:#313543;--line-gray-color:#393f4f;--content-text:#fff;--link-color:#8c8dff;--error-text-color:#fe6c6c}.mt-timeline{height:100%;overflow-y:auto;position:relative;background:var(--bg-color);scrollbar-color:var(--bg-hover-color) rgba(0,0,0,.1)}.mt-timeline a,.mt-timeline a:active,.mt-timeline a:link{text-decoration:none;color:var(--link-color)}.mt-timeline a:not(.toot-preview-link):hover{text-decoration:underline}.mt-timeline::-webkit-scrollbar{width:.75rem;height:.75rem}.mt-timeline::-webkit-scrollbar-corner{background:0 0}.mt-timeline::-webkit-scrollbar-thumb{border:0 var(--content-text);border-radius:2rem;background:var(--bg-hover-color)}.mt-timeline::-webkit-scrollbar-track{border:0 var(--content-text);border-radius:0;background:rgba(0,0,0,.1)}.mt-body{padding:1rem 1.5rem;white-space:pre-wrap;word-wrap:break-word}.mt-body .invisible{font-size:0;line-height:0;display:inline-block;width:0;height:0;position:absolute}.mt-toot{margin:.25rem;padding:1rem .5rem 1.5rem 4rem;position:relative;min-height:3.75rem;background-color:transparent;border-bottom:1px solid var(--line-gray-color)}.mt-toot:focus,.mt-toot:hover{cursor:pointer;background-color:var(--bg-hover-color)}.mt-toot p:last-child{margin-bottom:0}.mt-avatar{position:absolute;top:1rem;left:5px;width:3rem;height:3rem;background-repeat:no-repeat;background-position:50% 50%;background-size:contain;background-color:var(--bg-color);border-radius:5px}.mt-avatar-boosted{width:2.5rem;height:2.5rem}.mt-avatar-booster{width:1.5rem;height:1.5rem;top:1.5rem;left:1.5rem}.mt-user{display:table;font-weight:600;margin-bottom:1rem}.mt-user>a{color:var(--content-text)!important}.toot-text{margin-bottom:.25rem;color:var(--content-text)}.toot-text .spoiler-link{display:inline-block}.toot-text .spoiler-text-hidden{display:none}.toot-text.truncate{display:-webkit-box;overflow:hidden;-webkit-line-clamp:var(--text-max-lines);-webkit-box-orient:vertical}.toot-text:not(.truncate) .ellipsis::after{content:"..."}.toot-text blockquote{border-left:4px solid var(--line-gray-color);margin-left:0;padding-left:8px}.mt-error{position:absolute;display:flex;flex-direction:column;height:calc(100% - 3.5rem);width:calc(100% - 4.5rem);justify-content:center;align-items:center;color:var(--error-text-color);padding:.75rem;text-align:center}.mt-error-icon{font-size:2rem}.mt-error-message{padding:1rem 0}.toot-poll{margin-bottom:.25rem;color:var(--content-text)}.toot-poll ul{list-style:none;padding:0;margin:0}.toot-poll ul li{font-size:.9rem;margin-bottom:.5rem}.toot-poll ul li:not(:last-child){margin-bottom:.25rem}.toot-poll ul li:before{content:"◯";padding-right:.5rem}.toot-media{overflow:hidden;margin-bottom:.5rem}.toot-media-preview{position:relative;margin-top:.25rem;height:auto;text-align:center;width:100%}.toot-media>.spoiler-link{position:absolute;top:50%;left:50%;z-index:1;transform:translate(-50%,-50%)}.toot-media-spoiler>img{filter:blur(2rem)}.toot-media-preview a{display:block;position:absolute;top:0;right:0;bottom:0;left:0}.img-ratio14_7{position:relative;padding-top:56.95%;width:100%}.img-ratio14_7>img{width:100%;height:auto;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center}.toot-preview-link{min-height:4rem;display:flex;flex-direction:row;border:1px solid var(--line-gray-color);border-radius:.5rem;color:var(--link-color);font-size:.8rem;margin:1rem 0 .5rem 0;overflow:hidden}.toot-preview-image{width:40%;align-self:stretch}.toot-preview-image img{display:block;width:100%;height:100%;object-fit:cover}.toot-preview-noImage{width:40%;font-size:1.5rem;align-self:center;text-align:center}.toot-preview-content{width:60%;display:flex;align-self:center;flex-direction:column;padding:.5rem 1rem;gap:.5rem}.toot-preview-title{font-weight:600}.spoiler-link{border-radius:2px;background-color:var(--line-gray-color);border:0;color:var(--content-text);font-weight:700;font-size:.7rem;padding:0 .35rem;text-transform:uppercase;line-height:1.25rem;cursor:pointer;vertical-align:top}.toot-date{font-size:.75rem}.mt-body>.loading-spinner{position:absolute;width:3rem;height:3rem;margin:auto;top:calc(50% - 1.5rem);right:calc(50% - 1.5rem)}.loading-spinner{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns:svg='http://www.w3.org/2000/svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.0' viewBox='0 0 128 128' %3E%3Cg%3E%3Cpath d='M64 128A64 64 0 0 1 18.34 19.16L21.16 22a60 60 0 1 0 52.8-17.17l.62-3.95A64 64 0 0 1 64 128z' fill='%23404040'/%3E%3CanimateTransform attributeName='transform' type='rotate' from='0 64 64' to='360 64 64' dur='1000ms' repeatCount='indefinite'%3E%3C/animateTransform%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;background-position:center center;background-color:transparent;background-size:min(2.5rem,calc(100% - .5rem))}.mt-footer{margin:1rem auto 2rem auto;padding:0 2rem;text-align:center}.visually-hidden{position:absolute!important;width:1px!important;height:1px!important;padding:0!important;margin:-1px!important;overflow:hidden!important;clip:rect(0,0,0,0)!important;white-space:nowrap!important;border:0!important} \ No newline at end of file diff --git a/src/mastodon-timeline.min.js b/src/mastodon-timeline.min.js index 59dbcde..83f1640 100644 --- a/src/mastodon-timeline.min.js +++ b/src/mastodon-timeline.min.js @@ -1 +1 @@ -window.addEventListener("load",()=>{new MastodonApi({container_body_id:"mt-body",default_theme:"auto",instance_url:"https://mastodon.online",timeline_type:"local",user_id:"",profile_name:"",hashtag_name:"",toots_limit:"20",hide_unlisted:!1,hide_reblog:!1,hide_replies:!1,markdown_blockquote:!1,text_max_lines:"0",link_see_more:"See more posts at Mastodon"})});let MastodonApi=function(t){this.DEFAULT_THEME=t.default_theme||"auto",this.INSTANCE_URL=t.instance_url,this.USER_ID=t.user_id||"",this.PROFILE_NAME=this.USER_ID?t.profile_name:"",this.TIMELINE_TYPE=t.timeline_type||"local",this.HASHTAG_NAME=t.hashtag_name||"",this.TOOTS_LIMIT=t.toots_limit||"20",this.HIDE_UNLISTED=void 0!==t.hide_unlisted&&t.hide_unlisted,this.HIDE_REBLOG=void 0!==t.hide_reblog&&t.hide_reblog,this.HIDE_REPLIES=void 0!==t.hide_replies&&t.hide_replies,this.MARKDOWN_BLOCKQUOTE=void 0!==t.markdown_blockquote&&t.markdown_blockquote,this.TEXT_MAX_LINES=t.text_max_lines||"0",this.LINK_SEE_MORE=t.link_see_more,this.mtBodyContainer=document.getElementById(t.container_body_id),this.applyTheme(),this.getToots()};MastodonApi.prototype.applyTheme=function(){let t=function(t){document.documentElement.setAttribute("data-theme",t)};if("auto"===this.DEFAULT_THEME){let e=window.matchMedia("(prefers-color-scheme: dark)");e.matches?t("dark"):t("light"),e.addEventListener("change",e=>{e.matches?t("dark"):t("light")})}else t(this.DEFAULT_THEME)},MastodonApi.prototype.getToots=function(){let t=this,e="";"profile"===this.TIMELINE_TYPE?e=`${this.INSTANCE_URL}/api/v1/accounts/${this.USER_ID}/statuses?limit=${this.TOOTS_LIMIT}`:"hashtag"===this.TIMELINE_TYPE?e=`${this.INSTANCE_URL}/api/v1/timelines/tag/${this.HASHTAG_NAME}?limit=${this.TOOTS_LIMIT}`:"local"===this.TIMELINE_TYPE&&(e=`${this.INSTANCE_URL}/api/v1/timelines/public?local=true&limit=${this.TOOTS_LIMIT}`),fetch(e,{method:"get"}).then(t=>{if(t.ok)return t.json();if(404===t.status)throw Error("404 Not found",{cause:t});throw Error(t.status)}).then(e=>{for(let a in this.mtBodyContainer.innerHTML="",e)("public"==e[a].visibility||!this.HIDE_UNLISTED&&"unlisted"==e[a].visibility)&&(t.HIDE_REBLOG&&e[a].reblog||t.HIDE_REPLIES&&e[a].in_reply_to_id||o.call(t,e[a],a));if(""===this.mtBodyContainer.innerHTML)this.mtBodyContainer.setAttribute("role","none"),this.mtBodyContainer.innerHTML='
    \uD83D\uDCED
    Sorry, no toots to show
    Got '+e.length+' toots from the server but due to the "hide filters" applied, no toot is shown
    ';else if(t.LINK_SEE_MORE){let i="";"profile"===this.TIMELINE_TYPE?i=t.PROFILE_NAME:"hashtag"===this.TIMELINE_TYPE?i="tags/"+this.HASHTAG_NAME:"local"===this.TIMELINE_TYPE&&(i="public/local");let s='";this.mtBodyContainer.parentNode.insertAdjacentHTML("beforeend",s)}}).catch(t=>{this.mtBodyContainer.innerHTML='

    Sorry, request failed:
    '+t+"
    ",this.mtBodyContainer.setAttribute("role","none")});let o=function(t,e){let o,a,i,s,r;t.reblog?(s=t.reblog.url,o='
    '+t.account.username+" avatar
    ",a='',r=this.formatDate(t.reblog.created_at)):(s=t.url,o=''+t.account.username+" avatar",a='',r=this.formatDate(t.created_at));let n="";"0"!==this.TEXT_MAX_LINES&&(n="truncate",document.documentElement.style.setProperty("--text-max-lines",this.TEXT_MAX_LINES)),i=""!==t.spoiler_text?'
    '+t.spoiler_text+'
    '+this.formatTootText(t.content)+"
    ":t.reblog&&""!==t.reblog.content&&""!==t.reblog.spoiler_text?'
    '+t.reblog.spoiler_text+'
    '+this.formatTootText(t.reblog.content)+"
    ":t.reblog&&""!==t.reblog.content&&""===t.reblog.spoiler_text?'
    '+this.formatTootText(t.reblog.content)+"
    ":'
    '+this.formatTootText(t.content)+"
    ";let l="";if(t.media_attachments.length>0)for(let d in t.media_attachments)l=this.replaceMedias(t.media_attachments[d],t.sensitive);if(t.reblog&&t.reblog.media_attachments.length>0)for(let c in t.reblog.media_attachments)l=this.replaceMedias(t.reblog.media_attachments[c],t.reblog.sensitive);let h="",m="";if(t.poll){for(let p in t.poll.options)m+="
  • "+t.poll.options[p].title+"
  • ";h='
      '+m+"
    "}let u='",g='
    '+o+a+i+l+h+u+"
    ";this.mtBodyContainer.insertAdjacentHTML("beforeend",g)};this.mtBodyContainer.addEventListener("click",function(t){("article"==t.target.localName||"article"==t.target.offsetParent.localName||"img"==t.target.localName)&&a(t),"button"==t.target.localName&&"spoiler-link"==t.target.className&&i(t)}),this.mtBodyContainer.addEventListener("keydown",function(t){"Enter"===t.key&&"article"==t.target.localName&&a(t)});let a=function(t){let e=t.target.closest(".mt-toot").dataset.location;"a"!==t.target.localName&&"span"!==t.target.localName&&"button"!==t.target.localName&&e&&window.open(e,"_blank")},i=function(t){let e=t.target.nextSibling;"img"===e.localName?(t.target.parentNode.classList.remove("toot-media-spoiler"),t.target.style.display="none"):(e.classList.contains("spoiler-text-hidden")||e.classList.contains("spoiler-text-visible"))&&("Show more"==t.target.textContent?(e.classList.remove("spoiler-text-hidden"),e.classList.add("spoiler-text-visible"),t.target.setAttribute("aria-expanded","true"),t.target.textContent="Show less"):(e.classList.remove("spoiler-text-visible"),e.classList.add("spoiler-text-hidden"),t.target.setAttribute("aria-expanded","false"),t.target.textContent="Show more"))}},MastodonApi.prototype.formatTootText=function(t){let e=t;return e=this.addTarget2hashtagMention(e),this.MARKDOWN_BLOCKQUOTE&&(e=this.replaceHTMLtag(e,"

    >","

    ","

    ","

    ")),e},MastodonApi.prototype.addTarget2hashtagMention=function(t){let e=t.replaceAll('rel="tag"','rel="tag" target="_blank"');return e.replaceAll('class="u-url mention"','class="u-url mention" target="_blank"')},MastodonApi.prototype.replaceHTMLtag=function(t,e,o,a,i){if(!t.includes(e))return t;{let s=RegExp(e+"(.*?)"+o,"gi");return t.replace(s,a+"$1"+i)}},MastodonApi.prototype.replaceMedias=function(t,e){let o=e||!1,a='
    '+(o?'':"")+'
    ';return a},MastodonApi.prototype.formatDate=function(t){let e=new Date(t),o=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",][e.getMonth()]+" "+e.getDate()+", "+e.getFullYear();return o};const removeSpinner=function(t){let e="loading-spinner",o=t.closest("."+e);o&&o.classList.remove(e)}; \ No newline at end of file +window.addEventListener("load",()=>{new MastodonApi({container_body_id:"mt-body",default_theme:"auto",instance_url:"https://mastodon.online",timeline_type:"local",user_id:"",profile_name:"",hashtag_name:"",toots_limit:"20",hide_unlisted:!1,hide_reblog:!1,hide_replies:!1,hide_preview_link:!1,markdown_blockquote:!1,text_max_lines:"0",link_see_more:"See more posts at Mastodon"})});const MastodonApi=function(t){this.DEFAULT_THEME=t.default_theme||"auto",this.INSTANCE_URL=t.instance_url,this.USER_ID=t.user_id||"",this.PROFILE_NAME=this.USER_ID?t.profile_name:"",this.TIMELINE_TYPE=t.timeline_type||"local",this.HASHTAG_NAME=t.hashtag_name||"",this.TOOTS_LIMIT=t.toots_limit||"20",this.HIDE_UNLISTED=void 0!==t.hide_unlisted&&t.hide_unlisted,this.HIDE_REBLOG=void 0!==t.hide_reblog&&t.hide_reblog,this.HIDE_REPLIES=void 0!==t.hide_replies&&t.hide_replies,this.HIDE_PREVIEW_LINK=void 0!==t.hide_preview_link&&t.hide_preview_link,this.MARKDOWN_BLOCKQUOTE=void 0!==t.markdown_blockquote&&t.markdown_blockquote,this.TEXT_MAX_LINES=t.text_max_lines||"0",this.LINK_SEE_MORE=t.link_see_more,this.mtBodyContainer=document.getElementById(t.container_body_id),this.setTheme(),this.buildTimeline()};MastodonApi.prototype.setTheme=function(){let t=function(t){document.documentElement.setAttribute("data-theme",t)};if("auto"===this.DEFAULT_THEME){let e=window.matchMedia("(prefers-color-scheme: dark)");e.matches?t("dark"):t("light"),e.addEventListener("change",e=>{e.matches?t("dark"):t("light")})}else t(this.DEFAULT_THEME)},MastodonApi.prototype.buildTimeline=function(){let t=this,e="";"profile"===this.TIMELINE_TYPE?e=`${this.INSTANCE_URL}/api/v1/accounts/${this.USER_ID}/statuses?limit=${this.TOOTS_LIMIT}`:"hashtag"===this.TIMELINE_TYPE?e=`${this.INSTANCE_URL}/api/v1/timelines/tag/${this.HASHTAG_NAME}?limit=${this.TOOTS_LIMIT}`:"local"===this.TIMELINE_TYPE&&(e=`${this.INSTANCE_URL}/api/v1/timelines/public?local=true&limit=${this.TOOTS_LIMIT}`),fetch(e,{method:"get"}).then(t=>{if(t.ok)return t.json();if(404===t.status)throw Error("404 Not found",{cause:t});throw Error(t.status)}).then(e=>{for(let a in this.mtBodyContainer.innerHTML="",e)("public"==e[a].visibility||!this.HIDE_UNLISTED&&"unlisted"==e[a].visibility)&&(t.HIDE_REBLOG&&e[a].reblog||t.HIDE_REPLIES&&e[a].in_reply_to_id||o.call(t,e[a],Number(a)));if(""===this.mtBodyContainer.innerHTML)this.mtBodyContainer.setAttribute("role","none"),this.mtBodyContainer.innerHTML='
    \uD83D\uDCED
    Sorry, no toots to show
    Got '+e.length+' toots from the server but due to the "hide filters" applied, no toot is shown
    ';else if(t.LINK_SEE_MORE){let i="";"profile"===this.TIMELINE_TYPE?i=t.PROFILE_NAME:"hashtag"===this.TIMELINE_TYPE?i="tags/"+this.HASHTAG_NAME:"local"===this.TIMELINE_TYPE&&(i="public/local");let r='";this.mtBodyContainer.parentNode.insertAdjacentHTML("beforeend",r)}}).catch(t=>{this.mtBodyContainer.innerHTML='

    Sorry, request failed:
    '+t+"
    ",this.mtBodyContainer.setAttribute("role","none")});let o=function(t,e){this.mtBodyContainer.insertAdjacentHTML("beforeend",this.assambleToot(t,e))};this.mtBodyContainer.addEventListener("click",function(t){("article"==t.target.localName||"article"==t.target.offsetParent.localName||"img"==t.target.localName)&&a(t),"button"==t.target.localName&&"spoiler-link"==t.target.className&&i(t)}),this.mtBodyContainer.addEventListener("keydown",function(t){"Enter"===t.key&&"article"==t.target.localName&&a(t)});let a=function(t){let e=t.target.closest(".mt-toot").dataset.location;"a"!==t.target.localName&&"span"!==t.target.localName&&"button"!==t.target.localName&&"toot-preview-image"!==t.target.parentNode.className&&e&&window.open(e,"_blank")},i=function(t){let e=t.target.nextSibling;"img"===e.localName?(t.target.parentNode.classList.remove("toot-media-spoiler"),t.target.style.display="none"):(e.classList.contains("spoiler-text-hidden")||e.classList.contains("spoiler-text-visible"))&&("Show more"==t.target.textContent?(e.classList.remove("spoiler-text-hidden"),e.classList.add("spoiler-text-visible"),t.target.setAttribute("aria-expanded","true"),t.target.textContent="Show less"):(e.classList.remove("spoiler-text-visible"),e.classList.add("spoiler-text-hidden"),t.target.setAttribute("aria-expanded","false"),t.target.textContent="Show more"))}},MastodonApi.prototype.assambleToot=function(t,e){let o,a,i,r,s;t.reblog?(r=t.reblog.url,o='
    '+t.account.username+" avatar
    ",a='',s=this.formatDate(t.reblog.created_at)):(r=t.url,o=''+t.account.username+" avatar",a='',s=this.formatDate(t.created_at));let n="";"0"!==this.TEXT_MAX_LINES&&(n="truncate",document.documentElement.style.setProperty("--text-max-lines",this.TEXT_MAX_LINES)),i=""!==t.spoiler_text?'
    '+t.spoiler_text+'
    '+this.formatTootText(t.content)+"
    ":t.reblog&&""!==t.reblog.content&&""!==t.reblog.spoiler_text?'
    '+t.reblog.spoiler_text+'
    '+this.formatTootText(t.reblog.content)+"
    ":t.reblog&&""!==t.reblog.content&&""===t.reblog.spoiler_text?'
    '+this.formatTootText(t.reblog.content)+"
    ":'
    '+this.formatTootText(t.content)+"
    ";let l="";if(t.media_attachments.length>0)for(let d in t.media_attachments)l=this.placeMedias(t.media_attachments[d],t.sensitive);if(t.reblog&&t.reblog.media_attachments.length>0)for(let c in t.reblog.media_attachments)l=this.placeMedias(t.reblog.media_attachments[c],t.reblog.sensitive);let p="";!this.HIDE_PREVIEW_LINK&&t.card&&(p=this.placePreviewLink(t.card));let h="",m="";if(t.poll){for(let u in t.poll.options)m+="
  • "+t.poll.options[u].title+"
  • ";h='
      '+m+"
    "}let g='",v='
    '+o+a+i+l+p+h+g+"
    ";return v},MastodonApi.prototype.formatTootText=function(t){let e=t;return e=this.addTarget2hashtagMention(e),this.MARKDOWN_BLOCKQUOTE&&(e=this.replaceHTMLtag(e,"

    >","

    ","

    ","

    ")),e},MastodonApi.prototype.addTarget2hashtagMention=function(t){let e=t.replaceAll('rel="tag"','rel="tag" target="_blank"');return e.replaceAll('class="u-url mention"','class="u-url mention" target="_blank"')},MastodonApi.prototype.replaceHTMLtag=function(t,e,o,a,i){if(!t.includes(e))return t;{let r=RegExp(e+"(.*?)"+o,"gi");return t.replace(r,a+"$1"+i)}},MastodonApi.prototype.placeMedias=function(t,e){let o=e||!1,a='
    '+(o?'':"")+''+(t.description?t.description:
    ';return a},MastodonApi.prototype.placePreviewLink=function(t){return''+(t.image?'
    ':'
    \uD83D\uDCC4
    ')+'
    '+(t.provider_name?''+t.provider_name+"":"")+''+t.title+""+(t.author_name?'By '+t.author_name+"":"")+"
    "},MastodonApi.prototype.formatDate=function(t){let e=new Date(t),o=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",][e.getMonth()]+" "+e.getDate()+", "+e.getFullYear();return o};const removeSpinner=function(t){let e="loading-spinner",o=t.closest("."+e);o&&o.classList.remove(e)}; \ No newline at end of file