diff --git a/package.json b/package.json index ee68f73c..53161867 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,6 @@ "dependencies": { "classnames": "^2.2.6", "escape-html": "^1.0.3", - "is-url": "^1.2.4", "lodash": "^4.17.15", "react-dropzone": "^11.0.1", "react-image-crop": "^8.4.2", diff --git a/src/components/LinkInput.tsx b/src/components/LinkInput.tsx index cd401d32..45bd45c2 100644 --- a/src/components/LinkInput.tsx +++ b/src/components/LinkInput.tsx @@ -1,6 +1,6 @@ import React, { useRef, useState, useEffect } from 'react'; import { Node, NodeEntry } from 'slate'; -import isUrl from 'is-url'; +import isUrl, { prependHttps } from '../utils/isUrl'; import Modal from './Modal'; interface LinkInputProps { @@ -44,16 +44,10 @@ const LinkInput = (props: LinkInputProps): JSX.Element => { }; const onChange = (e: React.ChangeEvent): void => { - const prependProtocol = (url: string): string => { - if (!/^(?:f|ht)tps?:\/\//.test(url)) { - url = 'https://' + url; - } - return url; - }; - if (e.target.value.length <= url.length) { - setUrl(e.target.value); + if (e.target.value.length >= url.length) { + setUrl(prependHttps(e.target.value)); } else { - setUrl(prependProtocol(e.currentTarget.value)); + setUrl(e.target.value); } }; diff --git a/src/utils/isUrl.ts b/src/utils/isUrl.ts new file mode 100644 index 00000000..9fdf38c4 --- /dev/null +++ b/src/utils/isUrl.ts @@ -0,0 +1,17 @@ +const protocolRe = /^(?:f|ht)tps?:\/\//; +const hostnameRe = /([a-zA-Z]\.?)+\.([a-zA-Z]){2,}/; + +const urlRe = new RegExp(protocolRe.source + hostnameRe.source); +const mailRe = new RegExp('^mailto:([a-zA-Z](\\.|\\+)?)+@' + hostnameRe.source); +const onlyHostnameRe = new RegExp('^' + hostnameRe.source); + +const isUrl = (url: string): boolean => urlRe.test(url) || mailRe.test(url); + +export const prependHttps = (hostname: string): string => { + if (onlyHostnameRe.test(hostname)) { + return 'https://' + hostname; + } + return hostname; +}; + +export default isUrl; diff --git a/yarn.lock b/yarn.lock index 523d439c..43a33ebb 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3896,11 +3896,6 @@ is-symbol@^1.0.2: dependencies: has-symbols "^1.0.1" -is-url@^1.2.4: - version "1.2.4" - resolved "https://registry.yarnpkg.com/is-url/-/is-url-1.2.4.tgz#04a4df46d28c4cff3d73d01ff06abeb318a1aa52" - integrity sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww== - is-windows@^1.0.1, is-windows@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d"