-
Notifications
You must be signed in to change notification settings - Fork 105
/
slatejs-to-contentful-adapter.ts
82 lines (75 loc) 路 2.27 KB
/
slatejs-to-contentful-adapter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import flatMap from 'lodash.flatmap';
import { getDataOrDefault } from './helpers';
import { SchemaJSON, Schema, fromJSON } from './schema';
import * as Contentful from '@contentful/rich-text-types';
import {
ContentfulNode,
ContentfulElementNode,
SlateNode,
SlateElement,
SlateText,
SlateMarks,
} from './types';
export interface ToContentfulDocumentProperties {
document: SlateNode[];
schema?: SchemaJSON;
}
export default function toContentfulDocument({
document,
schema,
}: ToContentfulDocumentProperties): Contentful.Document {
// TODO:
// We allow adding data to the root document node, but Slate >v0.5.0
// has no concept of a root document node. We should determine whether
// this will be a compatibility problem for existing users.
return {
nodeType: Contentful.BLOCKS.DOCUMENT,
data: {},
content: flatMap(
document,
node => convertNode(node, fromJSON(schema)) as Contentful.TopLevelBlock[],
),
};
}
function convertNode(node: SlateNode, schema: Schema): ContentfulNode[] {
const nodes: ContentfulNode[] = [];
if (isSlateElement(node)) {
const contentfulElement: ContentfulElementNode = {
nodeType: node.type as Contentful.BLOCKS,
data: getDataOrDefault(node.data),
content: [],
};
if (!schema.isVoid(contentfulElement)) {
contentfulElement.content = flatMap(node.children, childNode =>
convertNode(childNode, schema),
);
}
if (contentfulElement.content.length === 0 && schema.isTextContainer(node.type)) {
contentfulElement.content.push(convertText({ text: '', data: {} }));
}
nodes.push(contentfulElement);
} else {
const contentfulText = convertText(node);
nodes.push(contentfulText);
}
return nodes;
}
function convertText(node: SlateText): Contentful.Text {
const { text, data, ...marks } = node;
return {
nodeType: 'text',
value: node.text,
marks: getMarkList(marks),
data: getDataOrDefault(node.data),
};
}
function getMarkList(marks: SlateMarks): Contentful.Mark[] {
const contentfulMarks: Contentful.Mark[] = [];
for (const mark of Object.keys(marks)) {
contentfulMarks.push({ type: mark });
}
return contentfulMarks;
}
function isSlateElement(node: SlateNode): node is SlateElement {
return 'type' in node;
}