1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-24 10:27:10 +02:00

Chore: Improve link detection function

This commit is contained in:
Laurent Cozic 2024-04-27 11:22:36 +01:00
parent 5268b5bf6b
commit a0faca0997
3 changed files with 48 additions and 8 deletions

View File

@ -36,7 +36,7 @@ import { focus } from '@joplin/lib/utils/focusHandler';
const md5 = require('md5');
const { clipboard } = require('electron');
const supportedLocales = require('./supportedLocales');
import { isLink } from '@joplin/utils/url';
import { hasProtocol } from '@joplin/utils/url';
const logger = Logger.create('TinyMCE');
@ -1195,7 +1195,7 @@ const TinyMCE = (props: NoteBodyEditorProps, ref: any) => {
editor.insertContent(result.html);
}
} else {
if (BaseItem.isMarkdownTag(pastedText) || isLink(pastedText)) { // Paste a link to a note
if (BaseItem.isMarkdownTag(pastedText) || hasProtocol(pastedText, ['https', 'joplin', 'file'])) { // Paste a link to a note
logger.info('onPaste: pasting as a Markdown tag');
const result = await markupToHtml.current(MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN, pastedText, markupRenderOptions({ bodyOnly: true }));
editor.insertContent(result.html);

View File

@ -1,4 +1,4 @@
import { fileUriToPath } from './url';
import { fileUriToPath, hasProtocol } from './url';
describe('utils/url', () => {
@ -28,4 +28,40 @@ describe('utils/url', () => {
expect(fileUriToPath('file:///c:/AUTOEXEC.BAT', 'win32')).toBe('c:\\AUTOEXEC.BAT');
}));
test.each([
[
'https://joplinapp.org',
'https',
true,
],
[
'https://joplinapp.org',
'http',
false,
],
[
'https://joplinapp.org',
['http', 'https'],
true,
],
[
'https://joplinapp.org',
[],
false,
],
[
'',
[],
false,
],
[
'joplin://openNote?id=ABCD',
['http', 'https', 'joplin'],
true,
],
])('should tell if a URL has a particular protocol', (url, protocol, expected) => {
const actual = hasProtocol(url, protocol);
expect(actual).toBe(expected);
});
});

View File

@ -101,9 +101,13 @@ export const isDataUrl = (path: string) => {
return path.startsWith('data:');
};
export const isLink = (text: string) => {
if (!text) return false;
const linkRegex = /^(https?|file|joplin):\/\/[^)\s]+$/;
return !!text.match(linkRegex);
};
export const hasProtocol = (url: string, protocol: string | string[]) => {
if (!url) return false;
const protocols = typeof protocol === 'string' ? [protocol] : protocol;
url = url.toLowerCase();
for (const p of protocols) {
if (url.startsWith(`${p.toLowerCase()}://`)) return true;
}
return false;
};