Compare commits

..
145 Commits
Author SHA1 Message Date
kyle 7693dfe5bc Merge pull request #4036 from shockey/v/3.7.0
v3.7.0
2017-12-16 00:36:21 -08:00
Kyle Shockey 7faf79ae38 Fix deepLinking scroll behavior 2017-12-16 00:28:53 -08:00
Kyle Shockey 9b5accc17f v3.7.0 2017-12-16 00:10:01 -08:00
kyle d0ffb2bb9d Merge pull request #4010 from heldersepu/master
Add defaultModelsExpandDepth
2017-12-15 18:31:03 -08:00
Kyle Shockey 87572a856b Remove redundant changes to dist/index.html
This is not necessary, since all of these options are the same
as the defaults
2017-12-15 18:25:37 -08:00
Kyle Shockey 292639de57 Undo changes to dev-helpers/index.html 2017-12-15 18:24:43 -08:00
kyle 15dbc20efd Merge branch 'master' into master 2017-12-15 18:22:07 -08:00
kyle 5e72f68738 Merge pull request #4020 from heldersepu/patch-1
Update response-body.jsx to support SVG images
2017-12-15 17:29:44 -08:00
kyle 2b3a590e29 Merge branch 'master' into patch-1 2017-12-15 17:26:53 -08:00
kyle 0413410a1d Merge pull request #3244 from swagger-api/feature/small-tweaks
Some small tweaks
2017-12-15 17:26:31 -08:00
Kyle Shockey 49333dfadc Merge branch 'master' of github.com:swagger-api/swagger-ui into feature/small-tweaks 2017-12-15 17:22:03 -08:00
Kyle Shockey d65d7b3dd7 Revert /dist to contents of master 2017-12-15 17:21:49 -08:00
kyle e594392920 Merge pull request #3980 from thompsongl/ft/deeplinking-link-component
ft/deeplinking-link-component
2017-12-15 17:08:11 -08:00
kyle 48fd8f7689 Merge branch 'master' into ft/deeplinking-link-component 2017-12-15 17:05:22 -08:00
kyle bb54eaa127 Merge pull request #4019 from swagger-api/swagger-ui/master
Do not display undocumenetd when there is a default response
2017-12-14 15:43:25 -08:00
Greg Thompson a41cdfd650 Merge branch 'master' into ft/deeplinking-link-component 2017-12-13 08:32:57 -06:00
Gonen Dukas 4320118f17 Merge branch 'master' into master 2017-12-13 14:51:43 +02:00
kyle 7f19d791f8 Merge pull request #4026 from swagger-api/ft/docs
Clarify wrapComponent interface in Plugin API docs
2017-12-12 15:55:23 -08:00
kyle 9147d2eac2 Merge branch 'master' into ft/docs 2017-12-12 15:49:23 -08:00
kyle 1613455bc4 Merge pull request #4006 from MartinNowak/patch-1
fix example integration
2017-12-12 15:49:05 -08:00
Helder Sepulveda 6ba6039eb7 Merge branch 'master' into master 2017-12-12 17:48:40 -05:00
Helder Sepulveda f3cb0d7195 Merge branch 'master' into patch-1 2017-12-12 17:44:50 -05:00
kyle 9034e3fcdf Merge branch 'master' into patch-1 2017-12-12 14:35:06 -08:00
kyle a9ee23413d Merge branch 'master' into ft/docs 2017-12-12 14:34:27 -08:00
kyle 9a7ef85aa4 Clarify wrapComponent interface in Plugin API docs 2017-12-12 14:33:41 -08:00
kyle 1b5c060834 Merge pull request #4013 from heldersepu/bug/loading
Show loading message when we are loading
2017-12-12 13:38:32 -08:00
Kyle Shockey dfa96e66a4 Improve a handful of error surfacing messages
`Spec` => `API definition`, notably.
2017-12-12 13:34:25 -08:00
Kyle Shockey 00f4fb3326 Add margin to loading container 2017-12-12 13:25:36 -08:00
Kyle Shockey 3db4f6c93a Wrap BaseLayout loading messages in swagger-ui+loading-container 2017-12-12 13:24:42 -08:00
Kyle Shockey 0864ca849f Use throbber in Standalone layout; center loading messages and content 2017-12-12 13:07:18 -08:00
kyle faa9ada6b8 class => className 2017-12-12 12:31:55 -08:00
Greg Thompson 0e883d4a7a Merge remote-tracking branch 'upstream/master' into ft/deeplinking-link-component 2017-12-12 09:18:12 -06:00
Helder Sepulveda b2a435afdc Replace text with Loading throbber 2017-12-12 07:41:33 -05:00
kyle 5c17153df1 Merge branch 'master' into master 2017-12-11 20:29:02 -08:00
kyle a967be9438 Merge branch 'master' into patch-1 2017-12-11 19:21:26 -08:00
kyle aaf62a4e60 Merge branch 'master' into patch-1 2017-12-11 19:20:29 -08:00
kyle 91ed3baae7 Merge branch 'master' into bug/loading 2017-12-11 19:18:52 -08:00
kyle 2f32056fae Merge pull request #3812 from swagger-api/feature/deeplink-zenscroll
Add zenscroll instead of scroll-to
2017-12-11 19:18:20 -08:00
kyle af14cc9e78 Add missing comma 2017-12-11 19:09:00 -08:00
kyle a94c6c0e7f Merge branch 'master' into feature/deeplink-zenscroll 2017-12-11 19:05:16 -08:00
Greg Thompson f819612144 Merge branch 'master' into ft/deeplinking-link-component 2017-12-11 14:28:28 -06:00
Greg Thompson d2e931f3e1 DeepLink feedback 2017-12-11 14:27:28 -06:00
Helder Sepulveda 8becc9a9a7 Update response-body.jsx
Add support for svg images, with this change we will show an actual preview of the image
2017-12-11 15:14:58 -05:00
Gonen Dukas a5d1853557 Do not display undocumenetd when there is a default response 2017-12-11 17:49:16 +02:00
Helder Sepulveda fb8c3e46e7 Merge branch 'master' into master 2017-12-11 08:51:02 -05:00
Helder Sepulveda 58b64294c8 Merge branch 'master' into bug/loading 2017-12-11 08:50:34 -05:00
kyle 351dbf981b Merge pull request #4014 from shockey/master
v3.6.1
2017-12-09 11:04:12 -08:00
Kyle Shockey 9ada122a6b Fix issue with specPath in Callbacks 2017-12-09 11:00:24 -08:00
Kyle Shockey 1f2ea4a8a3 v3.6.1 2017-12-09 10:49:24 -08:00
Helder Sepulveda d7857052c7 Merge branch 'master' into master 2017-12-09 11:23:43 -05:00
Helder Sepulveda 040d648e64 Merge branch 'master' into bug/loading 2017-12-09 11:22:49 -05:00
HelderSepu 67b2b716e4 Show loading message when we are loading 2017-12-09 11:12:41 -05:00
kyle 19d0f32ad5 Merge pull request #4012 from shockey/master
Style resolver error line jumps
2017-12-08 22:35:43 -08:00
kyle 7c9ce8b963 Merge branch 'master' into master 2017-12-08 22:29:40 -08:00
Kyle Shockey e355561e26 Style resolver error line jumps 2017-12-08 22:28:51 -08:00
kyle 8b1c6d7b30 Merge pull request #4011 from shockey/master
Add max-width to servers select element
2017-12-08 20:28:36 -08:00
Kyle Shockey 7e9ae598fa Merge branch 'master' of github.com:swagger-api/swagger-ui 2017-12-08 20:18:34 -08:00
Kyle Shockey 99d35e06ca Add max-width to servers select element 2017-12-08 20:18:03 -08:00
HelderSepu 28c706c70a Add defaultModelsExpandDepth
This change separates:
the Model (the one on the model-example section)
from
the Models (the ones at the bottom)
2017-12-08 21:12:41 -05:00
Greg Thompson 05fd5b354d update test 2017-12-08 10:20:55 -06:00
Greg Thompson f21601b0e8 Merge branch 'master' into ft/deeplinking-link-component 2017-12-08 09:54:58 -06:00
Martin Nowak 08b8f9c35a fix example integration 2017-12-08 13:22:25 +01:00
kyle 943f71be5d Merge pull request #4005 from shockey/oas-301-support
Accept OpenAPI 3.*
2017-12-07 17:47:18 -08:00
kyle 059520e819 Merge branch 'master' into oas-301-support 2017-12-07 17:43:33 -08:00
Kyle Shockey 3b35b0767e Accept OpenAPI 3.* 2017-12-07 17:42:49 -08:00
kyle eac66355aa Merge pull request #3814 from swagger-api/feature/spec-path
Propagate the specPath prop through most model components
2017-12-07 17:16:32 -08:00
Kyle Shockey 60ee667688 Linter & test harness fixes 2017-12-07 17:07:30 -08:00
kyle bfb4c7a8d7 Merge branch 'master' into feature/spec-path 2017-12-07 16:49:34 -08:00
kyle 832f5e4d30 Merge pull request #4004 from shockey/bug/3982-oas3-trace-method
OAS3 `TRACE` method operation display
2017-12-07 14:05:36 -08:00
kyle 70ba6a93ef Merge branch 'master' into bug/3982-oas3-trace-method 2017-12-07 14:03:11 -08:00
Kyle Shockey a7e71d8117 Add FIXME 2017-12-07 14:00:49 -08:00
Kyle Shockey 328f02c463 Move method filtering logic to Operations component 2017-12-07 14:00:47 -08:00
Kyle Shockey eb97b91d7e Add failing tests 2017-12-07 14:00:26 -08:00
kyle 3d8f500c48 Merge pull request #4003 from houjunchen/doc
Fix link in configuration.md
2017-12-07 11:39:55 -08:00
Abner Chen 112bca9065 fix link 2017-12-08 00:00:04 +08:00
kyle 841b9acf55 Merge pull request #3991 from keik/fix-case-style
Fix case style
2017-12-06 20:58:51 -08:00
kyle 2de55991f4 Merge branch 'master' into fix-case-style 2017-12-06 20:53:27 -08:00
kyle 5ef042d12c Merge pull request #3990 from keik/invalid-source-map-option
Pass `false` webpack devtool option instead of `null`
2017-12-06 19:58:16 -08:00
kyle 6e2230b881 Merge branch 'master' into invalid-source-map-option 2017-12-06 19:52:52 -08:00
kyle d773b79c45 Merge pull request #3997 from swagger-api/feature/load-swagger-ui-in-node
Be more nodejs friendly
2017-12-06 19:51:08 -08:00
Josh Ponelat 733cddf146 Be more nodejs friendly, tweak some lines 2017-12-06 21:02:45 +02:00
keik 372b1c6a6a Fix case style 2017-12-06 15:29:34 +09:00
keik 765fb75356 Pass false webpack devtool option instead of null 2017-12-06 15:25:22 +09:00
kyle e0ac7c11db Merge pull request #3989 from swagger-api/ft/docs
Add script documentation to development docs
2017-12-05 20:38:14 -08:00
Kyle Shockey c23b884d9a Add script documentation to development docs 2017-12-05 20:33:28 -08:00
kyle fc3e0b224a Merge pull request #3988 from swagger-api/shockey-patch-1
Finish sentence fragment in Plugin API documentation
2017-12-05 19:23:19 -08:00
kyle 47c560227b Finish sentence fragment in Plugin API documentation 2017-12-05 19:18:47 -08:00
kyle 743eb8c9c7 Merge pull request #3754 from swagger-api/ft/docs
Expand documentation
2017-12-05 18:51:19 -08:00
Kyle Shockey c68d1589ff Prepare revised documentation for merge 2017-12-05 18:46:10 -08:00
Kyle Shockey 5503a349a7 Test and touch up Plugin API docs 2017-12-05 18:37:29 -08:00
Kyle Shockey dc9e5ad9cd Fix a core system issue blocking preset-plugin wrapComponents
cc: 3968
2017-12-05 18:30:39 -08:00
Kyle Shockey a1da9d39b6 Inject React as a system function 2017-12-05 17:00:07 -08:00
Kyle Shockey 55622b6105 Add required parameters 2017-12-05 15:24:19 -08:00
Kyle Shockey 1b926d834f Sort parameters alphabetically 2017-12-05 15:22:37 -08:00
Kyle Shockey 8a8ddd7c51 Touch up configuration docs 2017-12-05 15:17:01 -08:00
Kyle Shockey ba605eb2ed Fix filter markdown 2017-12-05 15:14:49 -08:00
Kyle Shockey 07dac1b582 Add parameter type information 2017-12-05 15:13:19 -08:00
Kyle Shockey 2eba306698 Add plugin system documentation 2017-12-05 14:49:08 -08:00
Kyle Shockey b7f4b23025 Segment configuration document 2017-12-05 14:44:37 -08:00
Kyle Shockey d3e8875de0 Touch up swagger-ui-dist section 2017-12-04 23:01:22 -08:00
Kyle Shockey 675b3ff2f7 SwaggerUIBundle -> SwaggerUI 2017-12-04 23:00:26 -08:00
Kyle Shockey 84f4ec805e Reshuffle more documentation locations 2017-12-04 22:58:58 -08:00
Kyle Shockey c6bc13c3f5 Add note about swagger-ui-dist 2017-12-04 21:46:47 -08:00
Kyle Shockey b19af62e20 Move Docker section out of README, into installation.md 2017-12-04 21:40:10 -08:00
Kyle Shockey 930659d1d7 Fix some formatting issues in new documentation 2017-12-04 21:38:37 -08:00
Kyle Shockey 759aaa13ed Merge branch 'ft/docs' of github.com:swagger-api/swagger-ui into ft/docs 2017-12-04 21:31:49 -08:00
Kyle Shockey dc0fbee68e Add documentation links to README 2017-12-04 21:31:01 -08:00
Kyle Shockey f546c0b342 Move OAuth2 docs 2017-12-04 21:25:48 -08:00
Kyle Shockey 4bf3b209be Move CORS documentation 2017-12-04 21:24:14 -08:00
Kyle Shockey e3666b9a97 Remove parameters from README 2017-12-04 21:23:06 -08:00
Kyle Shockey 0fe17539e1 Add limitations.md 2017-12-04 20:58:53 -08:00
Kyle Shockey 9400c91820 Merge branch 'master' of github.com:swagger-api/swagger-ui into ft/docs 2017-12-04 20:38:09 -08:00
Greg Thompson 5bc8ba3694 Merge branch 'master' into ft/deeplinking-link-component 2017-12-04 14:15:36 -06:00
Greg Thompson 661b60fade add isShown prop 2017-12-04 14:14:28 -06:00
Josh Ponelat 780c5f1b83 Add conditionals to ModelWrapper testing for layout props 2017-12-04 16:11:02 +02:00
Josh Ponelat 41ae8242b6 fix test 2017-12-04 16:10:43 +02:00
Josh Ponelat c260263e4e fix issues with deeplink conflicts 2017-12-04 16:10:43 +02:00
Liam Shaw 80ec610485 add zen scroll 2017-12-04 16:10:43 +02:00
Josh Ponelat 3893cb4396 deep linking for models, operations and tags 2017-12-04 16:10:42 +02:00
Josh Ponelat f6b86d2d33 Refactor layout .show/.isShown to handle branch nodes 2017-12-04 16:09:24 +02:00
Greg Thompson 0b8cd7e32f add presentational component to allow for wrapping deeplinking links 2017-12-01 14:30:37 -06:00
Josh Ponelat 49d15e2a6f add specPath to parameters/requstBody 2017-11-03 17:50:47 +02:00
Josh Ponelat 009ee1d9fb propagate specPath through parameter-row 2017-11-03 17:50:46 +02:00
Josh Ponelat e53bd3aef3 add stub to models test for specSelectors.isOAS3) 2017-11-03 17:50:46 +02:00
Josh Ponelat 6719a0af33 add condition for OAS 3.0 model jumps 2017-11-03 17:50:46 +02:00
Josh Ponelat 29247869d9 add specPath to arrays 2017-11-03 17:50:46 +02:00
Josh Ponelat 91d4ab96d7 partial specPath changes 2017-11-03 17:50:46 +02:00
Kyle Shockey 345c8dee57 WIP 2017-11-01 13:30:07 -07:00
kyle a3180dc2bc Merge branch 'master' into ft/docs 2017-10-31 17:21:25 -07:00
kyle e3943893f7 Update interceptor documentation
For #3830
2017-10-26 15:03:14 -07:00
Josh Ponelat 3681e86fad build 2017-10-25 09:49:07 +02:00
Josh Ponelat 5db6a1d0c9 add guards to specSelectors 2017-10-25 09:39:44 +02:00
Josh Ponelat 1c6f8e8327 refactor specSelectors.allowTryItOutFor 2017-10-25 09:39:44 +02:00
Josh Ponelat c6f354ae6c clean up spec actions a bit 2017-10-25 09:39:44 +02:00
Josh Ponelat e8772fbe2a fix typo in error message 2017-10-25 09:39:40 +02:00
Josh Ponelat 22732e8cc5 change : {} to fromJS({}) in param-body.jsx 2017-10-25 09:39:40 +02:00
Josh Ponelat a14b4c8039 Extend AST traversal to include string pointer 2017-10-25 09:39:40 +02:00
Josh Ponelat 84cc9489d4 fix typo with clear_validate_params 2017-10-25 09:39:31 +02:00
Josh Ponelat 2a4c8b9377 add .aignore 2017-10-25 09:39:31 +02:00
kyle 176cd86462 Merge branch 'master' into ft/docs 2017-10-12 13:07:39 -07:00
Kyle Shockey e4471830f4 Remove gitbook stuff 2017-10-06 17:14:14 -07:00
Kyle Shockey 0011b2a7e2 Development docs! 2017-10-06 17:13:30 -07:00
Kyle Shockey 24463652a5 Tremendous, beautiful plugin docs 2017-10-04 20:52:28 -07:00
Kyle Shockey d133f5c2df MOAR DOCS 2017-10-06 12:08:27 -07:00
Kyle Shockey f6206d35fd Docs WIP 2017-10-04 18:39:13 -07:00
70 changed files with 1509 additions and 416 deletions
+1
View File
@@ -0,0 +1 @@
dist/
+1
View File
@@ -9,3 +9,4 @@ package-lock.json
*.iml
selenium-debug.log
test/e2e/db.json
docs/_book
+19 -212
View File
@@ -22,7 +22,7 @@ The OpenAPI Specification has undergone 5 revisions since initial creation in 20
Swagger UI Version | Release Date | OpenAPI Spec compatibility | Notes
------------------ | ------------ | -------------------------- | -----
3.6.0 | 2017-12-01 | 2.0, 3.0 | [tag v3.5=6.0](https://github.com/swagger-api/swagger-ui/tree/v3.6.0)
3.7.0 | 2017-12-15 | 2.0, 3.0 | [tag v3.7.0](https://github.com/swagger-api/swagger-ui/tree/v3.7.0)
3.0.21 | 2017-07-26 | 2.0 | [tag v3.0.21](https://github.com/swagger-api/swagger-ui/tree/v3.0.21)
2.2.10 | 2017-01-04 | 1.1, 1.2, 2.0 | [tag v2.2.10](https://github.com/swagger-api/swagger-ui/tree/v2.2.10)
2.1.5 | 2016-07-20 | 1.1, 1.2, 2.0 | [tag v2.1.5](https://github.com/swagger-api/swagger-ui/tree/v2.1.5)
@@ -30,43 +30,25 @@ Swagger UI Version | Release Date | OpenAPI Spec compatibility | Notes
1.0.13 | 2013-03-08 | 1.1, 1.2 | [tag v1.0.13](https://github.com/swagger-api/swagger-ui/tree/v1.0.13)
1.0.1 | 2011-10-11 | 1.0, 1.1 | [tag v1.0.1](https://github.com/swagger-api/swagger-ui/tree/v1.0.1)
## Documentation
### How to run
#### Usage
- [Installation](docs/usage/installation.md)
- [Configuration](docs/usage/configuration.md)
- [CORS](docs/usage/cors.md)
- [OAuth2](docs/usage/oauth2.md)
- [Deep Linking](docs/usage/deep-linking.md)
- [Limitations](docs/usage/limitations.md)
- [Version detection](docs/usage/version-detection.md)
##### Easy start! Docker
You can pull a pre-built docker image of the swagger-ui directly from Dockerhub:
```
docker pull swaggerapi/swagger-ui
docker run -p 80:8080 swaggerapi/swagger-ui
```
Will start nginx with swagger-ui on port 80.
Or you can provide your own swagger.json on your host
```
docker run -p 80:8080 -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo swaggerapi/swagger-ui
```
The base URL of the web application can be changed by specifying the `BASE_URL` environment variable:
```
docker run -p 80:8080 -e BASE_URL=/swagger -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo swaggerapi/swagger-ui
```
This will serve Swagger UI at `/swagger` instead of `/`.
##### Prerequisites
- Node 6.x
- NPM 3.x
If you just want to see your specs, open `dist/index.html` in your browser directly from your filesystem.
If you'd like to make modifications to the codebase, run the dev server with: `npm run dev`. A development server will open on `3200`.
If you'd like to rebuild the `/dist` folder with your codebase changes, run `npm run build`.
#### Customization
- [Overview](docs/customization/overview.md)
- [Plugin API](docs/customization/plugin-api.md)
- [Custom layout](docs/customization/custom-layout.md)
#### Development
- [Setting up](docs/development/setting-up.md)
- [Scripts](docs/development/scripts.md)
##### Integration Tests
@@ -75,194 +57,19 @@ http://nightwatchjs.org/gettingstarted#selenium-server-setup
Integration tests can be run locally with `npm run e2e` - be sure you aren't running a dev server when testing!
##### Browser support
### Browser support
Swagger UI works in the latest versions of Chrome, Safari, Firefox, Edge and IE11.
### Known Issues
To help with the migration, here are the currently known issues with 3.X. This list will update regularly, and will not include features that were not implemented in previous versions.
- Only part of the [parameters](#parameters) previously supported are available.
- Only part of the parameters previously supported are available.
- The JSON Form Editor is not implemented.
- Support for `collectionFormat` is partial.
- l10n (translations) is not implemented.
- Relative path support for external files is not implemented.
### Direct use of JS and CSS assets
To include the JS, CSS and image assets directly into a webpage, use the [swagger-ui-dist](https://www.npmjs.com/package/swagger-ui-dist) package.
The root directory of this package contains the contents of the _dist/_ directory of this repo.
As a node module, `swagger-ui-dist` also exports the `swagger-ui-bundle` and `swagger-ui-standalone-preset` objects.
### SwaggerUIBundle
To use swagger-ui's bundles, you should take a look at the [source of swagger-ui html page](https://github.com/swagger-api/swagger-ui/blob/master/dist/index.html) and customize it. This basically requires you to instantiate a SwaggerUi object as below:
```javascript
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
```
#### OAuth2 configuration
You can configure OAuth2 authorization by calling `initOAuth` method with passed configs under the instance of `SwaggerUIBundle`
default `client_id` and `client_secret`, `realm`, an application name `appName`, `scopeSeparator`, `additionalQueryStringParams`,
`useBasicAuthenticationWithAccessCodeGrant`.
Config Name | Description
--- | ---
client_id | Default clientId. MUST be a string
client_secret | Default clientSecret. MUST be a string
realm | realm query parameter (for oauth1) added to `authorizationUrl` and `tokenUrl` . MUST be a string
appName | application name, displayed in authorization popup. MUST be a string
scopeSeparator | scope separator for passing scopes, encoded before calling, default value is a space (encoded value `%20`). MUST be a string
additionalQueryStringParams | Additional query parameters added to `authorizationUrl` and `tokenUrl`. MUST be an object
useBasicAuthenticationWithAccessCodeGrant | Only activated for the `accessCode` flow. During the `authorization_code` request to the `tokenUrl`, pass the [Client Password](https://tools.ietf.org/html/rfc6749#section-2.3.1) using the HTTP Basic Authentication scheme (`Authorization` header with `Basic base64encoded[client_id:client_secret]`). The default is `false`
```javascript
const ui = SwaggerUIBundle({...})
// Method can be called in any place after calling constructor SwaggerUIBundle
ui.initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: " ",
additionalQueryStringParams: {test: "hello"}
})
```
If you'd like to use the bundle files via npm, check out the [`swagger-ui-dist` package](https://www.npmjs.com/package/swagger-ui-dist).
#### Parameters
Parameters with dots in their names are single strings used to organize subordinate parameters, and are not indicative of a nested structure.
Parameter Name | Description
--- | ---
url | The url pointing to API definition (normally `swagger.json` or `swagger.yaml`). Will be ignored if `urls` or `spec` is used.
urls | An array of API definition objects (`{url: "<url>", name: "<name>"}`) used by Topbar plugin. When used and Topbar plugin is enabled, the `url` parameter will not be parsed. Names and URLs must be unique among all items in this array, since they're used as identifiers.
urls.primaryName | When using `urls`, you can use this subparameter. If the value matches the name of a spec provided in `urls`, that spec will be displayed when Swagger-UI loads, instead of defaulting to the first spec in `urls`.
spec | A JSON object describing the OpenAPI Specification. When used, the `url` parameter will not be parsed. This is useful for testing manually-generated specifications without hosting them.
validatorUrl | By default, Swagger-UI attempts to validate specs against swagger.io's online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators ([Validator Badge](https://github.com/swagger-api/validator-badge)). Setting it to `null` will disable validation.
dom_id | The id of a dom element inside which SwaggerUi will put the user interface for swagger.
domNode | The HTML DOM element inside which SwaggerUi will put the user interface for swagger. Overrides `dom_id`.
oauth2RedirectUrl | OAuth redirect URL
tagsSorter | Apply a sort to the tag list of each API. It can be 'alpha' (sort by paths alphanumerically) or a function (see [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to learn how to write a sort function). Two tag name strings are passed to the sorter for each pass. Default is the order determined by Swagger-UI.
operationsSorter | Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged.
defaultModelRendering | Controls how models are shown when the API is first rendered. (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.) It can be set to 'model' or 'example', and the default is 'example'.
defaultModelExpandDepth | The default expansion depth for models. The default value is 1.
configUrl | Configs URL
parameterMacro | MUST be a function. Function to set default value to parameters. Accepts two arguments parameterMacro(operation, parameter). Operation and parameter are objects passed for context, both remain immutable
modelPropertyMacro | MUST be a function. Function to set default values to each property in model. Accepts one argument modelPropertyMacro(property), property is immutable
docExpansion | Controls the default expansion setting for the operations and tags. It can be 'list' (expands only the tags), 'full' (expands the tags and operations) or 'none' (expands nothing). The default is 'list'.
displayOperationId | Controls the display of operationId in operations list. The default is `false`.
displayRequestDuration | Controls the display of the request duration (in milliseconds) for `Try it out` requests. The default is `false`.
maxDisplayedTags | If set, limits the number of tagged operations displayed to at most this many. The default is to show all operations.
filter | If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown. Can be true/false to enable or disable, or an explicit filter string in which case filtering will be enabled using that string as the filter expression. Filtering is case sensitive matching the filter expression anywhere inside the tag.
deepLinking | If set to `true`, enables dynamic deep linking for tags and operations. [Docs](https://github.com/swagger-api/swagger-ui/blob/master/docs/deep-linking.md)
requestInterceptor | MUST be a function. Function to intercept remote definition, Try-It-Out, and OAuth2 requests. Accepts one argument requestInterceptor(request) and must return the potentially modified request.
responseInterceptor | MUST be a function. Function to intercept remote definition, Try-It-Out, and OAuth2 responses. Accepts one argument responseInterceptor(response) and must return the potentially modified response.
showMutatedRequest | If set to `true` (the default), uses the mutated request returned from a rquestInterceptor to produce the curl command in the UI, otherwise the request before the requestInterceptor was applied is used.
showExtensions | Controls the display of vendor extension (`x-`) fields and values for Operations, Parameters, and Schema. The default is `false`.
### Plugins
#### Topbar plugin
Topbar plugin enables top bar with input for spec path and explore button or a dropdown if `urls` is used. By default the plugin is enabled, and to disable it you need to remove Topbar plugin from presets in `src/standalone/index.js`:
```javascript
let preset = [
// TopbarPlugin,
ConfigsPlugin,
() => {
return {
components: { StandaloneLayout }
}
}
]
```
#### Configs plugin
Configs plugin allows to fetch external configs instead of passing them to `SwaggerUIBundle`. Fetched configs support two formats: JSON or yaml. The plugin is enabled by default.
There are three options of passing config:
- add a query parameter `config` with URL to a server where the configs are hosted. For ex. http://petstore.swagger.io/?config=http://localhost:3001/config.yaml
- add a config `configUrl` with URL to SwaggerUIBundle
- change default configs in `swagger-config.yaml` *Note: after changing, the project must be re-built*
These options can be used altogether, the order of inheritance is following (from the lowest priority to the highest):
`swagger-config.yaml` -> config passed to `SwaggerUIBundle` -> config fetched from `configUrl` passed to `SwaggerUIBundle` -> config fetched from URL passed as a query parameter `config`
## CORS Support
CORS is a technique to prevent websites from doing bad things with your personal data. Most browsers + JavaScript toolkits not only support CORS but enforce it, which has implications for your API server which supports Swagger.
You can read about CORS here: http://www.w3.org/TR/cors.
There are two cases where no action is needed for CORS support:
1. swagger-ui is hosted on the same server as the application itself (same host *and* port).
2. The application is located behind a proxy that enables the required CORS headers. This may already be covered within your organization.
Otherwise, CORS support needs to be enabled for:
1. Your Swagger docs. For Swagger 2.0 it's the `swagger.json`/`swagger.yaml` and any externally `$ref`ed docs.
2. For the `Try it now` button to work, CORS needs to be enabled on your API endpoints as well.
### Testing CORS Support
You can verify CORS support with one of three techniques:
- Curl your API and inspect the headers. For instance:
```bash
$ curl -I "http://petstore.swagger.io/v2/swagger.json"
HTTP/1.1 200 OK
Date: Sat, 31 Jan 2015 23:05:44 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
Content-Type: application/json
Content-Length: 0
```
This tells us that the petstore resource listing supports OPTIONS, and the following headers: `Content-Type`, `api_key`, `Authorization`.
- Try swagger-ui from your file system and look at the debug console. If CORS is not enabled, you'll see something like this:
```
XMLHttpRequest cannot load http://sad.server.com/v2/api-docs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
```
Swagger-UI cannot easily show this error state.
- Using the http://www.test-cors.org website. Keep in mind this will show a successful result even if `Access-Control-Allow-Headers` is not available, which is still required for Swagger-UI to function properly.
### Enabling CORS
The method of enabling CORS depends on the server and/or framework you use to host your application. http://enable-cors.org provides information on how to enable CORS in some common web servers.
Other servers/frameworks may provide you information on how to enable it specifically in their use case.
### CORS and Header Parameters
Swagger lets you easily send headers as parameters to requests. The name of these headers *MUST* be supported in your CORS configuration as well. From our example above:
```
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
```
Only headers with these names will be allowed to be sent by Swagger-UI.
## Security contact
Please disclose any security-related issues or vulnerabilities by emailing [security@swagger.io](mailto:security@swagger.io), instead of using the public issue tracker.
+15 -15
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+2 -2
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
# Swagger-UI
Welcome to the Swagger-UI documentation!
A table of contents can be found at `SUMMARY.md`.
+17
View File
@@ -0,0 +1,17 @@
#### Usage
- [Installation](docs/usage/installation.md)
- [Configuration](docs/usage/configuration.md)
- [CORS](docs/usage/cors.md)
- [OAuth2](docs/usage/oauth2.md)
- [Deep Linking](docs/usage/deep-linking.md)
- [Limitations](docs/usage/limitations.md)
- [Version detection](docs/usage/version-detection.md)
#### Customization
- [Overview](docs/customization/overview.md)
- [Plugin API](docs/customization/plugin-api.md)
- [Custom layout](docs/customization/custom-layout.md)
#### Development
- [Setting up](docs/development/setting-up.md)
- [Scripts](docs/development/scripts.md)
+3
View File
@@ -0,0 +1,3 @@
{
"title": "Swagger-UI"
}
+92
View File
@@ -0,0 +1,92 @@
# Creating a custom layout
**Layouts** are a special type of component that Swagger-UI uses as the root component for the entire application. You can define custom layouts in order to have high-level control over what ends up on the page.
By default, Swagger-UI uses `BaseLayout`, which is built into the application. You can specify a different layout to be used by passing the layout's name as the `layout` parameter to Swagger-UI. Be sure to provide your custom layout as a component to Swagger-UI.
<br>
For example, if you wanted to create a custom layout that only displayed operations, you could define an `OperationsLayout`:
```js
import React from "react"
// Create the layout component
class OperationsLayout extends React.Component {
render() {
const {
getComponent
} = this.props
const Operations = getComponent("Operations", true)
return {
<div>
<Operations />
</div>
}
}
}
// Create the plugin that provides our layout component
const OperationsLayoutPlugin = function() {
return {
components: {
OperationsLayout: OperationsLayout
}
}
}
// Provide the plugin to Swagger-UI, and select OperationsLayout
// as the layout for Swagger-UI
SwaggerUI({
url: "http://petstore.swagger.io/v2/swagger.json",
plugins: [ OperationsLayoutPlugin ],
layout: "OperationsLayout"
})
```
### Augmenting the default layout
If you'd like to build around the `BaseLayout` instead of replacing it, you can pull the `BaseLayout` into your custom layout and use it:
```js
import React from "react"
// Create the layout component
class AugmentingLayout extends React.Component {
render() {
const {
getComponent
} = this.props
const BaseLayout = getComponent("BaseLayout", true)
return {
<div>
<div className="myCustomHeader">
<h1>I have a custom header above Swagger-UI!</h1>
</div>
<BaseLayout />
</div>
}
}
}
// Create the plugin that provides our layout component
const AugmentingLayoutPlugin = function() {
return {
components: {
AugmentingLayout: AugmentingLayout
}
}
}
// Provide the plugin to Swagger-UI, and select AugmentingLayout
// as the layout for Swagger-UI
SwaggerUI({
url: "http://petstore.swagger.io/v2/swagger.json",
plugins: [ AugmentingLayoutPlugin ],
layout: "AugmentingLayout"
})
```
+71
View File
@@ -0,0 +1,71 @@
# Plugin system overview
### Prior art
Swagger-UI leans heavily on concepts and patterns found in React and Redux.
If you aren't already familiar, here's some suggested reading:
- [React: Quick Start (reactjs.org)](https://reactjs.org/docs/hello-world.html)
- [Redux README (redux.js.org)](http://redux.js.org/)
In the following documentation, we won't take the time to define the fundamentals covered in the resources above.
> **Note**: Some of the examples in this section contain JSX, which is a syntax extension to JavaScript that is useful for writing React components.
>
> If you don't want to set up a build pipeline capable of translating JSX to JavaScript, take a look at [React without JSX (reactjs.org)](https://reactjs.org/docs/react-without-jsx.html). You can use our `system.React` reference to leverage React without needing to pull a copy into your project.
### The System
The _system_ is the heart of the Swagger-UI application. At runtime, it's a JavaScript object that holds many things:
- React components
- Bound Redux actions and reducers
- Bound Reselect state selectors
- System-wide collection of available components
- Built-in helpers like `getComponent`, `makeMappedContainer`, and `getStore`
- References to the React and Immutable.js libraries (`system.React`, `system.Im`)
- User-defined helper functions
The system is built up when Swagger-UI is called by iterating through ("compiling") each plugin that Swagger-UI has been given, through the `presets` and `plugins` configuration options.
### Presets
Presets are arrays of plugins, which are provided to Swagger-UI through the `presets` configuration option. All plugins within presets are compiled before any plugins provided via the `plugins` configuration option. Consider the following example:
```javascript
const MyPreset = [FirstPlugin, SecondPlugin, ThirdPlugin]
SwaggerUI({
presets: [
MyPreset
]
})
```
By default, Swagger-UI includes the internal `ApisPreset`, which contains a set of plugins that provide baseline functionality for Swagger-UI. If you specify your own `presets` option, you need to add the ApisPreset manually, like so:
```javascript
SwaggerUI({
presets: [
SwaggerUI.presets.apis,
MyAmazingCustomPreset
]
})
```
The need to provide the `apis` preset when adding other presets is an artifact of Swagger-UI's original design, and will likely be removed in the next major version.
### getComponent
`getComponent` is a helper function injected into every container component, which is used to get references to components provided by the plugin system.
All components should be loaded through `getComponent`, since it allows other plugins to modify the component. It is preferred over a conventional `import` statement.
Container components in Swagger-UI can be loaded by passing `true` as the second argument to `getComponent`, like so:
```javascript
getComponent("ContainerComponentName", true)
```
This will map the current system as props to the component.
+382
View File
@@ -0,0 +1,382 @@
# Plugins
A plugin is a function that returns an object - more specifically, the object may contain functions and components that augment and modify Swagger-UI's functionality.
### Format
A plugin return value may contain any of these keys, where `myStateKey` is a name for a piece of state:
```javascript
{
statePlugins: {
myStateKey: {
actions,
reducers,
selectors,
wrapActions,
wrapSelectors
}
},
components: {},
wrapComponents: {},
fn: {}
}
```
### System is provided to plugins
Let's assume we have a plugin, `NormalPlugin`, that exposes a `doStuff` action under the `normal` state namespace.
```javascript
const ExtendingPlugin = function(system) {
return {
statePlugins: {
extending: {
actions: {
doExtendedThings: function(...args) {
// you can do other things in here if you want
return system.normalActions.doStuff(...args)
}
}
}
}
}
}
```
As you can see, each plugin is passed a reference to the `system` being built up. As long as `NormalPlugin` is compiled before `ExtendingPlugin`, this will work without any issues.
There is no dependency management built into the plugin system, so if you create a plugin that relies on another, it is your responsibility to make sure that the dependent plugin is loaded _after_ the plugin being depended on.
### Interfaces
##### Actions
```javascript
const MyActionPlugin = () => {
return {
statePlugins: {
example: {
actions: {
updateFavoriteColor: (str) => {
return {
type: "EXAMPLE_SET_FAV_COLOR",
payload: str
}
}
}
}
}
}
}
```
Once an action has been defined, you can use it anywhere that you can get a system reference:
```javascript
// elsewhere
system.exampleActions.updateFavoriteColor("blue")
```
The Action interface enables the creation of new Redux action creators within a piece of state in the Swagger-UI system.
This action creator function will be exposed to container components as `exampleActions.updateFavoriteColor`. When this action creator is called, the return value (which should be a [Flux Standard Action](https://github.com/acdlite/flux-standard-action)) will be passed to the `example` reducer, which we'll define in the next section.
For more information about the concept of actions in Redux, see the [Redux Actions documentation](http://redux.js.org/docs/basics/Actions.html).
##### Reducers
Reducers take a state (which is an [Immutable.js map](https://facebook.github.io/immutable-js/docs/#/Map)) and an action, and return a new state.
Reducers must be provided to the system under the name of the action type that they handle, in this case, `EXAMPLE_SET_FAV_COLOR`.
```javascript
const MyReducerPlugin = function(system) {
return {
statePlugins: {
example: {
reducers: {
"EXAMPLE_SET_FAV_COLOR": (state, action) => {
// you're only working with the state under the namespace, in this case "example".
// So you can do what you want, without worrying about /other/ namespaces
return state.set("favColor", action.payload)
}
}
}
}
}
}
```
##### Selectors
Selectors reach into their namespace's state to retrieve or derive data from the state.
They're an easy way to keep logic in one place, and is preferred over passing state data directly into components.
```javascript
const MySelectorPlugin = function(system) {
return {
statePlugins: {
example: {
selectors: {
myFavoriteColor: (state) => state.get("favColor")
}
}
}
}
}
```
You can also use the Reselect library to memoize your selectors, which is recommended for any selectors that will see heavy use, since Reselect automatically memoizes selector calls for you:
```javascript
import { createSelector } from "reselect"
const MySelectorPlugin = function(system) {
return {
statePlugins: {
example: {
selectors: {
// this selector will be memoized after it is run once for a
// value of `state`
myFavoriteColor: createSelector((state) => state.get("favColor"))
}
}
}
}
}
```
Once a selector has been defined, you can use it anywhere that you can get a system reference:
```javascript
system.exampleSelectors.myFavoriteColor() // gets `favColor` in state for you
```
##### Components
You can provide a map of components to be integrated into the system.
Be mindful of the key names for the components you provide, as you'll need to use those names to refer to the components elsewhere.
```javascript
class HelloWorldClass extends React.Component {
render() {
return <h1>Hello World!</h1>
}
}
const MyComponentPlugin = function(system) {
return {
components: {
HelloWorldClass: HelloWorldClass
// components can just be functions, these are called "stateless components"
HelloWorldStateless: () => <h1>Hello World!</h1>,
}
}
}
```
```javascript
// elsewhere
const HelloWorldStateless = system.getComponent("HelloWorldStateless")
const HelloWorldClass = system.getComponent("HelloWorldClass")
```
You can also "cancel out" any components that you don't want by creating a stateless component that always returns `null`:
```javascript
const NeverShowInfoPlugin = function(system) {
return {
components: {
info: () => null
}
}
}
```
##### Wrap-Actions
Wrap Actions allow you to override the behavior of an action in the system.
They are function factories with the signature `(oriAction, system) => (...args) => result`.
A Wrap Action's first argument is `oriAction`, which is the action being wrapped. It is your responsibility to call the `oriAction` - if you don't, the original action will not fire!
This mechanism is useful for conditionally overriding built-in behaviors, or listening to actions.
```javascript
// FYI: in an actual Swagger-UI, `updateSpec` is already defined in the core code
// it's just here for clarity on what's behind the scenes
const MySpecPlugin = function(system) {
return {
statePlugins: {
spec: {
actions: {
updateSpec: (str) => {
return {
type: "SPEC_UPDATE_SPEC",
payload: str
}
}
}
}
}
}
}
// this plugin allows you to watch changes to the spec that is in memory
const MyWrapActionPlugin = function(system) {
return {
statePlugins: {
spec: {
wrapActions: {
updateSpec: (oriAction, system) => (str) => {
// here, you can hand the value to some function that exists outside of Swagger-UI
console.log("Here is my API definition", str)
return oriAction(str) // don't forget! otherwise, Swagger-UI won't update
}
}
}
}
}
}
```
##### Wrap-Selectors
Wrap Selectors allow you to override the behavior of a selector in the system.
They are function factories with the signature `(oriSelector, system) => (state, ...args) => result`.
This interface is useful for controlling what data flows into components. We use this in the core code to disable selectors based on the API definition's version.
```javascript
import { createSelector } from 'reselect'
// FYI: in an actual Swagger-UI, the `url` spec selector is already defined
// it's just here for clarity on what's behind the scenes
const MySpecPlugin = function(system) {
return {
statePlugins: {
spec: {
selectors: {
url: createSelector(
state => state.get("url")
)
}
}
}
}
}
const MyWrapSelectorsPlugin = function(system) {
return {
statePlugins: {
spec: {
wrapSelectors: {
url: (oriSelector, system) => (state, ...args) => {
console.log('someone asked for the spec url!!! it is', state.get('url'))
// you can return other values here...
// but let's just enable the default behavior
return oriSelector(state, ...args)
}
}
}
}
}
}
```
##### Wrap-Components
Wrap Components allow you to override a component registered within the system.
Wrap Components are function factories with the signature `(OriginalComponent, system) => props => ReactElement`. If you'd prefer to provide a React component class, `(OriginalComponent, system) => ReactClass` works as well.
```javascript
const MyWrapBuiltinComponentPlugin = function(system) {
return {
wrapComponents: {
info: (Original, system) => (props) => {
return <div>
<h3>Hello world! I am above the Info component.</h3>
<Original {...props} />
</div>
}
}
}
}
```
Here's another example that includes a code sample of a component that will be wrapped:
```javascript
///// Overriding a component from a plugin
// Here's our normal, unmodified component.
const MyNumberDisplayPlugin = function(system) {
return {
components: {
NumberDisplay: ({ number }) => <span>{number}</span>
}
}
}
// Here's a component wrapper defined as a function.
const MyWrapComponentPlugin = function(system) {
return {
wrapComponents: {
NumberDisplay: (Original, system) => (props) => {
if(props.number > 10) {
return <div>
<h3>Warning! Big number ahead.</h3>
<OriginalComponent {...props} />
</div>
} else {
return <Original {...props} />
}
}
}
}
}
// Alternatively, here's the same component wrapper defined as a class.
const MyWrapComponentPlugin = function(system) {
return {
wrapComponents: {
NumberDisplay: (Original, system) => class WrappedNumberDisplay extends React.component {
render() {
if(props.number > 10) {
return <div>
<h3>Warning! Big number ahead.</h3>
<OriginalComponent {...props} />
</div>
} else {
return <Original {...props} />
}
}
}
}
}
}
```
##### fn
The fn interface allows you to add helper functions to the system for use elsewhere.
```javascript
import leftPad from "left-pad"
const MyFnPlugin = function(system) {
return {
fn: {
leftPad: leftPad
}
}
}
```
+30
View File
@@ -0,0 +1,30 @@
# Helpful scripts
Any of the scripts below can be run by typing `npm run <script name>` in the project's root directory.
### Developing
Script name | Description
--- | ---
`dev` | Spawn a hot-reloading dev server on port 3200.
`deps-check` | Generate a size and licensing report on Swagger-UI's dependencies.
`lint` | Report ESLint style errors and warnings.
`lint-errors` | Report ESLint style errors, without warnings.
`lint-fix` | Attempt to fix style errors automatically.
`watch` | Rebuild the core files in `/dist` when the source code changes. Useful for `npm link` with Swagger-Editor.
### Building
Script name | Description
--- | ---
`build` | Build a new set of JS and CSS assets, and output them to `/dist`.
`build-bundle` | Build `swagger-ui-bundle.js` only.
`build-core` | Build `swagger-ui.(js|css)` only.
`build-standalone` | Build `swagger-ui-standalone-preset.js` only.
### Testing
Script name | Description
--- | ---
`test` | Run unit tests in Node and run ESLint in errors-only mode.
`just-test` | Run unit tests in the browser with Karma.
`just-test-in-node` | Run unit tests in Node.
`just-check-coverage` | Generate a code coverage report with NYC.
`e2e` | Run end-to-end tests (requires JDK and Selenium).
+24
View File
@@ -0,0 +1,24 @@
# Setting up a dev environment
Swagger-UI includes a development server that provides hot module reloading and unminified stack traces, for easier development.
### Prerequisites
- Node.js `6.0.0` or greater
- npm `3.0.0` or greater
- git, any version
### Steps
1. `git clone git@github.com:swagger-api/swagger-ui.git`
2. `cd swagger-ui`
3. `npm install`
4. `npm run dev`
5. Wait a bit
6. Open http://localhost:3200/
## Bonus points
- Swagger-UI includes an ESLint rule definition. If you use a graphical editor, consider installing an ESLint plugin, which will point out syntax and style errors for you as you code.
- The linter runs as part of the PR test sequence, so don't think you can get away with not paying attention to it!
+78
View File
@@ -0,0 +1,78 @@
# Configuration
### How to configure
Swagger-UI accepts configuration parameters in four locations.
From lowest to highest precedence:
- The `swagger-config.yaml` in the project root directory, if it exists, is baked into the application
- configuration object passed as an argument to Swagger-UI (`SwaggerUI({ ... })`)
- configuration document fetched from a specified `configUrl`
- configuration items passed as key/value pairs in the URL query string
### Parameters
Parameters with dots in their names are single strings used to organize subordinate parameters, and are not indicative of a nested structure.
For readability, parameters are grouped by category and sorted alphabetically.
Type notations are formatted like so:
- `String=""` means a String type with a default value of `""`.
- `String=["a"*, "b", "c", "d"]` means a String type that can be `a`, `b`, `c`, or `d`, with the `*` indicating that `a` is the default value.
##### Core
Parameter Name | Description
--- | ---
`configUrl` | `String`. URL to fetch external configuration document from.
`dom_id` |`String`, **REQUIRED** if `domNode` is not provided. The id of a dom element inside which SwaggerUi will put the user interface for swagger.
`domNode` | `Element`, **REQUIRED** if `dom_id` is not provided. The HTML DOM element inside which SwaggerUi will put the user interface for swagger. Overrides `dom_id`.
`spec` | `Object={}`. A JS object describing the OpenAPI Specification. When used, the `url` parameter will not be parsed. This is useful for testing manually-generated specifications without hosting them.
`url` | `String`. The url pointing to API definition (normally `swagger.json` or `swagger.yaml`). Will be ignored if `urls` or `spec` is used.
`urls` | `String`. An array of API definition objects (`{url: "<url>", name: "<name>"}`) used by Topbar plugin. When used and Topbar plugin is enabled, the `url` parameter will not be parsed. Names and URLs must be unique among all items in this array, since they're used as identifiers.
`urls.primaryName` | `String`. When using `urls`, you can use this subparameter. If the value matches the name of a spec provided in `urls`, that spec will be displayed when Swagger-UI loads, instead of defaulting to the first spec in `urls`.
##### Plugin system
Read more about the plugin system in the [Customization documentation](/docs/customization/overview.md).
Parameter Name | Description
--- | ---
`layout` | `String="BaseLayout"`. The name of a component available via the plugin system to use as the top-level layout for Swagger-UI.
`plugins` | `Array=[]`. An array of plugin functions to use in Swagger-UI.
`presets` | `Array=[SwaggerUI.presets.ApisPreset]`. An array of presets to use in Swagger-UI. Usually, you'll want to include `ApisPreset` if you use this option.
##### Display
Parameter Name | Description
--- | ---
`deepLinking` | `Boolean=false`. If set to `true`, enables deep linking for tags and operations. See the [Deep Linking documentation](/docs/usage/deep-linking.md) for more information.
`displayOperationId` | `Boolean=false`. Controls the display of operationId in operations list. The default is `false`.
`defaultModelsExpandDepth` | `Number=1`. The default expansion depth for models (set to -1 completely hide the models).
`defaultModelExpandDepth` | `Number=1`. The default expansion depth for the model on the model-example section.
`defaultModelRendering` | `String=["example"*, "model"]`. Controls how the model is shown when the API is first rendered. (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.)
`displayRequestDuration` | `Boolean=false`. Controls the display of the request duration (in milliseconds) for Try-It-Out requests.
`docExpansion` | `String=["list"*, "full", "none"]`. Controls the default expansion setting for the operations and tags. It can be 'list' (expands only the tags), 'full' (expands the tags and operations) or 'none' (expands nothing).
`filter` | `Boolean=false OR String`. If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown. Can be Boolean to enable or disable, or a string, in which case filtering will be enabled using that string as the filter expression. Filtering is case sensitive matching the filter expression anywhere inside the tag.
`maxDisplayedTags` | `Number`. If set, limits the number of tagged operations displayed to at most this many. The default is to show all operations.
`operationsSorter` | `Function=(a => a)`. Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged.
`showExtensions` | `Boolean=false`. Controls the display of vendor extension (`x-`) fields and values for Operations, Parameters, and Schema.
`tagsSorter` | `Function=(a => a)`. Apply a sort to the tag list of each API. It can be 'alpha' (sort by paths alphanumerically) or a function (see [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to learn how to write a sort function). Two tag name strings are passed to the sorter for each pass. Default is the order determined by Swagger-UI.
##### Network
Parameter Name | Description
--- | ---
`oauth2RedirectUrl` | `String`. OAuth redirect URL.
`requestInterceptor` | `Function=(a => a)`. MUST be a function. Function to intercept remote definition, Try-It-Out, and OAuth2 requests. Accepts one argument requestInterceptor(request) and must return the potentially modified request.
`responseInterceptor` |`Function=(a => a)`. MUST be a function. Function to intercept remote definition, Try-It-Out, and OAuth2 responses. Accepts one argument responseInterceptor(response) and must return the potentially modified response.
`showMutatedRequest` | `Boolean=true`. If set to `true`, uses the mutated request returned from a requestInterceptor to produce the curl command in the UI, otherwise the request before the requestInterceptor was applied is used.
`validatorUrl` | `String="https://online.swagger.io/validator" OR null`. By default, Swagger-UI attempts to validate specs against swagger.io's online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators ([Validator Badge](https://github.com/swagger-api/validator-badge)). Setting it to `null` will disable validation.
##### Macros
Parameter Name | Description
--- | ---
`modelPropertyMacro` | `Function`. Function to set default values to each property in model. Accepts one argument modelPropertyMacro(property), property is immutable
`parameterMacro` | `Function`. Function to set default value to parameters. Accepts two arguments parameterMacro(operation, parameter). Operation and parameter are objects passed for context, both remain immutable
+60
View File
@@ -0,0 +1,60 @@
# CORS
CORS is a technique to prevent websites from doing bad things with your personal data. Most browsers + JavaScript toolkits not only support CORS but enforce it, which has implications for your API server which supports Swagger.
You can read about CORS here: http://www.w3.org/TR/cors.
There are two cases where no action is needed for CORS support:
1. swagger-ui is hosted on the same server as the application itself (same host *and* port).
2. The application is located behind a proxy that enables the required CORS headers. This may already be covered within your organization.
Otherwise, CORS support needs to be enabled for:
1. Your Swagger docs. For Swagger 2.0 it's the `swagger.json`/`swagger.yaml` and any externally `$ref`ed docs.
2. For the `Try it now` button to work, CORS needs to be enabled on your API endpoints as well.
### Testing CORS Support
You can verify CORS support with one of three techniques:
- Curl your API and inspect the headers. For instance:
```bash
$ curl -I "http://petstore.swagger.io/v2/swagger.json"
HTTP/1.1 200 OK
Date: Sat, 31 Jan 2015 23:05:44 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
Content-Type: application/json
Content-Length: 0
```
This tells us that the petstore resource listing supports OPTIONS, and the following headers: `Content-Type`, `api_key`, `Authorization`.
- Try swagger-ui from your file system and look at the debug console. If CORS is not enabled, you'll see something like this:
```
XMLHttpRequest cannot load http://sad.server.com/v2/api-docs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
```
Swagger-UI cannot easily show this error state.
- Using the http://www.test-cors.org website. Keep in mind this will show a successful result even if `Access-Control-Allow-Headers` is not available, which is still required for Swagger-UI to function properly.
### Enabling CORS
The method of enabling CORS depends on the server and/or framework you use to host your application. http://enable-cors.org provides information on how to enable CORS in some common web servers.
Other servers/frameworks may provide you information on how to enable it specifically in their use case.
### CORS and Header Parameters
Swagger lets you easily send headers as parameters to requests. The name of these headers *MUST* be supported in your CORS configuration as well. From our example above:
```
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
```
Only headers with these names will be allowed to be sent by Swagger-UI.
@@ -1,4 +1,4 @@
# Deep linking
# `deepLinking` parameter
Swagger-UI allows you to deeply link into tags and operations within a spec. When Swagger-UI is provided a URL fragment at runtime, it will automatically expand and scroll to a specified tag or operation.
+93
View File
@@ -0,0 +1,93 @@
# Installation
## Distribution channels
### NPM Registry
We publish two modules to npm: **`swagger-ui`** and **`swagger-ui-dist`**.
**`swagger-ui`** is meant for consumption by JavaScript web projects that include module bundlers, such as Webpack, Browserify, and Rollup. Its main file exports Swagger-UI's main function, and the module also includes a namespaced stylesheet at `swagger-ui/dist/swagger-ui.css`. Here's an example:
```javascript
import SwaggerUI from 'swagger-ui'
// or use require, if you prefer
const SwaggerUI = require('swagger-ui')
SwaggerUI({
dom_id: '#myDomId'
})
```
In contrast, **`swagger-ui-dist`** is meant for server-side projects that need assets to serve to clients. The module, when imported, includes an `absolutePath` helper function that returns the absolute filesystem path to where the `swagger-ui-dist` module is installed.
_Note: we suggest using `swagger-ui` when your tooling makes it possible, as `swagger-ui-dist`
will result in more code going across the wire._
The module's contents mirrors the `dist` folder you see in the Git repository. The most useful file is `swagger-ui-bundle.js`, which is a build of Swagger-UI that includes all the code it needs to run in one file. The folder also has an `index.html` asset, to make it easy to serve Swagger-UI like so:
```javascript
const express = require('express')
const pathToSwaggerUi = require('swagger-ui').absolutePath()
const app = express()
app.use(express.static(pathToSwaggerUi))
app.listen(3000)
```
The module also exports `SwaggerUIBundle` and `SwaggerUIStandalonePreset`, so
if you're in a JavaScript project that can't handle a tranditional npm module,
you could do something like this:
```js
var SwaggerUIBundle = require('swagger-ui-dist').SwaggerUIBundle
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "StandaloneLayout"
})
```
`SwaggerUIBundle` is equivalent to `SwaggerUI`.
### Docker Hub
You can pull a pre-built docker image of the swagger-ui directly from Dockerhub:
```
docker pull swaggerapi/swagger-ui
docker run -p 80:8080 swaggerapi/swagger-ui
```
Will start nginx with swagger-ui on port 80.
Or you can provide your own swagger.json on your host
```
docker run -p 80:8080 -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo swaggerapi/swagger-ui
```
The base URL of the web application can be changed by specifying the `BASE_URL` environment variable:
```
docker run -p 80:8080 -e BASE_URL=/swagger -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo swaggerapi/swagger-ui
```
This will serve Swagger UI at `/swagger` instead of `/`.
### unpkg
You can embed Swagger-UI's code directly in your HTML by using unkpg's interface:
```html
<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<!-- `SwaggerUIBundle` is now available on the page -->
```
See [unpkg's main page](https://unpkg.com/) for more information on how to use unpkg.
+38
View File
@@ -0,0 +1,38 @@
# Limitations
### Forbidden header names
Some header names cannot be controlled by web applications, due to security
features built into web browsers.
Forbidden headers include:
> - Accept-Charset
> - Accept-Encoding
> - Access-Control-Request-Headers
> - Access-Control-Request-Method
> - Connection
> - Content-Length
> - Cookie
> - Cookie2
> - Date
> - DNT
> - Expect
> - Host
> - Keep-Alive
> - Origin
> - Proxy-*
> - Sec-*
> - Referer
> - TE
> - Trailer
> - Transfer-Encoding
> - Upgrade
> - Via
>
> _[Forbidden header names (developer.mozilla.org)](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name)_
The biggest impact of this is that OpenAPI 3.0 Cookie parameters cannot be
controlled when running Swagger-UI in a browser.
For more context, see [#3956](https://github.com/swagger-api/swagger-ui/issues/3956).
+28
View File
@@ -0,0 +1,28 @@
# OAuth2 configuration
You can configure OAuth2 authorization by calling `initOAuth` method with passed configs under the instance of `SwaggerUIBundle`
default `client_id` and `client_secret`, `realm`, an application name `appName`, `scopeSeparator`, `additionalQueryStringParams`,
`useBasicAuthenticationWithAccessCodeGrant`.
Config Name | Description
--- | ---
client_id | Default clientId. MUST be a string
client_secret | Default clientSecret. MUST be a string
realm | realm query parameter (for oauth1) added to `authorizationUrl` and `tokenUrl` . MUST be a string
appName | application name, displayed in authorization popup. MUST be a string
scopeSeparator | scope separator for passing scopes, encoded before calling, default value is a space (encoded value `%20`). MUST be a string
additionalQueryStringParams | Additional query parameters added to `authorizationUrl` and `tokenUrl`. MUST be an object
useBasicAuthenticationWithAccessCodeGrant | Only activated for the `accessCode` flow. During the `authorization_code` request to the `tokenUrl`, pass the [Client Password](https://tools.ietf.org/html/rfc6749#section-2.3.1) using the HTTP Basic Authentication scheme (`Authorization` header with `Basic base64encoded[client_id:client_secret]`). The default is `false`
```javascript
const ui = SwaggerUI({...})
// Method can be called in any place after calling constructor SwaggerUIBundle
ui.initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: " ",
additionalQueryStringParams: {test: "hello"}
})
```
@@ -1,6 +1,6 @@
# Detecting your Swagger-UI version
At times, you're going to need to know which version of Swagger-UI you use.
At times, you're going to need to know which version of Swagger-UI you use.
The first step would be to detect which major version you currently use, as the method of detecting the version has changed. If your Swagger-UI has been heavily modified and you cannot detect from the look and feel which major version you use, you'd have to try both methods to get the exact version.
@@ -9,7 +9,7 @@ To help you visually detect which version you're using, we've included supportin
# Swagger-UI 3.X
![Swagger-UI 3](images/swagger-ui3.png)
![Swagger-UI 3](/docs/images/swagger-ui3.png)
Some distinct identifiers to Swagger-UI 3.X:
- The API version appears as a badge next to its title.
@@ -29,7 +29,7 @@ Note: This functionality was added in 3.0.8. If you're unable to execute it, you
# Swagger-UI 2.X and under
![Swagger-UI 2](images/swagger-ui2.png)
![Swagger-UI 2](/docs/images/swagger-ui2.png)
Some distinct identifiers to Swagger-UI 3.X:
- The API version appears at the bottom of the page.
+1 -1
View File
@@ -137,7 +137,7 @@ module.exports = function(rules, options) {
}
},
devtool: specialOptions.sourcemaps ? "nosource-source-map" : null,
devtool: specialOptions.sourcemaps ? "nosource-source-map" : false,
plugins,
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "swagger-ui",
"version": "3.6.0",
"version": "3.7.0",
"main": "dist/swagger-ui.js",
"repository": "git@github.com:swagger-api/swagger-ui.git",
"contributors": [
@@ -81,13 +81,14 @@
"scroll-to-element": "^2.0.0",
"serialize-error": "2.0.0",
"shallowequal": "0.2.2",
"swagger-client": "^3.4.0",
"swagger-client": "^3.4.2",
"url-parse": "^1.1.8",
"whatwg-fetch": "0.11.1",
"worker-loader": "^0.7.1",
"xml": "1.0.1",
"xml-but-prettier": "^1.0.1",
"yaml-js": "0.2.0"
"yaml-js": "0.2.0",
"zenscroll": "4.0.0"
},
"devDependencies": {
"autoprefixer": "7.1.1",
+4 -3
View File
@@ -12,11 +12,12 @@ export default class ArrayModel extends Component {
name: PropTypes.string,
required: PropTypes.bool,
expandDepth: PropTypes.number,
specPath: PropTypes.array.isRequired,
depth: PropTypes.number
}
render(){
let { getComponent, getConfigs, schema, depth, expandDepth, name } = this.props
let { getComponent, getConfigs, schema, depth, expandDepth, name, specPath } = this.props
let description = schema.get("description")
let items = schema.get("items")
let title = schema.get("title") || name
@@ -38,7 +39,7 @@ export default class ArrayModel extends Component {
*/
return <span className="model">
<ModelCollapse title={titleEl} collapsed={ depth > expandDepth } collapsedContent="[...]">
<ModelCollapse title={titleEl} expanded={ depth <= expandDepth } collapsedContent="[...]">
[
{
properties.size ? properties.entrySeq().map( ( [ key, v ] ) => <Property key={`${key}-${v}`} propKey={ key } propVal={ v } propStyle={ propStyle } />) : null
@@ -47,7 +48,7 @@ export default class ArrayModel extends Component {
!description ? null :
<Markdown source={ description } />
}
<span><Model { ...this.props } getConfigs={ getConfigs } name={null} schema={ items } required={ false } depth={ depth + 1 } /></span>
<span><Model { ...this.props } getConfigs={ getConfigs } specPath={[...specPath, "items"]} name={null} schema={ items } required={ false } depth={ depth + 1 } /></span>
]
</ModelCollapse>
</span>
+20
View File
@@ -0,0 +1,20 @@
import React from "react"
import PropTypes from "prop-types"
export const DeepLink = ({ enabled, path, text }) => {
return (
<a className="nostyle"
onClick={enabled ? (e) => e.preventDefault() : null}
href={enabled ? `#/${path}` : null}>
<span>{text}</span>
</a>
)
}
DeepLink.propTypes = {
enabled: PropTypes.bool,
isShown: PropTypes.bool,
path: PropTypes.string,
text: PropTypes.string
}
export default DeepLink
+1 -1
View File
@@ -73,7 +73,7 @@ const ThrownErrorItem = ( { error, jumpToLine } ) => {
<span style={{ whiteSpace: "pre-line", "maxWidth": "100%" }}>
{ error.get("message") }
</span>
<div>
<div style={{ "text-decoration": "underline", "cursor": "pointer" }}>
{ errorLine && jumpToLine ? <a onClick={jumpToLine.bind(null, errorLine)}>Jump to line { errorLine }</a> : null }
</div>
</div>
+12 -1
View File
@@ -61,7 +61,18 @@ export default class BaseLayout extends React.Component {
const isSpecEmpty = !specSelectors.specStr()
if(isSpecEmpty) {
return <h4>No spec provided.</h4>
let loadingMessage
if(isLoading) {
loadingMessage = <div className="loading"></div>
} else {
loadingMessage = <h4>No API definition provided.</h4>
}
return <div className="swagger-ui">
<div className="loading-container">
{loadingMessage}
</div>
</div>
}
return (
+25 -9
View File
@@ -4,31 +4,47 @@ import PropTypes from "prop-types"
export default class ModelCollapse extends Component {
static propTypes = {
collapsedContent: PropTypes.any,
collapsed: PropTypes.bool,
expanded: PropTypes.bool,
children: PropTypes.any,
title: PropTypes.element
title: PropTypes.element,
modelName: PropTypes.string,
onToggle: PropTypes.func.isRequired
}
static defaultProps = {
collapsedContent: "{...}",
collapsed: true,
expanded: false,
title: null
}
constructor(props, context) {
super(props, context)
let { collapsed, collapsedContent } = this.props
let { expanded, collapsedContent } = this.props
this.state = {
collapsed: collapsed !== undefined ? collapsed : ModelCollapse.defaultProps.collapsed,
expanded : expanded,
collapsedContent: collapsedContent || ModelCollapse.defaultProps.collapsedContent
}
}
componentWillReceiveProps(nextProps){
if(this.props.expanded!= nextProps.expanded){
this.setState({expanded: nextProps.expanded})
}
}
toggleCollapsed=()=>{
if(this.props.onToggle){
this.props.onToggle(this.props.modelName,!this.state.expanded)
}
this.setState({
collapsed: !this.state.collapsed
expanded: !this.state.expanded
})
}
@@ -38,10 +54,10 @@ export default class ModelCollapse extends Component {
<span>
{ title && <span onClick={this.toggleCollapsed} style={{ "cursor": "pointer" }}>{title}</span> }
<span onClick={ this.toggleCollapsed } style={{ "cursor": "pointer" }}>
<span className={ "model-toggle" + ( this.state.collapsed ? " collapsed" : "" ) }></span>
<span className={ "model-toggle" + ( this.state.expanded ? "" : " collapsed" ) }></span>
</span>
{ this.state.collapsed ? this.state.collapsedContent : this.props.children }
{ this.state.expanded ? this.props.children :this.state.collapsedContent }
</span>
)
}
}
}
+5 -3
View File
@@ -8,7 +8,8 @@ export default class ModelExample extends React.Component {
schema: PropTypes.object.isRequired,
example: PropTypes.any.isRequired,
isExecute: PropTypes.bool,
getConfigs: PropTypes.func.isRequired
getConfigs: PropTypes.func.isRequired,
specPath: PropTypes.array.isRequired,
}
constructor(props, context) {
@@ -32,7 +33,7 @@ export default class ModelExample extends React.Component {
}
render() {
let { getComponent, specSelectors, schema, example, isExecute, getConfigs } = this.props
let { getComponent, specSelectors, schema, example, isExecute, getConfigs, specPath } = this.props
let { defaultModelExpandDepth } = getConfigs()
const ModelWrapper = getComponent("ModelWrapper")
@@ -54,7 +55,8 @@ export default class ModelExample extends React.Component {
getComponent={ getComponent }
getConfigs={ getConfigs }
specSelectors={ specSelectors }
expandDepth={ defaultModelExpandDepth } />
expandDepth={ defaultModelExpandDepth }
specPath={specPath} />
}
+22 -3
View File
@@ -1,22 +1,41 @@
import React, { Component, } from "react"
import PropTypes from "prop-types"
//import layoutActions from "actions/layout"
export default class ModelWrapper extends Component {
export default class ModelComponent extends Component {
static propTypes = {
schema: PropTypes.object.isRequired,
name: PropTypes.string,
getComponent: PropTypes.func.isRequired,
getConfigs: PropTypes.func.isRequired,
specSelectors: PropTypes.object.isRequired,
expandDepth: PropTypes.number
expandDepth: PropTypes.number,
layoutActions: PropTypes.object,
layoutSelectors: PropTypes.object.isRequired
}
onToggle = (name,isShown) => {
// If this prop is present, we'll have deepLinking for it
if(this.props.layoutActions) {
this.props.layoutActions.show(["models", name],isShown)
}
}
render(){
let { getComponent, getConfigs } = this.props
const Model = getComponent("Model")
let expanded
if(this.props.layoutSelectors) {
// If this is prop is present, we'll have deepLinking for it
expanded = this.props.layoutSelectors.isShown(["models",this.props.name])
}
return <div className="model-box">
<Model { ...this.props } getConfigs={ getConfigs } depth={ 1 } expandDepth={ this.props.expandDepth || 0 }/>
<Model { ...this.props } getConfigs={ getConfigs } expanded={expanded} depth={ 1 } onToggle={ this.onToggle } expandDepth={ this.props.expandDepth || 0 }/>
</div>
}
}
+4 -2
View File
@@ -12,7 +12,8 @@ export default class Model extends PureComponent {
isRef: PropTypes.bool,
required: PropTypes.bool,
expandDepth: PropTypes.number,
depth: PropTypes.number
depth: PropTypes.number,
specPath: PropTypes.array.isRequired,
}
getModelName =( ref )=> {
@@ -31,7 +32,7 @@ export default class Model extends PureComponent {
}
render () {
let { getComponent, getConfigs, specSelectors, schema, required, name, isRef } = this.props
let { getComponent, getConfigs, specSelectors, schema, required, name, isRef, specPath } = this.props
const ObjectModel = getComponent("ObjectModel")
const ArrayModel = getComponent("ArrayModel")
const PrimitiveModel = getComponent("PrimitiveModel")
@@ -55,6 +56,7 @@ export default class Model extends PureComponent {
case "object":
return <ObjectModel
className="object" { ...this.props }
specPath={specPath}
getConfigs={ getConfigs }
schema={ schema }
name={ name }
+14 -9
View File
@@ -13,13 +13,14 @@ export default class Models extends Component {
render(){
let { specSelectors, getComponent, layoutSelectors, layoutActions, getConfigs } = this.props
let definitions = specSelectors.definitions()
let { docExpansion, defaultModelExpandDepth } = getConfigs()
let showModels = layoutSelectors.isShown("models", docExpansion === "full" || docExpansion === "list" )
let { docExpansion, defaultModelsExpandDepth } = getConfigs()
if (!definitions.size || defaultModelsExpandDepth < 0) return null
let showModels = layoutSelectors.isShown("models", defaultModelsExpandDepth > 0 && docExpansion !== "none")
const specPathBase = specSelectors.isOAS3() ? ["components", "schemas"] : ["definitions"]
const ModelWrapper = getComponent("ModelWrapper")
const Collapse = getComponent("Collapse")
if (!definitions.size) return null
const Collapse = getComponent("Collapse")
return <section className={ showModels ? "models is-open" : "models"}>
<h4 onClick={() => layoutActions.show("models", !showModels)}>
@@ -31,13 +32,17 @@ export default class Models extends Component {
<Collapse isOpened={showModels}>
{
definitions.entrySeq().map( ( [ name, model ])=>{
return <div className="model-container" key={ `models-section-${name}` }>
return <div id={ `model-${name}` } className="model-container" key={ `models-section-${name}` }>
<ModelWrapper name={ name }
expandDepth={ defaultModelExpandDepth }
expandDepth={ defaultModelsExpandDepth }
schema={ model }
specPath={[...specPathBase, name]}
getComponent={ getComponent }
getConfigs={ getConfigs }
specSelectors={ specSelectors }/>
specSelectors={ specSelectors }
getConfigs = {getConfigs}
layoutSelectors = {layoutSelectors}
layoutActions = {layoutActions}/>
</div>
}).toArray()
}
+23 -10
View File
@@ -10,17 +10,20 @@ export default class ObjectModel extends Component {
schema: PropTypes.object.isRequired,
getComponent: PropTypes.func.isRequired,
getConfigs: PropTypes.func.isRequired,
expanded: PropTypes.bool,
onToggle: PropTypes.func.isRequired,
specSelectors: PropTypes.object.isRequired,
name: PropTypes.string,
isRef: PropTypes.bool,
expandDepth: PropTypes.number,
depth: PropTypes.number
depth: PropTypes.number,
specPath: PropTypes.object.isRequired
}
render(){
let { schema, name, isRef, getComponent, getConfigs, depth, expandDepth, ...otherProps } = this.props
let { specSelectors } = otherProps
let { isOAS3 } = specSelectors
let { schema, name, isRef, getComponent, getConfigs, depth, onToggle, expanded, specPath, ...otherProps } = this.props
let { specSelectors,expandDepth } = otherProps
const { isOAS3 } = specSelectors
if(!schema) {
return null
@@ -39,14 +42,13 @@ export default class ObjectModel extends Component {
const Model = getComponent("Model")
const ModelCollapse = getComponent("ModelCollapse")
const JumpToPathSection = ({ name }) => {
const path = isOAS3 && isOAS3() ? `components.schemas.${name}` : `definitions.${name}`
return <span className="model-jump-to-path"><JumpToPath path={path} /></span>
const JumpToPathSection = () => {
return <span className="model-jump-to-path"><JumpToPath specPath={specPath} /></span>
}
const collapsedContent = (<span>
<span>{ braceOpen }</span>...<span>{ braceClose }</span>
{
isRef ? <JumpToPathSection name={ name }/> : ""
isRef ? <JumpToPathSection /> : ""
}
</span>)
@@ -60,10 +62,16 @@ export default class ObjectModel extends Component {
</span>
return <span className="model">
<ModelCollapse title={titleEl} collapsed={ depth > expandDepth } collapsedContent={ collapsedContent }>
<ModelCollapse
modelName={name}
title={titleEl}
onToggle = {onToggle}
expanded={ expanded ? true : depth <= expandDepth }
collapsedContent={ collapsedContent }>
<span className="brace-open object">{ braceOpen }</span>
{
!isRef ? null : <JumpToPathSection name={ name }/>
!isRef ? null : <JumpToPathSection />
}
<span className="inner-object">
{
@@ -94,6 +102,7 @@ export default class ObjectModel extends Component {
<Model key={ `object-${name}-${key}_${value}` } { ...otherProps }
required={ isRequired }
getComponent={ getComponent }
specPath={[...specPath, "properties", key]}
getConfigs={ getConfigs }
schema={ value }
depth={ depth + 1 } />
@@ -132,6 +141,7 @@ export default class ObjectModel extends Component {
<td>
<Model { ...otherProps } required={ false }
getComponent={ getComponent }
specPath={[...specPath, "additionalProperties"]}
getConfigs={ getConfigs }
schema={ additionalProperties }
depth={ depth + 1 } />
@@ -146,6 +156,7 @@ export default class ObjectModel extends Component {
{anyOf.map((schema, k) => {
return <div key={k}><Model { ...otherProps } required={ false }
getComponent={ getComponent }
specPath={[...specPath, "anyOf", k]}
getConfigs={ getConfigs }
schema={ schema }
depth={ depth + 1 } /></div>
@@ -161,6 +172,7 @@ export default class ObjectModel extends Component {
{oneOf.map((schema, k) => {
return <div key={k}><Model { ...otherProps } required={ false }
getComponent={ getComponent }
specPath={[...specPath, "oneOf", k]}
getConfigs={ getConfigs }
schema={ schema }
depth={ depth + 1 } /></div>
@@ -177,6 +189,7 @@ export default class ObjectModel extends Component {
<Model { ...otherProps }
required={ false }
getComponent={ getComponent }
specPath={[...specPath, "not"]}
getConfigs={ getConfigs }
schema={ not }
depth={ depth + 1 } />
+16 -10
View File
@@ -6,6 +6,7 @@ import { Iterable } from "immutable"
export default class Operation extends PureComponent {
static propTypes = {
specPath: PropTypes.array.isRequired,
operation: PropTypes.instanceOf(Iterable).isRequired,
response: PropTypes.instanceOf(Iterable),
request: PropTypes.instanceOf(Iterable),
@@ -31,11 +32,13 @@ export default class Operation extends PureComponent {
static defaultProps = {
operation: null,
response: null,
request: null
request: null,
specPath: []
}
render() {
let {
specPath,
response,
request,
toggleShown,
@@ -57,7 +60,6 @@ export default class Operation extends PureComponent {
let {
isShown,
isAuthorized,
jumpToKey,
path,
method,
op,
@@ -100,12 +102,13 @@ export default class Operation extends PureComponent {
const Schemes = getComponent( "schemes" )
const OperationServers = getComponent( "OperationServers" )
const OperationExt = getComponent( "OperationExt" )
const DeepLink = getComponent( "DeepLink" )
const { showExtensions } = getConfigs()
// Merge in Live Response
if(responses && response && response.size > 0) {
let notDocumented = !responses.get(String(response.get("status")))
let notDocumented = !responses.get(String(response.get("status"))) && !responses.get("default")
response = response.set("notDocumented", notDocumented)
}
@@ -114,15 +117,16 @@ export default class Operation extends PureComponent {
return (
<div className={deprecated ? "opblock opblock-deprecated" : isShown ? `opblock opblock-${method} is-open` : `opblock opblock-${method}`} id={isShownKey.join("-")} >
<div className={`opblock-summary opblock-summary-${method}`} onClick={toggleShown} >
{/*TODO: convert this into a component, that can be wrapped
and pulled in with getComponent */}
<span className="opblock-summary-method">{method.toUpperCase()}</span>
<span className={ deprecated ? "opblock-summary-path__deprecated" : "opblock-summary-path" } >
<a
className="nostyle"
onClick={isDeepLinkingEnabled ? (e) => e.preventDefault() : null}
href={isDeepLinkingEnabled ? `#/${isShownKey.join("/")}` : null}>
<span>{path}</span>
</a>
<JumpToPath path={jumpToKey} />
<DeepLink
enabled={isDeepLinkingEnabled}
isShown={isShown}
path={`${isShownKey.join("/")}`}
text={path} />
<JumpToPath path={specPath} /> {/*TODO: use wrapComponents here, swagger-ui doesn't care about jumpToPath */}
</span>
{ !showSummary ? null :
@@ -170,6 +174,7 @@ export default class Operation extends PureComponent {
<Parameters
parameters={parameters}
specPath={[...specPath, "parameters"]}
operation={operation}
onChangeKey={onChangeKey}
onTryoutClick = { onTryoutClick }
@@ -243,6 +248,7 @@ export default class Operation extends PureComponent {
specActions={ specActions }
produces={ produces }
producesValue={ operation.get("produces_value") }
specPath={[...specPath, "responses"]}
path={ path }
method={ method }
displayRequestDuration={ displayRequestDuration }
+28 -6
View File
@@ -2,6 +2,13 @@ import React from "react"
import PropTypes from "prop-types"
import { createDeepLinkPath, sanitizeUrl } from "core/utils"
const SWAGGER2_OPERATION_METHODS = [
"get", "put", "post", "delete", "options", "head", "patch"
]
const OAS3_OPERATION_METHODS = SWAGGER2_OPERATION_METHODS.concat(["trace"])
export default class Operations extends React.Component {
static propTypes = {
@@ -30,6 +37,7 @@ export default class Operations extends React.Component {
const OperationContainer = getComponent("OperationContainer", true)
const Collapse = getComponent("Collapse")
const Markdown = getComponent("Markdown")
const DeepLink = getComponent("DeepLink")
let {
docExpansion,
@@ -72,12 +80,11 @@ export default class Operations extends React.Component {
onClick={() => layoutActions.show(isShownKey, !showTag)}
className={!tagDescription ? "opblock-tag no-desc" : "opblock-tag" }
id={isShownKey.join("-")}>
<a
className="nostyle"
onClick={isDeepLinkingEnabled ? (e) => e.preventDefault() : null}
href= {isDeepLinkingEnabled ? `#/${tag}` : null}>
<span>{tag}</span>
</a>
<DeepLink
enabled={isDeepLinkingEnabled}
isShown={showTag}
path={tag}
text={tag} />
{ !tagDescription ? null :
<small>
<Markdown source={tagDescription} />
@@ -112,9 +119,24 @@ export default class Operations extends React.Component {
operations.map( op => {
const path = op.get("path")
const method = op.get("method")
const specPath = ["paths", path, method]
// FIXME: (someday) this logic should probably be in a selector,
// but doing so would require further opening up
// selectors to the plugin system, to allow for dynamic
// overriding of low-level selectors that other selectors
// rely on. --KS, 12/17
const validMethods = specSelectors.isOAS3() ?
OAS3_OPERATION_METHODS : SWAGGER2_OPERATION_METHODS
if(validMethods.indexOf(method) === -1) {
return null
}
return <OperationContainer
key={`${path}-${method}`}
specPath={specPath}
op={op}
path={path}
method={method}
+1 -1
View File
@@ -47,7 +47,7 @@ export default class ParamBody extends PureComponent {
updateValues = (props) => {
let { specSelectors, pathMethod, param, isExecute, consumesValue="" } = props
let parameter = specSelectors ? specSelectors.getParameter(pathMethod, param.get("name"), param.get("in")) : {}
let parameter = specSelectors ? specSelectors.getParameter(pathMethod, param.get("name"), param.get("in")) : fromJS({})
let isXml = /xml/i.test(consumesValue)
let isJson = /json/i.test(consumesValue)
let paramValue = isXml ? parameter.get("value_xml") : parameter.get("value")
+4 -2
View File
@@ -14,7 +14,8 @@ export default class ParameterRow extends Component {
onChangeConsumes: PropTypes.func.isRequired,
specSelectors: PropTypes.object.isRequired,
pathMethod: PropTypes.array.isRequired,
getConfigs: PropTypes.func.isRequired
getConfigs: PropTypes.func.isRequired,
specPath: PropTypes.array.isRequired,
}
constructor(props, context) {
@@ -69,7 +70,7 @@ export default class ParameterRow extends Component {
}
render() {
let {param, onChange, getComponent, getConfigs, isExecute, fn, onChangeConsumes, specSelectors, pathMethod} = this.props
let {param, onChange, getComponent, getConfigs, isExecute, fn, onChangeConsumes, specSelectors, pathMethod, specPath} = this.props
let { isOAS3 } = specSelectors
@@ -138,6 +139,7 @@ export default class ParameterRow extends Component {
{
bodyParam && schema ? <ModelExample getComponent={ getComponent }
specPath={[...specPath, "schema"]}
getConfigs={ getConfigs }
isExecute={ isExecute }
specSelectors={ specSelectors }
+8 -3
View File
@@ -20,7 +20,8 @@ export default class Parameters extends Component {
onCancelClick: PropTypes.func,
onChangeKey: PropTypes.array,
pathMethod: PropTypes.array.isRequired,
getConfigs: PropTypes.func.isRequired
getConfigs: PropTypes.func.isRequired,
specPath: PropTypes.array.isRequired,
}
@@ -30,6 +31,7 @@ export default class Parameters extends Component {
tryItOutEnabled: false,
allowTryItOut: true,
onChangeKey: [],
specPath: [],
}
onChange = ( param, value, isXml ) => {
@@ -58,6 +60,7 @@ export default class Parameters extends Component {
parameters,
allowTryItOut,
tryItOutEnabled,
specPath,
fn,
getComponent,
@@ -92,8 +95,10 @@ export default class Parameters extends Component {
</thead>
<tbody>
{
eachMap(parameters, (parameter) => (
<ParameterRow fn={ fn }
eachMap(parameters, (parameter, i) => (
<ParameterRow
fn={ fn }
specPath={[...specPath, i]}
getComponent={ getComponent }
getConfigs={ getConfigs }
param={ parameter }
+5 -1
View File
@@ -43,7 +43,11 @@ export default class ResponseBody extends React.Component {
// Image
} else if (/^image\//i.test(contentType)) {
bodyEl = <img style={{ maxWidth: "100%" }} src={ window.URL.createObjectURL(content) } />
if(contentType.includes("svg")) {
bodyEl = <div> { content } </div>
} else {
bodyEl = <img style={{ maxWidth: "100%" }} src={ window.URL.createObjectURL(content) } />
}
// Audio
} else if (/^audio\//i.test(contentType)) {
+9 -3
View File
@@ -47,6 +47,7 @@ export default class Response extends React.Component {
getComponent: PropTypes.func.isRequired,
getConfigs: PropTypes.func.isRequired,
specSelectors: PropTypes.object.isRequired,
specPath: PropTypes.array.isRequired,
fn: PropTypes.object.isRequired,
contentType: PropTypes.string,
controlsAcceptHeader: PropTypes.bool,
@@ -72,6 +73,7 @@ export default class Response extends React.Component {
code,
response,
className,
specPath,
fn,
getComponent,
getConfigs,
@@ -94,16 +96,19 @@ export default class Response extends React.Component {
const ContentType = getComponent("contentType")
var sampleResponse
var schema
var schema, specPathWithPossibleSchema
if(isOAS3()) {
let oas3SchemaForContentType = response.getIn(["content", this.state.responseContentType, "schema"])
const schemaPath = ["content", this.state.responseContentType, "schema"]
const oas3SchemaForContentType = response.getIn(schemaPath)
sampleResponse = oas3SchemaForContentType ? getSampleSchema(oas3SchemaForContentType.toJS(), this.state.responseContentType, {
includeReadOnly: true
}) : null
schema = oas3SchemaForContentType ? inferSchema(oas3SchemaForContentType.toJS()) : null
specPathWithPossibleSchema = oas3SchemaForContentType ? schemaPath : specPath
} else {
schema = inferSchema(response.toJS())
schema = inferSchema(response.toJS()) // TODO: don't convert back and forth. Lets just stick with immutable for inferSchema
specPathWithPossibleSchema = response.has("schema") ? [...specPath, "schema"] : specPath
sampleResponse = schema ? getSampleSchema(schema, contentType, {
includeReadOnly: true,
includeWriteOnly: true // writeOnly has no filtering effect in swagger 2.0
@@ -145,6 +150,7 @@ export default class Response extends React.Component {
{ example ? (
<ModelExample
specPath={specPathWithPossibleSchema}
getComponent={ getComponent }
getConfigs={ getConfigs }
specSelectors={ specSelectors }
+5 -1
View File
@@ -17,6 +17,7 @@ export default class Responses extends React.Component {
specSelectors: PropTypes.object.isRequired,
specActions: PropTypes.object.isRequired,
oas3Actions: PropTypes.object.isRequired,
specPath: PropTypes.array.isRequired,
fn: PropTypes.object.isRequired
}
@@ -60,7 +61,8 @@ export default class Responses extends React.Component {
specSelectors,
fn,
producesValue,
displayRequestDuration
displayRequestDuration,
specPath,
} = this.props
let defaultCode = defaultStatusCode( responses )
@@ -114,9 +116,11 @@ export default class Responses extends React.Component {
<tbody>
{
responses.entrySeq().map( ([code, response]) => {
let className = tryItOutResponse && tryItOutResponse.get("status") == code ? "response_current" : ""
return (
<Response key={ code }
specPath={[...specPath, code]}
isDefault={defaultCode === code}
fn={fn}
className={ className }
@@ -31,6 +31,7 @@ export default class OperationContainer extends PureComponent {
request: PropTypes.instanceOf(Iterable),
security: PropTypes.instanceOf(Iterable),
isDeepLinkingEnabled: PropTypes.bool.isRequired,
specPath: PropTypes.array.isRequired,
getComponent: PropTypes.func.isRequired,
authActions: PropTypes.object,
@@ -141,6 +142,7 @@ export default class OperationContainer extends PureComponent {
displayOperationId,
displayRequestDuration,
isDeepLinkingEnabled,
specPath,
specSelectors,
specActions,
getComponent,
@@ -187,6 +189,7 @@ export default class OperationContainer extends PureComponent {
onTryoutClick={this.onTryoutClick}
onCancelClick={this.onCancelClick}
onExecute={this.onExecute}
specPath={specPath}
specActions={ specActions }
specSelectors={ specSelectors }
+4 -2
View File
@@ -3,11 +3,12 @@ import deepExtend from "deep-extend"
import System from "core/system"
import win from "core/window"
import ApisPreset from "core/presets/apis"
import * as AllPlugins from "core/plugins/all"
import { parseSearch } from "core/utils"
if (process.env.NODE_ENV !== "production") {
window.Perf = require("react-addons-perf")
if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
win.Perf = require("react-addons-perf")
}
// eslint-disable-next-line no-undef
@@ -46,6 +47,7 @@ module.exports = function SwaggerUI(opts) {
showMutatedRequest: true,
defaultModelRendering: "example",
defaultModelExpandDepth: 1,
defaultModelsExpandDepth: 1,
showExtensions: false,
// Initial set of plugins ( TODO rename this, or refactor - we don't need presets _and_ plugins. Its just there for performance.
+1 -1
View File
@@ -46,7 +46,7 @@ export default function authorize ( { auth, authActions, errActions, configs, au
authId: name,
source: "validation",
level: "error",
message: "oauth2RedirectUri configuration is not passed. Oauth2 authorization cannot be performed."
message: "oauth2RedirectUrl configuration is not passed. Oauth2 authorization cannot be performed."
})
return
}
+33 -15
View File
@@ -103,30 +103,30 @@ export function positionRangeForPath(yaml, path) {
let ast = cachedCompose(yaml)
// simply walks the tree using current path recursively to the point that
// simply walks the tree using astValue path recursively to the point that
// path is empty.
return find(ast)
function find(current) {
if (current.tag === MAP_TAG) {
for (i = 0; i < current.value.length; i++) {
var pair = current.value[i]
function find(astValue, astKeyValue) {
if (astValue.tag === MAP_TAG) {
for (i = 0; i < astValue.value.length; i++) {
var pair = astValue.value[i]
var key = pair[0]
var value = pair[1]
if (key.value === path[0]) {
path.shift()
return find(value)
return find(value, key)
}
}
}
if (current.tag === SEQ_TAG) {
var item = current.value[path[0]]
if (astValue.tag === SEQ_TAG) {
var item = astValue.value[path[0]]
if (item && item.tag) {
path.shift()
return find(item)
return find(item, astKeyValue)
}
}
@@ -135,17 +135,35 @@ export function positionRangeForPath(yaml, path) {
return invalidRange
}
return {
/* jshint camelcase: false */
const range = {
start: {
line: current.start_mark.line,
column: current.start_mark.column
line: astValue.start_mark.line,
column: astValue.start_mark.column,
pointer: astValue.start_mark.pointer,
},
end: {
line: current.end_mark.line,
column: current.end_mark.column
line: astValue.end_mark.line,
column: astValue.end_mark.column,
pointer: astValue.end_mark.pointer,
}
}
if(astKeyValue) {
// eslint-disable-next-line camelcase
range.key_start = {
line: astKeyValue.start_mark.line,
column: astKeyValue.start_mark.column,
pointer: astKeyValue.start_mark.pointer,
}
// eslint-disable-next-line camelcase
range.key_end = {
line: astKeyValue.end_mark.line,
column: astKeyValue.end_mark.column,
pointer: astKeyValue.end_mark.pointer,
}
}
return range
}
}
@@ -1,8 +1,7 @@
import scrollTo from "scroll-to-element"
import zenscroll from "zenscroll"
import { escapeDeepLinkPath } from "core/utils"
const SCROLL_OFFSET = -5
let hasHashBeenParsed = false
let hasHashBeenParsed = false //TODO this forces code to only run once which may prevent scrolling if page not refreshed
export const updateResolved = (ori, { layoutActions, getConfigs }) => (...args) => {
@@ -12,7 +11,6 @@ export const updateResolved = (ori, { layoutActions, getConfigs }) => (...args)
if(!isDeepLinkingEnabled || isDeepLinkingEnabled === "false") {
return
}
if(window.location.hash && !hasHashBeenParsed ) {
let hash = window.location.hash.slice(1) // # is first character
@@ -30,21 +28,35 @@ export const updateResolved = (ori, { layoutActions, getConfigs }) => (...args)
let [tag, operationId] = hash.split("/")
let swaggerUI = document.querySelector(".swagger-ui")
let myScroller = zenscroll.createScroller(swaggerUI)
let target
if(tag && operationId) {
// Pre-expand and scroll to the operation
layoutActions.show(["operations-tag", tag], true)
layoutActions.show(["operations", tag, operationId], true)
scrollTo(`#operations-${escapeDeepLinkPath(tag)}-${escapeDeepLinkPath(operationId)}`, {
offset: SCROLL_OFFSET
})
target = document
.getElementById(`operations-${escapeDeepLinkPath(tag)}-${escapeDeepLinkPath(operationId)}`)
} else if(tag) {
// Pre-expand and scroll to the tag
layoutActions.show(["operations-tag", tag], true)
scrollTo(`#operations-tag-${escapeDeepLinkPath(tag)}`, {
offset: SCROLL_OFFSET
})
target = document.getElementById(`operations-tag-${escapeDeepLinkPath(tag)}`)
}
if(target) {
myScroller.to(target)
setTimeout(() => {
// Backup functionality: if we're still at the top of the document,
// scroll on the entire page (not within the Swagger-UI container)
if(zenscroll.getY() === 0) {
zenscroll.to(target)
}
}, 50)
}
}
-14
View File
@@ -37,17 +37,3 @@ export function changeMode(thing, mode="") {
payload: {thing, mode}
}
}
// export function onlyShow(thing, shown=true) {
// thing = normalizeArray(thing)
// if(thing.length < 2)
// throw new Error("layoutActions.onlyShow only works, when `thing` is an array with length > 1")
// return {
// type: ONLY_SHOW,
// payload: {thing, shown}
// }
// }
+9 -4
View File
@@ -1,3 +1,4 @@
import { fromJS } from "immutable"
import {
UPDATE_LAYOUT,
UPDATE_FILTER,
@@ -12,9 +13,14 @@ export default {
[UPDATE_FILTER]: (state, action) => state.set("filter", action.payload),
[SHOW]: (state, action) => {
let thing = action.payload.thing
let shown = action.payload.shown
return state.setIn(["shown"].concat(thing), shown)
const isShown = action.payload.shown
// This is one way to serialize an array, another (preferred) is to convert to json-pointer
// TODO: use json-pointer serilization instead of fromJS(...), for performance
const thingToShow = fromJS(action.payload.thing)
// This is a map of paths to bools
// eg: [one, two] => true
// eg: [one] => false
return state.update("shown", fromJS({}), a => a.set(thingToShow, isShown))
},
[UPDATE_MODE]: (state, action) => {
@@ -24,4 +30,3 @@ export default {
}
}
+2 -2
View File
@@ -1,5 +1,6 @@
import { createSelector } from "reselect"
import { normalizeArray } from "core/utils"
import { fromJS } from "immutable"
const state = state => state
@@ -9,7 +10,7 @@ export const currentFilter = state => state.get("filter")
export const isShown = (state, thing, def) => {
thing = normalizeArray(thing)
return Boolean(state.getIn(["shown", ...thing], def))
return state.get("shown", fromJS({})).get(fromJS(thing), def)
}
export const whatMode = (state, thing, def="") => {
@@ -21,4 +22,3 @@ export const showSummary = createSelector(
state,
state => !isShown(state, "editor")
)
@@ -10,6 +10,7 @@ const RequestBody = ({
specSelectors,
contentType,
isExecute,
specPath,
onChange
}) => {
const Markdown = getComponent("Markdown")
@@ -37,6 +38,7 @@ const RequestBody = ({
expandDepth={1}
isExecute={isExecute}
schema={mediaTypeValue.get("schema")}
specPath={[...specPath, "content", contentType]}
example={<RequestBodyEditor
requestBody={requestBody}
onChange={onChange}
@@ -56,7 +58,8 @@ RequestBody.propTypes = {
specSelectors: PropTypes.object.isRequired,
contentType: PropTypes.string,
isExecute: PropTypes.bool.isRequired,
onChange: PropTypes.func.isRequired
onChange: PropTypes.func.isRequired,
specPath: PropTypes.array.isRequired
}
export default RequestBody
+1 -1
View File
@@ -6,7 +6,7 @@ export function isOAS3(jsSpec) {
return false
}
return oasVersion.startsWith("3.0.0")
return oasVersion.startsWith("3")
}
export function isSwagger2(jsSpec) {
@@ -29,6 +29,7 @@ class Parameters extends Component {
fn: PropTypes.object.isRequired,
tryItOutEnabled: PropTypes.bool,
allowTryItOut: PropTypes.bool,
specPath: PropTypes.array.isRequired,
onTryoutClick: PropTypes.func,
onCancelClick: PropTypes.func,
onChangeKey: PropTypes.array,
@@ -92,6 +93,7 @@ class Parameters extends Component {
oas3Actions,
oas3Selectors,
pathMethod,
specPath,
operation
} = this.props
@@ -105,6 +107,8 @@ class Parameters extends Component {
const { isOAS3 } = specSelectors
const requestBody = operation.get("requestBody")
const requestBodySpecPath = [...specPath.slice(0, -1), "requestBody"] // remove the "parameters" part
return (
<div className="opblock-section">
<div className="opblock-section-header">
@@ -136,9 +140,10 @@ class Parameters extends Component {
</thead>
<tbody>
{
eachMap(parameters, (parameter) => (
eachMap(parameters, (parameter, i) => (
<ParameterRow fn={ fn }
getComponent={ getComponent }
specPath={[...specPath, i]}
getConfigs={ getConfigs }
param={ parameter }
key={ parameter.get( "name" ) }
@@ -175,6 +180,7 @@ class Parameters extends Component {
</div>
<div className="opblock-description-wrapper">
<RequestBody
specPath={requestBodySpecPath}
requestBody={requestBody}
isExecute={isExecute}
onChange={(value) => {
+11 -28
View File
@@ -1,6 +1,7 @@
import YAML from "js-yaml"
import parseUrl from "url-parse"
import serializeError from "serialize-error"
import isString from "lodash/isString"
import { isJSONObject } from "core/utils"
// Actions conform to FSA (flux-standard-actions)
@@ -17,27 +18,21 @@ export const SET_MUTATED_REQUEST = "spec_set_mutated_request"
export const LOG_REQUEST = "spec_log_request"
export const CLEAR_RESPONSE = "spec_clear_response"
export const CLEAR_REQUEST = "spec_clear_request"
export const ClEAR_VALIDATE_PARAMS = "spec_clear_validate_param"
export const CLEAR_VALIDATE_PARAMS = "spec_clear_validate_param"
export const UPDATE_OPERATION_VALUE = "spec_update_operation_value"
export const UPDATE_RESOLVED = "spec_update_resolved"
export const SET_SCHEME = "set_scheme"
export function updateSpec(spec) {
if(spec instanceof Error) {
return {type: UPDATE_SPEC, error: true, payload: spec}
}
const toStr = (str) => isString(str) ? str : ""
export function updateSpec(spec) {
const cleanSpec = (toStr(spec)).replace(/\t/g, " ")
if(typeof spec === "string") {
return {
type: UPDATE_SPEC,
payload: spec.replace(/\t/g, " ") || ""
payload: cleanSpec
}
}
return {
type: UPDATE_SPEC,
payload: ""
}
}
export function updateResolved(spec) {
@@ -52,9 +47,6 @@ export function updateUrl(url) {
}
export function updateJsonSpec(json) {
if(!json || typeof json !== "object") {
throw new Error("updateJson must only accept a simple JSON object")
}
return {type: UPDATE_JSON, payload: json}
}
@@ -76,7 +68,10 @@ export const parseToJson = (str) => ({specActions, specSelectors, errActions}) =
line: e.mark && e.mark.line ? e.mark.line + 1 : undefined
})
}
return specActions.updateJsonSpec(json)
if(json) {
return specActions.updateJsonSpec(json)
}
return {}
}
export const resolveSpec = (json, url) => ({specActions, specSelectors, errActions, fn: { fetch, resolve, AST }, getConfigs}) => {
@@ -130,18 +125,6 @@ export const resolveSpec = (json, url) => ({specActions, specSelectors, errActio
})
}
export const formatIntoYaml = () => ({specActions, specSelectors}) => {
let { specStr } = specSelectors
let { updateSpec } = specActions
try {
let yaml = YAML.safeDump(YAML.safeLoad(specStr()), {indent: 2})
updateSpec(yaml)
} catch(e) {
updateSpec(e)
}
}
export function changeParam( path, paramName, paramIn, value, isXml ){
return {
type: UPDATE_PARAM,
@@ -161,7 +144,7 @@ export const validateParams = ( payload, isOAS3 ) =>{
export function clearValidateParams( payload ){
return {
type: ClEAR_VALIDATE_PARAMS,
type: CLEAR_VALIDATE_PARAMS,
payload:{ pathMethod: payload }
}
}
+2 -2
View File
@@ -15,7 +15,7 @@ import {
UPDATE_OPERATION_VALUE,
CLEAR_RESPONSE,
CLEAR_REQUEST,
ClEAR_VALIDATE_PARAMS,
CLEAR_VALIDATE_PARAMS,
SET_SCHEME
} from "./actions"
@@ -64,7 +64,7 @@ export default {
})
})
},
[ClEAR_VALIDATE_PARAMS]: ( state, { payload: { pathMethod } } ) => {
[CLEAR_VALIDATE_PARAMS]: ( state, { payload: { pathMethod } } ) => {
return state.updateIn( [ "resolved", "paths", ...pathMethod, "parameters" ], fromJS([]), parameters => {
return parameters.withMutations( parameters => {
for ( let i = 0, len = parameters.count(); i < len; i++ ) {
+7 -7
View File
@@ -4,8 +4,6 @@ import { fromJS, Set, Map, OrderedMap, List } from "immutable"
const DEFAULT_TAG = "default"
const OPERATION_METHODS = ["get", "put", "post", "delete", "options", "head", "patch"]
const state = state => {
return state || Map()
}
@@ -97,9 +95,6 @@ export const operations = createSelector(
return {}
}
path.forEach((operation, method) => {
if(OPERATION_METHODS.indexOf(method) === -1) {
return
}
list = list.push(fromJS({
path: pathName,
method,
@@ -261,10 +256,11 @@ export const allowTryItOutFor = () => {
// Get the parameter value by parameter name
export function getParameter(state, pathMethod, name, inType) {
pathMethod = pathMethod || []
let params = spec(state).getIn(["paths", ...pathMethod, "parameters"], fromJS([]))
return params.filter( (p) => {
return params.find( (p) => {
return Map.isMap(p) && p.get("name") === name && p.get("in") === inType
}).first()
}) || Map() // Always return a map
}
export const hasHost = createSelector(
@@ -277,6 +273,7 @@ export const hasHost = createSelector(
// Get the parameter values, that the user filled out
export function parameterValues(state, pathMethod, isXml) {
pathMethod = pathMethod || []
let params = spec(state).getIn(["paths", ...pathMethod, "parameters"], fromJS([]))
return params.reduce( (hash, p) => {
let value = isXml && p.get("in") === "body" ? p.get("value_xml") : p.get("value")
@@ -300,6 +297,7 @@ export function parametersIncludeType(parameters, typeValue="") {
// Get the consumes/produces value that the user selected
export function contentTypeValues(state, pathMethod) {
pathMethod = pathMethod || []
let op = spec(state).getIn(["paths", ...pathMethod], fromJS({}))
const parameters = op.get("parameters") || new List()
@@ -318,6 +316,7 @@ export function contentTypeValues(state, pathMethod) {
// Get the consumes/produces by path
export function operationConsumes(state, pathMethod) {
pathMethod = pathMethod || []
return spec(state).getIn(["paths", ...pathMethod, "consumes"], fromJS({}))
}
@@ -334,6 +333,7 @@ export const canExecuteScheme = ( state, path, method ) => {
}
export const validateBeforeExecute = ( state, pathMethod ) => {
pathMethod = pathMethod || []
let params = spec(state).getIn(["paths", ...pathMethod, "parameters"], fromJS([]))
let isValid = true
+3 -1
View File
@@ -61,6 +61,7 @@ import PrimitiveModel from "core/components/primitive-model"
import Property from "core/components/property"
import TryItOutButton from "core/components/try-it-out-button"
import VersionStamp from "core/components/version-stamp"
import DeepLink from "core/components/deep-link"
import Markdown from "core/components/providers/markdown"
@@ -121,7 +122,8 @@ export default function() {
OperationExt,
OperationExtRow,
ParameterExt,
OperationContainer
OperationContainer,
DeepLink
}
}
+15 -7
View File
@@ -1,3 +1,4 @@
import React from "react"
import { createStore, applyMiddleware, bindActionCreators, compose } from "redux"
import Im, { fromJS, Map } from "immutable"
import deepExtend from "deep-extend"
@@ -97,7 +98,8 @@ export default class Store {
getComponents: this.getComponents.bind(this),
getState: this.getStore().getState,
getConfigs: this._getConfigs.bind(this),
Im
Im,
React
}, this.system.rootInjects || {})
}
@@ -264,8 +266,9 @@ export default class Store {
dispatch = dispatch || this.getStore().dispatch
const process = creator =>{
const actions = this.getActions()
const process = creator =>{
if( typeof( creator ) !== "function" ) {
return objMap(creator, prop => process(prop))
}
@@ -284,7 +287,7 @@ export default class Store {
}
}
return objMap(this.getActions(), actionCreator => bindActionCreators( process( actionCreator ), dispatch ) )
return objMap(actions, actionCreator => bindActionCreators( process( actionCreator ), dispatch ) )
}
getMapStateToProps() {
@@ -333,17 +336,22 @@ function systemExtend(dest={}, src={}) {
// Parses existing components in the system, and prepares them for wrapping via getComponents
if(src.wrapComponents) {
objMap(src.wrapComponents, (wrapperFn, key) => {
const ori = dest.components[key]
const ori = dest.components && dest.components[key]
if(ori && Array.isArray(ori)) {
dest.components[key] = ori.concat([wrapperFn])
delete src.wrapComponents[key]
} else if(ori) {
dest.components[key] = [ori, wrapperFn]
} else {
dest.components[key] = null
delete src.wrapComponents[key]
}
})
delete src.wrapComponents
if(!Object.keys(src.wrapComponents).length) {
// only delete wrapComponents if we've matched all of our wrappers to components
// this handles cases where the component to wrap may be out of our scope,
// but a higher recursive `combinePlugins` call will be able to handle it.
delete src.wrapComponents
}
}
+4 -1
View File
@@ -607,7 +607,10 @@ export const getSampleSchema = (schema, contentType="", config={}) => {
export const parseSearch = () => {
let map = {}
let search = window.location.search
let search = win.location.search
if(!search)
return {}
if ( search != "" ) {
let params = search.substr(1).split("&")
+1 -1
View File
@@ -1,6 +1,6 @@
// Promise global, Used ( at least ) by 'whatwg-fetch'. And required by IE 11
if(!window.Promise) {
if(typeof Promise === "undefined") {
require("core-js/fn/promise")
}
+9 -3
View File
@@ -1,3 +1,5 @@
import React from "react"
import PropTypes from "prop-types"
@@ -32,17 +34,21 @@ export default class StandaloneLayout extends React.Component {
{ Topbar ? <Topbar /> : null }
{ loadingStatus === "loading" &&
<div className="info">
<h4 className="title">Loading...</h4>
<div className="loading-container">
<div className="loading"></div>
</div>
</div>
}
{ loadingStatus === "failed" &&
<div className="info">
<h4 className="title">Failed to load spec.</h4>
<div className="loading-container">
<h4 className="title">Failed to load API definition.</h4>
</div>
</div>
}
{ loadingStatus === "failedConfig" &&
<div className="info" style={{ maxWidth: "880px", marginLeft: "auto", marginRight: "auto", textAlign: "center" }}>
<h4 className="title">Failed to load config.</h4>
<h4 className="title">Failed to load remote configuration.</h4>
</div>
}
{ !loadingStatus || loadingStatus === "success" && <BaseLayout /> }
+5
View File
@@ -653,6 +653,11 @@
.loading-container
{
padding: 40px 0 60px;
margin-top: 1em;
min-height: 1px;
display: flex;
justify-content: center;
.loading
{
position: relative;
+1
View File
@@ -11,6 +11,7 @@
select
{
min-width: 130px;
max-width: 100%;
}
}
+4 -3
View File
@@ -18,6 +18,7 @@ describe("<Models/>", function(){
return components[c]
},
specSelectors: {
isOAS3: () => false,
definitions: function() {
return fromJS({
def1: {},
@@ -31,18 +32,18 @@ describe("<Models/>", function(){
layoutActions: {},
getConfigs: () => ({
docExpansion: "list",
defaultModelExpandDepth: 0
defaultModelsExpandDepth: 0
})
}
it("passes defaultModelExpandDepth to ModelWrapper", function(){
it("passes defaultModelsExpandDepth to ModelWrapper", function(){
// When
let wrapper = shallow(<Models {...props}/>)
// Then should render tabs
expect(wrapper.find("ModelCollapse").length).toEqual(1)
expect(wrapper.find("ModelComponent").length).toBeGreaterThan(0)
expect(wrapper.find("ModelWrapper").length).toBeGreaterThan(0)
wrapper.find("ModelComponent").forEach((modelWrapper) => {
expect(modelWrapper.props().expandDepth).toBe(0)
})
+1
View File
@@ -25,6 +25,7 @@ describe("<ObjectModel />", function() {
}
},
isRef : false,
specPath: [],
schema: Immutable.fromJS(
{
"properties": {
+125
View File
@@ -0,0 +1,125 @@
/* eslint-env mocha */
import React from "react"
import expect, { createSpy } from "expect"
import { render } from "enzyme"
import { fromJS } from "immutable"
import DeepLink from "components/deep-link"
import Operations from "components/operations"
import {Collapse} from "components/layout-utils"
const components = {
Collapse,
DeepLink,
OperationContainer: ({ path, method }) => <span className="mocked-op" id={`${path}-${method}`} />
}
describe("<Operations/>", function(){
it("should render a Swagger2 `get` method, but not a `trace` or `foo` method", function(){
let props = {
fn: {},
specActions: {},
layoutActions: {},
getComponent: (name)=> {
return components[name] || null
},
getConfigs: () => {
return {}
},
specSelectors: {
isOAS3() { return false },
taggedOperations() {
return fromJS({
"default": {
"operations": [
{
"path": "/pets/{id}",
"method": "get"
},
{
"path": "/pets/{id}",
"method": "trace"
},
{
"path": "/pets/{id}",
"method": "foo"
},
]
}
})
},
},
layoutSelectors: {
currentFilter() {
return null
},
isShown() {
return true
},
show() {
return true
}
}
}
let wrapper = render(<Operations {...props}/>)
expect(wrapper.find("span.mocked-op").length).toEqual(1)
expect(wrapper.find("span.mocked-op").eq(0).attr("id")).toEqual("/pets/{id}-get")
})
it("should render an OAS3 `get` and `trace` method, but not a `foo` method", function(){
let props = {
fn: {},
specActions: {},
layoutActions: {},
getComponent: (name)=> {
return components[name] || null
},
getConfigs: () => {
return {}
},
specSelectors: {
isOAS3() { return true },
taggedOperations() {
return fromJS({
"default": {
"operations": [
{
"path": "/pets/{id}",
"method": "get"
},
{
"path": "/pets/{id}",
"method": "trace"
},
{
"path": "/pets/{id}",
"method": "foo"
},
]
}
})
},
},
layoutSelectors: {
currentFilter() {
return null
},
isShown() {
return true
},
show() {
return true
}
}
}
let wrapper = render(<Operations {...props}/>)
expect(wrapper.find("span.mocked-op").length).toEqual(2)
expect(wrapper.find("span.mocked-op").eq(0).attr("id")).toEqual("/pets/{id}-get")
expect(wrapper.find("span.mocked-op").eq(1).attr("id")).toEqual("/pets/{id}-trace")
})
})
+54
View File
@@ -136,4 +136,58 @@ describe("wrapComponents", () => {
expect(children.eq(0).text()).toEqual("Original component")
expect(children.eq(1).text()).toEqual("WOW much data")
})
it("should wrap correctly when registering more plugins", function(){
// Given
const mySystem = new System({
plugins: [
() => {
return {
statePlugins: {
doge: {
selectors: {
wow: () => () => {
return "WOW much data"
}
}
}
},
components: {
wow: () => <div>Original component</div>
}
}
}
]
})
mySystem.register([
function() {
return {
// Wrap the component and use the system
wrapComponents: {
wow: (OriginalComponent, system) => (props) => {
return <container>
<OriginalComponent {...props}></OriginalComponent>
<div>{system.dogeSelectors.wow()}</div>
</container>
}
}
}
}
])
// Then
var Component = mySystem.getSystem().getComponents("wow")
const wrapper = render(<Component name="Normal" />)
const container = wrapper.children().first()
expect(container[0].name).toEqual("container")
const children = container.children()
expect(children.length).toEqual(2)
expect(children.eq(0).text()).toEqual("Original component")
expect(children.eq(1).text()).toEqual("WOW much data")
})
})