@prismicio/migrate 0.0.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.
- package/LICENSE +202 -0
- package/README.md +96 -0
- package/dist/errors/PrismicRichTextError.cjs +6 -0
- package/dist/errors/PrismicRichTextError.cjs.map +1 -0
- package/dist/errors/PrismicRichTextError.d.ts +2 -0
- package/dist/errors/PrismicRichTextError.js +6 -0
- package/dist/errors/PrismicRichTextError.js.map +1 -0
- package/dist/errors/PrismicRichTextSerializerError.cjs +7 -0
- package/dist/errors/PrismicRichTextSerializerError.cjs.map +1 -0
- package/dist/errors/PrismicRichTextSerializerError.d.ts +3 -0
- package/dist/errors/PrismicRichTextSerializerError.js +7 -0
- package/dist/errors/PrismicRichTextSerializerError.js.map +1 -0
- package/dist/htmlAsRichText.cjs +11 -0
- package/dist/htmlAsRichText.cjs.map +1 -0
- package/dist/htmlAsRichText.d.ts +78 -0
- package/dist/htmlAsRichText.js +11 -0
- package/dist/htmlAsRichText.js.map +1 -0
- package/dist/index.cjs +9 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/RichTextFieldBuilder.cjs +115 -0
- package/dist/lib/RichTextFieldBuilder.cjs.map +1 -0
- package/dist/lib/RichTextFieldBuilder.d.ts +35 -0
- package/dist/lib/RichTextFieldBuilder.js +115 -0
- package/dist/lib/RichTextFieldBuilder.js.map +1 -0
- package/dist/lib/filterRichTextField.cjs +87 -0
- package/dist/lib/filterRichTextField.cjs.map +1 -0
- package/dist/lib/filterRichTextField.d.ts +10 -0
- package/dist/lib/filterRichTextField.js +87 -0
- package/dist/lib/filterRichTextField.js.map +1 -0
- package/dist/lib/hastSerializerHelpers.cjs +95 -0
- package/dist/lib/hastSerializerHelpers.cjs.map +1 -0
- package/dist/lib/hastSerializerHelpers.d.ts +28 -0
- package/dist/lib/hastSerializerHelpers.js +95 -0
- package/dist/lib/hastSerializerHelpers.js.map +1 -0
- package/dist/lib/hastToRichText.cjs +164 -0
- package/dist/lib/hastToRichText.cjs.map +1 -0
- package/dist/lib/hastToRichText.d.ts +30 -0
- package/dist/lib/hastToRichText.js +164 -0
- package/dist/lib/hastToRichText.js.map +1 -0
- package/dist/lib/rehypeRichText.cjs +59 -0
- package/dist/lib/rehypeRichText.cjs.map +1 -0
- package/dist/lib/rehypeRichText.d.ts +65 -0
- package/dist/lib/rehypeRichText.js +59 -0
- package/dist/lib/rehypeRichText.js.map +1 -0
- package/dist/types.d.ts +57 -0
- package/package.json +95 -0
- package/src/errors/PrismicRichTextError.ts +1 -0
- package/src/errors/PrismicRichTextSerializerError.ts +3 -0
- package/src/htmlAsRichText.ts +117 -0
- package/src/index.ts +7 -0
- package/src/lib/RichTextFieldBuilder.ts +164 -0
- package/src/lib/filterRichTextField.ts +158 -0
- package/src/lib/hastSerializerHelpers.ts +151 -0
- package/src/lib/hastToRichText.ts +294 -0
- package/src/lib/rehypeRichText.ts +185 -0
- package/src/types.ts +72 -0
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { LinkType, OEmbedType } from "@prismicio/client"
|
|
2
|
+
import type { RTEmbedNode, RTImageNode, RTLinkNode } from "@prismicio/client"
|
|
3
|
+
import type { Element } from "hast"
|
|
4
|
+
import { toHtml } from "hast-util-to-html"
|
|
5
|
+
|
|
6
|
+
import { PrismicRichTextSerializerError } from "../errors/PrismicRichTextSerializerError"
|
|
7
|
+
|
|
8
|
+
import type { RTPartialInlineNode } from "./RichTextFieldBuilder"
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Serializes a hast {@link Element} node to a {@link RTImageNode}.
|
|
12
|
+
*
|
|
13
|
+
* @param node - A hast node to serialize.
|
|
14
|
+
*
|
|
15
|
+
* @returns Equivalent {@link RTImageNode}.
|
|
16
|
+
*/
|
|
17
|
+
export const serializeImage = (node: Element): RTImageNode => {
|
|
18
|
+
const src = node.properties?.src as string | undefined
|
|
19
|
+
|
|
20
|
+
if (!src) {
|
|
21
|
+
throw new PrismicRichTextSerializerError(
|
|
22
|
+
"Element of type `img` is missing an `src` attribute",
|
|
23
|
+
)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const url = new URL(src, "https://noop.com")
|
|
27
|
+
|
|
28
|
+
let width = node.properties?.width as number | undefined
|
|
29
|
+
let height = node.properties?.height as number | undefined
|
|
30
|
+
let x = 0
|
|
31
|
+
let y = 0
|
|
32
|
+
let zoom = 1
|
|
33
|
+
|
|
34
|
+
// Attempt to infer the image dimensions from the URL imgix parameters.
|
|
35
|
+
if (url.hostname === "images.prismic.io") {
|
|
36
|
+
if (url.searchParams.has("w")) {
|
|
37
|
+
width = Number(url.searchParams.get("w"))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (url.searchParams.has("h")) {
|
|
41
|
+
height = Number(url.searchParams.get("h"))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (url.searchParams.has("rect")) {
|
|
45
|
+
const [rectX, rextY, rectW, _rectH] = url.searchParams
|
|
46
|
+
.get("rect")!
|
|
47
|
+
.split(",")
|
|
48
|
+
|
|
49
|
+
x = Number(rectX)
|
|
50
|
+
y = Number(rextY)
|
|
51
|
+
|
|
52
|
+
// This is not perfect but it's supposed to work on images without constraints.
|
|
53
|
+
if (width) {
|
|
54
|
+
zoom = Math.max(1, width / Number(rectW))
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
type: "image",
|
|
61
|
+
id: "",
|
|
62
|
+
url: src,
|
|
63
|
+
alt: (node.properties?.alt as string) ?? "",
|
|
64
|
+
copyright: (node.properties?.copyright as string) ?? null,
|
|
65
|
+
// This is not accurate. We're doing the casting because it seems the migration API
|
|
66
|
+
// accepts `undefined` values for those fields which is more convenient to us here.
|
|
67
|
+
// See: https://github.com/prismicio/prismic-client/pull/342#discussion_r1683650185
|
|
68
|
+
dimensions: { width: width as number, height: height as number },
|
|
69
|
+
edit: { x, y, zoom, background: "transparent" },
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Serializes a hast {@link Element} node to a {@link RTEmbedNode}.
|
|
75
|
+
*
|
|
76
|
+
* @param node - A hast node to serialize.
|
|
77
|
+
*
|
|
78
|
+
* @returns Equivalent {@link RTEmbedNode}.
|
|
79
|
+
*/
|
|
80
|
+
export const serializeEmbed = (node: Element): RTEmbedNode => {
|
|
81
|
+
const src = node.properties?.src as string | undefined
|
|
82
|
+
|
|
83
|
+
if (!src) {
|
|
84
|
+
throw new PrismicRichTextSerializerError(
|
|
85
|
+
"Element of type `embed` is missing an `src` attribute",
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const oembedBase = {
|
|
90
|
+
version: "1.0",
|
|
91
|
+
embed_url: src,
|
|
92
|
+
html: toHtml(node),
|
|
93
|
+
title: node.properties?.title as string | undefined,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const width = node.properties?.width as number | undefined
|
|
97
|
+
const height = node.properties?.height as number | undefined
|
|
98
|
+
|
|
99
|
+
// Remove the children of the embed node as we don't want to process them.
|
|
100
|
+
node.children = []
|
|
101
|
+
|
|
102
|
+
if (width && height) {
|
|
103
|
+
return {
|
|
104
|
+
type: "embed",
|
|
105
|
+
oembed: { ...oembedBase, type: OEmbedType.Rich, width, height },
|
|
106
|
+
}
|
|
107
|
+
} else {
|
|
108
|
+
return {
|
|
109
|
+
type: "embed",
|
|
110
|
+
oembed: { ...oembedBase, type: OEmbedType.Link },
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Serializes a hast {@link Element} node to a {@link RTPartialInlineNode}.
|
|
117
|
+
*
|
|
118
|
+
* @param node - A hast node to serialize.
|
|
119
|
+
* @param rtPartialInlineNode - A partial rich text node.
|
|
120
|
+
*
|
|
121
|
+
* @returns Equivalent {@link RTPartialInlineNode}.
|
|
122
|
+
*/
|
|
123
|
+
export const serializeSpan = (
|
|
124
|
+
node: Element,
|
|
125
|
+
rtPartialInlineNode:
|
|
126
|
+
| RTPartialInlineNode
|
|
127
|
+
| Omit<RTLinkNode, "start" | "end" | "data">,
|
|
128
|
+
): RTPartialInlineNode => {
|
|
129
|
+
if (
|
|
130
|
+
rtPartialInlineNode.type === "hyperlink" &&
|
|
131
|
+
!("data" in rtPartialInlineNode)
|
|
132
|
+
) {
|
|
133
|
+
const url = node.properties?.href as string | undefined
|
|
134
|
+
if (!url) {
|
|
135
|
+
throw new PrismicRichTextSerializerError(
|
|
136
|
+
"Element of type `hyperlink` is missing an `href` attribute",
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
type: "hyperlink",
|
|
142
|
+
data: {
|
|
143
|
+
link_type: LinkType.Web,
|
|
144
|
+
url,
|
|
145
|
+
target: node.properties?.target as string | undefined,
|
|
146
|
+
},
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return rtPartialInlineNode
|
|
151
|
+
}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
RTBlockNode,
|
|
3
|
+
RTInlineNode,
|
|
4
|
+
RTLabelNode,
|
|
5
|
+
RTTextNode,
|
|
6
|
+
RichTextField,
|
|
7
|
+
} from "@prismicio/client"
|
|
8
|
+
import { RichTextNodeType } from "@prismicio/client"
|
|
9
|
+
import type { Element, Root } from "hast"
|
|
10
|
+
import { toString } from "hast-util-to-string"
|
|
11
|
+
import { visit } from "unist-util-visit"
|
|
12
|
+
import type { VFile } from "vfile"
|
|
13
|
+
|
|
14
|
+
import type {
|
|
15
|
+
RichTextHTMLMapSerializer,
|
|
16
|
+
RichTextHTMLMapSerializerFunction,
|
|
17
|
+
RichTextHTMLMapSerializerShorthand,
|
|
18
|
+
} from "../types"
|
|
19
|
+
|
|
20
|
+
import { PrismicRichTextSerializerError } from "../errors/PrismicRichTextSerializerError"
|
|
21
|
+
|
|
22
|
+
import { RichTextFieldBuilder } from "./RichTextFieldBuilder"
|
|
23
|
+
import {
|
|
24
|
+
serializeEmbed,
|
|
25
|
+
serializeImage,
|
|
26
|
+
serializeSpan,
|
|
27
|
+
} from "./hastSerializerHelpers"
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Pick keys from a type, distributing the operation over a union.
|
|
31
|
+
*
|
|
32
|
+
* Taken from the `type-fest` package.
|
|
33
|
+
*
|
|
34
|
+
* @see https://github.com/sindresorhus/type-fest/blob/8a45ba048767aaffcebc7d190172d814a739feb0/source/distributed-pick.d.ts
|
|
35
|
+
*/
|
|
36
|
+
type DistributedPick<
|
|
37
|
+
ObjectType,
|
|
38
|
+
KeyType extends keyof ObjectType,
|
|
39
|
+
> = ObjectType extends unknown ? Pick<ObjectType, KeyType> : never
|
|
40
|
+
|
|
41
|
+
const DEFAULT_SERIALIZER: RichTextHTMLMapSerializer = {
|
|
42
|
+
h1: "heading1",
|
|
43
|
+
h2: "heading2",
|
|
44
|
+
h3: "heading3",
|
|
45
|
+
h4: "heading4",
|
|
46
|
+
h5: "heading5",
|
|
47
|
+
h6: "heading6",
|
|
48
|
+
p: "paragraph",
|
|
49
|
+
pre: "preformatted",
|
|
50
|
+
strong: "strong",
|
|
51
|
+
em: "em",
|
|
52
|
+
li: ({ context }) =>
|
|
53
|
+
context.listType === "group-o-list-item" ? "o-list-item" : "list-item",
|
|
54
|
+
ul: "group-list-item",
|
|
55
|
+
ol: "group-o-list-item",
|
|
56
|
+
img: "image",
|
|
57
|
+
iframe: "embed",
|
|
58
|
+
a: "hyperlink",
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const VFILE_RULE = "failed-to-serialize-node"
|
|
62
|
+
const VFILE_SOURCE = "prismic"
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Configuration that determines the output of `toRichText`.
|
|
66
|
+
*/
|
|
67
|
+
export type HASTToRichTextConfig = {
|
|
68
|
+
/**
|
|
69
|
+
* An optional HTML to rich text serializer. Will be merged with the default
|
|
70
|
+
* HTML to rich text serializer.
|
|
71
|
+
*/
|
|
72
|
+
serializer?: RichTextHTMLMapSerializer
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Whether or not the text processed should be marked as right-to-left.
|
|
76
|
+
*
|
|
77
|
+
* @defaultValue `false`
|
|
78
|
+
*/
|
|
79
|
+
direction?: "ltr" | "rtl"
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Transfor a hast tree to a rich text field.
|
|
84
|
+
*
|
|
85
|
+
* @param tree - The hast tree to transform.
|
|
86
|
+
* @param file - The vfile to attach warnings to.
|
|
87
|
+
* @param config - Configuration that determines the output of the function.
|
|
88
|
+
*
|
|
89
|
+
* @returns The rich text field equivalent of the provided hast tree.
|
|
90
|
+
*/
|
|
91
|
+
export const hastToRichText = (
|
|
92
|
+
tree: Root | Element,
|
|
93
|
+
file: VFile,
|
|
94
|
+
config?: HASTToRichTextConfig,
|
|
95
|
+
): RichTextField => {
|
|
96
|
+
const builder = new RichTextFieldBuilder()
|
|
97
|
+
|
|
98
|
+
// Merge the default serializer with the user-provided one.
|
|
99
|
+
const serializer = {
|
|
100
|
+
...DEFAULT_SERIALIZER,
|
|
101
|
+
...config?.serializer,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Keep track of the last text node type to append text nodes to in
|
|
105
|
+
// case of an image or an embed node is present inside a paragraph.
|
|
106
|
+
let lastRTTextNodeType: RTTextNode["type"] = RichTextNodeType.paragraph
|
|
107
|
+
|
|
108
|
+
// Keep track of the last list type to know whether we need to append
|
|
109
|
+
// `list-item` or `o-list-item` nodes.
|
|
110
|
+
let lastListType: "group-list-item" | "group-o-list-item" | undefined =
|
|
111
|
+
undefined
|
|
112
|
+
|
|
113
|
+
visit(tree, (node) => {
|
|
114
|
+
if (node.type === "element") {
|
|
115
|
+
// Transforms line break elements to line breaks
|
|
116
|
+
if (node.tagName === "br") {
|
|
117
|
+
try {
|
|
118
|
+
builder.appendText("\n")
|
|
119
|
+
} catch (error) {
|
|
120
|
+
// noop
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Resolves the serializer responsible for the current node.
|
|
125
|
+
let serializerOrShorthand:
|
|
126
|
+
| RichTextHTMLMapSerializerShorthand
|
|
127
|
+
| RichTextHTMLMapSerializerFunction
|
|
128
|
+
|
|
129
|
+
// We give priority to CSS selectors over tag names.
|
|
130
|
+
if (node.matchesSerializer && node.matchesSerializer in serializer) {
|
|
131
|
+
serializerOrShorthand = serializer[node.matchesSerializer]
|
|
132
|
+
} else if (node.tagName in serializer) {
|
|
133
|
+
serializerOrShorthand = serializer[node.tagName]
|
|
134
|
+
} else {
|
|
135
|
+
return
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
let shorthand: RichTextHTMLMapSerializerShorthand
|
|
139
|
+
if (typeof serializerOrShorthand === "function") {
|
|
140
|
+
const shorthandOrNode = serializerOrShorthand({
|
|
141
|
+
node,
|
|
142
|
+
context: { listType: lastListType },
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
if (!shorthandOrNode) {
|
|
146
|
+
// Exit on unhandled node.
|
|
147
|
+
return
|
|
148
|
+
} else if (
|
|
149
|
+
typeof shorthandOrNode === "object" &&
|
|
150
|
+
"type" in shorthandOrNode
|
|
151
|
+
) {
|
|
152
|
+
// When the serializer returns a rich text node, we append it and return.
|
|
153
|
+
switch (shorthandOrNode.type) {
|
|
154
|
+
case RichTextNodeType.strong:
|
|
155
|
+
case RichTextNodeType.em:
|
|
156
|
+
case RichTextNodeType.label:
|
|
157
|
+
case RichTextNodeType.hyperlink: {
|
|
158
|
+
const length = toString(node).trimEnd().length
|
|
159
|
+
|
|
160
|
+
try {
|
|
161
|
+
builder.appendSpan(shorthandOrNode, length)
|
|
162
|
+
} catch (error) {
|
|
163
|
+
// Happens when we extract an image/embed node inside an RTTextNode and that
|
|
164
|
+
// the next children is a span. The last RT node type is then an image/embed
|
|
165
|
+
// node, so we need to resume a new RT text node.
|
|
166
|
+
builder.appendTextNode(lastRTTextNodeType, config?.direction)
|
|
167
|
+
builder.appendSpan(shorthandOrNode, length)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
case RichTextNodeType.image:
|
|
174
|
+
case RichTextNodeType.embed:
|
|
175
|
+
builder.appendNode(shorthandOrNode)
|
|
176
|
+
|
|
177
|
+
return
|
|
178
|
+
|
|
179
|
+
default:
|
|
180
|
+
lastRTTextNodeType = shorthandOrNode.type
|
|
181
|
+
builder.appendNode(shorthandOrNode)
|
|
182
|
+
|
|
183
|
+
return
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Else it's a shorthand.
|
|
188
|
+
shorthand = shorthandOrNode
|
|
189
|
+
} else {
|
|
190
|
+
shorthand = serializerOrShorthand
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
let match:
|
|
194
|
+
| DistributedPick<
|
|
195
|
+
RTBlockNode | Exclude<RTInlineNode, RTLabelNode>,
|
|
196
|
+
"type"
|
|
197
|
+
>
|
|
198
|
+
| { type: "label"; data: { label: string } }
|
|
199
|
+
if (typeof shorthand === "string") {
|
|
200
|
+
match = { type: shorthand }
|
|
201
|
+
} else {
|
|
202
|
+
match = { type: RichTextNodeType.label, data: shorthand }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
try {
|
|
206
|
+
switch (match.type) {
|
|
207
|
+
case RichTextNodeType.heading1:
|
|
208
|
+
case RichTextNodeType.heading2:
|
|
209
|
+
case RichTextNodeType.heading3:
|
|
210
|
+
case RichTextNodeType.heading4:
|
|
211
|
+
case RichTextNodeType.heading5:
|
|
212
|
+
case RichTextNodeType.heading6:
|
|
213
|
+
case RichTextNodeType.paragraph:
|
|
214
|
+
case RichTextNodeType.preformatted:
|
|
215
|
+
case RichTextNodeType.listItem:
|
|
216
|
+
case RichTextNodeType.oListItem:
|
|
217
|
+
lastRTTextNodeType = match.type
|
|
218
|
+
builder.appendTextNode(match.type, config?.direction)
|
|
219
|
+
break
|
|
220
|
+
|
|
221
|
+
case RichTextNodeType.list:
|
|
222
|
+
case RichTextNodeType.oList:
|
|
223
|
+
lastListType = match.type
|
|
224
|
+
break
|
|
225
|
+
|
|
226
|
+
case RichTextNodeType.image:
|
|
227
|
+
builder.appendNode(serializeImage(node))
|
|
228
|
+
break
|
|
229
|
+
|
|
230
|
+
case RichTextNodeType.embed:
|
|
231
|
+
builder.appendNode(serializeEmbed(node))
|
|
232
|
+
break
|
|
233
|
+
|
|
234
|
+
case RichTextNodeType.strong:
|
|
235
|
+
case RichTextNodeType.em:
|
|
236
|
+
case RichTextNodeType.label:
|
|
237
|
+
case RichTextNodeType.hyperlink: {
|
|
238
|
+
const span = serializeSpan(node, match)
|
|
239
|
+
const length = toString(node).trimEnd().length
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
builder.appendSpan(span, length)
|
|
243
|
+
} catch (error) {
|
|
244
|
+
// Happens when we extract an image/embed node inside an RTTextNode and that
|
|
245
|
+
// the next children is a span. The last RT node type is then an image/embed
|
|
246
|
+
// node, so we need to resume a new RT text node.
|
|
247
|
+
builder.appendTextNode(lastRTTextNodeType, config?.direction)
|
|
248
|
+
builder.appendSpan(span, length)
|
|
249
|
+
}
|
|
250
|
+
break
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
default:
|
|
254
|
+
throw new Error(
|
|
255
|
+
`Unknown rich text node type: \`${
|
|
256
|
+
(match as { type: string }).type
|
|
257
|
+
}\``,
|
|
258
|
+
)
|
|
259
|
+
}
|
|
260
|
+
} catch (error) {
|
|
261
|
+
if (error instanceof PrismicRichTextSerializerError) {
|
|
262
|
+
file.message(error.message, {
|
|
263
|
+
cause: error,
|
|
264
|
+
place: node.position,
|
|
265
|
+
ruleId: VFILE_RULE,
|
|
266
|
+
source: VFILE_SOURCE,
|
|
267
|
+
})
|
|
268
|
+
|
|
269
|
+
return
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
throw error
|
|
273
|
+
}
|
|
274
|
+
} else if (node.type === "text") {
|
|
275
|
+
// Inspired from `hast-util-whitespace`, see:
|
|
276
|
+
// https://github.com/syntax-tree/hast-util-whitespace/blob/main/lib/index.js
|
|
277
|
+
if (!(node.value.replace(/[ \t\n\f\r]/g, "") === "")) {
|
|
278
|
+
try {
|
|
279
|
+
builder.appendText(node.value)
|
|
280
|
+
} catch (error) {
|
|
281
|
+
// Happens when we extract an image/embed node inside an RTTextNode. The last RT
|
|
282
|
+
// node type is then an image/embed node, so we need to resume a new RT text node.
|
|
283
|
+
builder.appendTextNode(lastRTTextNodeType, config?.direction)
|
|
284
|
+
builder.appendText(node.value)
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// We ignore the following node types:
|
|
290
|
+
// root, doctype, comment, raw
|
|
291
|
+
})
|
|
292
|
+
|
|
293
|
+
return builder.build()
|
|
294
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CustomTypeModelRichTextField,
|
|
3
|
+
RichTextField,
|
|
4
|
+
} from "@prismicio/client"
|
|
5
|
+
import type { Element, Root } from "hast"
|
|
6
|
+
import { select, selectAll } from "hast-util-select"
|
|
7
|
+
import rehypeMinifyWhitespace from "rehype-minify-whitespace"
|
|
8
|
+
import type { Plugin, Processor } from "unified"
|
|
9
|
+
import { remove } from "unist-util-remove"
|
|
10
|
+
import { SKIP, visit } from "unist-util-visit"
|
|
11
|
+
import type { VFile } from "vfile"
|
|
12
|
+
|
|
13
|
+
import { filterRichTextField } from "./filterRichTextField"
|
|
14
|
+
import type { HASTToRichTextConfig } from "./hastToRichText"
|
|
15
|
+
import { hastToRichText } from "./hastToRichText"
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Configuration options for {@link rehypeRichText}.
|
|
19
|
+
*/
|
|
20
|
+
export type RehypeRichTextConfig = {
|
|
21
|
+
/**
|
|
22
|
+
* A CSS selector that targets the section of the document to convert to rich
|
|
23
|
+
* text.
|
|
24
|
+
*
|
|
25
|
+
* @example `div.post`
|
|
26
|
+
*
|
|
27
|
+
* @defaultValue `":root"` - The top-level element of the document.
|
|
28
|
+
*/
|
|
29
|
+
container?: string
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A list of CSS selectors to exclude matching nodes from the document to
|
|
33
|
+
* process.
|
|
34
|
+
*
|
|
35
|
+
* @example `[".hidden", "aside"]`
|
|
36
|
+
*
|
|
37
|
+
* @defaultValue `[]` - No nodes are excluded.
|
|
38
|
+
*/
|
|
39
|
+
exclude?: string[]
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A list of CSS selectors to include only matching nodes from the document to
|
|
43
|
+
* process.
|
|
44
|
+
*
|
|
45
|
+
* @example `["p", "img"]`
|
|
46
|
+
*
|
|
47
|
+
* @defaultValue `[]` - All nodes are included.
|
|
48
|
+
*/
|
|
49
|
+
include?: string[]
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A rich text or title field model definition. When provided the serializer
|
|
53
|
+
* will filter out any node types not allowed by the model.
|
|
54
|
+
*
|
|
55
|
+
* @defaultValue `undefined` - No filtering is applied.
|
|
56
|
+
*/
|
|
57
|
+
model?: CustomTypeModelRichTextField
|
|
58
|
+
} & HASTToRichTextConfig
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A unified plugin that compiles a hast tree to a Prismic rich text field.
|
|
62
|
+
*
|
|
63
|
+
* @param config - Configuration options for the rehype rich text processor.
|
|
64
|
+
*/
|
|
65
|
+
// unified requires the function to be typed directly with the
|
|
66
|
+
// `Plugin` type to properly infer return types on processors.
|
|
67
|
+
export const rehypeRichText: Plugin<
|
|
68
|
+
[config?: RehypeRichTextConfig],
|
|
69
|
+
Root,
|
|
70
|
+
RichTextField
|
|
71
|
+
> = function rehypeRichText(config) {
|
|
72
|
+
// This is a bit dirty, but it seems like that's how rehype intends
|
|
73
|
+
// it to be due to JSDocs limitations(?), see:
|
|
74
|
+
// https://github.com/rehypejs/rehype/blob/f6912ac680704f1ef4b558ac57cbf0dd62ed0892/packages/rehype-stringify/lib/index.js#L18-L20
|
|
75
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
76
|
+
const self = this as unknown as Processor<
|
|
77
|
+
undefined,
|
|
78
|
+
undefined,
|
|
79
|
+
undefined,
|
|
80
|
+
Root,
|
|
81
|
+
RichTextField
|
|
82
|
+
>
|
|
83
|
+
|
|
84
|
+
// We need to exclude nodes _before_ we minify the tree as excluding
|
|
85
|
+
// nodes could end up in more whitespaces to trim.
|
|
86
|
+
self.use(() => {
|
|
87
|
+
return (tree: Root) => {
|
|
88
|
+
// Extract container node if any is specified.
|
|
89
|
+
if (config?.container) {
|
|
90
|
+
const element = select(config.container, tree)
|
|
91
|
+
|
|
92
|
+
if (!element) {
|
|
93
|
+
throw new Error(
|
|
94
|
+
`No container matching \`${config?.container}\` could be found in the input AST.`,
|
|
95
|
+
)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// We cannot reassign the tree itself, so we instead replace
|
|
99
|
+
// its children with the found element.
|
|
100
|
+
tree.children = [element]
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Remove excluded nodes if any are specified
|
|
104
|
+
if (config?.exclude) {
|
|
105
|
+
// We join selector to only run one query
|
|
106
|
+
const nodesToExclude = selectAll(config.exclude.join(", "), tree)
|
|
107
|
+
|
|
108
|
+
remove(tree, (node) => nodesToExclude.includes(node as Element))
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Include only nodes to include
|
|
112
|
+
if (config?.include) {
|
|
113
|
+
const nodesToInclude: Element[] = []
|
|
114
|
+
|
|
115
|
+
// We join selector to only run one query
|
|
116
|
+
const selector = config.include.join(", ")
|
|
117
|
+
const rawNodesToInclude = selectAll(selector, tree)
|
|
118
|
+
|
|
119
|
+
// We walk the tree to exclude matching nodes that are children of other matching nodes.
|
|
120
|
+
visit(tree, (node) => {
|
|
121
|
+
if (rawNodesToInclude.includes(node as Element)) {
|
|
122
|
+
nodesToInclude.push(node as Element)
|
|
123
|
+
|
|
124
|
+
// Stop traversing this part of the tree since we found its matching parent node.
|
|
125
|
+
return SKIP
|
|
126
|
+
}
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
// We cannot reassign the tree itself, so we instead replace
|
|
130
|
+
// its children with the found element.
|
|
131
|
+
tree.children = nodesToInclude
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Mark nodes matching CSS selectors
|
|
135
|
+
if (config?.serializer) {
|
|
136
|
+
for (const key in config.serializer) {
|
|
137
|
+
// HTML tag names are single word, lowercase strings, a-z and 1-6 (headings).
|
|
138
|
+
// Here we want to match anything that's not a valid HTML tag name and treat
|
|
139
|
+
// it as a CSS selector. See: https://regex101.com/r/LILLWH/1
|
|
140
|
+
if (!/^[a-z]+[1-6]?$/.test(key)) {
|
|
141
|
+
const matches = selectAll(key, tree)
|
|
142
|
+
|
|
143
|
+
for (let i = 0; i < matches.length; i++) {
|
|
144
|
+
matches[i].matchesSerializer = key
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
// `rehypeRichText` _depends_ on `rehypeMinifyWhitespace`, that's why it's
|
|
153
|
+
// registered within the plugin rather than on the processor directly.
|
|
154
|
+
self.use(rehypeMinifyWhitespace)
|
|
155
|
+
|
|
156
|
+
self.compiler = compiler
|
|
157
|
+
|
|
158
|
+
function compiler(tree: Root, file: VFile): RichTextField {
|
|
159
|
+
const richTextField = hastToRichText(tree, file, config)
|
|
160
|
+
|
|
161
|
+
if (config?.model) {
|
|
162
|
+
return filterRichTextField(richTextField, config.model)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return richTextField
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
declare module "unified" {
|
|
170
|
+
// Register unified processor the result type.
|
|
171
|
+
interface CompileResultMap {
|
|
172
|
+
RichTextField: RichTextField
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
declare module "hast" {
|
|
177
|
+
// Extend hast node with a rich text value.
|
|
178
|
+
interface Element {
|
|
179
|
+
/**
|
|
180
|
+
* A serializer this node matches to. Nodes are marked with this property
|
|
181
|
+
* when they match a CSS selector from the serializer map.
|
|
182
|
+
*/
|
|
183
|
+
matchesSerializer?: string
|
|
184
|
+
}
|
|
185
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { RTInlineNode, RTNode, RichTextNodeTypes } from "@prismicio/client"
|
|
2
|
+
import type { Element } from "hast"
|
|
3
|
+
|
|
4
|
+
import type { RTPartialInlineNode } from "./lib/RichTextFieldBuilder"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A shorthand definition for {@link RichTextHTMLMapSerializer} rich text node
|
|
8
|
+
* types.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* The `label` rich text node type is not available as is. Use an object
|
|
12
|
+
* containing your label name to convert to label nodes instead. For example:
|
|
13
|
+
* `u: { label: "underline" }`
|
|
14
|
+
* @remarks
|
|
15
|
+
* The `span` rich text node type is not available as it is not relevant in the
|
|
16
|
+
* context of going from HTML to Prismic rich text.
|
|
17
|
+
*/
|
|
18
|
+
export type RichTextHTMLMapSerializerShorthand =
|
|
19
|
+
| Exclude<RichTextNodeTypes, "label" | "span">
|
|
20
|
+
| { label: string }
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The payload provided to a {@link RichTextHTMLMapSerializerFunction}.
|
|
24
|
+
*/
|
|
25
|
+
type RichTextHTMLMapSerializerFunctionPayload = {
|
|
26
|
+
/**
|
|
27
|
+
* The hast {@link Element} node to serialize.
|
|
28
|
+
*/
|
|
29
|
+
node: Element
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Additional context information to help with the serialization.
|
|
33
|
+
*/
|
|
34
|
+
context: {
|
|
35
|
+
/**
|
|
36
|
+
* The list type of the last list node encountered if any.
|
|
37
|
+
*/
|
|
38
|
+
listType?: "group-list-item" | "group-o-list-item"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Serializes a hast {@link Element} node to a
|
|
44
|
+
* {@link RichTextHTMLMapSerializerShorthand} or a rich text node.
|
|
45
|
+
*
|
|
46
|
+
* @remarks
|
|
47
|
+
* Serializing to a rich text node directly is not recommended and is only
|
|
48
|
+
* available as an escape hatch. Prefer returning a
|
|
49
|
+
* {@link RichTextHTMLMapSerializerShorthand} instead.
|
|
50
|
+
*/
|
|
51
|
+
export type RichTextHTMLMapSerializerFunction = (
|
|
52
|
+
payload: RichTextHTMLMapSerializerFunctionPayload,
|
|
53
|
+
) =>
|
|
54
|
+
| RichTextHTMLMapSerializerShorthand
|
|
55
|
+
| RTNode
|
|
56
|
+
| RTInlineNode
|
|
57
|
+
| RTPartialInlineNode
|
|
58
|
+
| undefined
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Serializes a hast {@link Element} node matching the given HTML tag name or CSS
|
|
62
|
+
* selector to a Prismic rich text node.
|
|
63
|
+
*
|
|
64
|
+
* @remarks
|
|
65
|
+
* This serializer is used to serialize HTML to Prismic rich text. When
|
|
66
|
+
* serializing Prismic rich text to HTML with {@link asHTML}, use the
|
|
67
|
+
* {@link HTMLRichTextMapSerializer} type instead.
|
|
68
|
+
*/
|
|
69
|
+
export type RichTextHTMLMapSerializer = Record<
|
|
70
|
+
string,
|
|
71
|
+
RichTextHTMLMapSerializerShorthand | RichTextHTMLMapSerializerFunction
|
|
72
|
+
>
|