@prismicio/client 7.1.1 → 7.3.0

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 (120) hide show
  1. package/dist/createClient.cjs +24 -1
  2. package/dist/createClient.cjs.map +1 -1
  3. package/dist/createClient.d.ts +7 -0
  4. package/dist/createClient.js +24 -1
  5. package/dist/createClient.js.map +1 -1
  6. package/dist/errors/ForbiddenError.cjs.map +1 -1
  7. package/dist/errors/ForbiddenError.d.ts +1 -1
  8. package/dist/errors/ForbiddenError.js.map +1 -1
  9. package/dist/errors/NotFoundError.cjs.map +1 -1
  10. package/dist/errors/NotFoundError.d.ts +1 -1
  11. package/dist/errors/NotFoundError.js.map +1 -1
  12. package/dist/errors/ParsingError.cjs.map +1 -1
  13. package/dist/errors/ParsingError.d.ts +1 -1
  14. package/dist/errors/ParsingError.js.map +1 -1
  15. package/dist/errors/RefExpiredError.cjs +7 -0
  16. package/dist/errors/RefExpiredError.cjs.map +1 -0
  17. package/dist/errors/RefExpiredError.d.ts +8 -0
  18. package/dist/errors/RefExpiredError.js +7 -0
  19. package/dist/errors/RefExpiredError.js.map +1 -0
  20. package/dist/errors/RefNotFoundError.cjs +7 -0
  21. package/dist/errors/RefNotFoundError.cjs.map +1 -0
  22. package/dist/errors/RefNotFoundError.d.ts +8 -0
  23. package/dist/errors/RefNotFoundError.js +7 -0
  24. package/dist/errors/RefNotFoundError.js.map +1 -0
  25. package/dist/helpers/asHTML.cjs +43 -50
  26. package/dist/helpers/asHTML.cjs.map +1 -1
  27. package/dist/helpers/asHTML.d.ts +31 -6
  28. package/dist/helpers/asHTML.js +42 -49
  29. package/dist/helpers/asHTML.js.map +1 -1
  30. package/dist/helpers/asImagePixelDensitySrcSet.d.ts +1 -1
  31. package/dist/helpers/asImageSrc.d.ts +1 -1
  32. package/dist/helpers/asImageWidthSrcSet.cjs +1 -1
  33. package/dist/helpers/asImageWidthSrcSet.cjs.map +1 -1
  34. package/dist/helpers/asImageWidthSrcSet.d.ts +1 -1
  35. package/dist/helpers/asImageWidthSrcSet.js +1 -1
  36. package/dist/helpers/asImageWidthSrcSet.js.map +1 -1
  37. package/dist/helpers/asLinkAttrs.d.ts +1 -1
  38. package/dist/helpers/asText.cjs +2 -2
  39. package/dist/helpers/asText.cjs.map +1 -1
  40. package/dist/helpers/asText.js +1 -1
  41. package/dist/helpers/asText.js.map +1 -1
  42. package/dist/helpers/isFilled.d.ts +10 -13
  43. package/dist/index.cjs +8 -7
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.ts +28 -2
  46. package/dist/index.js +6 -2
  47. package/dist/index.js.map +1 -1
  48. package/dist/lib/serializerHelpers.cjs +91 -35
  49. package/dist/lib/serializerHelpers.cjs.map +1 -1
  50. package/dist/lib/serializerHelpers.d.ts +8 -8
  51. package/dist/lib/serializerHelpers.js +91 -35
  52. package/dist/lib/serializerHelpers.js.map +1 -1
  53. package/dist/package.json.cjs +1 -1
  54. package/dist/package.json.js +1 -1
  55. package/dist/richtext/asText.cjs +13 -0
  56. package/dist/richtext/asText.cjs.map +1 -0
  57. package/dist/richtext/asText.d.ts +12 -0
  58. package/dist/richtext/asText.js +13 -0
  59. package/dist/richtext/asText.js.map +1 -0
  60. package/dist/richtext/asTree.cjs +123 -0
  61. package/dist/richtext/asTree.cjs.map +1 -0
  62. package/dist/richtext/asTree.d.ts +14 -0
  63. package/dist/richtext/asTree.js +123 -0
  64. package/dist/richtext/asTree.js.map +1 -0
  65. package/dist/richtext/composeSerializers.cjs +17 -0
  66. package/dist/richtext/composeSerializers.cjs.map +1 -0
  67. package/dist/richtext/composeSerializers.d.ts +16 -0
  68. package/dist/richtext/composeSerializers.js +17 -0
  69. package/dist/richtext/composeSerializers.js.map +1 -0
  70. package/dist/richtext/index.d.ts +7 -0
  71. package/dist/richtext/serialize.cjs +19 -0
  72. package/dist/richtext/serialize.cjs.map +1 -0
  73. package/dist/richtext/serialize.d.ts +19 -0
  74. package/dist/richtext/serialize.js +19 -0
  75. package/dist/richtext/serialize.js.map +1 -0
  76. package/dist/richtext/types.cjs +11 -0
  77. package/dist/richtext/types.cjs.map +1 -0
  78. package/dist/richtext/types.d.ts +71 -0
  79. package/dist/richtext/types.js +11 -0
  80. package/dist/richtext/types.js.map +1 -0
  81. package/dist/richtext/wrapMapSerializer.cjs +24 -0
  82. package/dist/richtext/wrapMapSerializer.cjs.map +1 -0
  83. package/dist/richtext/wrapMapSerializer.d.ts +15 -0
  84. package/dist/richtext/wrapMapSerializer.js +24 -0
  85. package/dist/richtext/wrapMapSerializer.js.map +1 -0
  86. package/dist/richtext.cjs +15 -0
  87. package/dist/richtext.cjs.map +1 -0
  88. package/dist/richtext.js +15 -0
  89. package/dist/richtext.js.map +1 -0
  90. package/dist/types/value/image.d.ts +9 -0
  91. package/dist/types/value/linkToMedia.d.ts +1 -0
  92. package/dist/types/value/richText.cjs.map +1 -1
  93. package/dist/types/value/richText.d.ts +7 -0
  94. package/dist/types/value/richText.js.map +1 -1
  95. package/dist/types/value/sharedSlice.d.ts +1 -1
  96. package/dist/types/value/slice.d.ts +1 -1
  97. package/package.json +34 -15
  98. package/src/createClient.ts +55 -4
  99. package/src/errors/ForbiddenError.ts +5 -3
  100. package/src/errors/NotFoundError.ts +3 -1
  101. package/src/errors/ParsingError.ts +3 -1
  102. package/src/errors/RefExpiredError.ts +14 -0
  103. package/src/errors/RefNotFoundError.ts +14 -0
  104. package/src/helpers/asHTML.ts +166 -76
  105. package/src/helpers/asImageWidthSrcSet.ts +2 -0
  106. package/src/helpers/asText.ts +2 -2
  107. package/src/index.ts +9 -4
  108. package/src/lib/serializerHelpers.ts +140 -67
  109. package/src/richtext/asText.ts +27 -0
  110. package/src/richtext/asTree.ts +211 -0
  111. package/src/richtext/composeSerializers.ts +36 -0
  112. package/src/richtext/index.ts +14 -0
  113. package/src/richtext/serialize.ts +54 -0
  114. package/src/richtext/types.ts +153 -0
  115. package/src/richtext/wrapMapSerializer.ts +46 -0
  116. package/src/types/value/image.ts +9 -0
  117. package/src/types/value/linkToMedia.ts +1 -0
  118. package/src/types/value/richText.ts +7 -0
  119. package/src/types/value/sharedSlice.ts +1 -1
  120. package/src/types/value/slice.ts +1 -1
