Skip to content

Commit

Permalink
fix(link behavior): improve URL matching
Browse files Browse the repository at this point in the history
  • Loading branch information
christianhg committed Dec 19, 2024
1 parent 763b5b4 commit 2aacbc8
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 9 deletions.
10 changes: 1 addition & 9 deletions packages/editor/src/behaviors/behavior.links.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type {EditorSchema} from '../editor/define-schema'
import * as selectors from '../selectors'
import {looksLikeUrl} from '../utils/looks-like-url'
import {defineBehavior} from './behavior.types'

/**
Expand Down Expand Up @@ -80,12 +81,3 @@ export function createLinkBehaviors(config: LinkBehaviorsConfig) {

return linkBehaviors
}

function looksLikeUrl(text: string) {
let looksLikeUrl = false
try {
new URL(text)
looksLikeUrl = true
} catch {}
return looksLikeUrl
}
13 changes: 13 additions & 0 deletions packages/editor/src/utils/looks-like-url.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {expect, test} from 'vitest'
import {looksLikeUrl} from './looks-like-url'

test(looksLikeUrl.name, () => {
expect(looksLikeUrl('https://example.com')).toBe(true)
expect(looksLikeUrl('http://example.com')).toBe(true)
expect(looksLikeUrl('example.com')).toBe(true)
expect(looksLikeUrl('mailto:foo@example.com')).toBe(true)
expect(looksLikeUrl('tel:+123456789')).toBe(true)
expect(looksLikeUrl('http://example')).toBe(false)
expect(looksLikeUrl('http:example')).toBe(false)
expect(looksLikeUrl('a:b')).toBe(false)
})
31 changes: 31 additions & 0 deletions packages/editor/src/utils/looks-like-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export function looksLikeUrl(text: string) {
let looksLikeUrl = false
try {
try {
const url = new URL(text)

if (!sensibleProtocols.includes(url.protocol)) {
return false
}

const probablyHasTld =
url.hostname.length > 0 ? url.hostname.includes('.') : true

looksLikeUrl = probablyHasTld
} catch {
const url = new URL(`https://${text}`)

if (!sensibleProtocols.includes(url.protocol)) {
return false
}

const probablyHasTld =
url.hostname.length > 0 ? url.hostname.includes('.') : true

looksLikeUrl = probablyHasTld
}
} catch {}
return looksLikeUrl
}

const sensibleProtocols = ['http:', 'https:', 'mailto:', 'tel:']

0 comments on commit 2aacbc8

Please sign in to comment.