-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathms-list-converter.js
86 lines (65 loc) · 1.97 KB
/
ms-list-converter.js
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
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Browser dependencies
*/
const { parseInt } = window;
function isList( node ) {
return node.nodeName === 'OL' || node.nodeName === 'UL';
}
export default function msListConverter( node, doc ) {
if ( node.nodeName !== 'P' ) {
return;
}
const style = node.getAttribute( 'style' );
if ( ! style ) {
return;
}
// Quick check.
if ( style.indexOf( 'mso-list' ) === -1 ) {
return;
}
const matches = /mso-list\s*:[^;]+level([0-9]+)/i.exec( style );
if ( ! matches ) {
return;
}
let level = parseInt( matches[ 1 ], 10 ) - 1 || 0;
const prevNode = node.previousElementSibling;
// Add new list if no previous.
if ( ! prevNode || ! isList( prevNode ) ) {
// See https://html.spec.whatwg.org/multipage/grouping-content.html#attr-ol-type.
const type = node.textContent.trim().slice( 0, 1 );
const isNumeric = /[1iIaA]/.test( type );
const newListNode = doc.createElement( isNumeric ? 'ol' : 'ul' );
if ( isNumeric ) {
newListNode.setAttribute( 'type', type );
}
node.parentNode.insertBefore( newListNode, node );
}
const listNode = node.previousElementSibling;
const listType = listNode.nodeName;
const listItem = doc.createElement( 'li' );
let receivingNode = listNode;
// Remove the first span with list info.
node.removeChild( node.firstElementChild );
// Add content.
while ( node.firstChild ) {
listItem.appendChild( node.firstChild );
}
// Change pointer depending on indentation level.
while ( level-- ) {
receivingNode = receivingNode.lastElementChild || receivingNode;
// If it's a list, move pointer to the last item.
if ( isList( receivingNode ) ) {
receivingNode = receivingNode.lastElementChild || receivingNode;
}
}
// Make sure we append to a list.
if ( ! isList( receivingNode ) ) {
receivingNode = receivingNode.appendChild(
doc.createElement( listType )
);
}
// Append the list item to the list.
receivingNode.appendChild( listItem );
// Remove the wrapper paragraph.
node.parentNode.removeChild( node );
}