@prismicio/client 7.7.4 → 7.8.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 (63) hide show
  1. package/dist/index.cjs +0 -8
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.ts +0 -5
  4. package/dist/index.js +1 -9
  5. package/dist/index.js.map +1 -1
  6. package/dist/package.json.cjs +1 -1
  7. package/dist/package.json.js +1 -1
  8. package/package.json +3 -15
  9. package/src/index.ts +0 -8
  10. package/dist/errors/PrismicRichTextError.cjs +0 -6
  11. package/dist/errors/PrismicRichTextError.cjs.map +0 -1
  12. package/dist/errors/PrismicRichTextError.d.ts +0 -2
  13. package/dist/errors/PrismicRichTextError.js +0 -6
  14. package/dist/errors/PrismicRichTextError.js.map +0 -1
  15. package/dist/errors/PrismicRichTextSerializerError.cjs +0 -7
  16. package/dist/errors/PrismicRichTextSerializerError.cjs.map +0 -1
  17. package/dist/errors/PrismicRichTextSerializerError.d.ts +0 -3
  18. package/dist/errors/PrismicRichTextSerializerError.js +0 -7
  19. package/dist/errors/PrismicRichTextSerializerError.js.map +0 -1
  20. package/dist/helpers/unstable_htmlAsRichText.cjs +0 -11
  21. package/dist/helpers/unstable_htmlAsRichText.cjs.map +0 -1
  22. package/dist/helpers/unstable_htmlAsRichText.d.ts +0 -81
  23. package/dist/helpers/unstable_htmlAsRichText.js +0 -11
  24. package/dist/helpers/unstable_htmlAsRichText.js.map +0 -1
  25. package/dist/helpers/unstable_markdownAsRichText.cjs +0 -12
  26. package/dist/helpers/unstable_markdownAsRichText.cjs.map +0 -1
  27. package/dist/helpers/unstable_markdownAsRichText.d.ts +0 -30
  28. package/dist/helpers/unstable_markdownAsRichText.js +0 -12
  29. package/dist/helpers/unstable_markdownAsRichText.js.map +0 -1
  30. package/dist/lib/RichTextFieldBuilder.cjs +0 -115
  31. package/dist/lib/RichTextFieldBuilder.cjs.map +0 -1
  32. package/dist/lib/RichTextFieldBuilder.d.ts +0 -35
  33. package/dist/lib/RichTextFieldBuilder.js +0 -115
  34. package/dist/lib/RichTextFieldBuilder.js.map +0 -1
  35. package/dist/lib/filterRichTextField.cjs +0 -88
  36. package/dist/lib/filterRichTextField.cjs.map +0 -1
  37. package/dist/lib/filterRichTextField.d.ts +0 -12
  38. package/dist/lib/filterRichTextField.js +0 -88
  39. package/dist/lib/filterRichTextField.js.map +0 -1
  40. package/dist/lib/hastSerializerHelpers.cjs +0 -96
  41. package/dist/lib/hastSerializerHelpers.cjs.map +0 -1
  42. package/dist/lib/hastSerializerHelpers.d.ts +0 -28
  43. package/dist/lib/hastSerializerHelpers.js +0 -96
  44. package/dist/lib/hastSerializerHelpers.js.map +0 -1
  45. package/dist/lib/hastToRichText.cjs +0 -164
  46. package/dist/lib/hastToRichText.cjs.map +0 -1
  47. package/dist/lib/hastToRichText.d.ts +0 -30
  48. package/dist/lib/hastToRichText.js +0 -164
  49. package/dist/lib/hastToRichText.js.map +0 -1
  50. package/dist/lib/rehypeRichText.cjs +0 -59
  51. package/dist/lib/rehypeRichText.cjs.map +0 -1
  52. package/dist/lib/rehypeRichText.d.ts +0 -66
  53. package/dist/lib/rehypeRichText.js +0 -59
  54. package/dist/lib/rehypeRichText.js.map +0 -1
  55. package/src/errors/PrismicRichTextError.ts +0 -1
  56. package/src/errors/PrismicRichTextSerializerError.ts +0 -3
  57. package/src/helpers/unstable_htmlAsRichText.ts +0 -122
  58. package/src/helpers/unstable_markdownAsRichText.ts +0 -53
  59. package/src/lib/RichTextFieldBuilder.ts +0 -164
  60. package/src/lib/filterRichTextField.ts +0 -159
  61. package/src/lib/hastSerializerHelpers.ts +0 -157
  62. package/src/lib/hastToRichText.ts +0 -295
  63. package/src/lib/rehypeRichText.ts +0 -184
