Fix parsing of regular URLs

This commit is contained in:
Alex Gleason 2024-08-28 20:59:38 +02:00
parent cde70e4c8f
commit a63b838195
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
2 changed files with 32 additions and 22 deletions

View file

@ -10,7 +10,12 @@ Deno.test('parseNoteContent', () => {
assertEquals(firstUrl, undefined); 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( const { html } = parseNoteContent(
`did you see nostr:nprofile1qqsqgc0uhmxycvm5gwvn944c7yfxnnxm0nyh8tt62zhrvtd3xkj8fhgprdmhxue69uhkwmr9v9ek7mnpw3hhytnyv4mz7un9d3shjqgcwaehxw309ahx7umywf5hvefwv9c8qtmjv4kxz7gpzemhxue69uhhyetvv9ujumt0wd68ytnsw43z7s3al0v's speech?`, `did you see nostr:nprofile1qqsqgc0uhmxycvm5gwvn944c7yfxnnxm0nyh8tt62zhrvtd3xkj8fhgprdmhxue69uhkwmr9v9ek7mnpw3hhytnyv4mz7un9d3shjqgcwaehxw309ahx7umywf5hvefwv9c8qtmjv4kxz7gpzemhxue69uhhyetvv9ujumt0wd68ytnsw43z7s3al0v's speech?`,
[{ [{

View file

@ -33,8 +33,10 @@ function parseNoteContent(content: string, mentions: MastodonMention[]): ParsedN
return html`<a class="mention hashtag" href="${href}" rel="tag"><span>#</span>${tag}</a>`; return html`<a class="mention hashtag" href="${href}" rel="tag"><span>#</span>${tag}</a>`;
}, },
url: ({ attributes, content }) => { url: ({ attributes, content }) => {
const { protocol, pathname } = new URL(content);
if (protocol === 'nostr:') {
try { try {
const { pathname } = new URL(content);
const match = pathname.match(new RegExp(`^${nip19.BECH32_REGEX.source}`)); const match = pathname.match(new RegExp(`^${nip19.BECH32_REGEX.source}`));
if (match) { if (match) {
const bech32 = match[0]; const bech32 = match[0];
@ -50,14 +52,17 @@ function parseNoteContent(content: string, mentions: MastodonMention[]): ParsedN
return html`<span class="h-card"><a class="u-url mention" href="${href}" rel="ugc">@<span>${name}</span></a></span>${extra}`; return html`<span class="h-card"><a class="u-url mention" href="${href}" rel="ugc">@<span>${name}</span></a></span>${extra}`;
} }
} }
return content;
} catch { } catch {
// fallthrough
}
return content;
}
const attr = Object.entries(attributes) const attr = Object.entries(attributes)
.map(([name, value]) => `${name}="${value}"`) .map(([name, value]) => `${name}="${value}"`)
.join(' '); .join(' ');
return `<a ${attr}>${content}</a>`; return `<a ${attr}>${content}</a>`;
}
}, },
}, },
}).replace(/\n+$/, ''); }).replace(/\n+$/, '');