forked from Rosey/markdown-draft-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown-to-draft.js
More file actions
318 lines (280 loc) · 11.5 KB
/
markdown-to-draft.js
File metadata and controls
318 lines (280 loc) · 11.5 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
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
import { Remarkable } from 'remarkable';
const TRAILING_NEW_LINE = /\n$/;
// In DraftJS, string lengths are calculated differently than in JS itself (due
// to surrogate pairs). Instead of importing the entire UnicodeUtils file from
// FBJS, we use a simpler alternative, in the form of `Array.from`.
//
// Alternative: const { strlen } = require('fbjs/lib/UnicodeUtils');
function strlen(str) {
return Array.from(str).length;
}
// Block level items, key is Remarkable's key for them, value returned is
// A function that generates the raw draftjs key and block data.
//
// Why a function? Because in some cases (headers) we need additional information
// before we can determine the exact key to return. And blocks may also return data
const DefaultBlockTypes = {
paragraph_open: function (item) {
return {
type: 'unstyled',
text: '',
entityRanges: [],
inlineStyleRanges: []
};
},
blockquote_open: function (item) {
return {
type: 'blockquote',
text: ''
};
},
ordered_list_item_open: function () {
return {
type: 'ordered-list-item',
text: ''
};
},
unordered_list_item_open: function () {
return {
type: 'unordered-list-item',
text: ''
};
},
fence: function (item) {
return {
type: 'code-block',
data: {
language: item.params || ''
},
text: (item.content || '').replace(TRAILING_NEW_LINE, ''), // remarkable seems to always append an erronious trailing newline to its codeblock content, so we need to trim it out.
entityRanges: [],
inlineStyleRanges: []
};
},
heading_open: function (item) {
var type = 'header-' + ({
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six'
})[item.hLevel];
return {
type: type,
text: ''
};
}
};
// Entity types. These are things like links or images that require
// additional data and will be added to the `entityMap`
// again. In this case, key is remarkable key, value is
// meethod that returns the draftjs key + any data needed.
const DefaultBlockEntities = {
link_open: function (item) {
return {
type: 'LINK',
mutability: 'MUTABLE',
data: {
url: item.href,
href: item.href
}
};
}
};
// Entity styles. Simple Inline styles that aren't added to entityMap
// key is remarkable key, value is draftjs raw key
const DefaultBlockStyles = {
strong_open: 'BOLD',
em_open: 'ITALIC',
code: 'CODE'
};
// Remarkable blocks that stands alone.
const DefaultRemarkableStandaloneBlocks = [
'hr',
'fence'
]
// Key generator for entityMap items
var idCounter = -1;
function generateUniqueKey() {
idCounter++;
return idCounter;
}
/*
* Handle inline content in a block level item
* parses for BlockEntities (links, images) and BlockStyles (em, strong)
* doesn't handle block level items (blockquote, ordered list, etc)
*
* @param <Object> inlineItem - single object from remarkable data representation of markdown
* @param <Object> BlockEntities - key-value object of mappable block entity items. Passed in as param so users can include their own custom stuff
* @param <Object> BlockStyles - key-value object of mappable block styles items. Passed in as param so users can include their own custom stuff
*
* @return <Object>
* content: Entire text content for the inline item,
* blockEntities: New block eneities to be added to global block entity map
* blockEntityRanges: block-level representation of block entities including key to access the block entity from the global map
* blockStyleRanges: block-level representation of styles (eg strong, em)
*/
function parseInline(inlineItem, BlockEntities, BlockStyles) {
var content = '', blockEntities = {}, blockEntityRanges = [], blockInlineStyleRanges = [];
inlineItem.children.forEach(function (child) {
if (child.type === 'text') {
content += child.content;
} else if (child.type === 'softbreak') {
content += '\n';
} else if (child.type === 'hardbreak') {
content += '\n';
} else if (BlockStyles[child.type]) {
var key = generateUniqueKey();
var styleBlock = {
offset: strlen(content) || 0,
length: 0,
style: BlockStyles[child.type]
};
// Edge case hack because code items don't have inline content or open/close, unlike everything else
if (child.type === 'code') {
styleBlock.length = strlen(child.content);
content += child.content;
}
blockInlineStyleRanges.push(styleBlock);
} else if (BlockEntities[child.type]) {
var key = generateUniqueKey();
blockEntities[key] = BlockEntities[child.type](child);
blockEntityRanges.push({
offset: strlen(content) || 0,
length: 0,
key: key
});
} else if (child.type.indexOf('_close') !== -1 && BlockEntities[child.type.replace('_close', '_open')]) {
blockEntityRanges[blockEntityRanges.length - 1].length = strlen(content) - blockEntityRanges[blockEntityRanges.length - 1].offset;
} else if (child.type.indexOf('_close') !== -1 && BlockStyles[child.type.replace('_close', '_open')]) {
var type = BlockStyles[child.type.replace('_close', '_open')]
blockInlineStyleRanges = blockInlineStyleRanges
.map(style => {
if (style.length === 0 && style.style === type) {
style.length = strlen(content) - style.offset;
}
return style;
});
}
});
return {content, blockEntities, blockEntityRanges, blockInlineStyleRanges};
}
/**
* Convert markdown into raw draftjs object
*
* @param {String} markdown - markdown to convert into raw draftjs object
* @param {Object} options - optional additional data, see readme for what options can be passed in.
*
* @return {Object} rawDraftObject
**/
function markdownToDraft(string, options = {}) {
const remarkablePreset = options.remarkablePreset || options.remarkableOptions;
const remarkableOptions = typeof options.remarkableOptions === 'object' ? options.remarkableOptions : null;
const md = new Remarkable(remarkablePreset, remarkableOptions);
// if tables are not explicitly enabled, disable them by default
if (
!remarkableOptions ||
!remarkableOptions.enable ||
!remarkableOptions.enable.block ||
remarkableOptions.enable.block !== 'table' ||
remarkableOptions.enable.block.includes('table') === false
) {
md.block.ruler.disable('table');
}
// disable the specified rules
if (remarkableOptions && remarkableOptions.disable) {
for (let [key, value] of Object.entries(remarkableOptions.disable)) {
md[key].ruler.disable(value);
}
}
// enable the specified rules
if (remarkableOptions && remarkableOptions.enable) {
for (let [key, value] of Object.entries(remarkableOptions.enable)) {
md[key].ruler.enable(value);
}
}
// If users want to define custom remarkable plugins for custom markdown, they can be added here
if (options.remarkablePlugins) {
options.remarkablePlugins.forEach(function (plugin) {
md.use(plugin, {});
});
}
var blocks = []; // blocks will be returned as part of the final draftjs raw object
var entityMap = {}; // entitymap will be returned as part of the final draftjs raw object
var parsedData = md.parse(string, {}); // remarkable js takes markdown and makes it an array of style objects for us to easily parse
var currentListType = null; // Because of how remarkable's data is formatted, we need to cache what kind of list we're currently dealing with
var previousBlockEndingLine = 0;
// Allow user to define custom BlockTypes and Entities if they so wish
const BlockTypes = Object.assign({}, DefaultBlockTypes, options.blockTypes || {});
const BlockEntities = Object.assign({}, DefaultBlockEntities, options.blockEntities || {});
const BlockStyles = Object.assign({}, DefaultBlockStyles, options.blockStyles || {});
const RemarkableStandaloneBlocks = DefaultRemarkableStandaloneBlocks.concat(options.remarkableStandaloneBlocks)
parsedData.forEach(function (item) {
// Because of how remarkable's data is formatted, we need to cache what kind of list we're currently dealing with
if (item.type === 'bullet_list_open') {
currentListType = 'unordered_list_item_open';
} else if (item.type === 'ordered_list_open') {
currentListType = 'ordered_list_item_open';
}
var itemType = item.type;
if (itemType === 'list_item_open') {
itemType = currentListType;
}
if (itemType === 'inline') {
// Parse inline content and apply it to the most recently created block level item,
// which is where the inline content will belong.
var {content, blockEntities, blockEntityRanges, blockInlineStyleRanges} = parseInline(item, BlockEntities, BlockStyles);
var blockToModify = blocks[blocks.length - 1];
blockToModify.text = content;
blockToModify.inlineStyleRanges = blockInlineStyleRanges;
blockToModify.entityRanges = blockEntityRanges;
// The entity map is a master object separate from the block so just add any entities created for this block to the master object
Object.assign(entityMap, blockEntities);
} else if ((itemType.indexOf('_open') !== -1 || RemarkableStandaloneBlocks.includes(itemType)) && BlockTypes[itemType]) {
var depth = 0;
var block;
if (item.level > 0) {
depth = Math.floor(item.level / 2);
}
// Draftjs only supports 1 level of blocks, hence the item.level === 0 check
// List items will always be at least `level==1` though so we need a separate check for that
// If there’s nested block level items deeper than that, we need to make sure we capture this by cloning the topmost block
// otherwise we’ll accidentally overwrite its text. (eg if there's a blockquote with 3 nested paragraphs with inline text, without this check, only the last paragraph would be reflected)
if (item.level === 0 || item.type === 'list_item_open') {
block = Object.assign({
depth: depth
}, BlockTypes[itemType](item));
} else if (item.level > 0 && blocks[blocks.length - 1].text) {
block = Object.assign({}, blocks[blocks.length - 1]);
}
if (block && options.preserveNewlines) {
// Re: previousBlockEndingLine.... omg.
// So remarkable strips out empty newlines and doesn't make any entities to parse to restore them
// the only solution I could find is that there's a 2-value array on each block item called "lines" which is the start and end line of the block element.
// by keeping track of the PREVIOUS block element ending line and the NEXT block element starting line, we can find the difference between the new lines and insert
// an appropriate number of extra paragraphs to re-create those newlines in draftjs.
// This is probably my least favourite thing in this file, but not sure what could be better.
var totalEmptyParagraphsToCreate = item.lines[0] - previousBlockEndingLine;
for (var i = 0; i < totalEmptyParagraphsToCreate; i++) {
blocks.push(DefaultBlockTypes.paragraph_open());
}
}
if (block) {
previousBlockEndingLine = item.lines[1];
blocks.push(block);
}
}
});
// EditorState.createWithContent will error if there's no blocks defined
// Remarkable returns an empty array though. So we have to generate a 'fake'
// empty block in this case. 😑
if (!blocks.length) {
blocks.push(DefaultBlockTypes.paragraph_open());
}
return {
entityMap,
blocks
};
}
export default markdownToDraft;