@@ -1,66 +0,0 @@
1
- import type { Root } from "hast";
2
- import type { Plugin } from "unified";
3
- import type { CustomTypeModelRichTextField } from "../types/model/richText";
4
- import type { RichTextField } from "../types/value/richText";
5
- import type { HASTToRichTextConfig } from "./hastToRichText";
6
- /**
7
- * Configuration options for {@link rehypeRichText}.
8
- */
9
- export type RehypeRichTextConfig = {
10
- /**
11
- * A CSS selector that targets the section of the document to convert to rich
12
- * text.
13
- *
14
- * @example `div.post`
15
- *
16
- * @defaultValue `":root"` - The top-level element of the document.
17
- */
18
- container?: string;
19
- /**
20
- * A list of CSS selectors to exclude matching nodes from the document to
21
- * process.
22
- *
23
- * @example `[".hidden", "aside"]`
24
- *
25
- * @defaultValue `[]` - No nodes are excluded.
26
- */
27
- exclude?: string[];
28
- /**
29
- * A list of CSS selectors to include only matching nodes from the document to
30
- * process.
31
- *
32
- * @example `["p", "img"]`
33
- *
34
- * @defaultValue `[]` - All nodes are included.
35
- */
36
- include?: string[];
37
- /**
38
- * A rich text or title field model definition. When provided the serializer
39
- * will filter out any node types not allowed by the model.
40
- *
41
- * @defaultValue `undefined` - No filtering is applied.
42
- */
43
- model?: CustomTypeModelRichTextField;
44
- } & HASTToRichTextConfig;
45
- /**
46
- * A unified plugin that compiles a hast tree to a Prismic rich text field.
47
- *
48
- * @param config - Configuration options for the rehype rich text processor.
49
- */
50
- export declare const rehypeRichText: Plugin<[
51
- config?: RehypeRichTextConfig
52
- ], Root, RichTextField>;
53
- declare module "unified" {
54
- interface CompileResultMap {
55
- RichTextField: RichTextField;
56
- }
57
- }
58
- declare module "hast" {
59
- interface Element {
60
- /**
61
- * A serializer this node matches to. Nodes are marked with this property
62
- * when they match a CSS selector from the serializer map.
63
- */
64
- matchesSerializer?: string;
65
- }
66
- }
@@ -1,59 +0,0 @@
1
- import { select, selectAll } from "hast-util-select";
2
- import rehypeMinifyWhitespace from "rehype-minify-whitespace";
3
- import { remove } from "unist-util-remove";
4
- import { visit, SKIP } from "unist-util-visit";
5
- import { filterRichTextField } from "./filterRichTextField.js";
6
- import { hastToRichText } from "./hastToRichText.js";
7
- const rehypeRichText = function rehypeRichText2(config) {
8
- const self = this;
9
- self.use(() => {
10
- return (tree) => {
11
- if (config == null ? void 0 : config.container) {
12
- const element = select(config.container, tree);
13
- if (!element) {
14
- throw new Error(`No container matching \`${config == null ? void 0 : config.container}\` could be found in the input AST.`);
15
- }
16
- tree.children = [element];
17
- }
18
- if (config == null ? void 0 : config.exclude) {
19
- const nodesToExclude = selectAll(config.exclude.join(", "), tree);
20
- remove(tree, (node) => nodesToExclude.includes(node));
21
- }
22
- if (config == null ? void 0 : config.include) {
23
- const nodesToInclude = [];
24
- const selector = config.include.join(", ");
25
- const rawNodesToInclude = selectAll(selector, tree);
26
- visit(tree, (node) => {
27
- if (rawNodesToInclude.includes(node)) {
28
- nodesToInclude.push(node);
29
- return SKIP;
30
- }
31
- });
32
- tree.children = nodesToInclude;
33
- }
34
- if (config == null ? void 0 : config.serializer) {
35
- for (const key in config.serializer) {
36
- if (!/^[a-z]+[1-6]?$/.test(key)) {
37
- const matches = selectAll(key, tree);
38
- for (let i = 0; i < matches.length; i++) {
39
- matches[i].matchesSerializer = key;
40
- }
41
- }
42
- }
43
- }
44
- };
45
- });
46
- self.use(rehypeMinifyWhitespace);
47
- self.compiler = compiler;
48
- function compiler(tree, file) {
49
- const richTextField = hastToRichText(tree, file, config);
50
- if (config == null ? void 0 : config.model) {
51
- return filterRichTextField(richTextField, config.model);
52
- }
53
- return richTextField;
54
- }
55
- };
56
- export {
57
- rehypeRichText
58
- };
59
- //# sourceMappingURL=rehypeRichText.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rehypeRichText.js","sources":["../../../src/lib/rehypeRichText.ts"],"sourcesContent":["import type { Element, Root } from \"hast\"\nimport { select, selectAll } from \"hast-util-select\"\nimport rehypeMinifyWhitespace from \"rehype-minify-whitespace\"\nimport type { Plugin, Processor } from \"unified\"\nimport { remove } from \"unist-util-remove\"\nimport { SKIP, visit } from \"unist-util-visit\"\nimport type { VFile } from \"vfile\"\n\nimport type { CustomTypeModelRichTextField } from \"../types/model/richText\"\nimport type { RichTextField } from \"../types/value/richText\"\n\nimport { filterRichTextField } from \"./filterRichTextField\"\nimport type { HASTToRichTextConfig } from \"./hastToRichText\"\nimport { hastToRichText } from \"./hastToRichText\"\n\n/**\n * Configuration options for {@link rehypeRichText}.\n */\nexport type RehypeRichTextConfig = {\n\t/**\n\t * A CSS selector that targets the section of the document to convert to rich\n\t * text.\n\t *\n\t * @example `div.post`\n\t *\n\t * @defaultValue `\":root\"` - The top-level element of the document.\n\t */\n\tcontainer?: string\n\n\t/**\n\t * A list of CSS selectors to exclude matching nodes from the document to\n\t * process.\n\t *\n\t * @example `[\".hidden\", \"aside\"]`\n\t *\n\t * @defaultValue `[]` - No nodes are excluded.\n\t */\n\texclude?: string[]\n\n\t/**\n\t * A list of CSS selectors to include only matching nodes from the document to\n\t * process.\n\t *\n\t * @example `[\"p\", \"img\"]`\n\t *\n\t * @defaultValue `[]` - All nodes are included.\n\t */\n\tinclude?: string[]\n\n\t/**\n\t * A rich text or title field model definition. When provided the serializer\n\t * will filter out any node types not allowed by the model.\n\t *\n\t * @defaultValue `undefined` - No filtering is applied.\n\t */\n\tmodel?: CustomTypeModelRichTextField\n} & HASTToRichTextConfig\n\n/**\n * A unified plugin that compiles a hast tree to a Prismic rich text field.\n *\n * @param config - Configuration options for the rehype rich text processor.\n */\n// unified requires the function to be typed directly with the\n// `Plugin` type to properly infer return types on processors.\nexport const rehypeRichText: Plugin<\n\t[config?: RehypeRichTextConfig],\n\tRoot,\n\tRichTextField\n> = function rehypeRichText(config) {\n\t// This is a bit dirty, but it seems like that's how rehype intends\n\t// it to be due to JSDocs limitations(?), see:\n\t// https://github.com/rehypejs/rehype/blob/f6912ac680704f1ef4b558ac57cbf0dd62ed0892/packages/rehype-stringify/lib/index.js#L18-L20\n\t// eslint-disable-next-line @typescript-eslint/no-this-alias\n\tconst self = this as unknown as Processor<\n\t\tundefined,\n\t\tundefined,\n\t\tundefined,\n\t\tRoot,\n\t\tRichTextField\n\t>\n\n\t// We need to exclude nodes _before_ we minify the tree as excluding\n\t// nodes could end up in more whitespaces to trim.\n\tself.use(() => {\n\t\treturn (tree: Root) => {\n\t\t\t// Extract container node if any is specified.\n\t\t\tif (config?.container) {\n\t\t\t\tconst element = select(config.container, tree)\n\n\t\t\t\tif (!element) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`No container matching \\`${config?.container}\\` could be found in the input AST.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\t// We cannot reassign the tree itself, so we instead replace\n\t\t\t\t// its children with the found element.\n\t\t\t\ttree.children = [element]\n\t\t\t}\n\n\t\t\t// Remove excluded nodes if any are specified\n\t\t\tif (config?.exclude) {\n\t\t\t\t// We join selector to only run one query\n\t\t\t\tconst nodesToExclude = selectAll(config.exclude.join(\", \"), tree)\n\n\t\t\t\tremove(tree, (node) => nodesToExclude.includes(node as Element))\n\t\t\t}\n\n\t\t\t// Include only nodes to include\n\t\t\tif (config?.include) {\n\t\t\t\tconst nodesToInclude: Element[] = []\n\n\t\t\t\t// We join selector to only run one query\n\t\t\t\tconst selector = config.include.join(\", \")\n\t\t\t\tconst rawNodesToInclude = selectAll(selector, tree)\n\n\t\t\t\t// We walk the tree to exclude matching nodes that are children of other matching nodes.\n\t\t\t\tvisit(tree, (node) => {\n\t\t\t\t\tif (rawNodesToInclude.includes(node as Element)) {\n\t\t\t\t\t\tnodesToInclude.push(node as Element)\n\n\t\t\t\t\t\t// Stop traversing this part of the tree since we found its matching parent node.\n\t\t\t\t\t\treturn SKIP\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\t// We cannot reassign the tree itself, so we instead replace\n\t\t\t\t// its children with the found element.\n\t\t\t\ttree.children = nodesToInclude\n\t\t\t}\n\n\t\t\t// Mark nodes matching CSS selectors\n\t\t\tif (config?.serializer) {\n\t\t\t\tfor (const key in config.serializer) {\n\t\t\t\t\t// HTML tag names are single word, lowercase strings, a-z and 1-6 (headings).\n\t\t\t\t\t// Here we want to match anything that's not a valid HTML tag name and treat\n\t\t\t\t\t// it as a CSS selector. See: https://regex101.com/r/LILLWH/1\n\t\t\t\t\tif (!/^[a-z]+[1-6]?$/.test(key)) {\n\t\t\t\t\t\tconst matches = selectAll(key, tree)\n\n\t\t\t\t\t\tfor (let i = 0; i < matches.length; i++) {\n\t\t\t\t\t\t\tmatches[i].matchesSerializer = key\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\t// `rehypeRichText` _depends_ on `rehypeMinifyWhitespace`, that's why it's\n\t// registered within the plugin rather than on the processor directly.\n\tself.use(rehypeMinifyWhitespace)\n\n\tself.compiler = compiler\n\n\tfunction compiler(tree: Root, file: VFile): RichTextField {\n\t\tconst richTextField = hastToRichText(tree, file, config)\n\n\t\tif (config?.model) {\n\t\t\treturn filterRichTextField(richTextField, config.model)\n\t\t}\n\n\t\treturn richTextField\n\t}\n}\n\ndeclare module \"unified\" {\n\t// Register unified processor the result type.\n\tinterface CompileResultMap {\n\t\tRichTextField: RichTextField\n\t}\n}\n\ndeclare module \"hast\" {\n\t// Extend hast node with a rich text value.\n\tinterface Element {\n\t\t/**\n\t\t * A serializer this node matches to. Nodes are marked with this property\n\t\t * when they match a CSS selector from the serializer map.\n\t\t */\n\t\tmatchesSerializer?: string\n\t}\n}\n"],"names":["rehypeRichText"],"mappings":";;;;;;AAiEa,MAAA,iBAIT,SAASA,gBAAe,QAAM;AAKjC,QAAM,OAAO;AAUb,OAAK,IAAI,MAAK;AACb,WAAO,CAAC,SAAc;AAErB,UAAI,iCAAQ,WAAW;AACtB,cAAM,UAAU,OAAO,OAAO,WAAW,IAAI;AAE7C,YAAI,CAAC,SAAS;AACb,gBAAM,IAAI,MACT,2BAA2B,iCAAQ,SAAS,qCAAqC;AAAA,QAEnF;AAIK,aAAA,WAAW,CAAC,OAAO;AAAA,MACzB;AAGA,UAAI,iCAAQ,SAAS;AAEpB,cAAM,iBAAiB,UAAU,OAAO,QAAQ,KAAK,IAAI,GAAG,IAAI;AAEhE,eAAO,MAAM,CAAC,SAAS,eAAe,SAAS,IAAe,CAAC;AAAA,MAChE;AAGA,UAAI,iCAAQ,SAAS;AACpB,cAAM,iBAA4B,CAAA;AAGlC,cAAM,WAAW,OAAO,QAAQ,KAAK,IAAI;AACnC,cAAA,oBAAoB,UAAU,UAAU,IAAI;AAG5C,cAAA,MAAM,CAAC,SAAQ;AAChB,cAAA,kBAAkB,SAAS,IAAe,GAAG;AAChD,2BAAe,KAAK,IAAe;AAG5B,mBAAA;AAAA,UACR;AAAA,QAAA,CACA;AAID,aAAK,WAAW;AAAA,MACjB;AAGA,UAAI,iCAAQ,YAAY;AACZ,mBAAA,OAAO,OAAO,YAAY;AAIpC,cAAI,CAAC,iBAAiB,KAAK,GAAG,GAAG;AAC1B,kBAAA,UAAU,UAAU,KAAK,IAAI;AAEnC,qBAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AAChC,sBAAA,CAAC,EAAE,oBAAoB;AAAA,YAChC;AAAA,UACD;AAAA,QACD;AAAA,MACD;AAAA,IAAA;AAAA,EACD,CACA;AAID,OAAK,IAAI,sBAAsB;AAE/B,OAAK,WAAW;AAEP,WAAA,SAAS,MAAY,MAAW;AACxC,UAAM,gBAAgB,eAAe,MAAM,MAAM,MAAM;AAEvD,QAAI,iCAAQ,OAAO;AACX,aAAA,oBAAoB,eAAe,OAAO,KAAK;AAAA,IACvD;AAEO,WAAA;AAAA,EACR;AACD;"}
@@ -1 +0,0 @@
1
- export class PrismicRichTextError extends Error {}
@@ -1,3 +0,0 @@
1
- import { PrismicRichTextError } from "./PrismicRichTextError"
2
-
3
- export class PrismicRichTextSerializerError extends PrismicRichTextError {}
@@ -1,122 +0,0 @@
1
- import type { Element } from "hast"
2
- import rehypeParse from "rehype-parse"
3
- import { unified } from "unified"
4
-
5
- import type { RTPartialInlineNode } from "../lib/RichTextFieldBuilder"
6
- import type { RehypeRichTextConfig } from "../lib/rehypeRichText"
7
- import { rehypeRichText } from "../lib/rehypeRichText"
8
-
9
- import type {
10
- RTInlineNode,
11
- RTNode,
12
- RichTextField,
13
- RichTextNodeTypes,
14
- } from "../types/value/richText"
15
-
16
- // Used for TSDocs only.
17
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
18
- import type { HTMLRichTextMapSerializer, asHTML } from "./asHTML"
19
-
20
- /**
21
- * A shorthand definition for {@link RichTextHTMLMapSerializer} rich text node
22
- * types.
23
- *
24
- * @remarks
25
- * The `label` rich text node type is not available as is. Use an object
26
- * containing your label name to convert to label nodes instead. For example:
27
- * `u: { label: "underline" }`
28
- * @remarks
29
- * The `span` rich text node type is not available as it is not relevant in the
30
- * context of going from HTML to Prismic rich text.
31
- */
32
- export type RichTextHTMLMapSerializerShorthand =
33
- | Exclude<RichTextNodeTypes, "label" | "span">
34
- | { label: string }
35
-
36
- /**
37
- * The payload provided to a {@link RichTextHTMLMapSerializerFunction}.
38
- */
39
- type RichTextHTMLMapSerializerFunctionPayload = {
40
- /**
41
- * The hast {@link Element} node to serialize.
42
- */
43
- node: Element
44
-
45
- /**
46
- * Additional context information to help with the serialization.
47
- */
48
- context: {
49
- /**
50
- * The list type of the last list node encountered if any.
51
- */
52
- listType?: "group-list-item" | "group-o-list-item"
53
- }
54
- }
55
-
56
- /**
57
- * Serializes a hast {@link Element} node to a
58
- * {@link RichTextHTMLMapSerializerShorthand} or a rich text node.
59
- *
60
- * @remarks
61
- * Serializing to a rich text node directly is not recommended and is only
62
- * available as an escape hatch. Prefer returning a
63
- * {@link RichTextHTMLMapSerializerShorthand} instead.
64
- */
65
- export type RichTextHTMLMapSerializerFunction = (
66
- payload: RichTextHTMLMapSerializerFunctionPayload,
67
- ) =>
68
- | RichTextHTMLMapSerializerShorthand
69
- | RTNode
70
- | RTInlineNode
71
- | RTPartialInlineNode
72
- | undefined
73
-
74
- /**
75
- * Serializes a hast {@link Element} node matching the given HTML tag name or CSS
76
- * selector to a Prismic rich text node.
77
- *
78
- * @remarks
79
- * This serializer is used to serialize HTML to Prismic rich text. When
80
- * serializing Prismic rich text to HTML with {@link asHTML}, use the
81
- * {@link HTMLRichTextMapSerializer} type instead.
82
- */
83
- export type RichTextHTMLMapSerializer = Record<
84
- string,
85
- RichTextHTMLMapSerializerShorthand | RichTextHTMLMapSerializerFunction
86
- >
87
-
88
- /**
89
- * Configuration that determines the output of {@link htmlAsRichText}.
90
- */
91
- export type HTMLAsRichTextConfig = RehypeRichTextConfig
92
-
93
- /**
94
- * The return type of {@link htmlAsRichText}.
95
- */
96
- type HTMLAsRichTextReturnType = {
97
- result: RichTextField
98
- warnings: string[]
99
- }
100
-
101
- /**
102
- * Converts an HTML string to a rich text field.
103
- *
104
- * @param html - An HTML string.
105
- * @param config - Configuration that determines the output the function.
106
- *
107
- * @returns `html` as rich text.
108
- *
109
- * @experimental Names and implementations may change in the future.
110
- * `unstable_htmlAsRichText()` does not follow SemVer.
111
- */
112
- export const unstable_htmlAsRichText = (
113
- html: string,
114
- config?: HTMLAsRichTextConfig,
115
- ): HTMLAsRichTextReturnType => {
116
- const { result, messages } = unified()
117
- .use(rehypeParse, { emitParseErrors: true, missingDoctype: 0 })
118
- .use(rehypeRichText, config)
119
- .processSync(html)
120
-
121
- return { result, warnings: messages.map((message) => message.toString()) }
122
- }
@@ -1,53 +0,0 @@
1
- import remarkParse from "remark-parse"
2
- import remarkRehype from "remark-rehype"
3
- import { unified } from "unified"
4
-
5
- import type { RehypeRichTextConfig } from "../lib/rehypeRichText"
6
- import { rehypeRichText } from "../lib/rehypeRichText"
7
-
8
- import type { RichTextField } from "../types/value/richText"
9
-
10
- // Used for TSDocs only.
11
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
12
- import type { unstable_htmlAsRichText } from "./unstable_htmlAsRichText"
13
-
14
- /**
15
- * Configuration that determines the output of {@link markdownAsRichText}.
16
- */
17
- export type MarkdownAsRichTextConfig = RehypeRichTextConfig
18
-
19
- /**
20
- * The return type of {@link markdownAsRichText}.
21
- */
22
- type MarkdownAsRichTextReturnType = {
23
- result: RichTextField
24
- warnings: string[]
25
- }
26
-
27
- /**
28
- * Converts a markdown string to a rich text field.
29
- *
30
- * @remarks
31
- * To convert markdown to a rich text field, this function first converts it to
32
- * HTML. It's essentially a sugar above {@link unstable_htmlAsRichText}.
33
- *
34
- * @param markdown - A markdown string.
35
- * @param config - Configuration that determines the output of the function.
36
- *
37
- * @returns `markdown` as rich text.
38
- *
39
- * @experimental Names and implementations may change in the future.
40
- * `unstable_markdownAsRichText()` does not follow SemVer.
41
- */
42
- export const unstable_markdownAsRichText = (
43
- markdown: string,
44
- config?: MarkdownAsRichTextConfig,
45
- ): MarkdownAsRichTextReturnType => {
46
- const { result, messages } = unified()
47
- .use(remarkParse)
48
- .use(remarkRehype)
49
- .use(rehypeRichText, config)
50
- .processSync(markdown)
51
-
52
- return { result, warnings: messages.map((message) => message.toString()) }
53
- }
@@ -1,164 +0,0 @@
1
- import type {
2
- RTInlineNode,
3
- RTLinkNode,
4
- RTNode,
5
- RTTextNode,
6
- RichTextField,
7
- } from "../types/value/richText"
8
-
9
- import { PrismicRichTextError } from "../errors/PrismicRichTextError"
10
-
11
- /**
12
- * Omits keys from a type, distributing the operation over a union.
13
- *
14
- * Taken from the `type-fest` package.
15
- *
16
- * @see https://github.com/sindresorhus/type-fest/blob/8a45ba048767aaffcebc7d190172d814a739feb0/source/distributed-omit.d.ts
17
- */
18
- type DistributedOmit<
19
- ObjectType,
20
- KeyType extends keyof ObjectType,
21
- > = ObjectType extends unknown ? Omit<ObjectType, KeyType> : never
22
-
23
- /**
24
- * An inline node without its `start` and `end` properties.
25
- */
26
- export type RTPartialInlineNode = DistributedOmit<RTInlineNode, "start" | "end">
27
-
28
- export class RichTextFieldBuilder {
29
- #nodes: RTNode[] = []
30
-
31
- get #last(): RTNode | undefined {
32
- return this.#nodes[this.#nodes.length - 1]
33
- }
34
-
35
- appendNode(node: RTNode): void {
36
- this.cleanupLast()
37
-
38
- this.#nodes.push(node)
39
- }
40
-
41
- appendTextNode(
42
- type: RTTextNode["type"],
43
- direction: "ltr" | "rtl" = "ltr",
44
- ): void {
45
- this.appendNode({
46
- type,
47
- text: "",
48
- spans: [],
49
- direction,
50
- })
51
- }
52
-
53
- appendSpan(span: RTInlineNode): void
54
- appendSpan(partialSpan: RTPartialInlineNode, length: number): void
55
- appendSpan(
56
- spanOrPartialSpan: RTInlineNode | RTPartialInlineNode,
57
- length?: number,
58
- ): void {
59
- if (!this.isTextNode(this.#last)) {
60
- throw new PrismicRichTextError("Cannot add span to non-text last node")
61
- }
62
-
63
- let span: RTInlineNode
64
- if ("start" in spanOrPartialSpan && "end" in spanOrPartialSpan) {
65
- span = spanOrPartialSpan
66
- } else {
67
- const lastLength = this.#last.text.length
68
-
69
- span = {
70
- ...spanOrPartialSpan,
71
- start: lastLength,
72
- end: lastLength + length!,
73
- }
74
- }
75
-
76
- let lastIdenticalSpanIndex = -1
77
- for (let i = this.#last.spans.length - 1; i >= 0; i--) {
78
- const lastSpan = this.#last.spans[i]
79
-
80
- if (span.type === "strong" || span.type === "em") {
81
- if (lastSpan.type === span.type) {
82
- lastIdenticalSpanIndex = i
83
- break
84
- }
85
- } else if (span.type === "label") {
86
- if (
87
- lastSpan.type === "label" &&
88
- lastSpan.data.label === span.data.label
89
- ) {
90
- lastIdenticalSpanIndex = i
91
- break
92
- }
93
- } else if (span.type === "hyperlink") {
94
- if (lastSpan.type === "hyperlink") {
95
- // Check that all data fields are the same. Since it's not a
96
- // deep equal operation, this doesn't guarantee a perfect
97
- // match with content relationship.
98
- const isSameLink = (
99
- Object.entries(span.data) as [keyof RTLinkNode["data"], unknown][]
100
- ).every(([key, value]) => lastSpan.data[key] === value)
101
-
102
- if (isSameLink) {
103
- lastIdenticalSpanIndex = i
104
- break
105
- }
106
- }
107
- }
108
- }
109
-
110
- // Ignore empty spans.
111
- if (span.start === span.end) {
112
- return
113
- }
114
-
115
- // Prefer to extend the last span of the same type end
116
- // position if it ends at the start of the new span.
117
- if (this.#last.spans[lastIdenticalSpanIndex]?.end === span.start) {
118
- this.#last.spans[lastIdenticalSpanIndex].end = span.end
119
- } else {
120
- this.#last.spans.push(span)
121
- }
122
- }
123
-
124
- appendText(text: string): void {
125
- if (!this.isTextNode(this.#last)) {
126
- throw new PrismicRichTextError("Cannot append text to non-text last node")
127
- }
128
-
129
- if (this.#last.text) {
130
- this.#last.text += text
131
- } else {
132
- this.#last.text = text.trimStart()
133
- }
134
- }
135
-
136
- build(): RichTextField {
137
- // Ensure that the last text node is trimmed.
138
- this.cleanupLast()
139
-
140
- // Because `RichTextField` is defined as a non-empty
141
- // array, we have to cast `RTNode[]` to `RichTextField`.
142
- return this.#nodes as RichTextField
143
- }
144
-
145
- /**
146
- * Cleans up the current last node.
147
- */
148
- private cleanupLast(): void {
149
- if (this.isTextNode(this.#last)) {
150
- this.#last.text = this.#last.text.trimEnd()
151
- }
152
- }
153
-
154
- /**
155
- * Determines if a node is a text node.
156
- *
157
- * @param node - rich text node to check.
158
- *
159
- * @returns `true` if `node` is a text node, `false` otherwise.
160
- */
161
- private isTextNode(node?: RTNode): node is RTTextNode {
162
- return !!node && node.type !== "image" && node.type !== "embed"
163
- }
164
- }
@@ -1,159 +0,0 @@
1
- import type { CustomTypeModelRichTextField } from "../types/model/richText"
2
- import { LinkType } from "../types/value/link"
3
- import type {
4
- RTImageNode,
5
- RTNode,
6
- RTTextNode,
7
- RichTextField,
8
- RichTextNodeTypes,
9
- } from "../types/value/richText"
10
- import { RichTextNodeType } from "../types/value/richText"
11
- import type { TitleField } from "../types/value/title"
12
-
13
- /**
14
- * Get allowed nodes types from a rich text or title field custom type model.
15
- *
16
- * @param model - A rich text or title field custom type model.
17
- *
18
- * @returns An array of allowed nodes types.
19
- */
20
- const getAllowedNodeTypes = (
21
- model: CustomTypeModelRichTextField,
22
- ): RichTextNodeTypes[] => {
23
- const allowedNodeTypes: RichTextNodeTypes[] = [] // An empty array means no nodes are allowed by default.
24
-
25
- if (model.config) {
26
- if ("multi" in model.config && model.config.multi) {
27
- allowedNodeTypes.push(
28
- ...(model.config.multi.split(",") as RichTextNodeTypes[]),
29
- )
30
- } else if ("single" in model.config && model.config.single) {
31
- allowedNodeTypes.push(
32
- ...(model.config.single.split(",") as RichTextNodeTypes[]),
33
- )
34
- }
35
-
36
- if (model.config.labels?.length) {
37
- allowedNodeTypes.push("label")
38
- }
39
- }
40
-
41
- return allowedNodeTypes
42
- }
43
-
44
- /**
45
- * Filter an image node based on given model.
46
- *
47
- * @param node - An image node to filter.
48
- * @param model - A rich text or title field custom type model.
49
- *
50
- * @returns A filtered image node based on the given model.
51
- */
52
- const filterImageNode = (
53
- node: RTImageNode,
54
- model: CustomTypeModelRichTextField,
55
- ): RTImageNode => {
56
- if (
57
- !model.config?.allowTargetBlank &&
58
- node.linkTo?.link_type === LinkType.Web
59
- ) {
60
- return {
61
- ...node,
62
- linkTo: {
63
- ...node.linkTo,
64
- target: undefined,
65
- },
66
- }
67
- }
68
-
69
- return node
70
- }
71
-
72
- /**
73
- * Filter a text node based on given model.
74
- *
75
- * @param node - A text node to filter.
76
- * @param model - A rich text or title field custom type model.
77
- * @param allowedNodeTypes - An array of allowed nodes types.
78
- *
79
- * @returns A filtered text node based on the given model.
80
- */
81
- const filterTextNode = (
82
- node: RTTextNode,
83
- model: CustomTypeModelRichTextField,
84
- allowedNodeTypes: RichTextNodeTypes[],
85
- ): RTTextNode => {
86
- const filteredNode: RTTextNode = {
87
- ...node,
88
- spans: [],
89
- }
90
-
91
- for (let i = 0; i < node.spans.length; i++) {
92
- const span = node.spans[i]
93
-
94
- if (allowedNodeTypes.includes(span.type)) {
95
- if (span.type === RichTextNodeType.hyperlink) {
96
- if (
97
- !model.config?.allowTargetBlank &&
98
- span.data.link_type === LinkType.Web
99
- ) {
100
- filteredNode.spans.push({
101
- ...span,
102
- data: {
103
- ...span.data,
104
- target: undefined,
105
- },
106
- })
107
- } else {
108
- filteredNode.spans.push(span)
109
- }
110
- } else if (span.type === RichTextNodeType.label) {
111
- if (model.config?.labels?.includes(span.data.label)) {
112
- filteredNode.spans.push(span)
113
- }
114
- } else {
115
- filteredNode.spans.push(span)
116
- }
117
- }
118
- }
119
-
120
- return filteredNode
121
- }
122
-
123
- /**
124
- * Filter a rich text field based on given model.
125
- *
126
- * @param richTextField - A rich text or title field from Prismic.
127
- * @param model - A rich text or title field custom type model.
128
- *
129
- * @returns A rich text or title field filtered based on the given model.
130
- */
131
- export const filterRichTextField = <Field extends RichTextField | TitleField>(
132
- richTextField: Field,
133
- model: CustomTypeModelRichTextField,
134
- ): Field => {
135
- const nodes: RTNode[] = []
136
-
137
- const allowedNodeTypes = getAllowedNodeTypes(model)
138
-
139
- for (
140
- let i = 0;
141
- // Only process the first node if it's a "single" node rich text type
142
- i < (model.config && "multi" in model.config ? richTextField.length : 1);
143
- i++
144
- ) {
145
- const node = richTextField[i]
146
-
147
- if (allowedNodeTypes.includes(node.type)) {
148
- if (node.type === RichTextNodeType.image) {
149
- nodes.push(filterImageNode(node, model))
150
- } else if (node.type === RichTextNodeType.embed) {
151
- nodes.push(node)
152
- } else {
153
- nodes.push(filterTextNode(node, model, allowedNodeTypes))
154
- }
155
- }
156
- }
157
-
158
- return nodes as Field
159
- }