-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathstateToHTML.js
501 lines (464 loc) · 14 KB
/
stateToHTML.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// @flow
import combineOrderedStyles from './helpers/combineOrderedStyles';
import normalizeAttributes from './helpers/normalizeAttributes';
import styleToCSS from './helpers/styleToCSS';
import {
isAllowedHref,
getEntityRanges,
BLOCK_TYPE,
ENTITY_TYPE,
INLINE_STYLE,
} from 'draft-js-utils';
import type {
ContentState,
ContentBlock,
Entity,
EntityInstance,
} from 'draft-js';
import type {CharacterMetaList} from 'draft-js-utils';
type AttrMap = {[key: string]: string};
type Attributes = {[key: string]: string};
type StyleDescr = {[key: string]: number | string};
type RenderConfig = {
element?: string;
attributes?: Attributes;
style?: StyleDescr;
};
type BlockRenderer = (block: ContentBlock) => ?string;
type BlockRendererMap = {[blockType: string]: BlockRenderer};
type StyleMap = {[styleName: string]: RenderConfig};
type BlockStyleFn = (block: ContentBlock) => ?RenderConfig;
type EntityStyleFn = (entity: Entity) => ?RenderConfig;
type Options = {
inlineStyles?: StyleMap;
blockRenderers?: BlockRendererMap;
blockStyleFn?: BlockStyleFn;
entityStyleFn?: EntityStyleFn;
defaultBlockTag?: ?string;
};
const {BOLD, CODE, ITALIC, STRIKETHROUGH, UNDERLINE} = INLINE_STYLE;
const INDENT = ' ';
const BREAK = '<br>';
const DATA_ATTRIBUTE = /^data-([a-z0-9-]+)$/;
const DEFAULT_STYLE_MAP = {
[BOLD]: {element: 'strong'},
[CODE]: {element: 'code'},
[ITALIC]: {element: 'em'},
[STRIKETHROUGH]: {element: 'del'},
[UNDERLINE]: {element: 'u'},
};
// Order: inner-most style to outer-most.
// Examle: <em><strong>foo</strong></em>
const DEFAULT_STYLE_ORDER = [BOLD, ITALIC, UNDERLINE, STRIKETHROUGH, CODE];
// Map entity data to element attributes.
const ENTITY_ATTR_MAP: {[entityType: string]: AttrMap} = {
[ENTITY_TYPE.LINK]: {
url: 'href',
href: 'href',
rel: 'rel',
target: 'target',
title: 'title',
className: 'class',
},
[ENTITY_TYPE.IMAGE]: {
src: 'src',
height: 'height',
width: 'width',
alt: 'alt',
className: 'class',
},
};
// Map entity data to element attributes.
const DATA_TO_ATTR = {
[ENTITY_TYPE.LINK](entityType: string, entity: EntityInstance): ?Attributes {
let attrMap = ENTITY_ATTR_MAP.hasOwnProperty(entityType)
? ENTITY_ATTR_MAP[entityType]
: {};
let data = entity.getData();
let attrs = {};
for (let dataKey of Object.keys(data)) {
let dataValue = data[dataKey];
if (attrMap.hasOwnProperty(dataKey)) {
let attrKey = attrMap[dataKey];
if (attrKey === 'href' && !isAllowedHref(dataValue)) {
return null;
}
attrs[attrKey] = dataValue;
} else if (DATA_ATTRIBUTE.test(dataKey)) {
attrs[dataKey] = dataValue;
}
}
return attrs;
},
[ENTITY_TYPE.IMAGE](entityType: string, entity: EntityInstance): ?Attributes {
let attrMap = ENTITY_ATTR_MAP.hasOwnProperty(entityType)
? ENTITY_ATTR_MAP[entityType]
: {};
let data = entity.getData();
let attrs = {};
for (let dataKey of Object.keys(data)) {
let dataValue = data[dataKey];
if (attrMap.hasOwnProperty(dataKey)) {
let attrKey = attrMap[dataKey];
attrs[attrKey] = dataValue;
} else if (DATA_ATTRIBUTE.test(dataKey)) {
attrs[dataKey] = dataValue;
}
}
return attrs;
},
};
// The reason this returns an array is because a single block might get wrapped
// in two tags.
function getTags(blockType: string, defaultBlockTag): Array<string> {
switch (blockType) {
case BLOCK_TYPE.HEADER_ONE:
return ['h1'];
case BLOCK_TYPE.HEADER_TWO:
return ['h2'];
case BLOCK_TYPE.HEADER_THREE:
return ['h3'];
case BLOCK_TYPE.HEADER_FOUR:
return ['h4'];
case BLOCK_TYPE.HEADER_FIVE:
return ['h5'];
case BLOCK_TYPE.HEADER_SIX:
return ['h6'];
case BLOCK_TYPE.UNORDERED_LIST_ITEM:
case BLOCK_TYPE.ORDERED_LIST_ITEM:
return ['li'];
case BLOCK_TYPE.BLOCKQUOTE:
return ['blockquote'];
case BLOCK_TYPE.CODE:
return ['pre', 'code'];
case BLOCK_TYPE.ATOMIC:
return ['figure'];
default:
if (defaultBlockTag === null) {
return [];
}
return [defaultBlockTag || 'p'];
}
}
function getWrapperTag(blockType: string): ?string {
switch (blockType) {
case BLOCK_TYPE.UNORDERED_LIST_ITEM:
return 'ul';
case BLOCK_TYPE.ORDERED_LIST_ITEM:
return 'ol';
default:
return null;
}
}
class MarkupGenerator {
// These are related to state.
blocks: Array<ContentBlock>;
contentState: ContentState;
currentBlock: number;
indentLevel: number;
output: Array<string>;
totalBlocks: number;
wrapperTag: ?string;
// These are related to user-defined options.
options: Options;
inlineStyles: StyleMap;
styleOrder: Array<string>;
constructor(contentState: ContentState, options: ?Options) {
if (options == null) {
options = {};
}
this.contentState = contentState;
this.options = options;
let [
inlineStyles,
styleOrder,
] = combineOrderedStyles(options.inlineStyles, [
DEFAULT_STYLE_MAP,
DEFAULT_STYLE_ORDER,
]);
this.inlineStyles = inlineStyles;
this.styleOrder = styleOrder;
}
generate(): string {
this.output = [];
this.blocks = this.contentState.getBlocksAsArray();
this.totalBlocks = this.blocks.length;
this.currentBlock = 0;
this.indentLevel = 0;
this.wrapperTag = null;
while (this.currentBlock < this.totalBlocks) {
this.processBlock();
}
this.closeWrapperTag();
return this.output.join('').trim();
}
processBlock() {
let {blockRenderers, defaultBlockTag} = this.options;
let block = this.blocks[this.currentBlock];
let blockType = block.getType();
let newWrapperTag = getWrapperTag(blockType);
if (this.wrapperTag !== newWrapperTag) {
if (this.wrapperTag) {
this.closeWrapperTag();
}
if (newWrapperTag) {
this.openWrapperTag(newWrapperTag);
}
}
this.indent();
// Allow blocks to be rendered using a custom renderer.
let customRenderer =
blockRenderers != null && blockRenderers.hasOwnProperty(blockType)
? blockRenderers[blockType]
: null;
let customRendererOutput = customRenderer ? customRenderer(block) : null;
// Renderer can return null, which will cause processing to continue as normal.
if (customRendererOutput != null) {
this.output.push(customRendererOutput);
this.output.push('\n');
this.currentBlock += 1;
return;
}
this.writeStartTag(block, defaultBlockTag);
this.output.push(this.renderBlockContent(block));
// Look ahead and see if we will nest list.
let nextBlock = this.getNextBlock();
if (
canHaveDepth(blockType) &&
nextBlock &&
nextBlock.getDepth() === block.getDepth() + 1
) {
this.output.push('\n');
// This is a litle hacky: temporarily stash our current wrapperTag and
// render child list(s).
let thisWrapperTag = this.wrapperTag;
this.wrapperTag = null;
this.indentLevel += 1;
this.currentBlock += 1;
this.processBlocksAtDepth(nextBlock.getDepth());
this.wrapperTag = thisWrapperTag;
this.indentLevel -= 1;
this.indent();
} else {
this.currentBlock += 1;
}
this.writeEndTag(block, defaultBlockTag);
}
processBlocksAtDepth(depth: number) {
let block = this.blocks[this.currentBlock];
while (block && block.getDepth() === depth) {
this.processBlock();
block = this.blocks[this.currentBlock];
}
this.closeWrapperTag();
}
getNextBlock(): ContentBlock {
return this.blocks[this.currentBlock + 1];
}
writeStartTag(block, defaultBlockTag) {
let tags = getTags(block.getType(), defaultBlockTag);
let attrString;
if (this.options.blockStyleFn) {
let {attributes, style} = this.options.blockStyleFn(block) || {};
// Normalize `className` -> `class`, etc.
attributes = normalizeAttributes(attributes);
if (style != null) {
let styleAttr = styleToCSS(style);
attributes =
attributes == null
? {style: styleAttr}
: {...attributes, style: styleAttr};
}
attrString = stringifyAttrs(attributes);
} else {
attrString = '';
}
for (let tag of tags) {
this.output.push(`<${tag}${attrString}>`);
}
}
writeEndTag(block, defaultBlockTag) {
let tags = getTags(block.getType(), defaultBlockTag);
if (tags.length === 1) {
this.output.push(`</${tags[0]}>\n`);
} else {
let output = [];
for (let tag of tags) {
output.unshift(`</${tag}>`);
}
this.output.push(output.join('') + '\n');
}
}
openWrapperTag(wrapperTag: string) {
this.wrapperTag = wrapperTag;
this.indent();
this.output.push(`<${wrapperTag}>\n`);
this.indentLevel += 1;
}
closeWrapperTag() {
let {wrapperTag} = this;
if (wrapperTag) {
this.indentLevel -= 1;
this.indent();
this.output.push(`</${wrapperTag}>\n`);
this.wrapperTag = null;
}
}
indent() {
this.output.push(INDENT.repeat(this.indentLevel));
}
renderBlockContent(block: ContentBlock): string {
let blockType = block.getType();
let text = block.getText();
if (text === '') {
// Prevent element collapse if completely empty.
return BREAK;
}
text = this.preserveWhitespace(text);
let charMetaList: CharacterMetaList = block.getCharacterList();
let entityPieces = getEntityRanges(text, charMetaList);
return entityPieces
.map(([entityKey, stylePieces]) => {
let content = stylePieces
.map(([text, styleSet]) => {
let content = encodeContent(text);
for (let styleName of this.styleOrder) {
// If our block type is CODE then don't wrap inline code elements.
if (styleName === CODE && blockType === BLOCK_TYPE.CODE) {
continue;
}
if (styleSet.has(styleName)) {
let {element, attributes, style} = this.inlineStyles[styleName];
if (element == null) {
element = 'span';
}
// Normalize `className` -> `class`, etc.
attributes = normalizeAttributes(attributes);
if (style != null) {
let styleAttr = styleToCSS(style);
attributes =
attributes == null
? {style: styleAttr}
: {...attributes, style: styleAttr};
}
let attrString = stringifyAttrs(attributes);
content = `<${element}${attrString}>${content}</${element}>`;
}
}
return content;
})
.join('');
let entity = entityKey ? this.contentState.getEntity(entityKey) : null;
// Note: The `toUpperCase` below is for compatability with some libraries that use lower-case for image blocks.
let entityType = entity == null ? null : entity.getType().toUpperCase();
let entityStyle;
if (
entity != null &&
this.options.entityStyleFn &&
(entityStyle = this.options.entityStyleFn(entity))
) {
let {element, attributes, style} = entityStyle;
if (element == null) {
element = 'span';
}
// Normalize `className` -> `class`, etc.
attributes = normalizeAttributes(attributes);
if (style != null) {
let styleAttr = styleToCSS(style);
attributes =
attributes == null
? {style: styleAttr}
: {...attributes, style: styleAttr};
}
let attrString = stringifyAttrs(attributes);
return `<${element}${attrString}>${content}</${element}>`;
} else if (entityType != null && entityType === ENTITY_TYPE.LINK) {
let attrs = DATA_TO_ATTR.hasOwnProperty(entityType)
? DATA_TO_ATTR[entityType](entityType, entity)
: null;
if (attrs == null) {
return content;
}
let attrString = stringifyAttrs(attrs);
return `<a${attrString}>${content}</a>`;
} else if (entityType != null && entityType === ENTITY_TYPE.IMAGE) {
let attrs = DATA_TO_ATTR.hasOwnProperty(entityType)
? DATA_TO_ATTR[entityType](entityType, entity)
: null;
let attrString = stringifyAttrs(attrs);
return `<img${attrString}/>`;
} else {
return content;
}
})
.join('');
}
preserveWhitespace(text: string): string {
let length = text.length;
// Prevent leading/trailing/consecutive whitespace collapse.
let newText = new Array(length);
for (let i = 0; i < length; i++) {
if (
text[i] === ' ' &&
(i === 0 || i === length - 1 || text[i - 1] === ' ')
) {
newText[i] = '\xA0';
} else {
newText[i] = text[i];
}
}
return newText.join('');
}
}
function stringifyAttrs(attrs: ?Attributes) {
if (attrs == null) {
return '';
}
let parts = [];
for (let name of Object.keys(attrs)) {
let value = attrs[name];
if (value != null) {
parts.push(` ${name}="${encodeAttr(value + '')}"`);
}
}
return parts.join('');
}
function canHaveDepth(blockType: string): boolean {
switch (blockType) {
case BLOCK_TYPE.UNORDERED_LIST_ITEM:
case BLOCK_TYPE.ORDERED_LIST_ITEM:
return true;
default:
return false;
}
}
function encodeContent(text: string): string {
return text
.split('&')
.join('&')
.split('<')
.join('<')
.split('>')
.join('>')
.split('\xA0')
.join(' ')
.split('\n')
.join(BREAK + '\n');
}
function encodeAttr(text: string): string {
return text
.split('&')
.join('&')
.split('<')
.join('<')
.split('>')
.join('>')
.split('"')
.join('"');
}
export default function stateToHTML(
content: ContentState,
options: ?Options,
): string {
return new MarkupGenerator(content, options).generate();
}