@takeshape/util 11.45.5 → 11.47.1

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.
Files changed (242) hide show
  1. package/dist/cjs/common/arrays.js +42 -0
  2. package/dist/cjs/common/assert.js +9 -0
  3. package/dist/cjs/common/async-noop.js +5 -0
  4. package/dist/cjs/common/billing.js +35 -0
  5. package/dist/cjs/common/clone.js +76 -0
  6. package/dist/cjs/common/delay.js +28 -0
  7. package/dist/cjs/common/draftjs-templates.js +131 -0
  8. package/dist/cjs/common/draftjs.js +807 -0
  9. package/dist/cjs/common/get-image-url.js +8 -0
  10. package/dist/cjs/common/highlight-code.js +33 -0
  11. package/dist/cjs/common/http.js +19 -0
  12. package/dist/cjs/common/index.js +50 -0
  13. package/dist/cjs/common/map.js +7 -0
  14. package/dist/cjs/common/memoize.js +13 -0
  15. package/dist/cjs/common/merge.js +64 -0
  16. package/dist/cjs/common/mime.js +68 -0
  17. package/dist/cjs/common/names.js +13 -0
  18. package/dist/cjs/common/naming.js +65 -0
  19. package/dist/cjs/common/path-to-string.js +10 -0
  20. package/dist/cjs/common/persisted-queries.js +4 -0
  21. package/dist/cjs/common/predicate.js +15 -0
  22. package/dist/cjs/common/set-in.js +13 -0
  23. package/dist/cjs/common/sets.js +19 -0
  24. package/dist/cjs/common/sleep.js +9 -0
  25. package/dist/cjs/common/sort-object.js +16 -0
  26. package/dist/cjs/common/strings.js +74 -0
  27. package/dist/cjs/common/templates.js +109 -0
  28. package/dist/cjs/common/timezone.js +606 -0
  29. package/dist/cjs/common/tracing.js +2 -0
  30. package/dist/cjs/common/types.js +63 -0
  31. package/dist/cjs/common/unix-to-iso.js +15 -0
  32. package/dist/cjs/common/urls.js +9 -0
  33. package/dist/cjs/common/validation.js +5 -0
  34. package/dist/cjs/common/value.js +8 -0
  35. package/dist/cjs/common/visit.js +60 -0
  36. package/dist/cjs/node/encryption.js +31 -0
  37. package/dist/cjs/node/gzip.js +10 -0
  38. package/dist/cjs/node/index.js +19 -0
  39. package/dist/cjs/node/search-params.js +23 -0
  40. package/dist/cjs/package.json +1 -0
  41. package/dist/esm/common/arrays.js +33 -0
  42. package/dist/esm/common/assert.js +5 -0
  43. package/dist/esm/common/async-noop.js +2 -0
  44. package/dist/esm/common/billing.js +29 -0
  45. package/dist/esm/common/clone.js +71 -0
  46. package/dist/esm/common/delay.js +22 -0
  47. package/dist/esm/common/draftjs-templates.js +122 -0
  48. package/dist/esm/common/draftjs.js +792 -0
  49. package/{es → dist/esm/common}/get-image-url.js +2 -7
  50. package/dist/esm/common/highlight-code.js +26 -0
  51. package/dist/esm/common/http.js +15 -0
  52. package/dist/esm/common/index.js +34 -0
  53. package/{es → dist/esm/common}/map.js +2 -2
  54. package/dist/esm/common/memoize.js +6 -0
  55. package/dist/esm/common/merge.js +54 -0
  56. package/dist/esm/common/mime.js +60 -0
  57. package/dist/esm/common/names.js +9 -0
  58. package/dist/esm/common/naming.js +54 -0
  59. package/dist/esm/common/path-to-string.js +6 -0
  60. package/{es → dist/esm/common}/persisted-queries.js +1 -1
  61. package/{es → dist/esm/common}/predicate.js +4 -4
  62. package/dist/esm/common/set-in.js +7 -0
  63. package/dist/esm/common/sets.js +14 -0
  64. package/dist/esm/common/sleep.js +5 -0
  65. package/dist/esm/common/sort-object.js +12 -0
  66. package/dist/esm/common/strings.js +60 -0
  67. package/dist/esm/common/templates.js +95 -0
  68. package/dist/esm/common/timezone.js +602 -0
  69. package/dist/esm/common/tracing.js +1 -0
  70. package/dist/esm/common/types.js +50 -0
  71. package/dist/esm/common/unix-to-iso.js +9 -0
  72. package/dist/esm/common/urls.js +5 -0
  73. package/dist/esm/common/validation.js +2 -0
  74. package/dist/esm/common/value.js +4 -0
  75. package/dist/esm/common/visit.js +52 -0
  76. package/dist/esm/node/encryption.js +25 -0
  77. package/dist/esm/node/gzip.js +4 -0
  78. package/dist/esm/node/index.js +3 -0
  79. package/dist/esm/node/search-params.js +17 -0
  80. package/dist/esm/package.json +1 -0
  81. package/dist/tsconfig.types.tsbuildinfo +1 -0
  82. package/dist/{arrays.d.ts → types/common/arrays.d.ts} +0 -1
  83. package/dist/{assert.d.ts → types/common/assert.d.ts} +0 -1
  84. package/dist/{async-noop.d.ts → types/common/async-noop.d.ts} +0 -1
  85. package/dist/types/common/billing.d.ts +365 -0
  86. package/dist/{clone.d.ts → types/common/clone.d.ts} +0 -1
  87. package/dist/{delay.d.ts → types/common/delay.d.ts} +0 -1
  88. package/dist/{draftjs-templates.d.ts → types/common/draftjs-templates.d.ts} +1 -2
  89. package/dist/{draftjs.d.ts → types/common/draftjs.d.ts} +1 -2
  90. package/dist/{get-image-url.d.ts → types/common/get-image-url.d.ts} +0 -1
  91. package/dist/types/common/highlight-code.d.ts +14 -0
  92. package/dist/{http.d.ts → types/common/http.d.ts} +0 -1
  93. package/dist/types/common/index.d.ts +34 -0
  94. package/dist/{map.d.ts → types/common/map.d.ts} +0 -1
  95. package/dist/{memoize.d.ts → types/common/memoize.d.ts} +0 -1
  96. package/dist/{merge.d.ts → types/common/merge.d.ts} +0 -1
  97. package/dist/{mime.d.ts → types/common/mime.d.ts} +0 -1
  98. package/dist/{names.d.ts → types/common/names.d.ts} +0 -1
  99. package/dist/{naming.d.ts → types/common/naming.d.ts} +0 -1
  100. package/dist/{path-to-string.d.ts → types/common/path-to-string.d.ts} +0 -1
  101. package/dist/{persisted-queries.d.ts → types/common/persisted-queries.d.ts} +0 -1
  102. package/dist/{predicate.d.ts → types/common/predicate.d.ts} +0 -1
  103. package/dist/{set-in.d.ts → types/common/set-in.d.ts} +0 -1
  104. package/dist/{sets.d.ts → types/common/sets.d.ts} +0 -1
  105. package/dist/{sleep.d.ts → types/common/sleep.d.ts} +0 -1
  106. package/dist/{sort-object.d.ts → types/common/sort-object.d.ts} +0 -1
  107. package/dist/{strings.d.ts → types/common/strings.d.ts} +1 -2
  108. package/dist/{templates.d.ts → types/common/templates.d.ts} +1 -2
  109. package/dist/{timezone.d.ts → types/common/timezone.d.ts} +0 -1
  110. package/dist/{tracing.d.ts → types/common/tracing.d.ts} +1 -2
  111. package/dist/{types.d.ts → types/common/types.d.ts} +0 -1
  112. package/dist/{unix-to-iso.d.ts → types/common/unix-to-iso.d.ts} +0 -1
  113. package/dist/{urls.d.ts → types/common/urls.d.ts} +0 -1
  114. package/dist/{validation.d.ts → types/common/validation.d.ts} +0 -1
  115. package/dist/{value.d.ts → types/common/value.d.ts} +0 -1
  116. package/dist/{visit.d.ts → types/common/visit.d.ts} +0 -1
  117. package/dist/{encryption.d.ts → types/node/encryption.d.ts} +0 -1
  118. package/dist/{gzip.d.ts → types/node/gzip.d.ts} +1 -2
  119. package/dist/types/node/index.d.ts +3 -0
  120. package/dist/{search-params.d.ts → types/node/search-params.d.ts} +1 -2
  121. package/package.json +33 -21
  122. package/dist/arrays.d.ts.map +0 -1
  123. package/dist/arrays.js +0 -44
  124. package/dist/assert.d.ts.map +0 -1
  125. package/dist/assert.js +0 -11
  126. package/dist/async-noop.d.ts.map +0 -1
  127. package/dist/async-noop.js +0 -8
  128. package/dist/billing.d.ts +0 -366
  129. package/dist/billing.d.ts.map +0 -1
  130. package/dist/billing.js +0 -48
  131. package/dist/browser.d.ts +0 -2
  132. package/dist/browser.d.ts.map +0 -1
  133. package/dist/browser.js +0 -16
  134. package/dist/clone.d.ts.map +0 -1
  135. package/dist/clone.js +0 -101
  136. package/dist/common.d.ts +0 -32
  137. package/dist/common.d.ts.map +0 -1
  138. package/dist/common.js +0 -346
  139. package/dist/delay.d.ts.map +0 -1
  140. package/dist/delay.js +0 -34
  141. package/dist/draftjs-templates.d.ts.map +0 -1
  142. package/dist/draftjs-templates.js +0 -157
  143. package/dist/draftjs.d.ts.map +0 -1
  144. package/dist/draftjs.js +0 -836
  145. package/dist/encryption.d.ts.map +0 -1
  146. package/dist/encryption.js +0 -33
  147. package/dist/get-image-url.d.ts.map +0 -1
  148. package/dist/get-image-url.js +0 -15
  149. package/dist/gzip.d.ts.map +0 -1
  150. package/dist/gzip.js +0 -11
  151. package/dist/highlight-code.d.ts +0 -15
  152. package/dist/highlight-code.d.ts.map +0 -1
  153. package/dist/highlight-code.js +0 -35
  154. package/dist/http.d.ts.map +0 -1
  155. package/dist/http.js +0 -18
  156. package/dist/index.d.ts +0 -6
  157. package/dist/index.d.ts.map +0 -1
  158. package/dist/index.js +0 -60
  159. package/dist/map.d.ts.map +0 -1
  160. package/dist/map.js +0 -9
  161. package/dist/memoize.d.ts.map +0 -1
  162. package/dist/memoize.js +0 -13
  163. package/dist/merge.d.ts.map +0 -1
  164. package/dist/merge.js +0 -67
  165. package/dist/mime.d.ts.map +0 -1
  166. package/dist/mime.js +0 -37
  167. package/dist/names.d.ts.map +0 -1
  168. package/dist/names.js +0 -15
  169. package/dist/naming.d.ts.map +0 -1
  170. package/dist/naming.js +0 -91
  171. package/dist/path-to-string.d.ts.map +0 -1
  172. package/dist/path-to-string.js +0 -13
  173. package/dist/persisted-queries.d.ts.map +0 -1
  174. package/dist/persisted-queries.js +0 -7
  175. package/dist/predicate.d.ts.map +0 -1
  176. package/dist/predicate.js +0 -17
  177. package/dist/search-params.d.ts.map +0 -1
  178. package/dist/search-params.js +0 -25
  179. package/dist/set-in.d.ts.map +0 -1
  180. package/dist/set-in.js +0 -11
  181. package/dist/sets.d.ts.map +0 -1
  182. package/dist/sets.js +0 -21
  183. package/dist/sleep.d.ts.map +0 -1
  184. package/dist/sleep.js +0 -11
  185. package/dist/sort-object.d.ts.map +0 -1
  186. package/dist/sort-object.js +0 -21
  187. package/dist/strings.d.ts.map +0 -1
  188. package/dist/strings.js +0 -87
  189. package/dist/templates.d.ts.map +0 -1
  190. package/dist/templates.js +0 -120
  191. package/dist/timezone.d.ts.map +0 -1
  192. package/dist/timezone.js +0 -17
  193. package/dist/tracing.d.ts.map +0 -1
  194. package/dist/tracing.js +0 -5
  195. package/dist/types.d.ts.map +0 -1
  196. package/dist/types.js +0 -92
  197. package/dist/unix-to-iso.d.ts.map +0 -1
  198. package/dist/unix-to-iso.js +0 -17
  199. package/dist/urls.d.ts.map +0 -1
  200. package/dist/urls.js +0 -11
  201. package/dist/validation.d.ts.map +0 -1
  202. package/dist/validation.js +0 -8
  203. package/dist/value.d.ts.map +0 -1
  204. package/dist/value.js +0 -11
  205. package/dist/visit.d.ts.map +0 -1
  206. package/dist/visit.js +0 -61
  207. package/es/arrays.js +0 -33
  208. package/es/assert.js +0 -5
  209. package/es/async-noop.js +0 -2
  210. package/es/billing.js +0 -40
  211. package/es/browser.js +0 -1
  212. package/es/clone.js +0 -94
  213. package/es/common.js +0 -31
  214. package/es/delay.js +0 -26
  215. package/es/draftjs-templates.js +0 -147
  216. package/es/draftjs.js +0 -819
  217. package/es/encryption.js +0 -26
  218. package/es/gzip.js +0 -4
  219. package/es/highlight-code.js +0 -26
  220. package/es/http.js +0 -11
  221. package/es/index.js +0 -6
  222. package/es/memoize.js +0 -6
  223. package/es/merge.js +0 -58
  224. package/es/mime.js +0 -29
  225. package/es/names.js +0 -9
  226. package/es/naming.js +0 -78
  227. package/es/path-to-string.js +0 -6
  228. package/es/search-params.js +0 -17
  229. package/es/set-in.js +0 -6
  230. package/es/sets.js +0 -14
  231. package/es/sleep.js +0 -5
  232. package/es/sort-object.js +0 -14
  233. package/es/strings.js +0 -72
  234. package/es/templates.js +0 -105
  235. package/es/timezone.js +0 -10
  236. package/es/tracing.js +0 -1
  237. package/es/types.js +0 -80
  238. package/es/unix-to-iso.js +0 -9
  239. package/es/urls.js +0 -5
  240. package/es/validation.js +0 -2
  241. package/es/value.js +0 -4
  242. package/es/visit.js +0 -53
