| 1 |
import { isBlock, isVoid, hasVoid, isMeaningfulWhenBlank, hasMeaningfulWhenBlank } from './utilities' |
| 2 |
|
| 3 |
export default function Node (node, options) { |
| 4 |
node.isBlock = isBlock(node) |
| 5 |
node.isCode = node.nodeName === 'CODE' || node.parentNode.isCode |
| 6 |
node.isBlank = isBlank(node) |
| 7 |
node.flankingWhitespace = flankingWhitespace(node, options) |
| 8 |
return node |
| 9 |
} |
| 10 |
|
| 11 |
function isBlank (node) { |
| 12 |
return ( |
| 13 |
!isVoid(node) && |
| 14 |
!isMeaningfulWhenBlank(node) && |
| 15 |
/^\s*$/i.test(node.textContent) && |
| 16 |
!hasVoid(node) && |
| 17 |
!hasMeaningfulWhenBlank(node) |
| 18 |
) |
| 19 |
} |
| 20 |
|
| 21 |
function flankingWhitespace (node, options) { |
| 22 |
if (node.isBlock || (options.preformattedCode && node.isCode)) { |
| 23 |
return { leading: '', trailing: '' } |
| 24 |
} |
| 25 |
|
| 26 |
const edges = edgeWhitespace(node.textContent) |
| 27 |
|
| 28 |
|
| 29 |
if (edges.leadingAscii && isFlankedByWhitespace('left', node, options)) { |
| 30 |
edges.leading = edges.leadingNonAscii |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
if (edges.trailingAscii && isFlankedByWhitespace('right', node, options)) { |
| 35 |
edges.trailing = edges.trailingNonAscii |
| 36 |
} |
| 37 |
|
| 38 |
return { leading: edges.leading, trailing: edges.trailing } |
| 39 |
} |
| 40 |
|
| 41 |
function edgeWhitespace (string) { |
| 42 |
const m = string.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/) |
| 43 |
return { |
| 44 |
leading: m[1], |
| 45 |
leadingAscii: m[2], |
| 46 |
leadingNonAscii: m[3], |
| 47 |
trailing: m[4], |
| 48 |
trailingNonAscii: m[5], |
| 49 |
trailingAscii: m[6] |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
function isFlankedByWhitespace (side, node, options) { |
| 54 |
let sibling |
| 55 |
let regExp |
| 56 |
let isFlanked |
| 57 |
|
| 58 |
if (side === 'left') { |
| 59 |
sibling = node.previousSibling |
| 60 |
regExp = / $/ |
| 61 |
} else { |
| 62 |
sibling = node.nextSibling |
| 63 |
regExp = /^ / |
| 64 |
} |
| 65 |
|
| 66 |
if (sibling) { |
| 67 |
if (sibling.nodeType === 3) { |
| 68 |
isFlanked = regExp.test(sibling.nodeValue) |
| 69 |
} else if (options.preformattedCode && sibling.nodeName === 'CODE') { |
| 70 |
isFlanked = false |
| 71 |
} else if (sibling.nodeType === 1 && !isBlock(sibling)) { |
| 72 |
isFlanked = regExp.test(sibling.textContent) |
| 73 |
} |
| 74 |
} |
| 75 |
return isFlanked |
| 76 |
} |