/
topbar.jsx
392 lines (331 loc) · 12.1 KB
/
topbar.jsx
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import React from "react"
import PropTypes from "prop-types"
import Swagger from "swagger-client"
import URL from "url"
import DropdownMenu from "./DropdownMenu"
import reactFileDownload from "react-file-download"
import YAML from "js-yaml"
import beautifyJson from "json-beautify"
import Logo from "./logo_small.svg"
export default class Topbar extends React.Component {
constructor(props, context) {
super(props, context)
this.state = {
swaggerClient: null,
clients: [],
servers: [],
definitionVersion: "Unknown"
}
}
getGeneratorUrl = () => {
const { isOAS3, isSwagger2 } = this.props.specSelectors
const { swagger2GeneratorUrl, oas3GeneratorUrl } = this.props.getConfigs()
return isOAS3() ? oas3GeneratorUrl : (
isSwagger2() ? swagger2GeneratorUrl : null
)
}
instantiateGeneratorClient = () => {
const generatorUrl = this.getGeneratorUrl()
const isOAS3 = this.props.specSelectors.isOAS3()
if(!generatorUrl) {
return this.setState({
clients: [],
servers: []
})
}
Swagger(generatorUrl, {
requestInterceptor: (req) => {
req.headers["Accept"] = "application/json"
req.headers["Content-Type"] = "application/json"
}
})
.then(client => {
this.setState({
swaggerClient: client
})
const clientGetter = isOAS3 ? client.apis.clients.clientLanguages : client.apis.clients.clientOptions
const serverGetter = isOAS3 ? client.apis.servers.serverLanguages : client.apis.servers.serverOptions
clientGetter({}, {
// contextUrl is needed because swagger-client is curently
// not building relative server URLs correctly
contextUrl: generatorUrl
})
.then(res => {
this.setState({ clients: res.body || [] })
})
serverGetter({}, {
// contextUrl is needed because swagger-client is curently
// not building relative server URLs correctly
contextUrl: generatorUrl
})
.then(res => {
this.setState({ servers: res.body || [] })
})
})
}
downloadFile = (content, fileName) => {
if(window.Cypress) {
// HACK: temporary workaround for https://github.com/cypress-io/cypress/issues/949
// allows e2e tests to proceed without choking on file download native event
return
}
return reactFileDownload(content, fileName)
}
// Menu actions
importFromURL = () => {
let url = prompt("Enter the URL to import from:")
if(url) {
fetch(url)
.then(res => res.text())
.then(text => {
this.props.specActions.updateSpec(
YAML.dump(YAML.load(text), {
lineWidth: -1
})
)
})
}
}
saveAsYaml = () => {
let editorContent = this.props.specSelectors.specStr()
let language = this.getDefinitionLanguage()
let fileName = this.getFileName()
if(this.hasParserErrors()) {
if(language === "yaml") {
const shouldContinue = confirm("Swagger-Editor isn't able to parse your API definition. Are you sure you want to save the editor content as YAML?")
if(!shouldContinue) return
} else {
return alert("Save as YAML is not currently possible because Swagger-Editor wasn't able to parse your API definiton.")
}
}
if(language === "yaml") {
//// the content is YAML,
//// so download as-is
return this.downloadFile(editorContent, `${fileName}.yaml`)
}
//// the content is JSON,
//// so convert and download
// JSON String -> JS object
let jsContent = YAML.load(editorContent)
// JS object -> YAML string
let yamlContent = YAML.dump(jsContent)
this.downloadFile(yamlContent, `${fileName}.yaml`)
}
saveAsJson = () => {
let editorContent = this.props.specSelectors.specStr()
let fileName = this.getFileName()
if(this.hasParserErrors()) {
// we can't recover from a parser error in save as JSON
// because we are always parsing so we can beautify
return alert("Save as JSON is not currently possible because Swagger-Editor wasn't able to parse your API definiton.")
}
// JSON or YAML String -> JS object
let jsContent = YAML.load(editorContent)
// JS Object -> pretty JSON string
let prettyJsonContent = beautifyJson(jsContent, null, 2)
this.downloadFile(prettyJsonContent, `${fileName}.json`)
}
saveAsText = () => {
// Download raw text content
console.warn("DEPRECATED: saveAsText will be removed in the next minor version.")
let editorContent = this.props.specSelectors.specStr()
let isOAS3 = this.props.specSelectors.isOAS3()
let fileName = isOAS3 ? "openapi.txt" : "swagger.txt"
this.downloadFile(editorContent, fileName)
}
convertToYaml = () => {
// Editor content -> JS object -> YAML string
let editorContent = this.props.specSelectors.specStr()
let jsContent = YAML.load(editorContent)
let yamlContent = YAML.dump(jsContent)
this.props.specActions.updateSpec(yamlContent)
}
downloadGeneratedFile = (type, name) => {
let { specSelectors } = this.props
let swaggerClient = this.state.swaggerClient
if(!swaggerClient) {
// Swagger client isn't ready yet.
return
}
if(specSelectors.isOAS3()) {
// Generator 3 only has one generate endpoint for all types of things...
// since we're using the tags interface we may as well use the client reference to it
swaggerClient.apis.clients.generate({}, {
requestBody: {
spec: specSelectors.specJson(),
type: type.toUpperCase(),
lang: name
},
contextUrl: this.getGeneratorUrl()
}).then(res => {
this.downloadFile(res.data, `${name}-${type}-generated.zip`)
})
} else if(type === "server") {
swaggerClient.apis.servers.generateServerForLanguage({
framework : name,
body: JSON.stringify({
spec: specSelectors.specJson()
}),
headers: JSON.stringify({
Accept: "application/json"
})
})
.then(res => this.handleResponse(res, { type, name }))
} else if(type === "client") {
swaggerClient.apis.clients.generateClient({
language : name,
body: JSON.stringify({
spec: specSelectors.specJson()
})
})
.then(res => this.handleResponse(res, { type, name }))
}
}
handleResponse = (res, { type, name }) => {
if(!res.ok) {
return console.error(res)
}
let downloadUrl = URL.parse(res.body.link)
// HACK: workaround for Swagger.io Generator 2.0's lack of HTTPS downloads
if(downloadUrl.hostname === "generator.swagger.io") {
downloadUrl.protocol = "https:"
delete downloadUrl.port
delete downloadUrl.host
}
fetch(URL.format(downloadUrl))
.then(res => res.blob())
.then(res => {
this.downloadFile(res, `${name}-${type}-generated.zip`)
})
}
clearEditor = () => {
if(window.localStorage) {
window.localStorage.removeItem("swagger-editor-content")
this.props.specActions.updateSpec("")
}
}
// Helpers
showModal = (name) => {
this.setState({
[name]: true
})
}
hideModal = (name) => {
this.setState({
[name]: false
})
}
// Logic helpers
hasParserErrors = () => {
return this.props.errSelectors.allErrors().filter(err => err.get("source") === "parser").size > 0
}
getFileName = () => {
// Use `isSwagger2` here, because we want to default to `openapi` if we don't know.
if(this.props.specSelectors.isSwagger2 && this.props.specSelectors.isSwagger2()) {
return "swagger"
}
return "openapi"
}
getDefinitionLanguage = () => {
let editorContent = this.props.specSelectors.specStr() || ""
if(editorContent.trim()[0] === "{") {
return "json"
}
return "yaml"
}
getDefinitionVersion = () => {
const { isOAS3, isSwagger2 } = this.props.specSelectors
return isOAS3() ? "OAS3" : (
isSwagger2() ? "Swagger2" : "Unknown"
)
}
///// Lifecycle
componentDidMount() {
this.instantiateGeneratorClient()
}
componentDidUpdate() {
const version = this.getDefinitionVersion()
if(this.state.definitionVersion !== version) {
// definition version has changed; need to reinstantiate
// our Generator client
// --
// TODO: fix this if there's A Better Way
// eslint-disable-next-line react/no-did-update-set-state
this.setState({
definitionVersion: version
}, () => this.instantiateGeneratorClient())
}
}
render() {
let { getComponent, specSelectors, topbarActions } = this.props
const Link = getComponent("Link")
const TopbarInsert = getComponent("TopbarInsert")
const ImportFileMenuItem = getComponent("ImportFileMenuItem")
const ConvertDefinitionMenuItem = getComponent("ConvertDefinitionMenuItem")
let showServersMenu = this.state.servers && this.state.servers.length
let showClientsMenu = this.state.clients && this.state.clients.length
let definitionLanguage = this.getDefinitionLanguage()
let isJson = definitionLanguage === "json"
let makeMenuOptions = (name) => {
let stateKey = `is${name}MenuOpen`
let toggleFn = () => this.setState({ [stateKey]: !this.state[stateKey] })
return {
isOpen: !!this.state[stateKey],
close: () => this.setState({ [stateKey]: false }),
align: "left",
toggle: <span className="menu-item" onClick={toggleFn}>{ name }</span>
}
}
const saveAsElements = []
if(isJson) {
saveAsElements.push(<li><button type="button" onClick={this.saveAsJson}>Save as JSON</button></li>)
saveAsElements.push(<li><button type="button" onClick={this.saveAsYaml}>Convert and save as YAML</button></li>)
} else {
saveAsElements.push(<li><button type="button" onClick={this.saveAsYaml}>Save as YAML</button></li>)
saveAsElements.push(<li><button type="button" onClick={this.saveAsJson}>Convert and save as JSON</button></li>)
}
return (
<div className="swagger-editor-standalone">
<div className="topbar">
<div className="topbar-wrapper">
<Link href="#">
<img height="35" className="topbar-logo__img" src={ Logo } alt=""/>
</Link>
<DropdownMenu {...makeMenuOptions("File")}>
<li><button type="button" onClick={this.importFromURL}>Import URL</button></li>
<ImportFileMenuItem onDocumentLoad={content => this.props.specActions.updateSpec(content)} />
<li role="separator"></li>
{saveAsElements}
<li role="separator"></li>
<li><button type="button" onClick={this.clearEditor}>Clear editor</button></li>
</DropdownMenu>
<DropdownMenu {...makeMenuOptions("Edit")}>
<li><button type="button" onClick={this.convertToYaml}>Convert to YAML</button></li>
<ConvertDefinitionMenuItem
isSwagger2={specSelectors.isSwagger2()}
onClick={() => topbarActions.showModal("convert")}
/>
</DropdownMenu>
<TopbarInsert {...this.props} />
{ showServersMenu ? <DropdownMenu className="long" {...makeMenuOptions("Generate Server")}>
{ this.state.servers
.map((serv, i) => <li key={i}><button type="button" onClick={this.downloadGeneratedFile.bind(null, "server", serv)}>{serv}</button></li>) }
</DropdownMenu> : null }
{ showClientsMenu ? <DropdownMenu className="long" {...makeMenuOptions("Generate Client")}>
{ this.state.clients
.map((cli, i) => <li key={i}><button type="button" onClick={this.downloadGeneratedFile.bind(null, "client", cli)}>{cli}</button></li>) }
</DropdownMenu> : null }
</div>
</div>
</div>
)
}
}
Topbar.propTypes = {
specSelectors: PropTypes.object.isRequired,
errSelectors: PropTypes.object.isRequired,
specActions: PropTypes.object.isRequired,
topbarActions: PropTypes.object.isRequired,
getComponent: PropTypes.func.isRequired,
getConfigs: PropTypes.func.isRequired
}