@@ -0,0 +1,792 @@
1
+ import { getImageUrl } from '@takeshape/routing';
2
+ import render from 'dom-serializer';
3
+ import he from 'he';
4
+ import { ElementType, parseDOM } from 'htmlparser2';
5
+ import escape from 'lodash/escape.js';
6
+ import forEach from 'lodash/forEach.js';
7
+ import pickBy from 'lodash/pickBy.js';
8
+ import unescape from 'lodash/unescape.js';
9
+ import { draftToMarkdown, markdownToDraft } from 'markdown-draft-js';
10
+ import shortid from 'shortid';
11
+ import Url from 'url-parse';
12
+ import { getDraftjsImage, getDraftjsOembed, getDraftjsPullquote } from './draftjs-templates.js';
13
+ import { imageTemplate, imageTemplateMdx, oembedTemplate, oembedTemplateMdx } from './templates.js';
14
+ const SUPERSCRIPT_MARKER = 'TEMPORARY_SUPERSCRIPT_MARKER_TLfDNyf7VYKDduyL';
15
+ const SUBSCRIPT_MARKER = 'TEMPORARY_SUBSCRIPT_MARKER_K5VrdPEzyQyy2RcY';
16
+ const INSERT_MARKER = 'TEMPORARY_INSERT_MARKER_FSYdr8m8CS7YLb8y';
17
+ const EXTERNAL_LINK_MARKER = 'TEMPORARY_EXTERNAL_LINK_MARKER_HP3vprmERkc9ZAss';
18
+ const pullquoteStyle = 'font-style: italic; margin: 2em 2.5em;';
19
+ const getDraftjsEmpty = (depth = 0) => {
20
+ return {
21
+ key: shortid.generate(),
22
+ depth,
23
+ type: 'unstyled',
24
+ text: '',
25
+ entityRanges: [],
26
+ inlineStyleRanges: []
27
+ };
28
+ };
29
+ const REMOVAL_MARKER_TYPE = 'removal-marker';
30
+ const getDraftjsRemovalMarker = (depth = 0) => {
31
+ return {
32
+ key: shortid.generate(),
33
+ type: REMOVAL_MARKER_TYPE,
34
+ depth,
35
+ text: '',
36
+ entityRanges: [],
37
+ inlineStyleRanges: []
38
+ };
39
+ };
40
+ const mdxShortcodePrefix = (tagName) => `TS${tagName}`;
41
+ const handleMultiword = (markdown, marker, markdownSyntax, markdownRegex) => {
42
+ const parts = markdown.replace(markdownRegex, `\\${markdownSyntax}`).split(marker);
43
+ let result = '';
44
+ let open = false;
45
+ for (const [i, part] of parts.entries()) {
46
+ if (open) {
47
+ result += part.replace(/\s+/g, (match) => `${markdownSyntax}${match}${markdownSyntax}`);
48
+ }
49
+ else {
50
+ result += part;
51
+ }
52
+ if (i !== parts.length - 1) {
53
+ result += markdownSyntax;
54
+ open = !open;
55
+ }
56
+ }
57
+ return result;
58
+ };
59
+ // Workaround inability to reasonably process child content using draftToMarkdown
60
+ const handleExternalLinks = (markdown) => {
61
+ const regex = /(<TSExternalLink text="TEMPORARY_EXTERNAL_LINK_MARKER_HP3vprmERkc9ZAss" href="[^"]+">)([^<]+)<\/TSExternalLink>/g;
62
+ return markdown.replace(regex, (match, openTag, content) => match.replace(EXTERNAL_LINK_MARKER, content));
63
+ };
64
+ /**
65
+ * Adjust entity ranges or inline style ranges to insert `amount` space starting at `after`.
66
+ * For example, take this visualization of a range with offset 5 and length 5, where
67
+ * the vertical bars are the start and end of the range, inclusive:
68
+ * -----|---|-----
69
+ * If you insert amount 5 after 0 you get this:
70
+ * ----------|---|-----
71
+ * If you insert amount 5 after 7 you get this:
72
+ * -----|--------|-----
73
+ * If you insert amount 5 after 10 you get this:
74
+ * -----|---|----------
75
+ * If you insert amount -2 after 7 you get this:
76
+ * -----|-|-----
77
+ */
78
+ export const adjustRanges = (ranges, after, amount) => {
79
+ return ranges.map((range) => ({
80
+ ...range,
81
+ offset: range.offset > after ? range.offset + amount : range.offset,
82
+ length: range.offset <= after && range.offset + range.length > after ? range.length + amount : range.length
83
+ }));
84
+ };
85
+ /**
86
+ * Encode HTML entities in this draftjs state.
87
+ * We adjust ranges so that their offsets and lengths are still correct with the encoded text.
88
+ * EG `&#x27;` is 5 characters longer than `'` so if there is a single apostrophe before a link,
89
+ * the link entity's offset needs to be increased by 5 when the text is encoded.
90
+ * This also applies to the entity's length if there are escaped characters inside the entity.
91
+ */
92
+ export const encodeHtmlEntities = (draftjs) => {
93
+ const result = {
94
+ ...draftjs,
95
+ blocks: draftjs.blocks.map((block) => {
96
+ let { text } = block;
97
+ let { entityRanges, inlineStyleRanges } = block;
98
+ for (let i = 0; i < text.length; i++) {
99
+ const char = text.charAt(i);
100
+ const encodedChar = he.encode(char);
101
+ if (encodedChar !== char) {
102
+ const offset = encodedChar.length - char.length;
103
+ entityRanges = adjustRanges(entityRanges, i, offset);
104
+ inlineStyleRanges = adjustRanges(inlineStyleRanges, i, offset);
105
+ text = text.substring(0, i) + encodedChar + text.substring(i + 1);
106
+ i += offset;
107
+ }
108
+ }
109
+ return {
110
+ ...block,
111
+ entityRanges,
112
+ inlineStyleRanges,
113
+ text
114
+ };
115
+ })
116
+ };
117
+ return result;
118
+ };
119
+ export function fromDraftjs(draftjs, styleItems, entityItems) {
120
+ let markdown = draftToMarkdown(encodeHtmlEntities(draftjs), {
121
+ styleItems: {
122
+ 'section-break': {
123
+ open() {
124
+ return '***';
125
+ },
126
+ close() {
127
+ return '';
128
+ }
129
+ },
130
+ SUP: {
131
+ open() {
132
+ return SUPERSCRIPT_MARKER;
133
+ },
134
+ close() {
135
+ return SUPERSCRIPT_MARKER;
136
+ }
137
+ },
138
+ SUB: {
139
+ open() {
140
+ return SUBSCRIPT_MARKER;
141
+ },
142
+ close() {
143
+ return SUBSCRIPT_MARKER;
144
+ }
145
+ },
146
+ UNDERLINE: {
147
+ open() {
148
+ return INSERT_MARKER;
149
+ },
150
+ close() {
151
+ return INSERT_MARKER;
152
+ }
153
+ },
154
+ 'code-block': {
155
+ open(entity) {
156
+ const lang = entity?.data?.lang ?? '';
157
+ return `\`\`\`${lang}\n`;
158
+ },
159
+ close() {
160
+ return '\n```';
161
+ }
162
+ },
163
+ ...styleItems
164
+ },
165
+ entityItems: {
166
+ LINK: {
167
+ open(entity) {
168
+ if (entity?.data?.target === '_blank') {
169
+ const url = escape(entity?.data?.url || entity?.data?.href || '');
170
+ return `<TSExternalLink text="${EXTERNAL_LINK_MARKER}" href="${url}">`;
171
+ }
172
+ return '[';
173
+ },
174
+ close(entity) {
175
+ if (entity?.data?.target === '_blank') {
176
+ return '</TSExternalLink>';
177
+ }
178
+ return ']('.concat(entity?.data?.url || entity?.data?.href || '', ')');
179
+ }
180
+ },
181
+ ...entityItems
182
+ }
183
+ });
184
+ markdown = handleExternalLinks(markdown);
185
+ markdown = handleMultiword(markdown, SUPERSCRIPT_MARKER, '^', /\^/g);
186
+ markdown = handleMultiword(markdown, SUBSCRIPT_MARKER, '~', /~/g);
187
+ markdown = markdown.replace(/\+/g, '\\+').replace(new RegExp(INSERT_MARKER, 'g'), '++');
188
+ return markdown;
189
+ }
190
+ export function draftjsToMd(draftjs, assets) {
191
+ return fromDraftjs(draftjs, {
192
+ pullquote: {
193
+ open() {
194
+ return `<aside style="${pullquoteStyle}">`;
195
+ },
196
+ close() {
197
+ return '</aside>';
198
+ }
199
+ }
200
+ }, {
201
+ oembed: {
202
+ open() {
203
+ return '';
204
+ },
205
+ close(entity) {
206
+ if (!entity?.data) {
207
+ return '';
208
+ }
209
+ const { data } = entity;
210
+ return oembedTemplate((str) => str, data);
211
+ }
212
+ },
213
+ image: {
214
+ open() {
215
+ return '';
216
+ },
217
+ close(entity) {
218
+ if (!entity?.data) {
219
+ return '';
220
+ }
221
+ const { data } = entity;
222
+ const asset = assets[data.id];
223
+ if (asset === undefined) {
224
+ return '';
225
+ }
226
+ const imageTemplateData = {
227
+ ...data,
228
+ alignment: data.alignment,
229
+ size: data.size,
230
+ asset,
231
+ caption: getAssetField(data, asset, 'caption'),
232
+ credit: getAssetField(data, asset, 'credit'),
233
+ imageParams: {}
234
+ };
235
+ return imageTemplate((str) => str, imageTemplateData);
236
+ }
237
+ }
238
+ });
239
+ }
240
+ function getTextFromDraftjs(draftjs) {
241
+ return draftjs?.blocks?.[0]?.text;
242
+ }
243
+ function getAssetField(data, asset, field) {
244
+ const dataText = getTextFromDraftjs(data[field]);
245
+ if (dataText) {
246
+ return dataText;
247
+ }
248
+ if (asset[field]) {
249
+ return getTextFromDraftjs(asset[field]);
250
+ }
251
+ return '';
252
+ }
253
+ export function draftjsToMdx(draftjs, assets, prefix = mdxShortcodePrefix) {
254
+ return fromDraftjs(draftjs, {
255
+ pullquote: {
256
+ open() {
257
+ return `<${prefix('Pullquote')}>`;
258
+ },
259
+ close() {
260
+ return `</${prefix('Pullquote')}>`;
261
+ }
262
+ }
263
+ }, {
264
+ oembed: {
265
+ open() {
266
+ return '';
267
+ },
268
+ close(entity) {
269
+ if (!entity?.data) {
270
+ return '';
271
+ }
272
+ const { data } = entity;
273
+ return oembedTemplateMdx(prefix, data);
274
+ }
275
+ },
276
+ image: {
277
+ open() {
278
+ return '';
279
+ },
280
+ close(entity) {
281
+ const asset = assets[entity?.data?.id];
282
+ if (!entity?.data || asset === undefined) {
283
+ return '';
284
+ }
285
+ const { data } = entity;
286
+ const imageUrlOptions = process.env.NODE_ENV === 'production' ? {} : { baseUrl: 'https://images.dev.takeshape.io' };
287
+ return imageTemplateMdx(prefix, {
288
+ ...data,
289
+ assetId: data.id,
290
+ assetPath: asset.path,
291
+ credit: getAssetField(data, asset, 'credit'),
292
+ caption: getAssetField(data, asset, 'caption'),
293
+ link: data.link?.url,
294
+ linkisexternal: data.link?.external ? 'true' : 'false',
295
+ src: getImageUrl(asset.path, data.imageParams, imageUrlOptions)
296
+ });
297
+ }
298
+ }
299
+ });
300
+ }
301
+ function getAssetIdFromImageSrc(src) {
302
+ return new Url(src).pathname.split('/')[3];
303
+ }
304
+ function parseFigureClass(className) {
305
+ if (className === undefined) {
306
+ return {
307
+ alignment: undefined,
308
+ size: undefined
309
+ };
310
+ }
311
+ const parts = className.split(' ');
312
+ return {
313
+ alignment: parts[0],
314
+ size: parts[1]
315
+ };
316
+ }
317
+ function htmlDomToDraftjsImage(dom, item, entityKeyGenerator) {
318
+ for (const figure of dom) {
319
+ if (figure.type === ElementType.Tag && figure.name === 'figure') {
320
+ let link;
321
+ const figureChildOne = figure.children?.[0];
322
+ const figureChildTwo = figure.children?.[1];
323
+ if (figureChildOne?.type === ElementType.Tag && figureChildOne?.name === 'a') {
324
+ link = figureChildOne;
325
+ }
326
+ let figcaption;
327
+ if (figureChildOne?.type === ElementType.Tag && figureChildOne?.name === 'figcaption') {
328
+ figcaption = figureChildOne;
329
+ }
330
+ else if (figureChildTwo?.type === ElementType.Tag && figureChildTwo?.name === 'figcaption') {
331
+ figcaption = figure.children[1];
332
+ }
333
+ const img = link ? link.children[0] : figure.children[0];
334
+ if (img?.type !== ElementType.Tag || img?.name !== 'img') {
335
+ return;
336
+ }
337
+ const figcaptionChild = figcaption?.type === ElementType.Tag ? figcaption?.children[0] : undefined;
338
+ let caption;
339
+ if (figcaptionChild?.type === ElementType.Tag &&
340
+ figcaptionChild?.name === 'span' &&
341
+ figcaptionChild?.attribs.class === 'caption') {
342
+ caption = figcaptionChild;
343
+ }
344
+ const captionChildThree = figcaption?.type === ElementType.Tag ? figcaption?.children[2] : undefined;
345
+ let credit;
346
+ if (captionChildThree?.type === ElementType.Tag &&
347
+ captionChildThree?.name === 'span' &&
348
+ captionChildThree?.attribs.class === 'credit') {
349
+ credit = captionChildThree;
350
+ }
351
+ const { alignment, size } = parseFigureClass(figure.attribs.class);
352
+ return getDraftjsImage({
353
+ captionText: caption?.children[0].type === ElementType.Text ? (caption.children[0].data ?? '') : '',
354
+ creditText: credit?.children[0].type === ElementType.Text ? (credit?.children[0].data ?? '') : '',
355
+ alignment,
356
+ size,
357
+ assetId: getAssetIdFromImageSrc(img.attribs.src),
358
+ linkUrl: link?.attribs.href,
359
+ linkIsExternal: link?.attribs.target === '_blank',
360
+ key: entityKeyGenerator(),
361
+ depth: item.level,
362
+ path: getImagePathFromUrl(img.attribs.src)
363
+ });
364
+ }
365
+ }
366
+ }
367
+ function htmlDomToOembed(dom, item, entityKeyGenerator) {
368
+ for (const oembedDiv of dom) {
369
+ if (oembedDiv.type === ElementType.Tag && oembedDiv.name === 'div' && oembedDiv.attribs.class === 'oembed') {
370
+ const blockquote = oembedDiv.children[0];
371
+ if (blockquote?.type !== ElementType.Tag || blockquote?.name !== 'blockquote') {
372
+ return;
373
+ }
374
+ const script = oembedDiv.children[2];
375
+ if (script?.type !== 'script' || script?.name !== 'script') {
376
+ return;
377
+ }
378
+ return getDraftjsOembed({
379
+ html: `${render(blockquote)}\n${render(script)}\n`,
380
+ key: entityKeyGenerator(),
381
+ depth: item.level
382
+ });
383
+ }
384
+ }
385
+ }
386
+ function mdxToDraftjsOembed(item, entityKeyGenerator) {
387
+ if (item.content.startsWith(`<${mdxShortcodePrefix('Oembed')}`)) {
388
+ const dom = parseDOM(item.content, { decodeEntities: true })[0];
389
+ if (dom.type !== ElementType.Tag) {
390
+ return;
391
+ }
392
+ return getDraftjsOembed({
393
+ html: unescape(dom.attribs.html),
394
+ width: dom.attribs.width ? Number(dom.attribs.width) : undefined,
395
+ height: dom.attribs.height ? Number(dom.attribs.height) : undefined,
396
+ url: unescape(dom.attribs.url),
397
+ author_name: unescape(dom.attribs.author_name),
398
+ author_url: unescape(dom.attribs.author_url),
399
+ type: unescape(dom.attribs.type),
400
+ cache_age: Number(dom.attribs.cache_age),
401
+ provider_name: unescape(dom.attribs.provider_name),
402
+ provider_url: unescape(dom.attribs.provider_url),
403
+ version: unescape(dom.attribs.version),
404
+ key: entityKeyGenerator(),
405
+ depth: item.level
406
+ });
407
+ }
408
+ }
409
+ function htmlDomToPullquote(dom, item) {
410
+ for (const pullquote of dom) {
411
+ if (pullquote.type === ElementType.Tag &&
412
+ pullquote.name === 'aside' &&
413
+ pullquote.attribs.style === pullquoteStyle) {
414
+ const text = pullquote.children[0];
415
+ if (text?.type !== 'text') {
416
+ return;
417
+ }
418
+ return getDraftjsPullquote({
419
+ text: text.data,
420
+ depth: item.level
421
+ });
422
+ }
423
+ }
424
+ }
425
+ function fromMd(md, blockEntities, blockTypes) {
426
+ md = md.replace(/\\\+/g, '+').replace(/\\~/g, '~').replace(/\\\^/g, '^');
427
+ return markdownToDraft(md, {
428
+ remarkablePreset: 'full',
429
+ remarkableOptions: {
430
+ html: true
431
+ },
432
+ blockStyles: {
433
+ ins_open: 'UNDERLINE',
434
+ sub: 'SUB',
435
+ sup: 'SUP'
436
+ },
437
+ blockEntities,
438
+ blockTypes: {
439
+ hr(item) {
440
+ if (!item) {
441
+ return getDraftjsEmpty();
442
+ }
443
+ return {
444
+ key: shortid.generate(),
445
+ text: ' ',
446
+ type: 'section-break',
447
+ depth: item.level,
448
+ inlineStyleRanges: [],
449
+ entityRanges: [],
450
+ data: {}
451
+ };
452
+ },
453
+ fence(item) {
454
+ if (!item) {
455
+ return getDraftjsEmpty();
456
+ }
457
+ return {
458
+ type: 'code-block',
459
+ data: {
460
+ // In markdown-to-draft this is language, we require lang
461
+ lang: item.params || ''
462
+ },
463
+ // Using the text handling from markdown-to-draft
464
+ text: he.decode((item.content || '').replace(/\n$/, '')),
465
+ entityRanges: [],
466
+ inlineStyleRanges: []
467
+ };
468
+ },
469
+ ...blockTypes
470
+ }
471
+ });
472
+ }
473
+ export function mdToDraftjs(mdx) {
474
+ const entities = {};
475
+ // Start really high to avoid conflicts with keys created by markdown-draft-js
476
+ let currentEntityKey = 1000000;
477
+ function entityKeyGenerator() {
478
+ return currentEntityKey++;
479
+ }
480
+ const result = fromMd(mdx, {}, {
481
+ htmlblock(item) {
482
+ if (item === undefined) {
483
+ return getDraftjsEmpty();
484
+ }
485
+ const dom = parseDOM(item.content, { decodeEntities: false });
486
+ const image = htmlDomToDraftjsImage(dom, item, entityKeyGenerator);
487
+ if (image) {
488
+ Object.assign(entities, image.entities);
489
+ return image.contentBlock;
490
+ }
491
+ const oembed = htmlDomToOembed(dom, item, entityKeyGenerator);
492
+ if (oembed) {
493
+ Object.assign(entities, oembed.entities);
494
+ return oembed.contentBlock;
495
+ }
496
+ const pullquote = htmlDomToPullquote(dom, item);
497
+ if (pullquote) {
498
+ Object.assign(entities, pullquote.entities);
499
+ return pullquote.contentBlock;
500
+ }
501
+ return getDraftjsEmpty(item.level);
502
+ }
503
+ });
504
+ result.entityMap = {
505
+ ...result.entityMap,
506
+ ...entities
507
+ };
508
+ return result;
509
+ }
510
+ export function getImagePathFromUrl(url) {
511
+ return new Url(url).pathname.substr(1);
512
+ }
513
+ function mdxToBr(item) {
514
+ if (item.content.startsWith('<br/>')) {
515
+ return {
516
+ key: shortid.generate(),
517
+ depth: item.depth,
518
+ type: 'unstyled',
519
+ text: '',
520
+ entityRanges: [],
521
+ inlineStyleRanges: []
522
+ };
523
+ }
524
+ }
525
+ function mdxToLinkData(item) {
526
+ if (item.content.startsWith('<TSExternalLink')) {
527
+ const dom = parseDOM(item.content, { decodeEntities: false })[0];
528
+ if (dom.type !== ElementType.Tag) {
529
+ return;
530
+ }
531
+ return {
532
+ url: dom.attribs.href,
533
+ target: '_blank',
534
+ text: dom.attribs.text
535
+ };
536
+ }
537
+ }
538
+ function mdxToDraftjsImage(item, entityKeyGenerator) {
539
+ if (item.content.startsWith(`<${mdxShortcodePrefix('Image')}`)) {
540
+ const dom = parseDOM(item.content, { decodeEntities: false })[0];
541
+ if (dom.type !== ElementType.Tag) {
542
+ return;
543
+ }
544
+ return getDraftjsImage({
545
+ captionText: unescape(dom.attribs.caption).replace(/<\/?p>/g, ''),
546
+ creditText: unescape(dom.attribs.credit).replace(/<\/?p>/g, ''),
547
+ alignment: dom.attribs.alignment,
548
+ size: dom.attribs.size,
549
+ assetId: dom.attribs.id,
550
+ linkUrl: dom.attribs.link,
551
+ linkIsExternal: dom.attribs.linkisexternal === 'true',
552
+ key: entityKeyGenerator(),
553
+ depth: item.level,
554
+ path: getImagePathFromUrl(decodeURIComponent(dom.attribs.src))
555
+ });
556
+ }
557
+ }
558
+ function mdxToDraftjsPullquote(item) {
559
+ if (item.content.startsWith(`<${mdxShortcodePrefix('Pullquote')}`)) {
560
+ const dom = parseDOM(item.content, { decodeEntities: false })[0];
561
+ if (dom.type !== ElementType.Tag) {
562
+ return;
563
+ }
564
+ return getDraftjsPullquote({
565
+ text: unescape(dom.attribs.text),
566
+ depth: item.level
567
+ });
568
+ }
569
+ }
570
+ /**
571
+ * Mutates result to replace empty entities with links,
572
+ * assuming there is nothing else they could be...
573
+ */
574
+ function addLinks(state, links) {
575
+ let linkNumber = 0;
576
+ let linkOpen = false;
577
+ for (const block of state.blocks) {
578
+ let blockIsCustom = false;
579
+ for (const [i, entityRange] of block.entityRanges.entries()) {
580
+ const entity = state.entityMap[entityRange.key];
581
+ if (entity === undefined) {
582
+ throw new Error('Missing entity');
583
+ }
584
+ if (i === 0 && entity.data?.marker) {
585
+ blockIsCustom = true;
586
+ continue;
587
+ }
588
+ if (blockIsCustom && i === Object.keys(block.entityRanges).length - 1) {
589
+ continue;
590
+ }
591
+ // Ignore line breaks that were inserted around blocks
592
+ if (entity.depth === undefined) {
593
+ continue;
594
+ }
595
+ const link = links[linkNumber];
596
+ if (link && !linkOpen) {
597
+ entity.type = 'LINK';
598
+ entity.mutability = 'MUTABLE';
599
+ entity.data = link;
600
+ const decodedText = he.decode(link.text);
601
+ entity.text = decodedText;
602
+ entityRange.length += decodedText.length;
603
+ linkNumber++;
604
+ }
605
+ linkOpen = !linkOpen;
606
+ }
607
+ }
608
+ }
609
+ /**
610
+ * Mutate state to replace blocks with our custom versions
611
+ * Return a list of entity keys that should be removed
612
+ */
613
+ function replaceBlocks(state, replacementBlocks) {
614
+ let entityKeysToExclude = [];
615
+ for (let i = 0; i < state.blocks.length; i++) {
616
+ const block = state.blocks[i];
617
+ for (const entityKey of Object.keys(state.entityMap)) {
618
+ let removeBlockEntityKeys = false;
619
+ const blockEntityKeys = block.entityRanges.map((range) => range.key);
620
+ if (blockEntityKeys.includes(Number(entityKey))) {
621
+ const entity = state.entityMap[entityKey];
622
+ const markerKey = entity.data?.marker;
623
+ const replacementBlock = replacementBlocks[markerKey];
624
+ if (replacementBlock && !removeBlockEntityKeys) {
625
+ const originalBlock = state.blocks[i];
626
+ const originalBlockText = state.blocks[i].text;
627
+ replacementBlock.text = originalBlockText !== '' ? originalBlockText : replacementBlock.text;
628
+ replacementBlock.inlineStyleRanges = originalBlock.inlineStyleRanges;
629
+ const removeBlockEntities = entity.data.type === 'image' || entity.data.type === 'oembed';
630
+ if (!removeBlockEntities) {
631
+ replacementBlock.entityRanges = originalBlock.entityRanges.filter((entityRange) => state.entityMap[entityRange.key].data?.marker === undefined);
632
+ }
633
+ state.blocks[i] = replacementBlock;
634
+ if (removeBlockEntities) {
635
+ removeBlockEntityKeys = true;
636
+ }
637
+ }
638
+ }
639
+ if (removeBlockEntityKeys) {
640
+ entityKeysToExclude = entityKeysToExclude.concat(blockEntityKeys);
641
+ }
642
+ }
643
+ }
644
+ return entityKeysToExclude;
645
+ }
646
+ const blockStarts = [
647
+ {
648
+ regex: ' <TSImage',
649
+ replacement: ' <TSImage'
650
+ },
651
+ {
652
+ regex: ' <TSOembed',
653
+ replacement: ' <TSOembed'
654
+ },
655
+ {
656
+ regex: '\\*\\*\\*',
657
+ replacement: '***'
658
+ },
659
+ {
660
+ regex: '```',
661
+ replacement: '```'
662
+ }
663
+ ];
664
+ const blockEnds = [
665
+ {
666
+ lookBehind: '<TSImage.*(?=/>)',
667
+ regex: '/>',
668
+ replacement: '/>'
669
+ },
670
+ {
671
+ regex: '</TSOembed>',
672
+ replacement: '</TSOembed>'
673
+ },
674
+ {
675
+ regex: '\\*\\*\\*',
676
+ replacement: '***'
677
+ },
678
+ {
679
+ regex: '```',
680
+ replacement: '```'
681
+ }
682
+ ];
683
+ const getLookBehindValue = (end, str) => {
684
+ if (end.lookBehind) {
685
+ const behindMatch = new RegExp(end.lookBehind).exec(str);
686
+ if (behindMatch) {
687
+ return behindMatch[0];
688
+ }
689
+ }
690
+ return '';
691
+ };
692
+ /**
693
+ * Make sure there is a place to put the cursor around block-level items such as images and oembeds
694
+ */
695
+ export function insertBreaksAroundBlocks(mdx) {
696
+ for (const start of blockStarts) {
697
+ mdx = mdx.replace(new RegExp(`^${start.regex}`, 'g'), `<br/>\n\n${start.replacement}`);
698
+ }
699
+ for (const end of blockEnds) {
700
+ mdx = mdx.replace(new RegExp(`${end.lookBehind ?? ''}${end.regex}\\s*$`, 'g'), (match) => {
701
+ return `${getLookBehindValue(end, match)}${end.replacement}\n\n<br/>`;
702
+ });
703
+ for (const start of blockStarts) {
704
+ mdx = mdx.replace(new RegExp(`${end.lookBehind ?? ''}${end.regex}\\s*${start.regex}`, 'g'), (match) => {
705
+ return `${getLookBehindValue(end, match)}${end.replacement ?? 'FFF'}\n\n<br/>\n\n${start.replacement}`;
706
+ });
707
+ }
708
+ }
709
+ return mdx;
710
+ }
711
+ export function mdxToDraftjs(mdx) {
712
+ const replacementBlocks = {};
713
+ const entities = {};
714
+ const oembedKeyToHtml = {};
715
+ let currentOembedKey;
716
+ // Start really high to avoid conflicts with keys created by markdown-draft-js
717
+ let currentEntityKey = 1000000;
718
+ function entityKeyGenerator() {
719
+ return currentEntityKey++;
720
+ }
721
+ mdx = insertBreaksAroundBlocks(mdx);
722
+ const links = [];
723
+ const result = fromMd(mdx, {
724
+ htmltag(item) {
725
+ if (item === undefined) {
726
+ return getDraftjsEmpty();
727
+ }
728
+ const br = mdxToBr(item);
729
+ if (br) {
730
+ return br;
731
+ }
732
+ const linkData = mdxToLinkData(item);
733
+ if (linkData) {
734
+ links.push(linkData);
735
+ }
736
+ const image = mdxToDraftjsImage(item, entityKeyGenerator);
737
+ if (image) {
738
+ replacementBlocks[image.contentBlock.key] = image.contentBlock;
739
+ Object.assign(entities, image.entities);
740
+ return {
741
+ data: {
742
+ marker: image.contentBlock.key,
743
+ type: 'image'
744
+ }
745
+ };
746
+ }
747
+ const oembed = mdxToDraftjsOembed(item, entityKeyGenerator);
748
+ if (oembed) {
749
+ currentOembedKey = Object.keys(oembed.entities)[0];
750
+ replacementBlocks[oembed.contentBlock.key] = oembed.contentBlock;
751
+ Object.assign(entities, oembed.entities);
752
+ return {
753
+ data: {
754
+ marker: oembed.contentBlock.key,
755
+ type: 'oembed'
756
+ }
757
+ };
758
+ }
759
+ const pullquote = mdxToDraftjsPullquote(item);
760
+ if (pullquote) {
761
+ replacementBlocks[pullquote.contentBlock.key] = pullquote.contentBlock;
762
+ Object.assign(entities, pullquote.entities);
763
+ return {
764
+ data: {
765
+ marker: pullquote.contentBlock.key,
766
+ type: 'pullquote'
767
+ }
768
+ };
769
+ }
770
+ return getDraftjsEmpty(item.level);
771
+ }
772
+ }, {
773
+ htmlblock(item) {
774
+ if (item && currentOembedKey) {
775
+ oembedKeyToHtml[currentOembedKey] = item.content.replace(`</${mdxShortcodePrefix('Oembed')}>\n`, '');
776
+ currentOembedKey = undefined;
777
+ }
778
+ return getDraftjsRemovalMarker();
779
+ }
780
+ });
781
+ addLinks(result, links);
782
+ const entityKeysToExclude = replaceBlocks(result, replacementBlocks);
783
+ result.blocks = result.blocks.filter((block) => block.type !== REMOVAL_MARKER_TYPE);
784
+ forEach(oembedKeyToHtml, (html, key) => {
785
+ entities[key].data.html = html;
786
+ });
787
+ result.entityMap = pickBy({
788
+ ...result.entityMap,
789
+ ...entities
790
+ }, (entity, key) => entity.data?.marker === undefined && !entityKeysToExclude.includes(Number(key)));
791
+ return result;
792
+ }