@takeshape/util 8.16.0 → 8.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/draftjs.js ADDED
@@ -0,0 +1,901 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.draftjsToMd = draftjsToMd;
7
+ exports.draftjsToMdx = draftjsToMdx;
8
+ exports.fromDraftjs = fromDraftjs;
9
+ exports.getImagePathFromUrl = getImagePathFromUrl;
10
+ exports.insertBreaksAroundBlocks = insertBreaksAroundBlocks;
11
+ exports.mdToDraftjs = mdToDraftjs;
12
+ exports.mdxToDraftjs = mdxToDraftjs;
13
+
14
+ var _markdownDraftJs = require("markdown-draft-js");
15
+
16
+ var _templates = require("./templates");
17
+
18
+ var _htmlparser = require("htmlparser2");
19
+
20
+ var _urlParse = _interopRequireDefault(require("url-parse"));
21
+
22
+ var _domSerializer = _interopRequireDefault(require("dom-serializer"));
23
+
24
+ var _shortid = _interopRequireDefault(require("shortid"));
25
+
26
+ var _draftjsTemplates = require("./draftjs-templates");
27
+
28
+ var _escape = _interopRequireDefault(require("lodash/escape"));
29
+
30
+ var _unescape = _interopRequireDefault(require("lodash/unescape"));
31
+
32
+ var _pickBy = _interopRequireDefault(require("lodash/pickBy"));
33
+
34
+ var _routing = require("@takeshape/routing");
35
+
36
+ var _forEach = _interopRequireDefault(require("lodash/forEach"));
37
+
38
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
39
+
40
+ /*
41
+ * The intention is to move all this to the client package in the end, but right now it's here
42
+ * to be shared between the draftjs / mdx implementations, which span the client / server differently.
43
+ */
44
+ // With @types/htmlparser2 it says parseDOM is not exported; excluding types for now
45
+ // @ts-expect-error Untyped
46
+ const SUPERSCRIPT_MARKER = 'TEMPORARY_SUPERSCRIPT_MARKER_TLfDNyf7VYKDduyL';
47
+ const SUBSCRIPT_MARKER = 'TEMPORARY_SUBSCRIPT_MARKER_K5VrdPEzyQyy2RcY';
48
+ const INSERT_MARKER = 'TEMPORARY_INSERT_MARKER_FSYdr8m8CS7YLb8y';
49
+ const EXTERNAL_LINK_MARKER = 'TEMPORARY_EXTERNAL_LINK_MARKER_HP3vprmERkc9ZAss';
50
+ const pullquoteStyle = 'font-style: italic; margin: 2em 2.5em;';
51
+
52
+ const getDraftjsEmpty = (depth = 0) => {
53
+ return {
54
+ key: _shortid.default.generate(),
55
+ depth,
56
+ type: 'unstyled',
57
+ text: '',
58
+ entityRanges: [],
59
+ inlineStyleRanges: []
60
+ };
61
+ };
62
+
63
+ const REMOVAL_MARKER_TYPE = 'removal-marker';
64
+
65
+ const getDraftjsRemovalMarker = (depth = 0) => {
66
+ return {
67
+ key: _shortid.default.generate(),
68
+ type: REMOVAL_MARKER_TYPE,
69
+ depth,
70
+ text: '',
71
+ entityRanges: [],
72
+ inlineStyleRanges: []
73
+ };
74
+ };
75
+
76
+ const mdxShortcodePrefix = tagName => `TS${tagName}`;
77
+
78
+ const handleMultiword = (markdown, marker, markdownSyntax, markdownRegex) => {
79
+ const parts = markdown.replace(markdownRegex, `\\${markdownSyntax}`).split(marker);
80
+ let result = '';
81
+ let open = false;
82
+
83
+ for (const [i, part] of parts.entries()) {
84
+ if (open) {
85
+ result += part.replace(/\s+/g, match => `${markdownSyntax}${match}${markdownSyntax}`);
86
+ } else {
87
+ result += part;
88
+ }
89
+
90
+ if (i !== parts.length - 1) {
91
+ result += markdownSyntax;
92
+ open = !open;
93
+ }
94
+ }
95
+
96
+ return result;
97
+ }; // Workaround inability to reasonably process child content using draftToMarkdown
98
+
99
+
100
+ const handleExternalLinks = markdown => {
101
+ const regex = /(<TSExternalLink text="TEMPORARY_EXTERNAL_LINK_MARKER_HP3vprmERkc9ZAss" href="[^"]+">)([^<]+)<\/TSExternalLink>/g;
102
+ return markdown.replace(regex, (match, openTag, content) => match.replace(EXTERNAL_LINK_MARKER, (0, _escape.default)(content)));
103
+ };
104
+
105
+ function fromDraftjs(draftjs, styleItems, entityItems) {
106
+ let markdown = (0, _markdownDraftJs.draftToMarkdown)(draftjs, {
107
+ styleItems: {
108
+ 'section-break': {
109
+ open() {
110
+ return '***';
111
+ },
112
+
113
+ close() {
114
+ return '';
115
+ }
116
+
117
+ },
118
+ SUP: {
119
+ open() {
120
+ return SUPERSCRIPT_MARKER;
121
+ },
122
+
123
+ close() {
124
+ return SUPERSCRIPT_MARKER;
125
+ }
126
+
127
+ },
128
+ SUB: {
129
+ open() {
130
+ return SUBSCRIPT_MARKER;
131
+ },
132
+
133
+ close() {
134
+ return SUBSCRIPT_MARKER;
135
+ }
136
+
137
+ },
138
+ UNDERLINE: {
139
+ open() {
140
+ return INSERT_MARKER;
141
+ },
142
+
143
+ close() {
144
+ return INSERT_MARKER;
145
+ }
146
+
147
+ },
148
+ 'code-block': {
149
+ open(entity) {
150
+ var _entity$data;
151
+
152
+ const lang = (entity === null || entity === void 0 ? void 0 : (_entity$data = entity.data) === null || _entity$data === void 0 ? void 0 : _entity$data.lang) ?? '';
153
+ return `\`\`\`${lang}\n`;
154
+ },
155
+
156
+ close() {
157
+ return '\n```';
158
+ }
159
+
160
+ },
161
+ ...styleItems
162
+ },
163
+ entityItems: {
164
+ LINK: {
165
+ open(entity) {
166
+ var _entity$data2;
167
+
168
+ if ((entity === null || entity === void 0 ? void 0 : (_entity$data2 = entity.data) === null || _entity$data2 === void 0 ? void 0 : _entity$data2.target) === '_blank') {
169
+ var _entity$data3, _entity$data4;
170
+
171
+ const url = (0, _escape.default)((entity === null || entity === void 0 ? void 0 : (_entity$data3 = entity.data) === null || _entity$data3 === void 0 ? void 0 : _entity$data3.url) || (entity === null || entity === void 0 ? void 0 : (_entity$data4 = entity.data) === null || _entity$data4 === void 0 ? void 0 : _entity$data4.href) || '');
172
+ return `<TSExternalLink text="${EXTERNAL_LINK_MARKER}" href="${url}">`;
173
+ }
174
+
175
+ return '[';
176
+ },
177
+
178
+ close(entity) {
179
+ var _entity$data5, _entity$data6, _entity$data7;
180
+
181
+ if ((entity === null || entity === void 0 ? void 0 : (_entity$data5 = entity.data) === null || _entity$data5 === void 0 ? void 0 : _entity$data5.target) === '_blank') {
182
+ return '</TSExternalLink>';
183
+ }
184
+
185
+ return ']('.concat((entity === null || entity === void 0 ? void 0 : (_entity$data6 = entity.data) === null || _entity$data6 === void 0 ? void 0 : _entity$data6.url) || (entity === null || entity === void 0 ? void 0 : (_entity$data7 = entity.data) === null || _entity$data7 === void 0 ? void 0 : _entity$data7.href) || '', ')');
186
+ }
187
+
188
+ },
189
+ ...entityItems
190
+ }
191
+ });
192
+ markdown = handleExternalLinks(markdown);
193
+ markdown = handleMultiword(markdown, SUPERSCRIPT_MARKER, '^', /\^/g);
194
+ markdown = handleMultiword(markdown, SUBSCRIPT_MARKER, '~', /~/g); // eslint-disable-next-line security-node/non-literal-reg-expr
195
+
196
+ markdown = markdown.replace(/\+/g, '\\+').replace(new RegExp(INSERT_MARKER, 'g'), '++');
197
+ return markdown;
198
+ }
199
+
200
+ function draftjsToMd(draftjs, assets) {
201
+ return fromDraftjs(draftjs, {
202
+ pullquote: {
203
+ open() {
204
+ return `<aside style="${pullquoteStyle}">`;
205
+ },
206
+
207
+ close() {
208
+ return '</aside>';
209
+ }
210
+
211
+ }
212
+ }, {
213
+ oembed: {
214
+ open() {
215
+ return '';
216
+ },
217
+
218
+ close(entity) {
219
+ if (!(entity !== null && entity !== void 0 && entity.data)) {
220
+ return '';
221
+ }
222
+
223
+ const {
224
+ data
225
+ } = entity;
226
+ return (0, _templates.oembedTemplate)(str => str, data);
227
+ }
228
+
229
+ },
230
+ image: {
231
+ open() {
232
+ return '';
233
+ },
234
+
235
+ close(entity) {
236
+ if (!(entity !== null && entity !== void 0 && entity.data)) {
237
+ return '';
238
+ }
239
+
240
+ const {
241
+ data
242
+ } = entity;
243
+ const asset = assets[data.id];
244
+
245
+ if (asset === undefined) {
246
+ return '';
247
+ }
248
+
249
+ const imageTemplateData = { ...data,
250
+ alignment: data.alignment,
251
+ size: data.size,
252
+ asset,
253
+ caption: getAssetField(data, asset, 'caption'),
254
+ credit: getAssetField(data, asset, 'credit'),
255
+ imageParams: {}
256
+ };
257
+ return (0, _templates.imageTemplate)(str => str, imageTemplateData);
258
+ }
259
+
260
+ }
261
+ });
262
+ }
263
+
264
+ function getTextFromDraftjs(draftjs) {
265
+ var _draftjs$blocks, _draftjs$blocks$;
266
+
267
+ return draftjs === null || draftjs === void 0 ? void 0 : (_draftjs$blocks = draftjs.blocks) === null || _draftjs$blocks === void 0 ? void 0 : (_draftjs$blocks$ = _draftjs$blocks[0]) === null || _draftjs$blocks$ === void 0 ? void 0 : _draftjs$blocks$.text;
268
+ }
269
+
270
+ function getAssetField(data, asset, field) {
271
+ const dataText = getTextFromDraftjs(data[field]);
272
+
273
+ if (dataText) {
274
+ return dataText;
275
+ }
276
+
277
+ if (asset[field]) {
278
+ return getTextFromDraftjs(asset[field]);
279
+ }
280
+
281
+ return '';
282
+ }
283
+
284
+ function draftjsToMdx(draftjs, assets, prefix = mdxShortcodePrefix) {
285
+ return fromDraftjs(draftjs, {
286
+ pullquote: {
287
+ open() {
288
+ return `<${prefix('Pullquote')}>`;
289
+ },
290
+
291
+ close() {
292
+ return `</${prefix('Pullquote')}>`;
293
+ }
294
+
295
+ }
296
+ }, {
297
+ oembed: {
298
+ open() {
299
+ return '';
300
+ },
301
+
302
+ close(entity) {
303
+ if (!(entity !== null && entity !== void 0 && entity.data)) {
304
+ return '';
305
+ }
306
+
307
+ const {
308
+ data
309
+ } = entity;
310
+ return (0, _templates.oembedTemplateMdx)(prefix, data);
311
+ }
312
+
313
+ },
314
+ image: {
315
+ open() {
316
+ return '';
317
+ },
318
+
319
+ close(entity) {
320
+ var _entity$data8, _data$link, _data$link2;
321
+
322
+ const asset = assets[entity === null || entity === void 0 ? void 0 : (_entity$data8 = entity.data) === null || _entity$data8 === void 0 ? void 0 : _entity$data8.id];
323
+
324
+ if (!(entity !== null && entity !== void 0 && entity.data) || asset === undefined) {
325
+ return '';
326
+ }
327
+
328
+ const {
329
+ data
330
+ } = entity;
331
+ const imageUrlOptions = process.env.NODE_ENV === 'production' ? {} : {
332
+ baseUrl: 'https://images.dev.takeshape.io'
333
+ };
334
+ return (0, _templates.imageTemplateMdx)(prefix, { ...data,
335
+ assetId: data.id,
336
+ assetPath: asset.path,
337
+ credit: getAssetField(data, asset, 'credit'),
338
+ caption: getAssetField(data, asset, 'caption'),
339
+ link: (_data$link = data.link) === null || _data$link === void 0 ? void 0 : _data$link.url,
340
+ linkisexternal: (_data$link2 = data.link) !== null && _data$link2 !== void 0 && _data$link2.external ? 'true' : 'false',
341
+ src: (0, _routing.getImageUrl)(asset.path, data.imageParams, imageUrlOptions)
342
+ });
343
+ }
344
+
345
+ }
346
+ });
347
+ }
348
+
349
+ function getAssetIdFromImageSrc(src) {
350
+ return new _urlParse.default(src).pathname.split('/')[3];
351
+ }
352
+
353
+ function parseFigureClass(className) {
354
+ if (className === undefined) {
355
+ return {
356
+ alignment: undefined,
357
+ size: undefined
358
+ };
359
+ }
360
+
361
+ const parts = className.split(' ');
362
+ return {
363
+ alignment: parts[0],
364
+ size: parts[1]
365
+ };
366
+ } // eslint-disable-next-line complexity
367
+
368
+
369
+ function htmlDomToDraftjsImage(dom, item, entityKeyGenerator) {
370
+ for (const figure of dom) {
371
+ if (figure.type === 'tag' && figure.name === 'figure') {
372
+ var _figure$children, _figure$children2, _figcaption, _figcaption2, _caption, _credit, _link, _link2;
373
+
374
+ let link;
375
+ const figureChildOne = (_figure$children = figure.children) === null || _figure$children === void 0 ? void 0 : _figure$children[0];
376
+ const figureChildTwo = (_figure$children2 = figure.children) === null || _figure$children2 === void 0 ? void 0 : _figure$children2[1];
377
+
378
+ if ((figureChildOne === null || figureChildOne === void 0 ? void 0 : figureChildOne.type) === 'tag' && (figureChildOne === null || figureChildOne === void 0 ? void 0 : figureChildOne.name) === 'a') {
379
+ link = figureChildOne;
380
+ }
381
+
382
+ let figcaption;
383
+
384
+ if ((figureChildOne === null || figureChildOne === void 0 ? void 0 : figureChildOne.type) === 'tag' && (figureChildOne === null || figureChildOne === void 0 ? void 0 : figureChildOne.name) === 'figcaption') {
385
+ figcaption = figureChildOne;
386
+ } else if ((figureChildTwo === null || figureChildTwo === void 0 ? void 0 : figureChildTwo.type) === 'tag' && (figureChildTwo === null || figureChildTwo === void 0 ? void 0 : figureChildTwo.name) === 'figcaption') {
387
+ figcaption = figure.children[1];
388
+ }
389
+
390
+ const img = link ? link.children[0] : figure.children[0];
391
+
392
+ if ((img === null || img === void 0 ? void 0 : img.type) !== 'tag' || (img === null || img === void 0 ? void 0 : img.name) !== 'img') {
393
+ return;
394
+ }
395
+
396
+ const figcaptionChild = (_figcaption = figcaption) === null || _figcaption === void 0 ? void 0 : _figcaption.children[0];
397
+ let caption;
398
+
399
+ if ((figcaptionChild === null || figcaptionChild === void 0 ? void 0 : figcaptionChild.type) === 'tag' && (figcaptionChild === null || figcaptionChild === void 0 ? void 0 : figcaptionChild.name) === 'span' && (figcaptionChild === null || figcaptionChild === void 0 ? void 0 : figcaptionChild.attribs.class) === 'caption') {
400
+ caption = figcaptionChild;
401
+ }
402
+
403
+ const captionChildThree = (_figcaption2 = figcaption) === null || _figcaption2 === void 0 ? void 0 : _figcaption2.children[2];
404
+ let credit;
405
+
406
+ if ((captionChildThree === null || captionChildThree === void 0 ? void 0 : captionChildThree.type) === 'tag' && (captionChildThree === null || captionChildThree === void 0 ? void 0 : captionChildThree.name) === 'span' && (captionChildThree === null || captionChildThree === void 0 ? void 0 : captionChildThree.attribs.class) === 'credit') {
407
+ credit = captionChildThree;
408
+ }
409
+
410
+ const {
411
+ alignment,
412
+ size
413
+ } = parseFigureClass(figure.attribs.class);
414
+ return (0, _draftjsTemplates.getDraftjsImage)({
415
+ captionText: ((_caption = caption) === null || _caption === void 0 ? void 0 : _caption.children[0].data) ?? '',
416
+ creditText: ((_credit = credit) === null || _credit === void 0 ? void 0 : _credit.children[0].data) ?? '',
417
+ alignment,
418
+ size,
419
+ assetId: getAssetIdFromImageSrc(img.attribs.src),
420
+ linkUrl: (_link = link) === null || _link === void 0 ? void 0 : _link.attribs.href,
421
+ linkIsExternal: ((_link2 = link) === null || _link2 === void 0 ? void 0 : _link2.attribs.target) === '_blank',
422
+ key: entityKeyGenerator(),
423
+ depth: item.level,
424
+ path: getImagePathFromUrl(img.attribs.src)
425
+ });
426
+ }
427
+ }
428
+ }
429
+
430
+ function htmlDomToOembed(dom, item, entityKeyGenerator) {
431
+ for (const oembedDiv of dom) {
432
+ if (oembedDiv.type === 'tag' && oembedDiv.name === 'div' && oembedDiv.attribs.class === 'oembed') {
433
+ const blockquote = oembedDiv.children[0];
434
+
435
+ if ((blockquote === null || blockquote === void 0 ? void 0 : blockquote.type) !== 'tag' || (blockquote === null || blockquote === void 0 ? void 0 : blockquote.name) !== 'blockquote') {
436
+ return;
437
+ }
438
+
439
+ const script = oembedDiv.children[2];
440
+
441
+ if ((script === null || script === void 0 ? void 0 : script.type) !== 'script' || (script === null || script === void 0 ? void 0 : script.name) !== 'script') {
442
+ return;
443
+ }
444
+
445
+ return (0, _draftjsTemplates.getDraftjsOembed)({
446
+ html: `${(0, _domSerializer.default)(blockquote)}\n${(0, _domSerializer.default)(script)}\n`,
447
+ key: entityKeyGenerator(),
448
+ depth: item.level
449
+ });
450
+ }
451
+ }
452
+ }
453
+
454
+ function mdxToDraftjsOembed(item, entityKeyGenerator) {
455
+ if (item.content.startsWith(`<${mdxShortcodePrefix('Oembed')}`)) {
456
+ const dom = (0, _htmlparser.parseDOM)(item.content)[0];
457
+ return (0, _draftjsTemplates.getDraftjsOembed)({
458
+ html: (0, _unescape.default)(dom.attribs.html),
459
+ width: dom.attribs.width ? Number(dom.attribs.width) : undefined,
460
+ height: dom.attribs.height ? Number(dom.attribs.height) : undefined,
461
+ url: (0, _unescape.default)(dom.attribs.url),
462
+ author_name: (0, _unescape.default)(dom.attribs.author_name),
463
+ author_url: (0, _unescape.default)(dom.attribs.author_url),
464
+ type: (0, _unescape.default)(dom.attribs.type),
465
+ cache_age: Number(dom.attribs.cache_age),
466
+ provider_name: (0, _unescape.default)(dom.attribs.provider_name),
467
+ provider_url: (0, _unescape.default)(dom.attribs.provider_url),
468
+ version: (0, _unescape.default)(dom.attribs.version),
469
+ key: entityKeyGenerator(),
470
+ depth: item.level
471
+ });
472
+ }
473
+ }
474
+
475
+ function htmlDomToPullquote(dom, item) {
476
+ for (const pullquote of dom) {
477
+ if (pullquote.type === 'tag' && pullquote.name === 'aside' && pullquote.attribs.style === pullquoteStyle) {
478
+ const text = pullquote.children[0];
479
+
480
+ if ((text === null || text === void 0 ? void 0 : text.type) !== 'text') {
481
+ return;
482
+ }
483
+
484
+ return (0, _draftjsTemplates.getDraftjsPullquote)({
485
+ text: text.data,
486
+ depth: item.level
487
+ });
488
+ }
489
+ }
490
+ }
491
+
492
+ function fromMd(md, blockEntities, blockTypes) {
493
+ md = md.replace(/\\\+/g, '+').replace(/\\~/g, '~').replace(/\\\^/g, '^');
494
+ return (0, _markdownDraftJs.markdownToDraft)(md, {
495
+ remarkablePreset: 'full',
496
+ remarkableOptions: {
497
+ html: true
498
+ },
499
+ blockStyles: {
500
+ ins_open: 'UNDERLINE',
501
+ sub: 'SUB',
502
+ sup: 'SUP'
503
+ },
504
+ blockEntities,
505
+ blockTypes: {
506
+ hr(item) {
507
+ if (!item) {
508
+ return getDraftjsEmpty();
509
+ }
510
+
511
+ return {
512
+ key: _shortid.default.generate(),
513
+ text: ' ',
514
+ type: 'section-break',
515
+ depth: item.level,
516
+ inlineStyleRanges: [],
517
+ entityRanges: [],
518
+ data: {}
519
+ };
520
+ },
521
+
522
+ fence(item) {
523
+ if (!item) {
524
+ return getDraftjsEmpty();
525
+ }
526
+
527
+ return {
528
+ type: 'code-block',
529
+ data: {
530
+ // In markdown-to-draft this is language, we require lang
531
+ lang: item.params || ''
532
+ },
533
+ // Using the text handling from markdown-to-draft
534
+ text: (item.content || '').replace(/\n$/, ''),
535
+ entityRanges: [],
536
+ inlineStyleRanges: []
537
+ };
538
+ },
539
+
540
+ ...blockTypes
541
+ }
542
+ });
543
+ }
544
+
545
+ function mdToDraftjs(mdx) {
546
+ const entities = {}; // Start really high to avoid conflicts with keys created by markdown-draft-js
547
+
548
+ let currentEntityKey = 1000000;
549
+
550
+ function entityKeyGenerator() {
551
+ return currentEntityKey++;
552
+ }
553
+
554
+ const result = fromMd(mdx, {}, {
555
+ htmlblock(item) {
556
+ if (item === undefined) {
557
+ return getDraftjsEmpty();
558
+ }
559
+
560
+ const dom = (0, _htmlparser.parseDOM)(item.content);
561
+ const image = htmlDomToDraftjsImage(dom, item, entityKeyGenerator);
562
+
563
+ if (image) {
564
+ Object.assign(entities, image.entities);
565
+ return image.contentBlock;
566
+ }
567
+
568
+ const oembed = htmlDomToOembed(dom, item, entityKeyGenerator);
569
+
570
+ if (oembed) {
571
+ Object.assign(entities, oembed.entities);
572
+ return oembed.contentBlock;
573
+ }
574
+
575
+ const pullquote = htmlDomToPullquote(dom, item);
576
+
577
+ if (pullquote) {
578
+ Object.assign(entities, pullquote.entities);
579
+ return pullquote.contentBlock;
580
+ }
581
+
582
+ return getDraftjsEmpty(item.level);
583
+ }
584
+
585
+ });
586
+ result.entityMap = { ...result.entityMap,
587
+ ...entities
588
+ };
589
+ return result;
590
+ }
591
+
592
+ function getImagePathFromUrl(url) {
593
+ return new _urlParse.default(url).pathname.substr(1);
594
+ }
595
+
596
+ function mdxToBr(item) {
597
+ if (item.content.startsWith('<br/>')) {
598
+ return {
599
+ key: _shortid.default.generate(),
600
+ depth: item.depth,
601
+ type: 'unstyled',
602
+ text: '',
603
+ entityRanges: [],
604
+ inlineStyleRanges: []
605
+ };
606
+ }
607
+ }
608
+
609
+ function mdxToLinkData(item) {
610
+ if (item.content.startsWith('<TSExternalLink')) {
611
+ const dom = (0, _htmlparser.parseDOM)(item.content)[0];
612
+ return {
613
+ url: dom.attribs.href,
614
+ target: '_blank',
615
+ text: dom.attribs.text
616
+ };
617
+ }
618
+ }
619
+
620
+ function mdxToDraftjsImage(item, entityKeyGenerator) {
621
+ if (item.content.startsWith(`<${mdxShortcodePrefix('Image')}`)) {
622
+ const dom = (0, _htmlparser.parseDOM)(item.content)[0];
623
+ return (0, _draftjsTemplates.getDraftjsImage)({
624
+ captionText: (0, _unescape.default)(dom.attribs.caption).replace(/<\/?p>/g, ''),
625
+ creditText: (0, _unescape.default)(dom.attribs.credit).replace(/<\/?p>/g, ''),
626
+ alignment: dom.attribs.alignment,
627
+ size: dom.attribs.size,
628
+ assetId: dom.attribs.id,
629
+ linkUrl: dom.attribs.link,
630
+ linkIsExternal: dom.attribs.linkisexternal === 'true',
631
+ key: entityKeyGenerator(),
632
+ depth: item.level,
633
+ path: getImagePathFromUrl(decodeURIComponent(dom.attribs.src))
634
+ });
635
+ }
636
+ }
637
+
638
+ function mdxToDraftjsPullquote(item) {
639
+ if (item.content.startsWith(`<${mdxShortcodePrefix('Pullquote')}`)) {
640
+ const dom = (0, _htmlparser.parseDOM)(item.content)[0];
641
+ return (0, _draftjsTemplates.getDraftjsPullquote)({
642
+ text: (0, _unescape.default)(dom.attribs.text),
643
+ depth: item.level
644
+ });
645
+ }
646
+ }
647
+
648
+ /**
649
+ * Mutates result to replace empty entities with links,
650
+ * assuming there is nothing else they could be...
651
+ */
652
+ function addLinks(state, links) {
653
+ let linkNumber = 0;
654
+ let linkOpen = false;
655
+
656
+ for (const block of state.blocks) {
657
+ let blockIsCustom = false;
658
+
659
+ for (const [i, entityRange] of block.entityRanges.entries()) {
660
+ var _entity$data9;
661
+
662
+ const entity = state.entityMap[entityRange.key];
663
+
664
+ if (entity === undefined) {
665
+ throw new Error('Missing entity');
666
+ }
667
+
668
+ if (i === 0 && (_entity$data9 = entity.data) !== null && _entity$data9 !== void 0 && _entity$data9.marker) {
669
+ blockIsCustom = true;
670
+ continue;
671
+ }
672
+
673
+ if (blockIsCustom && i === Object.keys(block.entityRanges).length - 1) {
674
+ continue;
675
+ } // Ignore line breaks that were inserted around blocks
676
+
677
+
678
+ if (entity.depth === undefined) {
679
+ continue;
680
+ }
681
+
682
+ const link = links[linkNumber];
683
+
684
+ if (link && !linkOpen) {
685
+ entity.type = 'LINK';
686
+ entity.mutability = 'MUTABLE';
687
+ entity.data = link;
688
+ entity.text = link.text;
689
+ entityRange.length += link.text.length;
690
+ linkNumber++;
691
+ }
692
+
693
+ linkOpen = !linkOpen;
694
+ }
695
+ }
696
+ }
697
+ /**
698
+ * Mutate state to replace blocks with our custom versions
699
+ * Return a list of entity keys that should be removed
700
+ */
701
+
702
+
703
+ function replaceBlocks(state, replacementBlocks) {
704
+ let entityKeysToExclude = [];
705
+
706
+ for (let i = 0; i < state.blocks.length; i++) {
707
+ const block = state.blocks[i];
708
+
709
+ for (const entityKey of Object.keys(state.entityMap)) {
710
+ let removeBlockEntityKeys = false;
711
+ const blockEntityKeys = block.entityRanges.map(range => range.key);
712
+
713
+ if (blockEntityKeys.includes(Number(entityKey))) {
714
+ var _entity$data10;
715
+
716
+ const entity = state.entityMap[entityKey];
717
+ const markerKey = (_entity$data10 = entity.data) === null || _entity$data10 === void 0 ? void 0 : _entity$data10.marker;
718
+ const replacementBlock = replacementBlocks[markerKey];
719
+
720
+ if (replacementBlock && !removeBlockEntityKeys) {
721
+ const originalBlock = state.blocks[i];
722
+ const originalBlockText = state.blocks[i].text;
723
+ replacementBlock.text = originalBlockText !== '' ? originalBlockText : replacementBlock.text;
724
+ replacementBlock.inlineStyleRanges = originalBlock.inlineStyleRanges;
725
+ const removeBlockEntities = entity.data.type === 'image' || entity.data.type === 'oembed'; // eslint-disable-next-line max-depth
726
+
727
+ if (!removeBlockEntities) {
728
+ replacementBlock.entityRanges = originalBlock.entityRanges.filter(entityRange => {
729
+ var _state$entityMap$enti;
730
+
731
+ return ((_state$entityMap$enti = state.entityMap[entityRange.key].data) === null || _state$entityMap$enti === void 0 ? void 0 : _state$entityMap$enti.marker) === undefined;
732
+ });
733
+ }
734
+
735
+ state.blocks[i] = replacementBlock; // eslint-disable-next-line max-depth
736
+
737
+ if (removeBlockEntities) {
738
+ removeBlockEntityKeys = true;
739
+ }
740
+ }
741
+ }
742
+
743
+ if (removeBlockEntityKeys) {
744
+ entityKeysToExclude = entityKeysToExclude.concat(blockEntityKeys);
745
+ }
746
+ }
747
+ }
748
+
749
+ return entityKeysToExclude;
750
+ }
751
+
752
+ const blockStarts = [{
753
+ regex: ' <TSImage',
754
+ replacement: ' <TSImage'
755
+ }, {
756
+ regex: ' <TSOembed',
757
+ replacement: ' <TSOembed'
758
+ }, {
759
+ regex: '\\*\\*\\*',
760
+ replacement: '***'
761
+ }, {
762
+ regex: '```',
763
+ replacement: '```'
764
+ }];
765
+ const blockEnds = [{
766
+ regex: '(?<=<TSImage[^>]+)/>',
767
+ replacement: '/>'
768
+ }, {
769
+ regex: '</TSOembed>',
770
+ replacement: '</TSOembed>'
771
+ }, {
772
+ regex: '\\*\\*\\*',
773
+ replacement: '***'
774
+ }, {
775
+ regex: '```',
776
+ replacement: '```'
777
+ }];
778
+ /**
779
+ * Make sure there is a place to put the cursor around block-level items such as images and oembeds
780
+ */
781
+
782
+ function insertBreaksAroundBlocks(mdx) {
783
+ for (const start of blockStarts) {
784
+ // eslint-disable-next-line security-node/non-literal-reg-expr
785
+ mdx = mdx.replace(new RegExp(`^${start.regex}`, 'g'), `<br/>\n\n${start.replacement}`);
786
+ }
787
+
788
+ for (const end of blockEnds) {
789
+ // eslint-disable-next-line security-node/non-literal-reg-expr
790
+ mdx = mdx.replace(new RegExp(`${end.regex}\\s*$`, 'g'), `${end.replacement}\n\n<br/>`);
791
+
792
+ for (const start of blockStarts) {
793
+ mdx = mdx.replace( // eslint-disable-next-line security-node/non-literal-reg-expr
794
+ new RegExp(`${end.regex}\\s*${start.regex}`, 'g'), `${end.replacement}\n\n<br/>\n\n${start.replacement}`);
795
+ }
796
+ }
797
+
798
+ return mdx;
799
+ }
800
+
801
+ function mdxToDraftjs(mdx) {
802
+ const replacementBlocks = {};
803
+ const entities = {};
804
+ const oembedKeyToHtml = {};
805
+ let currentOembedKey; // Start really high to avoid conflicts with keys created by markdown-draft-js
806
+
807
+ let currentEntityKey = 1000000;
808
+
809
+ function entityKeyGenerator() {
810
+ return currentEntityKey++;
811
+ }
812
+
813
+ mdx = insertBreaksAroundBlocks(mdx);
814
+ const links = [];
815
+ const result = fromMd(mdx, {
816
+ htmltag(item) {
817
+ if (item === undefined) {
818
+ return getDraftjsEmpty();
819
+ }
820
+
821
+ const br = mdxToBr(item);
822
+
823
+ if (br) {
824
+ return br;
825
+ }
826
+
827
+ const linkData = mdxToLinkData(item);
828
+
829
+ if (linkData) {
830
+ links.push(linkData);
831
+ }
832
+
833
+ const image = mdxToDraftjsImage(item, entityKeyGenerator);
834
+
835
+ if (image) {
836
+ replacementBlocks[image.contentBlock.key] = image.contentBlock;
837
+ Object.assign(entities, image.entities);
838
+ return {
839
+ data: {
840
+ marker: image.contentBlock.key,
841
+ type: 'image'
842
+ }
843
+ };
844
+ }
845
+
846
+ const oembed = mdxToDraftjsOembed(item, entityKeyGenerator);
847
+
848
+ if (oembed) {
849
+ currentOembedKey = Object.keys(oembed.entities)[0];
850
+ replacementBlocks[oembed.contentBlock.key] = oembed.contentBlock;
851
+ Object.assign(entities, oembed.entities);
852
+ return {
853
+ data: {
854
+ marker: oembed.contentBlock.key,
855
+ type: 'oembed'
856
+ }
857
+ };
858
+ }
859
+
860
+ const pullquote = mdxToDraftjsPullquote(item);
861
+
862
+ if (pullquote) {
863
+ replacementBlocks[pullquote.contentBlock.key] = pullquote.contentBlock;
864
+ Object.assign(entities, pullquote.entities);
865
+ return {
866
+ data: {
867
+ marker: pullquote.contentBlock.key,
868
+ type: 'pullquote'
869
+ }
870
+ };
871
+ }
872
+
873
+ return getDraftjsEmpty(item.level);
874
+ }
875
+
876
+ }, {
877
+ htmlblock(item) {
878
+ if (item && currentOembedKey) {
879
+ oembedKeyToHtml[currentOembedKey] = item.content.replace(`</${mdxShortcodePrefix('Oembed')}>\n`, '');
880
+ currentOembedKey = undefined;
881
+ }
882
+
883
+ return getDraftjsRemovalMarker();
884
+ }
885
+
886
+ });
887
+ addLinks(result, links);
888
+ const entityKeysToExclude = replaceBlocks(result, replacementBlocks);
889
+ result.blocks = result.blocks.filter(block => block.type !== REMOVAL_MARKER_TYPE);
890
+ (0, _forEach.default)(oembedKeyToHtml, (html, key) => {
891
+ entities[key].data.html = html;
892
+ });
893
+ result.entityMap = (0, _pickBy.default)({ ...result.entityMap,
894
+ ...entities
895
+ }, (entity, key) => {
896
+ var _entity$data11;
897
+
898
+ return ((_entity$data11 = entity.data) === null || _entity$data11 === void 0 ? void 0 : _entity$data11.marker) === undefined && !entityKeysToExclude.includes(Number(key));
899
+ });
900
+ return result;
901
+ }