forked from sourcegraph/sourcegraph-public-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSettingsFile.tsx
276 lines (245 loc) · 9.7 KB
/
SettingsFile.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
import { LoadingSpinner } from '@sourcegraph/react-loading-spinner'
import * as H from 'history'
import * as _monaco from 'monaco-editor' // type only
import * as React from 'react'
import { Subject, Subscription } from 'rxjs'
import { distinctUntilChanged, filter, map, startWith } from 'rxjs/operators'
import * as GQL from '../../../shared/src/graphql/schema'
import { SaveToolbar } from '../components/SaveToolbar'
import { settingsActions } from '../site-admin/configHelpers'
import { ThemeProps } from '../../../shared/src/theme'
import { eventLogger } from '../tracking/eventLogger'
interface Props extends ThemeProps {
history: H.History
settings: GQL.ISettings | null
/**
* JSON Schema of the document.
*/
jsonSchema?: { $id: string }
/**
* Called when the user saves changes to the settings file's contents.
*/
onDidCommit: (lastID: number | null, contents: string) => void
/**
* Called when the user discards changes to the settings file's contents.
*/
onDidDiscard: () => void
/**
* The error that occurred on the last call to the onDidCommit callback,
* if any.
*/
commitError?: Error
}
interface State {
contents?: string
saving: boolean
/**
* The lastID that we started editing from. If null, then no
* previous versions of the settings exist, and we're creating them from
* scratch.
*/
editingLastID?: number | null
}
const emptySettings = '{\n // add settings here (Ctrl+Space to see hints)\n}'
const disposableToFn = (disposable: _monaco.IDisposable) => () => disposable.dispose()
const MonacoSettingsEditor = React.lazy(async () => ({
default: (await import('./MonacoSettingsEditor')).MonacoSettingsEditor,
}))
export class SettingsFile extends React.PureComponent<Props, State> {
private componentUpdates = new Subject<Props>()
private subscriptions = new Subscription()
private editor?: _monaco.editor.ICodeEditor
private monaco: typeof _monaco | null = null
constructor(props: Props) {
super(props)
this.state = { saving: false }
// Reset state upon navigation to a different subject.
this.subscriptions.add(
this.componentUpdates
.pipe(
startWith(props),
map(({ settings }) => settings),
distinctUntilChanged()
)
.subscribe(() => {
if (this.state.contents !== undefined) {
this.setState({ contents: undefined })
}
})
)
// Saving ended (in failure) if we get a commitError.
this.subscriptions.add(
this.componentUpdates
.pipe(
map(({ commitError }) => commitError),
distinctUntilChanged(),
filter(commitError => !!commitError)
)
.subscribe(() => this.setState({ saving: false }))
)
// We are finished saving when we receive the new settings ID and it's
// higher than the one we saved on top of.
const refreshedAfterSave = this.componentUpdates.pipe(
filter(({ settings }) => !!settings),
distinctUntilChanged(
(a, b) =>
(!a.settings && !!b.settings) ||
(!!a.settings && !b.settings) ||
(!!a.settings &&
!!b.settings &&
a.settings.contents === b.settings.contents &&
a.settings.id === b.settings.id)
),
filter(
({ settings, commitError }) =>
!!settings &&
!commitError &&
((typeof this.state.editingLastID === 'number' && settings.id > this.state.editingLastID) ||
(typeof settings.id === 'number' && this.state.editingLastID === null))
)
)
this.subscriptions.add(
refreshedAfterSave.subscribe(({ settings }) =>
this.setState({
saving: false,
editingLastID: undefined,
contents: settings ? settings.contents : undefined,
})
)
)
}
public componentDidMount(): void {
// Prevent navigation when dirty.
this.subscriptions.add(
this.props.history.block((location: H.Location, action: H.Action) => {
if (action === 'REPLACE') {
return undefined
}
if (this.state.saving || this.dirty) {
return 'Discard settings changes?'
}
return undefined // allow navigation
})
)
}
public componentDidUpdate(): void {
this.componentUpdates.next(this.props)
}
public componentWillUnmount(): void {
this.subscriptions.unsubscribe()
}
private get dirty(): boolean {
return this.state.contents !== undefined && this.state.contents !== this.getPropsSettingsContentsOrEmpty()
}
public render(): JSX.Element | null {
const dirty = this.dirty
const contents =
this.state.contents === undefined ? this.getPropsSettingsContentsOrEmpty() : this.state.contents
return (
<div className="settings-file e2e-settings-file d-flex flex-grow-1 flex-column">
<SaveToolbar
dirty={dirty}
error={this.props.commitError}
saving={this.state.saving}
onSave={this.save}
onDiscard={this.discard}
/>
<div className="site-admin-configuration-page__action-groups">
<div className="site-admin-configuration-page__actions">
{settingsActions.map(({ id, label }) => (
<button
type="button"
key={id}
className="btn btn-secondary btn-sm site-admin-configuration-page__action"
onClick={() => this.runAction(id)}
>
{label}
</button>
))}
</div>
</div>
<React.Suspense fallback={<LoadingSpinner className="icon-inline mt-2" />}>
<MonacoSettingsEditor
value={contents}
jsonSchema={this.props.jsonSchema}
onChange={this.onEditorChange}
readOnly={this.state.saving}
monacoRef={this.monacoRef}
isLightTheme={this.props.isLightTheme}
onDidSave={this.save}
/>
</React.Suspense>
</div>
)
}
private monacoRef = (monacoValue: typeof _monaco | null): void => {
this.monaco = monacoValue
if (this.monaco) {
this.subscriptions.add(
disposableToFn(
this.monaco.editor.onDidCreateEditor(editor => {
this.editor = editor
})
)
)
this.subscriptions.add(
disposableToFn(
this.monaco.editor.onDidCreateModel(async model => {
// This function can only be called if the lazy MonacoSettingsEditor component was loaded,
// so this import call will not incur another load.
const { MonacoSettingsEditor } = await import('./MonacoSettingsEditor')
if (this.editor && MonacoSettingsEditor.isStandaloneCodeEditor(this.editor)) {
for (const { id, label, run } of settingsActions) {
MonacoSettingsEditor.addEditorAction(this.editor, model, label, id, run)
}
}
})
)
)
}
}
private runAction(id: string): void {
if (this.editor) {
const action = this.editor.getAction(id)
action.run().then(
() => undefined,
err => console.error(err)
)
} else {
alert('Wait for editor to load before running action.')
}
}
private getPropsSettingsContentsOrEmpty(settings = this.props.settings): string {
return settings ? settings.contents : emptySettings
}
private getPropsSettingsID(): number | null {
return this.props.settings ? this.props.settings.id : null
}
private discard = (): void => {
if (
this.getPropsSettingsContentsOrEmpty() === this.state.contents ||
window.confirm('Discard settings edits?')
) {
eventLogger.log('SettingsFileDiscard')
this.setState({
contents: undefined,
editingLastID: undefined,
})
this.props.onDidDiscard()
} else {
eventLogger.log('SettingsFileDiscardCanceled')
}
}
private onEditorChange = (newValue: string): void => {
if (newValue !== this.getPropsSettingsContentsOrEmpty()) {
this.setState({ editingLastID: this.getPropsSettingsID() })
}
this.setState({ contents: newValue })
}
private save = (): void => {
eventLogger.log('SettingsFileSaved')
this.setState({ saving: true }, () => {
this.props.onDidCommit(this.getPropsSettingsID(), this.state.contents!)
})
}
}