From e3b849543140a9d3772fd96820ebdf67c32c3a5c Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 16 Nov 2018 21:30:01 +0900 Subject: [PATCH] [MFM] Better URL parsing --- src/mfm/parse/elements/url.ts | 6 ++++-- test/mfm.ts | 33 +++++++++++++++++++++++++++++---- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/mfm/parse/elements/url.ts b/src/mfm/parse/elements/url.ts index c711ca023..411f2ebfa 100644 --- a/src/mfm/parse/elements/url.ts +++ b/src/mfm/parse/elements/url.ts @@ -9,9 +9,11 @@ export type TextElementUrl = { }; export default function(text: string) { - const match = text.match(/^https?:\/\/[\w\/:%#@\$&\?!\(\)\[\]~\.=\+\-]+/); + const match = text.match(/^https?:\/\/[\w\/:%#@\$&\?!\(\)\[\]~\.,=\+\-]+/); if (!match) return null; - const url = match[0]; + let url = match[0]; + if (url.endsWith('.')) url = url.substr(0, url.lastIndexOf('.')); + if (url.endsWith(',')) url = url.substr(0, url.lastIndexOf(',')); return { type: 'url', content: url, diff --git a/test/mfm.ts b/test/mfm.ts index 7bd81a2a6..27d0ffe66 100644 --- a/test/mfm.ts +++ b/test/mfm.ts @@ -160,12 +160,37 @@ describe('Text', () => { }); it('url', () => { - const tokens = analyze('https://himasaku.net'); + const tokens1 = analyze('https://example.com'); assert.deepEqual([{ type: 'url', - content: 'https://himasaku.net', - url: 'https://himasaku.net' - }], tokens); + content: 'https://example.com', + url: 'https://example.com' + }], tokens1); + + const tokens2 = analyze('https://example.com.'); + assert.deepEqual([{ + type: 'url', + content: 'https://example.com', + url: 'https://example.com' + }, { + type: 'text', content: '.' + }], tokens2); + + const tokens3 = analyze('https://example.com/foo?bar=a,b'); + assert.deepEqual([{ + type: 'url', + content: 'https://example.com/foo?bar=a,b', + url: 'https://example.com/foo?bar=a,b' + }], tokens3); + + const tokens4 = analyze('https://example.com/foo, bar'); + assert.deepEqual([{ + type: 'url', + content: 'https://example.com/foo', + url: 'https://example.com/foo' + }, { + type: 'text', content: ', bar' + }], tokens4); }); it('link', () => {