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