-
Notifications
You must be signed in to change notification settings - Fork 879
/
parse-html.js
301 lines (272 loc) · 10.6 KB
/
parse-html.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
var firepad = firepad || { };
/**
* Helper to parse html into Firepad-compatible lines / text.
* @type {*}
*/
firepad.ParseHtml = (function () {
var LIST_TYPE = firepad.LineFormatting.LIST_TYPE;
/**
* Represents the current parse state as an immutable structure. To create a new ParseState, use
* the withXXX methods.
*
* @param opt_listType
* @param opt_lineFormatting
* @param opt_textFormatting
* @constructor
*/
function ParseState(opt_listType, opt_lineFormatting, opt_textFormatting) {
this.listType = opt_listType || LIST_TYPE.UNORDERED;
this.lineFormatting = opt_lineFormatting || firepad.LineFormatting();
this.textFormatting = opt_textFormatting || firepad.Formatting();
}
ParseState.prototype.withTextFormatting = function(textFormatting) {
return new ParseState(this.listType, this.lineFormatting, textFormatting);
};
ParseState.prototype.withLineFormatting = function(lineFormatting) {
return new ParseState(this.listType, lineFormatting, this.textFormatting);
};
ParseState.prototype.withListType = function(listType) {
return new ParseState(listType, this.lineFormatting, this.textFormatting);
};
ParseState.prototype.withIncreasedIndent = function() {
var lineFormatting = this.lineFormatting.indent(this.lineFormatting.getIndent() + 1);
return new ParseState(this.listType, lineFormatting, this.textFormatting);
};
ParseState.prototype.withAlign = function(align) {
var lineFormatting = this.lineFormatting.align(align);
return new ParseState(this.listType, lineFormatting, this.textFormatting);
};
/**
* Mutable structure representing the current parse output.
* @constructor
*/
function ParseOutput() {
this.lines = [ ];
this.currentLine = [];
this.currentLineListItemType = null;
}
ParseOutput.prototype.newlineIfNonEmpty = function(state) {
this.cleanLine_();
if (this.currentLine.length > 0) {
this.newline(state);
}
};
ParseOutput.prototype.newlineIfNonEmptyOrListItem = function(state) {
this.cleanLine_();
if (this.currentLine.length > 0 || this.currentLineListItemType !== null) {
this.newline(state);
}
};
ParseOutput.prototype.newline = function(state) {
this.cleanLine_();
var lineFormatting = state.lineFormatting;
if (this.currentLineListItemType !== null) {
lineFormatting = lineFormatting.listItem(this.currentLineListItemType);
this.currentLineListItemType = null;
}
this.lines.push(firepad.Line(this.currentLine, lineFormatting));
this.currentLine = [];
};
ParseOutput.prototype.makeListItem = function(type) {
this.currentLineListItemType = type;
};
ParseOutput.prototype.cleanLine_ = function() {
// Kinda' a hack, but we remove leading and trailing spaces (since these aren't significant in html) and
// replaces nbsp's with normal spaces.
if (this.currentLine.length > 0) {
var last = this.currentLine.length - 1;
this.currentLine[0].text = this.currentLine[0].text.replace(/^ +/, '');
this.currentLine[last].text = this.currentLine[last].text.replace(/ +$/g, '');
for(var i = 0; i < this.currentLine.length; i++) {
this.currentLine[i].text = this.currentLine[i].text.replace(/\u00a0/g, ' ');
}
}
// If after stripping trailing whitespace, there's nothing left, clear currentLine out.
if (this.currentLine.length === 1 && this.currentLine[0].text === '') {
this.currentLine = [];
}
};
var entityManager_;
function parseHtml(html, entityManager) {
// Create DIV with HTML (as a convenient way to parse it).
var div = (firepad.document || document).createElement('div');
div.innerHTML = html;
// HACK until I refactor this.
entityManager_ = entityManager;
var output = new ParseOutput();
var state = new ParseState();
parseNode(div, state, output);
return output.lines;
}
// Fix IE8.
var Node = Node || {
ELEMENT_NODE: 1,
TEXT_NODE: 3
};
function parseNode(node, state, output) {
// Give entity manager first crack at it.
if (node.nodeType === Node.ELEMENT_NODE) {
var entity = entityManager_.fromElement(node);
if (entity) {
output.currentLine.push(new firepad.Text(
firepad.sentinelConstants.ENTITY_SENTINEL_CHARACTER,
new firepad.Formatting(entity.toAttributes())
));
return;
}
}
switch (node.nodeType) {
case Node.TEXT_NODE:
// This probably isn't exactly right, but mostly works...
var text = node.nodeValue.replace(/[ \n\t]+/g, ' ');
output.currentLine.push(firepad.Text(text, state.textFormatting));
break;
case Node.ELEMENT_NODE:
var style = node.getAttribute('style') || '';
state = parseStyle(state, style);
switch (node.nodeName.toLowerCase()) {
case 'div':
case 'h1':
case 'h2':
case 'h3':
case 'p':
output.newlineIfNonEmpty(state);
parseChildren(node, state, output);
output.newlineIfNonEmpty(state);
break;
case 'center':
state = state.withAlign('center');
output.newlineIfNonEmpty(state);
parseChildren(node, state.withAlign('center'), output);
output.newlineIfNonEmpty(state);
break;
case 'b':
case 'strong':
parseChildren(node, state.withTextFormatting(state.textFormatting.bold(true)), output);
break;
case 'u':
parseChildren(node, state.withTextFormatting(state.textFormatting.underline(true)), output);
break;
case 'i':
case 'em':
parseChildren(node, state.withTextFormatting(state.textFormatting.italic(true)), output);
break;
case 's':
parseChildren(node, state.withTextFormatting(state.textFormatting.strike(true)), output);
break;
case 'font':
var face = node.getAttribute('face');
var color = node.getAttribute('color');
var size = parseInt(node.getAttribute('size'));
if (face) { state = state.withTextFormatting(state.textFormatting.font(face)); }
if (color) { state = state.withTextFormatting(state.textFormatting.color(color)); }
if (size) { state = state.withTextFormatting(state.textFormatting.fontSize(size)); }
parseChildren(node, state, output);
break;
case 'br':
output.newline(state);
break;
case 'ul':
output.newlineIfNonEmptyOrListItem(state);
var listType = node.getAttribute('class') === 'firepad-todo' ? LIST_TYPE.TODO : LIST_TYPE.UNORDERED;
parseChildren(node, state.withListType(listType).withIncreasedIndent(), output);
output.newlineIfNonEmpty(state);
break;
case 'ol':
output.newlineIfNonEmptyOrListItem(state);
parseChildren(node, state.withListType(LIST_TYPE.ORDERED).withIncreasedIndent(), output);
output.newlineIfNonEmpty(state);
break;
case 'li':
parseListItem(node, state, output);
break;
case 'style': // ignore.
break;
default:
parseChildren(node, state, output);
break;
}
break;
default:
// Ignore other nodes (comments, etc.)
break;
}
}
function parseChildren(node, state, output) {
if (node.hasChildNodes()) {
for(var i = 0; i < node.childNodes.length; i++) {
parseNode(node.childNodes[i], state, output);
}
}
}
function parseListItem(node, state, output) {
// Note: <li> is weird:
// * Only the first line in the <li> tag should be a list item (i.e. with a bullet or number next to it).
// * <li></li> should create an empty list item line; <li><ol><li></li></ol></li> should create two.
output.newlineIfNonEmptyOrListItem(state);
var listType = (node.getAttribute('class') === 'firepad-checked') ? LIST_TYPE.TODOCHECKED : state.listType;
output.makeListItem(listType);
var oldLine = output.currentLine;
parseChildren(node, state, output);
if (oldLine === output.currentLine || output.currentLine.length > 0) {
output.newline(state);
}
}
function parseStyle(state, styleString) {
var textFormatting = state.textFormatting;
var lineFormatting = state.lineFormatting;
var styles = styleString.split(';');
for(var i = 0; i < styles.length; i++) {
var stylePieces = styles[i].split(':');
if (stylePieces.length !== 2)
continue;
var prop = firepad.utils.trim(stylePieces[0]).toLowerCase();
var val = firepad.utils.trim(stylePieces[1]).toLowerCase();
switch (prop) {
case 'text-decoration':
var underline = val.indexOf('underline') >= 0;
var strike = val.indexOf('line-through') >= 0;
textFormatting = textFormatting.underline(underline).strike(strike);
break;
case 'font-weight':
var bold = (val === 'bold') || parseInt(val) >= 600;
textFormatting = textFormatting.bold(bold);
break;
case 'font-style':
var italic = (val === 'italic' || val === 'oblique');
textFormatting = textFormatting.italic(italic);
break;
case 'color':
textFormatting = textFormatting.color(val);
break;
case 'background-color':
textFormatting = textFormatting.backgroundColor(val);
break;
case 'text-align':
lineFormatting = lineFormatting.align(val);
break;
case 'font-size':
var size = null;
var allowedValues = ['px','pt','%','em','xx-small','x-small','small','medium','large','x-large','xx-large','smaller','larger'];
if (firepad.utils.stringEndsWith(val, allowedValues)) {
size = val;
}
else if (parseInt(val)) {
size = parseInt(val)+'px';
}
if (size) {
textFormatting = textFormatting.fontSize(size);
}
break;
case 'font-family':
var font = firepad.utils.trim(val.split(',')[0]); // get first font.
font = font.replace(/['"]/g, ''); // remove quotes.
font = font.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() });
textFormatting = textFormatting.font(font);
break;
}
}
return state.withLineFormatting(lineFormatting).withTextFormatting(textFormatting);
}
return parseHtml;
})();