@@ -1,34 +1,82 @@
1
+ import type { RichTextMapSerializer } from "../richtext/types";
1
2
  import { LinkType } from "../types/value/link";
2
- import {
3
- RTBlockNode,
4
- RTEmbedNode,
5
- RTImageNode,
6
- RTInlineNode,
7
- RTLinkNode,
8
- RTPreformattedNode,
9
- RichTextNodeType,
10
- } from "../types/value/richText";
3
+ import { RTAnyNode } from "../types/value/richText";
11
4
 
5
+ import {
6
+ HTMLRichTextMapSerializer,
7
+ HTMLStrictRichTextMapSerializer,
8
+ } from "../helpers/asHTML";
12
9
  import { LinkResolverFunction, asLink } from "../helpers/asLink";
13
10
 
14
11
  import { escapeHTML } from "./escapeHTML";
15
12
 
16
- export const getLabel = (node: RTBlockNode | RTInlineNode): string => {
17
- return "data" in node && "label" in node.data
18
- ? ` class="${node.data.label}"`
19
- : "";
13
+ type Attributes = Record<string, string | boolean | null | undefined>;
14
+ const formatAttributes = (node: RTAnyNode, attributes: Attributes): string => {
15
+ const _attributes = { ...attributes };
16
+
17
+ // Add label to attributes
18
+ if ("data" in node && "label" in node.data && node.data.label) {
19
+ _attributes.class = _attributes.class
20
+ ? `${_attributes.class} ${node.data.label}`
21
+ : node.data.label;
22
+ }
23
+
24
+ const result = [];
25
+
26
+ for (const key in _attributes) {
27
+ const value = _attributes[key];
28
+
29
+ if (value) {
30
+ if (typeof value === "boolean") {
31
+ result.push(key);
32
+ } else {
33
+ result.push(`${key}="${escapeHTML(value)}"`);
34
+ }
35
+ }
36
+ }
37
+
38
+ // Add a space at the beginning if there's any result
39
+ if (result.length) {
40
+ result.unshift("");
41
+ }
42
+
43
+ return result.join(" ");
44
+ };
45
+
46
+ const getGeneralAttributes = (
47
+ serializerOrShorthand?: HTMLRichTextMapSerializer[keyof HTMLRichTextMapSerializer],
48
+ ): Attributes => {
49
+ return serializerOrShorthand && typeof serializerOrShorthand !== "function"
50
+ ? serializerOrShorthand
51
+ : {};
20
52
  };
21
53
 
22
- export const serializeStandardTag = (
54
+ export const serializeStandardTag = <
55
+ BlockType extends keyof RichTextMapSerializer<string>,
56
+ >(
23
57
  tag: string,
24
- node: RTBlockNode | RTInlineNode,
25
- children: string[],
26
- ): string => {
27
- return `<${tag}${getLabel(node)}>${children.join("")}</${tag}>`;
58
+ serializerOrShorthand?: HTMLRichTextMapSerializer[BlockType],
59
+ ): NonNullable<HTMLStrictRichTextMapSerializer[BlockType]> => {
60
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
61
+
62
+ return (({ node, children }) => {
63
+ return `<${tag}${formatAttributes(
64
+ node,
65
+ generalAttributes,
66
+ )}>${children}</${tag}>`;
67
+ }) as NonNullable<HTMLStrictRichTextMapSerializer[BlockType]>;
28
68
  };
29
69
 
30
- export const serializePreFormatted = (node: RTPreformattedNode): string => {
31
- return `<pre${getLabel(node)}>${escapeHTML(node.text)}</pre>`;
70
+ export const serializePreFormatted = (
71
+ serializerOrShorthand?: HTMLRichTextMapSerializer["preformatted"],
72
+ ): NonNullable<HTMLStrictRichTextMapSerializer["preformatted"]> => {
73
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
74
+
75
+ return ({ node }) => {
76
+ return `<pre${formatAttributes(node, generalAttributes)}>${escapeHTML(
77
+ node.text,
78
+ )}</pre>`;
79
+ };
32
80
  };
33
81
 
34
82
  export const serializeImage = (
@@ -36,35 +84,57 @@ export const serializeImage = (
36
84
  | LinkResolverFunction<string | null | undefined>
37
85
  | undefined
38
86
  | null,
39
- node: RTImageNode,
40
- ): string => {
41
- let imageTag = `<img src="${node.url}" alt="${escapeHTML(node.alt)}"${
42
- node.copyright ? ` copyright="${escapeHTML(node.copyright)}"` : ""
43
- } />`;
44
-
45
- // If the image has a link, we wrap it with an anchor tag
46
- if (node.linkTo) {
47
- imageTag = serializeHyperlink(
48
- linkResolver,
49
- {
50
- type: RichTextNodeType.hyperlink,
51
- data: node.linkTo,
52
- start: 0,
53
- end: 0,
54
- },
55
- [imageTag],
56
- );
57
- }
87
+ serializerOrShorthand?: HTMLRichTextMapSerializer["image"],
88
+ ): NonNullable<HTMLStrictRichTextMapSerializer["image"]> => {
89
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
90
+
91
+ return ({ node }) => {
92
+ const attributes = {
93
+ ...generalAttributes,
94
+ src: node.url,
95
+ alt: node.alt,
96
+ copyright: node.copyright,
97
+ };
98
+
99
+ let imageTag = `<img${formatAttributes(node, attributes)} />`;
100
+
101
+ // If the image has a link, we wrap it with an anchor tag
102
+ if (node.linkTo) {
103
+ imageTag = serializeHyperlink(linkResolver)({
104
+ type: "hyperlink",
105
+ node: {
106
+ type: "hyperlink",
107
+ data: node.linkTo,
108
+ start: 0,
109
+ end: 0,
110
+ },
111
+ text: "",
112
+ children: imageTag,
113
+ key: "",
114
+ })!;
115
+ }
58
116
 
59
- return `<p class="block-img">${imageTag}</p>`;
117
+ return `<p class="block-img">${imageTag}</p>`;
118
+ };
60
119
  };
61
120
 
62
- export const serializeEmbed = (node: RTEmbedNode): string => {
63
- return `<div data-oembed="${node.oembed.embed_url}" data-oembed-type="${
64
- node.oembed.type
65
- }" data-oembed-provider="${node.oembed.provider_name}"${getLabel(node)}>${
66
- node.oembed.html
67
- }</div>`;
121
+ export const serializeEmbed = (
122
+ serializerOrShorthand?: HTMLRichTextMapSerializer["embed"],
123
+ ): NonNullable<HTMLStrictRichTextMapSerializer["embed"]> => {
124
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
125
+
126
+ return ({ node }) => {
127
+ const attributes = {
128
+ ...generalAttributes,
129
+ ["data-oembed"]: node.oembed.embed_url,
130
+ ["data-oembed-type"]: node.oembed.type,
131
+ ["data-oembed-provider"]: node.oembed.provider_name,
132
+ };
133
+
134
+ return `<div${formatAttributes(node, attributes)}>${
135
+ node.oembed.html
136
+ }</div>`;
137
+ };
68
138
  };
69
139
 
70
140
  export const serializeHyperlink = (
@@ -72,30 +142,33 @@ export const serializeHyperlink = (
72
142
  | LinkResolverFunction<string | null | undefined>
73
143
  | undefined
74
144
  | null,
75
- node: RTLinkNode,
76
- children: string[],
77
- ): string => {
78
- switch (node.data.link_type) {
79
- case LinkType.Web: {
80
- return `<a href="${escapeHTML(node.data.url)}" ${
81
- node.data.target ? `target="${node.data.target}" ` : ""
82
- }rel="noopener noreferrer"${getLabel(node)}>${children.join("")}</a>`;
83
- }
145
+ serializerOrShorthand?: HTMLRichTextMapSerializer["hyperlink"],
146
+ ): NonNullable<HTMLStrictRichTextMapSerializer["hyperlink"]> => {
147
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
84
148
 
85
- case LinkType.Document: {
86
- return `<a href="${asLink(node.data, linkResolver)}"${getLabel(
87
- node,
88
- )}>${children.join("")}</a>`;
89
- }
149
+ return ({ node, children }): string => {
150
+ const attributes = {
151
+ ...generalAttributes,
152
+ };
90
153
 
91
- case LinkType.Media: {
92
- return `<a href="${node.data.url}"${getLabel(node)}>${children.join(
93
- "",
94
- )}</a>`;
154
+ if (node.data.link_type === LinkType.Web) {
155
+ attributes.href = node.data.url;
156
+ attributes.target = node.data.target;
157
+ attributes.rel = "noopener noreferrer";
158
+ } else if (node.data.link_type === LinkType.Document) {
159
+ attributes.href = asLink(node.data, { linkResolver });
160
+ } else if (node.data.link_type === LinkType.Media) {
161
+ attributes.href = node.data.url;
95
162
  }
96
- }
163
+
164
+ return `<a${formatAttributes(node, attributes)}>${children}</a>`;
165
+ };
97
166
  };
98
167
 
99
- export const serializeSpan = (content?: string): string => {
100
- return content ? escapeHTML(content).replace(/\n/g, "<br />") : "";
168
+ export const serializeSpan = (): NonNullable<
169
+ HTMLStrictRichTextMapSerializer["span"]
170
+ > => {
171
+ return ({ text }): string => {
172
+ return text ? escapeHTML(text).replace(/\n/g, "<br />") : "";
173
+ };
101
174
  };
@@ -0,0 +1,27 @@
1
+ import { RTTextNode, RichTextField } from "../types/value/richText";
2
+
3
+ /**
4
+ * Serializes a rich text or title field to a plain text string
5
+ *
6
+ * @param richTextField - A rich text or title field from Prismic
7
+ * @param separator - Separator used to join each element, defaults to a space
8
+ *
9
+ * @returns Plain text equivalent of the provided rich text or title field
10
+ *
11
+ * @see Templating rich text and title fields from Prismic {@link https://prismic.io/docs/technologies/templating-rich-text-and-title-fields-javascript}
12
+ */
13
+ export const asText = (
14
+ richTextField: RichTextField,
15
+ separator = " ",
16
+ ): string => {
17
+ let result = "";
18
+
19
+ for (let i = 0; i < richTextField.length; i++) {
20
+ if ("text" in richTextField[i]) {
21
+ result +=
22
+ (result ? separator : "") + (richTextField[i] as RTTextNode).text;
23
+ }
24
+ }
25
+
26
+ return result;
27
+ };
@@ -0,0 +1,211 @@
1
+ import {
2
+ RTAnyNode,
3
+ RTBlockNode,
4
+ RTInlineNode,
5
+ RTListItemNode,
6
+ RTNode,
7
+ RTOListItemNode,
8
+ RTTextNode,
9
+ RichTextNodeType,
10
+ } from "../types/value/richText";
11
+ import { Tree, TreeNode } from "./types";
12
+
13
+ const uuid = (): string => {
14
+ return (++uuid.i).toString();
15
+ };
16
+ uuid.i = 0;
17
+
18
+ /**
19
+ * Parses a rich text or title field into a tree
20
+ *
21
+ * @remarks
22
+ * This is a low level helper mainly intended to be used by higher level
23
+ * packages. Most users aren't expected to this function directly.
24
+ *
25
+ * @param nodes - A rich text or title field from Prismic
26
+ *
27
+ * @returns Tree from given rich text or title field
28
+ */
29
+ export const asTree = (nodes: RTNode[]): Tree => {
30
+ const preparedNodes = prepareNodes(nodes);
31
+
32
+ const children: TreeNode[] = [];
33
+ for (let i = 0; i < preparedNodes.length; i++) {
34
+ children.push(nodeToTreeNode(preparedNodes[i]));
35
+ }
36
+
37
+ return {
38
+ key: uuid(),
39
+ children,
40
+ };
41
+ };
42
+
43
+ const createTreeNode = (
44
+ node: RTAnyNode,
45
+ children: TreeNode[] = [],
46
+ ): TreeNode => {
47
+ return {
48
+ key: uuid(),
49
+ type: node.type,
50
+ text: "text" in node ? node.text : undefined,
51
+ node,
52
+ children,
53
+ };
54
+ };
55
+
56
+ const createTextTreeNode = (text: string): TreeNode => {
57
+ return createTreeNode({
58
+ type: RichTextNodeType.span,
59
+ text,
60
+ spans: [],
61
+ });
62
+ };
63
+
64
+ const prepareNodes = (nodes: RTNode[]): RTBlockNode[] => {
65
+ const mutNodes: RTBlockNode[] = nodes.slice(0);
66
+
67
+ for (let i = 0; i < mutNodes.length; i++) {
68
+ const node = mutNodes[i];
69
+
70
+ if (
71
+ node.type === RichTextNodeType.listItem ||
72
+ node.type === RichTextNodeType.oListItem
73
+ ) {
74
+ const items: (RTListItemNode | RTOListItemNode)[] = [
75
+ node as RTListItemNode | RTOListItemNode,
76
+ ];
77
+
78
+ while (mutNodes[i + 1] && mutNodes[i + 1].type === node.type) {
79
+ items.push(mutNodes[i + 1] as RTListItemNode | RTOListItemNode);
80
+ mutNodes.splice(i, 1);
81
+ }
82
+
83
+ if (node.type === RichTextNodeType.listItem) {
84
+ mutNodes[i] = {
85
+ type: RichTextNodeType.list,
86
+ items: items as RTListItemNode[],
87
+ };
88
+ } else {
89
+ mutNodes[i] = {
90
+ type: RichTextNodeType.oList,
91
+ items: items as RTOListItemNode[],
92
+ };
93
+ }
94
+ }
95
+ }
96
+
97
+ return mutNodes;
98
+ };
99
+
100
+ const nodeToTreeNode = (node: RTBlockNode): TreeNode => {
101
+ if ("text" in node) {
102
+ return createTreeNode(
103
+ node,
104
+ textNodeSpansToTreeNodeChildren(node.spans, node),
105
+ );
106
+ }
107
+
108
+ if ("items" in node) {
109
+ const children: TreeNode[] = [];
110
+ for (let i = 0; i < node.items.length; i++) {
111
+ children.push(nodeToTreeNode(node.items[i]));
112
+ }
113
+
114
+ return createTreeNode(node, children);
115
+ }
116
+
117
+ return createTreeNode(node);
118
+ };
119
+
120
+ const textNodeSpansToTreeNodeChildren = (
121
+ spans: RTInlineNode[],
122
+ node: RTTextNode,
123
+ parentSpan?: RTInlineNode,
124
+ ): TreeNode[] => {
125
+ if (!spans.length) {
126
+ return [createTextTreeNode(node.text)];
127
+ }
128
+
129
+ const mutSpans: RTInlineNode[] = spans.slice(0);
130
+
131
+ // Sort spans using the following criteria:
132
+ //
133
+ // 1. By start index (ascending)
134
+ // 2. If start indices are equal, by end index (descending)
135
+ //
136
+ // If start and end indices of more than one span are equal, use what
137
+ // the API gives without modifications.
138
+ //
139
+ // Sorting using this algorithm ensures proper detection of child
140
+ // spans.
141
+ mutSpans.sort((a, b) => a.start - b.start || b.end - a.end);
142
+
143
+ const children: TreeNode[] = [];
144
+
145
+ for (let i = 0; i < mutSpans.length; i++) {
146
+ const span = mutSpans[i];
147
+ const parentSpanStart = (parentSpan && parentSpan.start) || 0;
148
+ const spanStart = span.start - parentSpanStart;
149
+ const spanEnd = span.end - parentSpanStart;
150
+ const text = node.text.slice(spanStart, spanEnd);
151
+
152
+ const childSpans: RTInlineNode[] = [];
153
+ for (let j = i; j < mutSpans.length; j++) {
154
+ const siblingSpan = mutSpans[j];
155
+
156
+ if (siblingSpan !== span) {
157
+ if (siblingSpan.start >= span.start && siblingSpan.end <= span.end) {
158
+ childSpans.push(siblingSpan);
159
+ mutSpans.splice(j, 1);
160
+ j--;
161
+ } else if (
162
+ siblingSpan.start < span.end &&
163
+ siblingSpan.end > span.start
164
+ ) {
165
+ childSpans.push({
166
+ ...siblingSpan,
167
+ end: span.end,
168
+ });
169
+ mutSpans[j] = {
170
+ ...siblingSpan,
171
+ start: span.end,
172
+ };
173
+ }
174
+ }
175
+ }
176
+
177
+ if (i === 0 && spanStart > 0) {
178
+ children.push(createTextTreeNode(node.text.slice(0, spanStart)));
179
+ }
180
+
181
+ const spanWithText = { ...span, text };
182
+ children.push(
183
+ createTreeNode(
184
+ spanWithText,
185
+ textNodeSpansToTreeNodeChildren(
186
+ childSpans,
187
+ {
188
+ ...node,
189
+ text,
190
+ },
191
+ span,
192
+ ),
193
+ ),
194
+ );
195
+
196
+ if (spanEnd < node.text.length) {
197
+ children.push(
198
+ createTextTreeNode(
199
+ node.text.slice(
200
+ spanEnd,
201
+ mutSpans[i + 1]
202
+ ? mutSpans[i + 1].start - parentSpanStart
203
+ : undefined,
204
+ ),
205
+ ),
206
+ );
207
+ }
208
+ }
209
+
210
+ return children;
211
+ };
@@ -0,0 +1,36 @@
1
+ import { RichTextFunctionSerializer } from "./types";
2
+
3
+ /**
4
+ * Takes an array of serializers and returns a serializer applying provided
5
+ * serializers sequentially until a result is returned
6
+ *
7
+ * @remarks
8
+ * This is a low level helper mainly intended to be used by higher level
9
+ * packages Most users aren't expected to this function directly
10
+ *
11
+ * @typeParam SerializerReturnType - Return type of serializers
12
+ *
13
+ * @param serializers - Serializers to compose
14
+ *
15
+ * @returns Composed serializer
16
+ */
17
+ export const composeSerializers = <SerializerReturnType>(
18
+ ...serializers: (
19
+ | RichTextFunctionSerializer<SerializerReturnType>
20
+ | undefined
21
+ )[]
22
+ ): RichTextFunctionSerializer<SerializerReturnType> => {
23
+ return (...args) => {
24
+ for (let i = 0; i < serializers.length; i++) {
25
+ const serializer = serializers[i];
26
+
27
+ if (serializer) {
28
+ const res = serializer(...args);
29
+
30
+ if (res != null) {
31
+ return res;
32
+ }
33
+ }
34
+ }
35
+ };
36
+ };
@@ -0,0 +1,14 @@
1
+ export { asTree } from "./asTree";
2
+ export { asText } from "./asText";
3
+
4
+ export { serialize } from "./serialize";
5
+ export { wrapMapSerializer } from "./wrapMapSerializer";
6
+ export { composeSerializers } from "./composeSerializers";
7
+
8
+ export { RichTextNodeType as Element } from "../types/value/richText";
9
+
10
+ export type {
11
+ RichTextFunctionSerializer,
12
+ RichTextMapSerializer,
13
+ RichTextMapSerializerFunction,
14
+ } from "./types";
@@ -0,0 +1,54 @@
1
+ import type { RichTextField } from "../types/value/richText";
2
+ import { RichTextFunctionSerializer, TreeNode } from "./types";
3
+
4
+ import { asTree } from "./asTree";
5
+
6
+ /**
7
+ * Serializes a rich text or title field with a given serializer
8
+ *
9
+ * @remarks
10
+ * This is a low level helper mainly intended to be used by higher level
11
+ * packages Most users aren't expected to this function directly
12
+ *
13
+ * @typeParam SerializerReturnType - Return type of the serializer
14
+ *
15
+ * @param richTextField - A rich text or title field from Prismic
16
+ * @param serializer - A function serializer to apply
17
+ *
18
+ * @returns An array of serialized nodes
19
+ *
20
+ * @see Templating rich text and title fields from Prismic {@link https://prismic.io/docs/technologies/templating-rich-text-and-title-fields-javascript}
21
+ */
22
+ export const serialize = <SerializerReturnType>(
23
+ richTextField: RichTextField,
24
+ serializer: RichTextFunctionSerializer<SerializerReturnType>,
25
+ ): SerializerReturnType[] => {
26
+ return serializeTreeNodes<SerializerReturnType>(
27
+ asTree(richTextField).children,
28
+ serializer,
29
+ );
30
+ };
31
+
32
+ const serializeTreeNodes = <T>(
33
+ nodes: TreeNode[],
34
+ serializer: RichTextFunctionSerializer<T>,
35
+ ): T[] => {
36
+ const serializedTreeNodes: T[] = [];
37
+
38
+ for (let i = 0; i < nodes.length; i++) {
39
+ const treeNode = nodes[i];
40
+ const serializedTreeNode = serializer(
41
+ treeNode.type,
42
+ treeNode.node,
43
+ treeNode.text,
44
+ serializeTreeNodes(treeNode.children, serializer),
45
+ treeNode.key,
46
+ );
47
+
48
+ if (serializedTreeNode != null) {
49
+ serializedTreeNodes.push(serializedTreeNode);
50
+ }
51
+ }
52
+
53
+ return serializedTreeNodes;
54
+ };