diff --git a/components/Blocks/TextBlock/useHandlePaste.ts b/components/Blocks/TextBlock/useHandlePaste.ts index 1e45f54b..d12d4c9f 100644 --- a/components/Blocks/TextBlock/useHandlePaste.ts +++ b/components/Blocks/TextBlock/useHandlePaste.ts @@ -11,6 +11,8 @@ import { useEntitySetContext } from "components/EntitySetProvider"; import { v7 } from "uuid"; import { Replicache } from "replicache"; import { markdownToHtml } from "src/htmlMarkdownParsers"; +import { betterIsUrl, isUrl } from "src/utils/isURL"; +import { TextSelection } from "prosemirror-state"; const parser = ProsemirrorDOMParser.fromSchema(schema); export const useHandlePaste = ( @@ -28,6 +30,18 @@ export const useHandlePaste = ( let text = e.clipboardData.getData("text"); let editorState = useEditorStates.getState().editorStates[entityID]; if (!editorState) return; + if (text && betterIsUrl(text)) { + let selection = view.state.selection as TextSelection; + if (selection.empty) return; + let tr = view.state.tr; + let { from, to } = selection; + tr.addMark(from, to, schema.marks.link.create({ href: text })); + + setEditorState(entityID, { + editor: view.state.apply(tr), + }); + return true; + } if (!textHTML && text) { console.log(text); textHTML = markdownToHtml(text); diff --git a/src/utils/isURL.ts b/src/utils/isURL.ts index 12c0c8c2..dabe6e05 100644 --- a/src/utils/isURL.ts +++ b/src/utils/isURL.ts @@ -8,3 +8,28 @@ var nonLocalhostDomainRE = /^[^\s\.]+\.\S{2,}$/; export function isUrl(str: string) { return str.includes("."); } + +export function betterIsUrl(string: string) { + if (typeof string !== "string") { + return false; + } + + var match = string.match(protocolAndDomainRE); + if (!match) { + return false; + } + + var everythingAfterProtocol = match[1]; + if (!everythingAfterProtocol) { + return false; + } + + if ( + localhostDomainRE.test(everythingAfterProtocol) || + nonLocalhostDomainRE.test(everythingAfterProtocol) + ) { + return true; + } + + return false; +}