I was trying to follow this:
https://github.com/ProseMirror/prosemirror/issues/90#issuecomment-202933072
to get link pasting working nicely in my project, but I ran into some issues while updating it. This is what I ended up with:
let linkPlugin = new Plugin({
props: {
transformPasted: (slice: Slice) => {
return new Slice(linkify(slice.content), slice.openLeft, slice.openRight)
}
}
})
const HTTP_LINK_REGEX = /\bhttps?:\/\/[\w_\/\.]+/g
let linkify = function(fragment: Fragment): Fragment {
var linkified : Node[] = []
fragment.forEach(function(child: Node){
if (child.isText) {
const text = child.text as string
var pos = 0, match
while (match = HTTP_LINK_REGEX.exec(text)) {
var start = match.index
var end = start + match[0].length
var link = child.type.schema.marks['link']
// simply copy across the text from before the match
if (start > 0) {
linkified.push(child.cut(pos, start))
}
const urlText = text.slice(start, end)
linkified.push(
child.cut(start, end).mark(link.create({href: urlText}).addToSet(child.marks))
)
pos = end
}
// copy over whatever is left
if (pos < text.length) {
linkified.push(child.cut(pos))
}
} else {
linkified.push(child.copy(linkify(child.content)))
}
})
return Fragment.fromArray(linkified)
}
In particular, my first attempt I used
child.type.create(undefined, child.cut(start, end), link.create({href: urlText}).addToSet(child.marks))
This was invoking the generic Node constructor here: https://github.com/ProseMirror/prosemirror-model/blob/master/src/node.js#L22
rather than the TextNode
constructor, so I ended up with a text
node which had node.text == undefined
, which then caused an error to be thrown while rendering.
Updating the code to the above:
child.cut(start, end).mark(link.create({href: urlText}).addToSet(child.marks))
fixed the issue (the created node had text
populated).
Is there a reason why one way works and another doesn’t? Or should I file a bug regarding this issue?