2023-07-24 08:58:07 +00:00
|
|
|
import { Editor } from '@tiptap/core'
|
|
|
|
import { validateUrl } from '../../../utils/validateUrl'
|
|
|
|
import { InlineForm } from '../InlineForm'
|
|
|
|
import { useLocalize } from '../../../context/localize'
|
|
|
|
import { createEditorTransaction } from 'solid-tiptap'
|
|
|
|
|
|
|
|
type Props = {
|
|
|
|
editor: Editor
|
2023-07-28 19:53:21 +00:00
|
|
|
onClose: () => void
|
2023-07-24 08:58:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export const checkUrl = (url) => {
|
|
|
|
try {
|
|
|
|
new URL(url)
|
|
|
|
return url
|
|
|
|
} catch {
|
|
|
|
return `https://${url}`
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const InsertLinkForm = (props: Props) => {
|
|
|
|
const { t } = useLocalize()
|
|
|
|
const currentUrl = createEditorTransaction(
|
|
|
|
() => props.editor,
|
|
|
|
(ed) => {
|
|
|
|
return (ed && ed.getAttributes('link').href) || ''
|
|
|
|
}
|
|
|
|
)
|
|
|
|
const handleClearLinkForm = () => {
|
|
|
|
if (currentUrl()) {
|
|
|
|
props.editor.chain().focus().unsetLink().run()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const handleLinkFormSubmit = (value: string) => {
|
|
|
|
props.editor
|
|
|
|
.chain()
|
|
|
|
.focus()
|
|
|
|
.setLink({ href: checkUrl(value) })
|
|
|
|
.run()
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div>
|
|
|
|
<InlineForm
|
|
|
|
placeholder={t('Enter URL address')}
|
|
|
|
initialValue={currentUrl() ?? ''}
|
|
|
|
onClear={handleClearLinkForm}
|
|
|
|
validate={(value) => (validateUrl(value) ? '' : t('Invalid url format'))}
|
|
|
|
onSubmit={handleLinkFormSubmit}
|
2023-07-28 19:53:21 +00:00
|
|
|
onClose={() => props.onClose()}
|
2023-07-24 08:58:07 +00:00
|
|
|
/>
|
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|