-
Notifications
You must be signed in to change notification settings - Fork 395
/
withInitialValue.js
142 lines (125 loc) · 5.47 KB
/
withInitialValue.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/* eslint-disable max-nested-callbacks */
import React from 'react'
import {streamingComponent} from 'react-props-stream'
import {merge, from, of} from 'rxjs'
import {map, switchMap, scan, filter, distinctUntilChanged, catchError} from 'rxjs/operators'
import schema from 'part:@sanity/base/schema'
import {observePaths} from 'part:@sanity/base/preview'
import {getDraftId, getPublishedId} from 'part:@sanity/base/util/draft-utils'
import ErrorPane from '../pane/ErrorPane'
import LoadingPane from '../pane/LoadingPane'
import BrokenReferences from '../components/BrokenReferences'
import {
templateExists,
getTemplateById,
getTemplatesBySchemaType,
resolveInitialValue
} from '@sanity/base/initial-value-templates'
const withInitialValue = Pane =>
streamingComponent(props$ =>
props$.pipe(
switchMap(props => {
const {options} = props
// See if the document ID has a draft or a published document
return merge(
observePaths(getDraftId(options.id), ['_type']).pipe(map(draft => ({draft}))),
observePaths(getPublishedId(options.id), ['_type']).pipe(map(published => ({published})))
).pipe(
scan((prev, res) => ({...prev, ...res}), {}),
// Wait until we know the state of both draft and published
filter(res => 'draft' in res && 'published' in res),
map(res => res.draft || res.published),
// Only update if we didn't previously have a document but we now do
distinctUntilChanged((prev, next) => Boolean(prev) !== Boolean(next)),
switchMap(document => {
const {templateName, parameters} = getInitialValueProps(document, props)
const shouldResolve = Boolean(templateName)
const documentType = options.type || (document && document._type)
// If we were not passed a schema type, use the resolved value if available
const paneOptions = options.type ? options : {...options, type: documentType}
if (!shouldResolve) {
// Wrap in broken references component to prevent "reload"
// when going from missing document to a document that exists
return of(
<BrokenReferences document={{}} type={documentType} schema={schema}>
<Pane {...props} options={paneOptions} />
</BrokenReferences>
)
}
return merge(
of({isResolving: true}),
resolveInitialValueWithParameters(templateName, parameters).pipe(
catchError(resolveError => {
/* eslint-disable no-console */
console.group('Failed to resolve initial value')
console.error(resolveError)
console.error('Template ID: %s', templateName)
console.error('Parameters: %o', parameters || {})
console.groupEnd()
/* eslint-enable no-console */
return of({resolveError})
})
)
).pipe(
switchMap(({isResolving, initialValue, resolveError}) => {
if (resolveError) {
return of(
<ErrorPane>
<h2>Failed to resolve initial value</h2>
<p>Check developer console for details</p>
</ErrorPane>
)
}
const title =
documentType && `New ${schema.get(documentType).title || documentType}`
return of(
isResolving ? (
<LoadingPane {...props} title={title} message="Resolving initial value…" />
) : (
<BrokenReferences document={initialValue} type={documentType} schema={schema}>
<Pane {...props} initialValue={initialValue} options={paneOptions} />
</BrokenReferences>
)
)
})
)
})
)
})
)
)
function getInitialValueProps(document, props) {
if (document) {
return {}
}
const {template: definedTemplate} = props.options
const {template: urlTemplate, ...urlParameters} = props.urlParameters || {}
if (urlTemplate && definedTemplate && definedTemplate !== urlTemplate) {
// eslint-disable-next-line no-console
console.warn(
`Conflicting templates: URL says "${urlParameters.template}", structure node says "${definedTemplate}". Using "${definedTemplate}".`
)
}
const {options = {}} = props
const template = options.template || urlTemplate
const typeTemplates = getTemplatesBySchemaType(options.type)
const parameters = {...options.templateParameters, ...urlParameters}
let templateName = template
// If we have not specified a specific template, and we only have a single
// template available for a schema type, use it
if (!template && typeTemplates.length === 1) {
templateName = typeTemplates[0].id
}
return {templateName, parameters}
}
function resolveInitialValueWithParameters(templateName, parameters) {
if (!templateExists(templateName)) {
// eslint-disable-next-line no-console
console.warn('Template "%s" not defined, using empty initial value', templateName)
return of({isResolving: false, initialValue: undefined})
}
return from(resolveInitialValue(getTemplateById(templateName), parameters)).pipe(
map(initialValue => ({isResolving: false, initialValue}))
)
}
export default withInitialValue