Skip to content

Commit 36f3823

Browse files
committed
Attempt to shorten links if not shortened
This usually comes from non-Mastodon instances
1 parent a66a4e2 commit 36f3823

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/utils/enhance-content.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ function _enhanceContent(content, opts = {}) {
3737
links.forEach((link) => {
3838
if (/^https?:\/\//i.test(link.textContent.trim())) {
3939
link.classList.add('has-url-text');
40+
shortenLink(link);
4041
}
4142
});
4243
}
@@ -287,6 +288,30 @@ const defaultRejectFilter = [
287288
const defaultRejectFilterMap = Object.fromEntries(
288289
defaultRejectFilter.map((nodeName) => [nodeName, true]),
289290
);
291+
292+
const URL_PREFIX_REGEX = /^(https?:\/\/(www\.)?|xmpp:)/;
293+
const URL_DISPLAY_LENGTH = 30;
294+
// Similar to https://github.com/mastodon/mastodon/blob/1666b1955992e16f4605b414c6563ca25b3a3f18/app/lib/text_formatter.rb#L54-L69
295+
function shortenLink(link) {
296+
if (!link || link.querySelector?.('*')) {
297+
return;
298+
}
299+
try {
300+
const url = link.innerText.trim();
301+
const prefix = (url.match(URL_PREFIX_REGEX) || [])[0] || '';
302+
if (!prefix) return;
303+
const displayURL = url.slice(
304+
prefix.length,
305+
prefix.length + URL_DISPLAY_LENGTH,
306+
);
307+
const suffix = url.slice(prefix.length + URL_DISPLAY_LENGTH);
308+
const cutoff = url.slice(prefix.length).length > URL_DISPLAY_LENGTH;
309+
link.innerHTML = `<span class="invisible">${prefix}</span><span class=${
310+
cutoff ? 'ellipsis' : ''
311+
}>${displayURL}</span><span class="invisible">${suffix}</span>`;
312+
} catch (e) {}
313+
}
314+
290315
function extractTextNodes(dom, opts = {}) {
291316
const textNodes = [];
292317
const rejectFilterMap = Object.assign(

0 commit comments

Comments
 (0)