Merge branch 'fix-url' into 'main'

Fix parsing of regular URLs

See merge request soapbox-pub/ditto!471
This commit is contained in:
Alex Gleason 2024-08-28 19:07:37 +00:00
commit 043e579c10
2 changed files with 32 additions and 22 deletions

View file

@ -10,7 +10,12 @@ Deno.test('parseNoteContent', () => {
assertEquals(firstUrl, undefined);
});
Deno.test('parseNoteContent handles apostrophes', () => {
Deno.test('parseNoteContent parses URLs', () => {
const { html } = parseNoteContent(`check out my website: https://alexgleason.me`, []);
assertEquals(html, 'check out my website: <a href="https://alexgleason.me">https://alexgleason.me</a>');
});
Deno.test('parseNoteContent parses mentions with apostrophes', () => {
const { html } = parseNoteContent(
`did you see nostr:nprofile1qqsqgc0uhmxycvm5gwvn944c7yfxnnxm0nyh8tt62zhrvtd3xkj8fhgprdmhxue69uhkwmr9v9ek7mnpw3hhytnyv4mz7un9d3shjqgcwaehxw309ahx7umywf5hvefwv9c8qtmjv4kxz7gpzemhxue69uhhyetvv9ujumt0wd68ytnsw43z7s3al0v's speech?`,
[{

View file

@ -33,31 +33,36 @@ function parseNoteContent(content: string, mentions: MastodonMention[]): ParsedN
return html`<a class="mention hashtag" href="${href}" rel="tag"><span>#</span>${tag}</a>`;
},
url: ({ attributes, content }) => {
try {
const { pathname } = new URL(content);
const match = pathname.match(new RegExp(`^${nip19.BECH32_REGEX.source}`));
if (match) {
const bech32 = match[0];
const extra = pathname.slice(bech32.length);
const decoded = nip19.decode(bech32);
const pubkey = getDecodedPubkey(decoded);
if (pubkey) {
const mention = mentions.find((m) => m.id === pubkey);
const npub = nip19.npubEncode(pubkey);
const acct = mention?.acct ?? npub;
const name = mention?.acct ?? npub.substring(0, 8);
const href = mention?.url ?? Conf.local(`/@${acct}`);
return html`<span class="h-card"><a class="u-url mention" href="${href}" rel="ugc">@<span>${name}</span></a></span>${extra}`;
const { protocol, pathname } = new URL(content);
if (protocol === 'nostr:') {
try {
const match = pathname.match(new RegExp(`^${nip19.BECH32_REGEX.source}`));
if (match) {
const bech32 = match[0];
const extra = pathname.slice(bech32.length);
const decoded = nip19.decode(bech32);
const pubkey = getDecodedPubkey(decoded);
if (pubkey) {
const mention = mentions.find((m) => m.id === pubkey);
const npub = nip19.npubEncode(pubkey);
const acct = mention?.acct ?? npub;
const name = mention?.acct ?? npub.substring(0, 8);
const href = mention?.url ?? Conf.local(`/@${acct}`);
return html`<span class="h-card"><a class="u-url mention" href="${href}" rel="ugc">@<span>${name}</span></a></span>${extra}`;
}
}
} catch {
// fallthrough
}
return content;
} catch {
const attr = Object.entries(attributes)
.map(([name, value]) => `${name}="${value}"`)
.join(' ');
return `<a ${attr}>${content}</a>`;
}
const attr = Object.entries(attributes)
.map(([name, value]) => `${name}="${value}"`)
.join(' ');
return `<a ${attr}>${content}</a>`;
},
},
}).replace(/\n+$/, '');