-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathextractLinkParagraphs.js
More file actions
73 lines (66 loc) · 1.69 KB
/
extractLinkParagraphs.js
File metadata and controls
73 lines (66 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { isLinkToSelfWithHash } from './../helpers/links.js'
/**
* Get a list of all paragraphs that can be converted into a preview.
*
* @param {Document} doc - the prosemirror doc
* @return {Array} paragraphs with one link only found in the doc
*/
export default function extractLinkParagraphs(doc) {
const paragraphs = []
doc.descendants((node, pos) => {
if (previewPossible(node)) {
paragraphs.push(Object.freeze({
pos,
nodeSize: node.nodeSize,
type: 'text-only',
}))
} else if (node.type.name === 'preview') {
paragraphs.push(Object.freeze({
pos,
nodeSize: node.nodeSize,
type: 'link-preview',
}))
}
})
return paragraphs
}
/**
* Is it possible to convert the node into a preview?
* @param {object} node the node in question
* @return {boolean}
*/
function previewPossible(node) {
if (node.type.name !== 'paragraph' || hasOtherContent(node)) {
return false
}
const href = extractHref(node.firstChild)
if (!href || isLinkToSelfWithHash(href)) {
return false
}
return true
}
/**
* Does the node contain more content than the first child
* @param {object} node node to inspect
* @return {boolean}
*/
function hasOtherContent(node) {
return node.childCount > 2
|| (node.childCount === 2 && node.lastChild.textContent.trim())
}
/**
* Get the link href of the given node
* @param {object} node to inspect
* @return {string} The href of the link mark of the node
*/
function extractHref(node) {
if (!node) {
return undefined
}
const link = node.marks.find(mark => mark.type.name === 'link')
return link?.attrs.href
}