-
Notifications
You must be signed in to change notification settings - Fork 392
/
DocumentPaneProvider.tsx
279 lines (254 loc) · 8.99 KB
/
DocumentPaneProvider.tsx
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// @todo: remove the following line when part imports has been removed from this file
///<reference types="@sanity/types/parts" />
import React, {memo, useCallback, useEffect, useMemo, useState} from 'react'
import {Path, SanityDocument} from '@sanity/types'
import {
useConnectionState,
useDocumentOperation,
useEditState,
useValidationStatus,
} from '@sanity/react-hooks'
import {omit} from 'lodash'
import {useToast} from '@sanity/ui'
import {fromString as pathFromString, pathFor} from '@sanity/util/paths'
import isHotkey from 'is-hotkey'
import {setLocation} from 'part:@sanity/base/datastore/presence'
import resolveDocumentActions from 'part:@sanity/base/document-actions/resolver'
import resolveDocumentBadges from 'part:@sanity/base/document-badges/resolver'
import {getPublishedId} from 'part:@sanity/base/util/draft-utils'
import schema from 'part:@sanity/base/schema'
import {useMemoObservable} from 'react-rx'
import {PaneMenuItem} from '../../types'
import {useDeskTool} from '../../contexts/deskTool'
import {usePaneRouter} from '../../contexts/paneRouter'
import {useUnique} from '../../utils/useUnique'
import {versionedClient} from '../../versionedClient'
import {useReferringDocuments} from '../../components/confirmDeleteDialog/useReferringDocuments'
import {createObservableController} from './documentHistory/history/Controller'
import {Timeline} from './documentHistory/history/Timeline'
import {DocumentPaneContext, DocumentPaneContextValue} from './DocumentPaneContext'
import {useInitialValue} from './initialValue'
import {getMenuItems} from './menuItems'
import {DocumentPaneProviderProps} from './types'
import {getPreviewUrl} from './usePreviewUrl'
declare const __DEV__: boolean
const emptyObject = {} as Record<string, string | undefined>
type Props = {children: React.ReactElement} & DocumentPaneProviderProps
/**
* @internal
*/
// eslint-disable-next-line complexity, max-statements
export const DocumentPaneProvider = memo(({children, index, pane, paneKey}: Props) => {
const paneRouter = usePaneRouter()
const {features} = useDeskTool()
const {push: pushToast} = useToast()
const {options, menuItemGroups, title = null, views: viewsProp = []} = pane
const initialValueRaw = useInitialValue(options.id, options)
const initialValue = useUnique(initialValueRaw)
const documentIdRaw = options.id
const documentId = getPublishedId(documentIdRaw)
const documentType = options.type
const {patch}: any = useDocumentOperation(documentId, documentType)
const editState = useEditState(documentId, documentType)
const {markers: markersRaw} = useValidationStatus(documentId, documentType)
const connectionState = useConnectionState(documentId, documentType)
const documentSchema = schema.get(documentType)
const {totalCount, isLoading: isReferencesLoading} = useReferringDocuments(options.id, {
externalPollInterval: 1000 * 60,
})
const totalReferenceCount = isReferencesLoading ? undefined : totalCount
const value: Partial<SanityDocument> =
editState?.draft || editState?.published || initialValue.value
const actions = useMemo(() => (editState ? resolveDocumentActions(editState) : null), [editState])
const badges = useMemo(() => (editState ? resolveDocumentBadges(editState) : null), [editState])
const markers = useUnique(markersRaw)
const views = useUnique(viewsProp)
const params = paneRouter.params || emptyObject
const [focusPath, setFocusPath] = useState<Path>(() =>
params.path ? pathFromString(params.path) : []
)
const activeViewId = params.view || (views[0] && views[0].id) || null
const timeline = useMemo(() => new Timeline({publishedId: documentId, enableTrace: __DEV__}), [
documentId,
])
const [timelineMode, setTimelineMode] = useState<'since' | 'rev' | 'closed'>('closed')
// NOTE: this emits sync so can never be null
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const {historyController} = useMemoObservable(
() =>
createObservableController({
timeline,
documentId,
documentType,
client: versionedClient,
}),
[timeline, documentId, documentType, timeline, versionedClient]
)!
/**
* @todo: this will now happen on each render, but should be refactored so it happens only when
* the `rev`, `since` or `historyController` values change.
*/
historyController.setRange(params.since || null, params.rev || null)
const changesOpen = historyController.changesPanelActive()
const previewUrl = useMemo(() => getPreviewUrl(historyController, value), [
historyController,
value,
])
const hasValue = Boolean(value)
const menuItems = useMemo(() => getMenuItems({features, hasValue, changesOpen, previewUrl}), [
features,
hasValue,
changesOpen,
previewUrl,
])
const inspectOpen = params.inspect === 'on'
const compareValue: Partial<SanityDocument> | null = changesOpen
? historyController.sinceAttributes()
: editState?.published || null
const ready = connectionState === 'connected' && editState.ready
const viewOlderVersion = historyController.onOlderRevision()
const displayed: Partial<SanityDocument> | null = useMemo(
() => (viewOlderVersion ? historyController.displayed() : value),
// eslint-disable-next-line react-hooks/exhaustive-deps
[historyController, params.rev, params.since, value, viewOlderVersion]
)
const setTimelineRange = useCallback(
(newSince: string, newRev: string | null) => {
paneRouter.setParams({
...paneRouter.params,
since: newSince,
rev: newRev || undefined,
})
},
[paneRouter]
)
const handleFocus = useCallback(
(nextFocusPath: Path) => {
setFocusPath(pathFor(nextFocusPath))
setLocation([
{
type: 'document',
documentId,
path: nextFocusPath,
lastActiveAt: new Date().toISOString(),
},
])
},
[documentId, setFocusPath]
)
const handleChange = useCallback((patches) => patch.execute(patches, initialValue.value), [
patch,
initialValue.value,
])
const handleHistoryClose = useCallback(() => {
paneRouter.setParams({...params, since: undefined})
}, [paneRouter, params])
const handleHistoryOpen = useCallback(() => {
paneRouter.setParams({...params, since: '@lastPublished'})
}, [paneRouter, params])
const handlePaneClose = useCallback(() => paneRouter.closeCurrent(), [paneRouter])
const handlePaneSplit = useCallback(() => paneRouter.duplicateCurrent(), [paneRouter])
const toggleInspect = useCallback(
(toggle = !inspectOpen) => {
if (toggle) {
paneRouter.setParams({...params, inspect: 'on'})
} else {
paneRouter.setParams(omit(params, 'inspect'))
}
},
[inspectOpen, paneRouter, params]
)
const handleMenuAction = useCallback(
(item: PaneMenuItem) => {
if (item.action === 'production-preview' && previewUrl) {
window.open(previewUrl)
return true
}
if (item.action === 'inspect') {
toggleInspect(true)
return true
}
if (item.action === 'reviewChanges') {
handleHistoryOpen()
return true
}
return false
},
[handleHistoryOpen, previewUrl, toggleInspect]
)
const handleKeyUp = useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
for (const item of menuItems) {
if (item.shortcut) {
if (isHotkey(item.shortcut, event)) {
event.preventDefault()
event.stopPropagation()
handleMenuAction(item)
return
}
}
}
},
[handleMenuAction, menuItems]
)
const handleInspectClose = useCallback(() => toggleInspect(false), [toggleInspect])
const documentPane: DocumentPaneContextValue = {
actions,
activeViewId,
badges,
changesOpen,
compareValue,
connectionState,
displayed,
documentId,
documentIdRaw,
documentSchema,
documentType,
editState,
focusPath,
handleChange,
handleFocus,
handleHistoryClose,
handleHistoryOpen,
handleInspectClose,
handleKeyUp,
handleMenuAction,
handlePaneClose,
handlePaneSplit,
historyController,
index,
inspectOpen,
markers,
menuItems,
menuItemGroups: menuItemGroups || [],
paneKey,
previewUrl,
ready,
setTimelineMode,
setTimelineRange,
timeline,
timelineMode,
title,
totalReferenceCount,
value,
views,
}
useEffect(() => {
if (connectionState === 'reconnecting') {
pushToast({
id: 'desk-tool/reconnecting',
status: 'warning',
title: <>Connection lost. Reconnecting…</>,
})
}
}, [connectionState, pushToast])
// Reset `focusPath` when `documentId` or `params.path` changes
useEffect(() => {
// Reset focus path
setFocusPath(params.path ? pathFromString(params.path) : [])
}, [documentId, params.path])
return (
<DocumentPaneContext.Provider value={documentPane}>{children}</DocumentPaneContext.Provider>
)
})
DocumentPaneProvider.displayName = 'DocumentPaneProvider'