feat(richtext-lexical): update validation of custom URLs to include relative and anchor links (#6525)

Updates the regex to allow relative and anchor links as well. Manually
tested all common variations of absolute, relative and anchor links with
a combination

## Type of change

- [x] New feature (non-breaking change which adds functionality)
This commit is contained in:
Paul
2024-05-28 00:55:00 -03:00
committed by GitHub
parent 96181d91a6
commit 8a91a7adbb

View File

@@ -14,8 +14,16 @@ export function sanitizeUrl(url: string): string {
} }
// Source: https://stackoverflow.com/a/8234912/2013580 // Source: https://stackoverflow.com/a/8234912/2013580
const urlRegExp = const absoluteRegExp =
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z\d.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z\d.-]+)((?:\/[+~%/.\w-]*)?\??[-+=&;%@.\w]*#?\w*)?)/ /(?:[A-Za-z]{3,9}:(?:\/\/)?(?:[-;:&=+$,\w]+@)?[A-Za-z\d.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z\d.-]+)(?:\/[+~%/.\w-]*)?\??[-+=&;%@.\w]*#?\w*/
/**
* This regex checks for relative URLs starting with / or anchor links starting with # in a string. Tested for the following use cases:
* - /privacy-policy
* - /privacy-policy#primary-terms
* - #primary-terms
* */
const relativeOrAnchorRegExp = /^[\w\-./]*(?:#\w[\w-]*)?$/
// Do not keep validateUrl function too loose. This is run when pasting in text, to determine if links are in that text and if it should create AutoLinkNodes. // Do not keep validateUrl function too loose. This is run when pasting in text, to determine if links are in that text and if it should create AutoLinkNodes.
// This is why we do not allow stuff like anchors here, as we don't want copied anchors to be turned into AutoLinkNodes. // This is why we do not allow stuff like anchors here, as we don't want copied anchors to be turned into AutoLinkNodes.
@@ -28,7 +36,10 @@ export function validateUrl(url: string): boolean {
if (url === 'https://') return true if (url === 'https://') return true
// This makes sure URLs starting with www. instead of https are valid too // This makes sure URLs starting with www. instead of https are valid too
if (urlRegExp.test(url)) return true if (absoluteRegExp.test(url)) return true
// Check relative or anchor links
if (relativeOrAnchorRegExp.test(url)) return true
// While this doesn't allow URLs starting with www (which is why we use the regex above), it does properly handle tel: URLs // While this doesn't allow URLs starting with www (which is why we use the regex above), it does properly handle tel: URLs
try { try {