forked from coracle/flotilla
Get link extension working better
This commit is contained in:
@@ -1,14 +1,11 @@
|
||||
import {Node, nodePasteRule, type PasteRuleMatch} from "@tiptap/core"
|
||||
import {last} from '@welshman/lib'
|
||||
import {Node, InputRule, nodePasteRule, type PasteRuleMatch} from "@tiptap/core"
|
||||
import type {Node as ProsemirrorNode} from "@tiptap/pm/model"
|
||||
import type {MarkdownSerializerState} from "prosemirror-markdown"
|
||||
import {createPasteRuleMatch, createInputRuleMatch} from './util'
|
||||
|
||||
export const LINK_REGEX =
|
||||
/^([a-z\+:]{2,30}:\/\/)?[^<>\(\)\s]+\.[a-z]{2,6}[^\s]*[^<>"'\.!?,:\s\)\(]*/gi
|
||||
|
||||
export const createPasteRuleMatch = <T extends Record<string, unknown>>(
|
||||
match: RegExpMatchArray,
|
||||
data: T,
|
||||
): PasteRuleMatch => ({index: match.index!, replaceWith: match[2], text: match[0], match, data})
|
||||
/([a-z\+:]{2,30}:\/\/)?[^<>\(\)\s]+\.[a-z]{2,6}[^\s]*[^<>"'\.!?,:\s\)\(]*/gi
|
||||
|
||||
export interface LinkAttributes {
|
||||
url: string
|
||||
@@ -65,6 +62,42 @@ export const LinkExtension = Node.create({
|
||||
},
|
||||
}
|
||||
},
|
||||
addInputRules() {
|
||||
return [
|
||||
new InputRule({
|
||||
find: text => {
|
||||
const match = last(Array.from(text.matchAll(LINK_REGEX)))
|
||||
|
||||
if (match && text.length === match.index + match[0].length + 1) {
|
||||
return {
|
||||
index: match.index!,
|
||||
text: match[0],
|
||||
data: {
|
||||
url: match[0],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
handler: ({state, range, match}) => {
|
||||
const {tr} = state
|
||||
|
||||
if (match[0]) {
|
||||
try {
|
||||
tr.insert(range.from - 1, this.type.create(match.data))
|
||||
.delete(tr.mapping.map(range.from - 1), tr.mapping.map(range.to))
|
||||
.insert(tr.mapping.map(range.to), this.editor.schema.text(last(Array.from(match.input!))))
|
||||
} catch (e) {
|
||||
// If the node was already linkified, the above code breaks for whatever reason
|
||||
}
|
||||
}
|
||||
|
||||
tr.scrollIntoView()
|
||||
},
|
||||
}),
|
||||
]
|
||||
},
|
||||
addPasteRules() {
|
||||
return [
|
||||
nodePasteRule({
|
||||
|
||||
Reference in New Issue
Block a user