webapp/src/components/Editor/InsertLinkForm/InsertLinkForm.tsx

68 lines
1.6 KiB
TypeScript
Raw Normal View History

import { Editor } from '@tiptap/core'
2024-09-27 13:46:43 +00:00
import { createEffect, createSignal, onCleanup } from 'solid-js'
import { useLocalize } from '~/context/localize'
2024-07-13 11:42:53 +00:00
import { validateUrl } from '~/utils/validate'
import { InlineForm } from '../InlineForm'
type Props = {
editor: Editor
2023-07-28 19:53:21 +00:00
onClose: () => void
}
2024-06-24 17:50:27 +00:00
export const checkUrl = (url: string) => {
try {
new URL(url)
return url
} catch {
return `https://${url}`
}
}
export const InsertLinkForm = (props: Props) => {
const { t } = useLocalize()
2024-09-27 13:46:43 +00:00
const [currentUrl, setCurrentUrl] = createSignal('')
createEffect(() => {
const url = props.editor.getAttributes('link').href
setCurrentUrl(url || '')
})
createEffect(() => {
const updateListener = () => {
const url = props.editor.getAttributes('link').href
setCurrentUrl(url || '')
2024-06-26 08:22:05 +00:00
}
2024-09-27 13:46:43 +00:00
props.editor.on('update', updateListener)
onCleanup(() => props.editor.off('update', updateListener))
})
const handleClearLinkForm = () => {
if (currentUrl()) {
2024-07-31 21:41:15 +00:00
props.editor?.chain().focus().unsetLink().run()
}
}
const handleLinkFormSubmit = (value: string) => {
props.editor
2024-07-31 21:41:15 +00:00
?.chain()
.focus()
.setLink({ href: checkUrl(value) })
.run()
2024-09-27 13:46:43 +00:00
props.onClose()
}
2024-09-27 13:46:43 +00:00
return (
<div>
<InlineForm
placeholder={t('Enter URL address')}
initialValue={currentUrl() ?? ''}
onClear={handleClearLinkForm}
validate={(value) => (validateUrl(value) ? '' : t('Invalid url format'))}
onSubmit={handleLinkFormSubmit}
2024-09-15 16:41:02 +00:00
onClose={props.onClose}
/>
</div>
)
}