UNPKG

2.22 kBPlain TextView Raw
1import {camelCase} from 'lodash'
2import {EditorNode, SerializeOptions, Serializable} from './StructureNodes'
3import {SerializeError, HELP_URL} from './SerializeError'
4import {SchemaType} from './parts/Schema'
5
6export type PartialEditorNode = {
7 id?: string
8 title?: string
9 options?: {
10 id?: string
11 type?: string
12 }
13}
14
15export class EditorBuilder implements Serializable {
16 protected spec: PartialEditorNode
17
18 constructor(spec?: EditorNode) {
19 this.spec = spec ? spec : {}
20 }
21
22 id(id: string): EditorBuilder {
23 return this.clone({id})
24 }
25
26 getId() {
27 return this.spec.id
28 }
29
30 title(title: string) {
31 return this.clone({title, id: this.spec.id || camelCase(title)})
32 }
33
34 getTitle() {
35 return this.spec.title
36 }
37
38 documentId(documentId: string): EditorBuilder {
39 return this.clone({
40 options: {
41 ...(this.spec.options || {}),
42 id: documentId
43 }
44 })
45 }
46
47 getDocumentId() {
48 return this.spec.options && this.spec.options.id
49 }
50
51 schemaType(documentType: SchemaType | string): EditorBuilder {
52 return this.clone({
53 options: {
54 ...(this.spec.options || {}),
55 type: typeof documentType === 'string' ? documentType : documentType.name
56 }
57 })
58 }
59
60 getSchemaType() {
61 return this.spec.options && this.spec.options.type
62 }
63
64 serialize({path, index, hint}: SerializeOptions = {path: []}): EditorNode {
65 const {id, options} = this.spec
66 if (typeof id !== 'string' || !id) {
67 throw new SerializeError('`id` is required for editor nodes', path, index, hint).withHelpUrl(
68 HELP_URL.ID_REQUIRED
69 )
70 }
71
72 if (!options || !options.id) {
73 throw new SerializeError(
74 'document id (`id`) is required for editor nodes',
75 path,
76 id,
77 hint
78 ).withHelpUrl(HELP_URL.DOCUMENT_ID_REQUIRED)
79 }
80
81 return {
82 ...this.spec,
83 id,
84 type: 'document',
85 options: {id: options.id, type: options.type}
86 }
87 }
88
89 clone(withSpec: PartialEditorNode = {}) {
90 const builder = new EditorBuilder()
91 const options = {...(this.spec.options || {}), ...(withSpec.options || {})}
92 builder.spec = {...this.spec, ...withSpec, options}
93 return builder
94 }
95}