+const getExampleComponent = ( sampleResponse, HighlightCode ) => {
+ if (
+ sampleResponse !== undefined &&
+ sampleResponse !== null
+ ) { return
}
@@ -29,20 +21,24 @@ export default class Response extends React.Component {
super(props, context)
this.state = {
- responseContentType: ""
+ responseContentType: "",
}
}
static propTypes = {
+ path: PropTypes.string.isRequired,
+ method: PropTypes.string.isRequired,
code: PropTypes.string.isRequired,
response: PropTypes.instanceOf(Iterable),
className: PropTypes.string,
getComponent: PropTypes.func.isRequired,
getConfigs: PropTypes.func.isRequired,
specSelectors: PropTypes.object.isRequired,
+ oas3Actions: PropTypes.object.isRequired,
specPath: ImPropTypes.list.isRequired,
fn: PropTypes.object.isRequired,
contentType: PropTypes.string,
+ activeExamplesKey: PropTypes.string,
controlsAcceptHeader: PropTypes.bool,
onContentTypeChange: PropTypes.func
}
@@ -61,8 +57,21 @@ export default class Response extends React.Component {
})
}
+ getTargetExamplesKey = () => {
+ const { response, contentType, activeExamplesKey } = this.props
+
+ const activeContentType = this.state.responseContentType || contentType
+ const activeMediaType = response.getIn(["content", activeContentType], Map({}))
+ const examplesForMediaType = activeMediaType.get("examples", null)
+
+ const firstExamplesKey = examplesForMediaType.keySeq().first()
+ return activeExamplesKey || firstExamplesKey
+ }
+
render() {
let {
+ path,
+ method,
code,
response,
className,
@@ -72,14 +81,14 @@ export default class Response extends React.Component {
getConfigs,
specSelectors,
contentType,
- controlsAcceptHeader
+ controlsAcceptHeader,
+ oas3Actions,
} = this.props
let { inferSchema } = fn
- let { isOAS3 } = specSelectors
+ let isOAS3 = specSelectors.isOAS3()
let headers = response.get("headers")
- let examples = response.get("examples")
let links = response.get("links")
const Headers = getComponent("headers")
const HighlightCode = getComponent("highlightCode")
@@ -87,44 +96,53 @@ export default class Response extends React.Component {
const Markdown = getComponent( "Markdown" )
const OperationLink = getComponent("operationLink")
const ContentType = getComponent("contentType")
+ const ExamplesSelect = getComponent("ExamplesSelect")
+ const Example = getComponent("Example")
+
var sampleResponse
- var sampleSchema
var schema, specPathWithPossibleSchema
const activeContentType = this.state.responseContentType || contentType
+ const activeMediaType = response.getIn(["content", activeContentType], Map({}))
+ const examplesForMediaType = activeMediaType.get("examples", null)
- if(isOAS3()) {
- const mediaType = response.getIn(["content", activeContentType], Map({}))
- const oas3SchemaForContentType = mediaType.get("schema", Map({}))
+ // Goal: find a schema value for `schema`
+ if(isOAS3) {
+ const oas3SchemaForContentType = activeMediaType.get("schema", Map({}))
- if(mediaType.get("example") !== undefined) {
- sampleSchema = stringify(mediaType.get("example"))
- } else {
- sampleSchema = getSampleSchema(oas3SchemaForContentType.toJS(), this.state.responseContentType, {
- includeReadOnly: true
- })
- }
- sampleResponse = oas3SchemaForContentType ? sampleSchema : null
schema = oas3SchemaForContentType ? inferSchema(oas3SchemaForContentType.toJS()) : null
specPathWithPossibleSchema = oas3SchemaForContentType ? List(["content", this.state.responseContentType, "schema"]) : specPath
} else {
- schema = inferSchema(response.toJS()) // TODO: don't convert back and forth. Lets just stick with immutable for inferSchema
+ schema = response.get("schema")
specPathWithPossibleSchema = response.has("schema") ? specPath.push("schema") : specPath
- sampleResponse = schema ? getSampleSchema(schema, activeContentType, {
+ }
+
+ // Goal: find an example value for `sampleResponse`
+ if(isOAS3) {
+ const oas3SchemaForContentType = activeMediaType.get("schema", Map({}))
+
+ if(examplesForMediaType) {
+ const targetExamplesKey = this.getTargetExamplesKey()
+ const targetExample = examplesForMediaType.get(targetExamplesKey, Map({}))
+ sampleResponse = stringify(targetExample.get("value"))
+ } else if(activeMediaType.get("example") !== undefined) {
+ // use the example key's value
+ sampleResponse = stringify(activeMediaType.get("example"))
+ } else {
+ // use an example value generated based on the schema
+ sampleResponse = getSampleSchema(oas3SchemaForContentType.toJS(), this.state.responseContentType, {
+ includeReadOnly: true
+ })
+ }
+ } else {
+ sampleResponse = schema ? getSampleSchema(schema.toJS(), activeContentType, {
includeReadOnly: true,
includeWriteOnly: true // writeOnly has no filtering effect in swagger 2.0
}) : null
}
- if(examples) {
- examples = examples.map(example => {
- // Remove unwanted properties from examples
- return example.set ? example.set("$$ref", undefined) : example
- })
- }
-
- let example = getExampleComponent( sampleResponse, examples, HighlightCode )
+ let example = getExampleComponent( sampleResponse, HighlightCode )
return (
@@ -137,20 +155,55 @@ export default class Response extends React.Component {
- { isOAS3 ?
-
-
+
+
+ Media type
+
+
+ {controlsAcceptHeader ? (
+
+ Controls Accept header.
+
+ ) : null}
+
+ {examplesForMediaType ? (
+
+
+ Examples
+
+
+ oas3Actions.setActiveExamplesMember({
+ name: key,
+ pathMethod: [path, method],
+ contextType: "responses",
+ contextName: code
+ })
+ }
+ showLabels={false}
/>
- { controlsAcceptHeader ? Controls Accept header. : null }
-
- : null }
+
+ ) : null}
+
+ ) : null}
- { example ? (
+ { example || schema ? (
+ ) : null }
+
+ { isOAS3 && examplesForMediaType ? (
+
) : null}
{ headers ? (
@@ -167,9 +228,8 @@ export default class Response extends React.Component {
/>
) : null}
-
- {specSelectors.isOAS3() ?
+ {isOAS3 ? |
{ links ?
links.toSeq().map((link, key) => {
return
diff --git a/src/core/components/responses.jsx b/src/core/components/responses.jsx
index 397a2c75..474bfd92 100644
--- a/src/core/components/responses.jsx
+++ b/src/core/components/responses.jsx
@@ -18,6 +18,7 @@ export default class Responses extends React.Component {
specSelectors: PropTypes.object.isRequired,
specActions: PropTypes.object.isRequired,
oas3Actions: PropTypes.object.isRequired,
+ oas3Selectors: PropTypes.object.isRequired,
specPath: ImPropTypes.list.isRequired,
fn: PropTypes.object.isRequired
}
@@ -28,17 +29,20 @@ export default class Responses extends React.Component {
displayRequestDuration: false
}
- shouldComponentUpdate(nextProps) {
- // BUG: props.tryItOutResponse is always coming back as a new Immutable instance
- let render = this.props.tryItOutResponse !== nextProps.tryItOutResponse
- || this.props.responses !== nextProps.responses
- || this.props.produces !== nextProps.produces
- || this.props.producesValue !== nextProps.producesValue
- || this.props.displayRequestDuration !== nextProps.displayRequestDuration
- || this.props.path !== nextProps.path
- || this.props.method !== nextProps.method
- return render
- }
+ // These performance-enhancing checks were disabled as part of Multiple Examples
+ // because they were causing data-consistency issues
+ //
+ // shouldComponentUpdate(nextProps) {
+ // // BUG: props.tryItOutResponse is always coming back as a new Immutable instance
+ // let render = this.props.tryItOutResponse !== nextProps.tryItOutResponse
+ // || this.props.responses !== nextProps.responses
+ // || this.props.produces !== nextProps.produces
+ // || this.props.producesValue !== nextProps.producesValue
+ // || this.props.displayRequestDuration !== nextProps.displayRequestDuration
+ // || this.props.path !== nextProps.path
+ // || this.props.method !== nextProps.method
+ // return render
+ // }
onChangeProducesWrapper = ( val ) => this.props.specActions.changeProducesValue([this.props.path, this.props.method], val)
@@ -64,6 +68,10 @@ export default class Responses extends React.Component {
producesValue,
displayRequestDuration,
specPath,
+ path,
+ method,
+ oas3Selectors,
+ oas3Actions,
} = this.props
let defaultCode = defaultStatusCode( responses )
@@ -121,6 +129,8 @@ export default class Responses extends React.Component {
let className = tryItOutResponse && tryItOutResponse.get("status") == code ? "response_current" : ""
return (
)
}).toArray()
diff --git a/src/core/json-schema-components.jsx b/src/core/json-schema-components.jsx
index 63a4dbfc..e349ee72 100644
--- a/src/core/json-schema-components.jsx
+++ b/src/core/json-schema-components.jsx
@@ -4,7 +4,6 @@ import { List, fromJS } from "immutable"
import cx from "classnames"
import ImPropTypes from "react-immutable-proptypes"
import DebounceInput from "react-debounce-input"
-import { getSampleSchema } from "core/utils"
//import "less/json-schema-form"
const noop = ()=> {}
@@ -18,7 +17,8 @@ const JsonSchemaPropShape = {
errors: ImPropTypes.list,
required: PropTypes.bool,
dispatchInitialValue: PropTypes.bool,
- description: PropTypes.any
+ description: PropTypes.any,
+ disabled: PropTypes.bool,
}
const JsonSchemaDefaultProps = {
@@ -43,7 +43,7 @@ export class JsonSchemaForm extends Component {
}
render() {
- let { schema, errors, value, onChange, getComponent, fn } = this.props
+ let { schema, errors, value, onChange, getComponent, fn, disabled } = this.props
if(schema.toJS)
schema = schema.toJS()
@@ -51,7 +51,7 @@ export class JsonSchemaForm extends Component {
let { type, format="" } = schema
let Comp = (format ? getComponent(`JsonSchema_${type}_${format}`) : getComponent(`JsonSchema_${type}`)) || getComponent("JsonSchema_string")
- return
+ return
}
}
@@ -65,7 +65,7 @@ export class JsonSchema_string extends Component {
}
onEnumChange = (val) => this.props.onChange(val)
render() {
- let { getComponent, value, schema, errors, required, description } = this.props
+ let { getComponent, value, schema, errors, required, description, disabled } = this.props
let enumValue = schema["enum"]
errors = errors.toJS ? errors.toJS() : []
@@ -80,7 +80,7 @@ export class JsonSchema_string extends Component {
onChange={ this.onEnumChange }/>)
}
- const isDisabled = schema["in"] === "formData" && !("FormData" in window)
+ const isDisabled = disabled || (schema["in"] === "formData" && !("FormData" in window))
const Input = getComponent("Input")
if (schema["type"] === "file") {
return ()
}
return (
-
+
{ !value || !value.count || value.count() < 1 ? null :
value.map( (item,i) => {
let schema = Object.assign({}, itemSchema)
@@ -183,13 +184,32 @@ export class JsonSchema_array extends PureComponent {
}
return (
- this.onItemChange(val, i)} schema={schema} />
-
+ this.onItemChange(val, i)}
+ schema={schema}
+ disabled={disabled}
+ />
+ { !disabled ? (
+
+ ) : null }
)
}).toArray()
}
-
+ { !disabled ? (
+
+ ) : null }
)
}
@@ -201,7 +221,7 @@ export class JsonSchema_boolean extends Component {
onEnumChange = (val) => this.props.onChange(val)
render() {
- let { getComponent, value, errors, schema, required } = this.props
+ let { getComponent, value, errors, schema, required, disabled } = this.props
errors = errors.toJS ? errors.toJS() : []
const Select = getComponent("Select")
@@ -209,6 +229,7 @@ export class JsonSchema_boolean extends Component {
return ( )
@@ -223,16 +244,6 @@ export class JsonSchema_object extends PureComponent {
static propTypes = JsonSchemaPropShape
static defaultProps = JsonSchemaDefaultProps
- componentDidMount() {
- if(!this.props.value && this.props.schema) {
- this.resetValueToSample()
- }
- }
-
- resetValueToSample = () => {
- this.onChange(getSampleSchema(this.props.schema) )
- }
-
onChange = (value) => {
this.props.onChange(value)
}
@@ -247,7 +258,8 @@ export class JsonSchema_object extends PureComponent {
let {
getComponent,
value,
- errors
+ errors,
+ disabled
} = this.props
const TextArea = getComponent("TextArea")
@@ -258,6 +270,7 @@ export class JsonSchema_object extends PureComponent {
className={cx({ invalid: errors.size })}
title={ errors.size ? errors.join(", ") : ""}
value={value}
+ disabled={disabled}
onChange={ this.handleOnChange }/>
)
@@ -267,4 +280,4 @@ export class JsonSchema_object extends PureComponent {
function valueOrEmptyList(value) {
return List.isList(value) ? value : List()
-}
\ No newline at end of file
+}
diff --git a/src/core/plugins/oas3/actions.js b/src/core/plugins/oas3/actions.js
index ac6f244a..0985c784 100644
--- a/src/core/plugins/oas3/actions.js
+++ b/src/core/plugins/oas3/actions.js
@@ -3,6 +3,7 @@
export const UPDATE_SELECTED_SERVER = "oas3_set_servers"
export const UPDATE_REQUEST_BODY_VALUE = "oas3_set_request_body_value"
+export const UPDATE_ACTIVE_EXAMPLES_MEMBER = "oas3_set_active_examples_member"
export const UPDATE_REQUEST_CONTENT_TYPE = "oas3_set_request_content_type"
export const UPDATE_RESPONSE_CONTENT_TYPE = "oas3_set_response_content_type"
export const UPDATE_SERVER_VARIABLE_VALUE = "oas3_set_server_variable_value"
@@ -21,6 +22,13 @@ export function setRequestBodyValue ({ value, pathMethod }) {
}
}
+export function setActiveExamplesMember ({ name, pathMethod, contextType, contextName }) {
+ return {
+ type: UPDATE_ACTIVE_EXAMPLES_MEMBER,
+ payload: { name, pathMethod, contextType, contextName }
+ }
+}
+
export function setRequestContentType ({ value, pathMethod }) {
return {
type: UPDATE_REQUEST_CONTENT_TYPE,
diff --git a/src/core/plugins/oas3/components/request-body-editor.jsx b/src/core/plugins/oas3/components/request-body-editor.jsx
index c4af8096..6d6d09d2 100644
--- a/src/core/plugins/oas3/components/request-body-editor.jsx
+++ b/src/core/plugins/oas3/components/request-body-editor.jsx
@@ -1,24 +1,19 @@
import React, { PureComponent } from "react"
import PropTypes from "prop-types"
-import { fromJS } from "immutable"
-import { getSampleSchema, stringify } from "core/utils"
+import { stringify } from "core/utils"
const NOOP = Function.prototype
export default class RequestBodyEditor extends PureComponent {
static propTypes = {
- requestBody: PropTypes.object.isRequired,
- mediaType: PropTypes.string.isRequired,
onChange: PropTypes.func,
getComponent: PropTypes.func.isRequired,
- isExecute: PropTypes.bool,
- specSelectors: PropTypes.object.isRequired,
+ value: PropTypes.string,
+ defaultValue: PropTypes.string,
};
static defaultProps = {
- mediaType: "application/json",
- requestBody: fromJS({}),
onChange: NOOP,
};
@@ -26,108 +21,75 @@ export default class RequestBodyEditor extends PureComponent {
super(props, context)
this.state = {
- isEditBox: false,
- userDidModify: false,
- value: ""
- }
- }
-
- componentDidMount() {
- this.setValueToSample.call(this)
- }
-
- componentWillReceiveProps(nextProps) {
- if(this.props.mediaType !== nextProps.mediaType) {
- // media type was changed
- this.setValueToSample(nextProps.mediaType)
+ value: stringify(props.value) || props.defaultValue
}
- if(!this.props.isExecute && nextProps.isExecute) {
- // we just entered execute mode,
- // so enable editing for convenience
- this.setState({ isEditBox: true })
- }
+ // this is the glue that makes sure our initial value gets set as the
+ // current request body value
+ // TODO: achieve this in a selector instead
+ props.onChange(props.value)
}
- componentDidUpdate(prevProps) {
- if(this.props.requestBody !== prevProps.requestBody) {
- // force recalc of value if the request body definition has changed
- this.setValueToSample(this.props.mediaType)
- }
- }
+ applyDefaultValue = (nextProps) => {
+ const { onChange, defaultValue } = (nextProps ? nextProps : this.props)
- setValueToSample = (explicitMediaType) => {
- this.onChange(this.sample(explicitMediaType))
- }
-
- resetValueToSample = (explicitMediaType) => {
- this.setState({ userDidModify: false })
- this.setValueToSample(explicitMediaType)
- }
-
- sample = (explicitMediaType) => {
- let { requestBody, mediaType } = this.props
- let mediaTypeValue = requestBody.getIn(["content", explicitMediaType || mediaType])
- let schema = mediaTypeValue.get("schema").toJS()
- let mediaTypeExample = mediaTypeValue.get("example") !== undefined ? stringify(mediaTypeValue.get("example")) : null
-
- return mediaTypeExample || getSampleSchema(schema, explicitMediaType || mediaType, {
- includeWriteOnly: true
+ this.setState({
+ value: defaultValue
})
+
+ return onChange(defaultValue)
}
onChange = (value) => {
- this.setState({value})
- this.props.onChange(value)
+ this.props.onChange(stringify(value))
}
- handleOnChange = e => {
- const { mediaType } = this.props
- const isJson = /json/i.test(mediaType)
- const inputValue = isJson ? e.target.value.trim() : e.target.value
+ onDomChange = e => {
+ const inputValue = e.target.value
- this.setState({ userDidModify: true })
- this.onChange(inputValue)
+ this.setState({
+ value: inputValue,
+ }, () => this.onChange(inputValue))
}
- toggleIsEditBox = () => this.setState( state => ({isEditBox: !state.isEditBox}))
+ componentWillReceiveProps(nextProps) {
+ if(
+ this.props.value !== nextProps.value &&
+ nextProps.value !== this.state.value
+ ) {
+
+ this.setState({
+ value: stringify(nextProps.value)
+ })
+ }
+
+
+
+ if(!nextProps.value && nextProps.defaultValue && !!this.state.value) {
+ // if new value is falsy, we have a default, AND the falsy value didn't
+ // come from us originally
+ this.applyDefaultValue(nextProps)
+ }
+ }
render() {
let {
- isExecute,
- getComponent,
- mediaType,
+ getComponent
} = this.props
- const Button = getComponent("Button")
- const TextArea = getComponent("TextArea")
- const HighlightCode = getComponent("highlightCode")
+ let {
+ value
+ } = this.state
- let { value, isEditBox, userDidModify } = this.state
+ const TextArea = getComponent("TextArea")
return (
- {
- isEditBox && isExecute
- ?
- : (value && )
- }
-
-
- {
- !isExecute ? null
- :
-
- }
- { userDidModify &&
-
- }
-
-
-
+
)
diff --git a/src/core/plugins/oas3/components/request-body.jsx b/src/core/plugins/oas3/components/request-body.jsx
index 15d3c45a..00b5d97d 100644
--- a/src/core/plugins/oas3/components/request-body.jsx
+++ b/src/core/plugins/oas3/components/request-body.jsx
@@ -4,6 +4,36 @@ import ImPropTypes from "react-immutable-proptypes"
import { Map, OrderedMap, List } from "immutable"
import { getCommonExtensions, getSampleSchema, stringify } from "core/utils"
+function getDefaultRequestBodyValue(requestBody, mediaType, activeExamplesKey) {
+ let mediaTypeValue = requestBody.getIn(["content", mediaType])
+ let schema = mediaTypeValue.get("schema").toJS()
+ let example =
+ mediaTypeValue.get("example") !== undefined
+ ? stringify(mediaTypeValue.get("example"))
+ : null
+ let currentExamplesValue = mediaTypeValue.getIn([
+ "examples",
+ activeExamplesKey,
+ "value"
+ ])
+
+ if (mediaTypeValue.get("examples")) {
+ // the media type DOES have examples
+ return stringify(currentExamplesValue) || ""
+ } else {
+ // the media type DOES NOT have examples
+ return stringify(
+ example ||
+ getSampleSchema(schema, mediaType, {
+ includeWriteOnly: true
+ }) ||
+ ""
+ )
+ }
+}
+
+
+
const RequestBody = ({
requestBody,
requestBodyValue,
@@ -14,7 +44,9 @@ const RequestBody = ({
contentType,
isExecute,
specPath,
- onChange
+ onChange,
+ activeExamplesKey,
+ updateActiveExamplesKey,
}) => {
const handleFile = (e) => {
onChange(e.target.files[0])
@@ -23,6 +55,9 @@ const RequestBody = ({
const Markdown = getComponent("Markdown")
const ModelExample = getComponent("modelExample")
const RequestBodyEditor = getComponent("RequestBodyEditor")
+ const HighlightCode = getComponent("highlightCode")
+ const ExamplesSelectValueRetainer = getComponent("ExamplesSelectValueRetainer")
+ const Example = getComponent("Example")
const { showCommonExtensions } = getConfigs()
@@ -32,6 +67,11 @@ const RequestBody = ({
const mediaTypeValue = requestBodyContent.get(contentType, OrderedMap())
const schemaForMediaType = mediaTypeValue.get("schema", OrderedMap())
+ const examplesForMediaType = mediaTypeValue.get("examples", OrderedMap())
+
+ const handleExamplesSelect = (key /*, { isSyntheticChange } */) => {
+ updateActiveExamplesKey(key)
+ }
if(!mediaTypeValue.size) {
return null
@@ -83,7 +123,7 @@ const RequestBody = ({
const format = prop.get("format")
const description = prop.get("description")
const currentValue = requestBodyValue.get(key)
-
+
let initialValue = prop.get("default") || prop.get("example") || ""
if (initialValue === "" && type === "object") {
@@ -139,23 +179,63 @@ const RequestBody = ({
{ requestBodyDescription &&
}
- }
- />
+ {
+ examplesForMediaType ? (
+
+ ) : null
+ }
+ {
+ isExecute ? (
+
+
+
+ ) : (
+
+ }
+ />
+ )
+ }
+ {
+ examplesForMediaType ? (
+
+ ) : null
+ }
}
@@ -169,7 +249,9 @@ RequestBody.propTypes = {
contentType: PropTypes.string,
isExecute: PropTypes.bool.isRequired,
onChange: PropTypes.func.isRequired,
- specPath: PropTypes.array.isRequired
+ specPath: PropTypes.array.isRequired,
+ activeExamplesKey: PropTypes.string,
+ updateActiveExamplesKey: PropTypes.func,
}
export default RequestBody
diff --git a/src/core/plugins/oas3/reducers.js b/src/core/plugins/oas3/reducers.js
index 871aff89..c37b637a 100644
--- a/src/core/plugins/oas3/reducers.js
+++ b/src/core/plugins/oas3/reducers.js
@@ -1,6 +1,7 @@
import {
UPDATE_SELECTED_SERVER,
UPDATE_REQUEST_BODY_VALUE,
+ UPDATE_ACTIVE_EXAMPLES_MEMBER,
UPDATE_REQUEST_CONTENT_TYPE,
UPDATE_SERVER_VARIABLE_VALUE,
UPDATE_RESPONSE_CONTENT_TYPE
@@ -15,6 +16,10 @@ export default {
let [path, method] = pathMethod
return state.setIn( [ "requestData", path, method, "bodyValue" ], value)
},
+ [UPDATE_ACTIVE_EXAMPLES_MEMBER]: (state, { payload: { name, pathMethod, contextType, contextName } } ) =>{
+ let [path, method] = pathMethod
+ return state.setIn( [ "examples", path, method, contextType, contextName, "activeExample" ], name)
+ },
[UPDATE_REQUEST_CONTENT_TYPE]: (state, { payload: { value, pathMethod } } ) =>{
let [path, method] = pathMethod
return state.setIn( [ "requestData", path, method, "requestContentType" ], value)
diff --git a/src/core/plugins/oas3/selectors.js b/src/core/plugins/oas3/selectors.js
index c65a6882..432831e2 100644
--- a/src/core/plugins/oas3/selectors.js
+++ b/src/core/plugins/oas3/selectors.js
@@ -26,6 +26,11 @@ export const requestBodyValue = onlyOAS3((state, path, method) => {
}
)
+export const activeExamplesMember = onlyOAS3((state, path, method, type, name) => {
+ return state.getIn(["examples", path, method, type, name, "activeExample"]) || null
+ }
+)
+
export const requestContentType = onlyOAS3((state, path, method) => {
return state.getIn(["requestData", path, method, "requestContentType"]) || null
}
diff --git a/src/core/plugins/oas3/wrap-components/index.js b/src/core/plugins/oas3/wrap-components/index.js
index fd0c99f5..2c421add 100644
--- a/src/core/plugins/oas3/wrap-components/index.js
+++ b/src/core/plugins/oas3/wrap-components/index.js
@@ -1,6 +1,5 @@
import Markdown from "./markdown"
import AuthItem from "./auth-item"
-import parameters from "./parameters"
import VersionStamp from "./version-stamp"
import OnlineValidatorBadge from "./online-validator-badge"
import Model from "./model"
@@ -9,7 +8,6 @@ import JsonSchema_string from "./json-schema-string"
export default {
Markdown,
AuthItem,
- parameters,
JsonSchema_string,
VersionStamp,
model: Model,
diff --git a/src/core/presets/base.js b/src/core/presets/base.js
index cff809cd..015cd80d 100644
--- a/src/core/presets/base.js
+++ b/src/core/presets/base.js
@@ -25,6 +25,9 @@ import AuthItem from "core/components/auth/auth-item"
import AuthError from "core/components/auth/error"
import ApiKeyAuth from "core/components/auth/api-key-auth"
import BasicAuth from "core/components/auth/basic-auth"
+import Example from "core/components/example"
+import ExamplesSelect from "core/components/examples-select"
+import ExamplesSelectValueRetainer from "core/components/examples-select-value-retainer"
import Oauth2 from "core/components/auth/oauth2"
import Clear from "core/components/clear"
import LiveResponse from "core/components/live-response"
@@ -41,7 +44,7 @@ import HighlightCode from "core/components/highlight-code"
import Responses from "core/components/responses"
import Response from "core/components/response"
import ResponseBody from "core/components/response-body"
-import Parameters from "core/components/parameters"
+import { Parameters } from "core/components/parameters"
import ParameterExt from "core/components/parameter-extension"
import ParameterIncludeEmpty from "core/components/parameter-include-empty"
import ParameterRow from "core/components/parameter-row"
@@ -152,7 +155,10 @@ export default function() {
DeepLink,
InfoUrl,
InfoBasePath,
- SvgAssets
+ SvgAssets,
+ Example,
+ ExamplesSelect,
+ ExamplesSelectValueRetainer,
}
}
diff --git a/src/core/utils.js b/src/core/utils.js
index ccc27c36..ffbb2948 100644
--- a/src/core/utils.js
+++ b/src/core/utils.js
@@ -780,7 +780,7 @@ export function stringify(thing) {
return thing
}
- if (thing.toJS) {
+ if (thing && thing.toJS) {
thing = thing.toJS()
}
@@ -793,6 +793,10 @@ export function stringify(thing) {
}
}
+ if(thing === null || thing === undefined) {
+ return ""
+ }
+
return thing.toString()
}
diff --git a/src/style/_form.scss b/src/style/_form.scss
index be712eba..939f4d40 100644
--- a/src/style/_form.scss
+++ b/src/style/_form.scss
@@ -70,6 +70,27 @@ textarea
{
@include invalidFormElement();
}
+
+}
+
+input,
+textarea,
+select {
+ &[disabled] {
+ // opacity: 0.85;
+ background-color: #fafafa;
+ color: #888;
+ cursor: not-allowed;
+ }
+}
+
+select[disabled] {
+ border-color: #888;
+}
+
+textarea[disabled] {
+ background-color: #41444e;
+ color: #fff;
}
@keyframes shake
diff --git a/src/style/_layout.scss b/src/style/_layout.scss
index 474ef7a2..bfcfdafe 100644
--- a/src/style/_layout.scss
+++ b/src/style/_layout.scss
@@ -98,6 +98,51 @@
@include text_code();
}
+.parameter-controls {
+ margin-top: 0.75em;
+}
+
+.examples {
+ &__title {
+ display: block;
+ font-size: 1.1em;
+ font-weight: bold;
+ margin-bottom: 0.75em;
+ }
+
+ &__section {
+ margin-top: 1.5em;
+ }
+ &__section-header {
+ font-weight: bold;
+ font-size: .9rem;
+ margin-bottom: .5rem;
+ // color: #555;
+ }
+}
+
+.examples-select {
+ margin-bottom: .75em;
+
+ &__section-label {
+ font-weight: bold;
+ font-size: .9rem;
+ margin-right: .5rem;
+ }
+}
+
+.example {
+ &__section {
+ margin-top: 1.5em;
+ }
+ &__section-header {
+ font-weight: bold;
+ font-size: .9rem;
+ margin-bottom: .5rem;
+ // color: #555;
+ }
+}
+
.view-line-link
{
position: relative;
@@ -374,12 +419,14 @@
}
}
+.model-example {
+ margin-top: 1em;
+}
.tab
{
display: flex;
- margin: 20px 0 10px 0;
padding: 0;
list-style: none;
@@ -538,46 +585,6 @@
}
}
-.response-col_description__inner
-{
- div.markdown, div.renderedMarkdown
- {
- font-size: 12px;
- font-style: italic;
-
- display: block;
-
- margin: 0;
- padding: 10px;
-
- border-radius: 4px;
- background: $response-col-description-inner-markdown-background-color;
-
- @include text_code($response-col-description-inner-markdown-font-color);
-
- p
- {
- margin: 0;
- @include text_code($response-col-description-inner-markdown-font-color);
- }
-
- a
- {
- @include text_code($response-col-description-inner-markdown-link-font-color);
- text-decoration: underline;
- &:hover {
- color: $response-col-description-inner-markdown-link-font-color-hover;
- }
- }
-
- th
- {
- @include text_code($response-col-description-inner-markdown-font-color);
- border-bottom: 1px solid $response-col-description-inner-markdown-font-color;
- }
- }
-}
-
.opblock-body
{
.opblock-loading-animation
@@ -744,19 +751,38 @@
}
}
-.response-content-type {
- padding-top: 1em;
+.response-controls {
+ padding-top: 1em;
+ display: flex;
+}
- &.controls-accept-header {
- select {
- border-color: $response-content-type-controls-accept-header-select-border-color;
+.response-control-media-type {
+ margin-right: 1em;
+
+ &--accept-controller {
+ select {
+ border-color: $response-content-type-controls-accept-header-select-border-color;
+ }
}
- small {
- color: $response-content-type-controls-accept-header-small-font-color;
- font-size: .7em;
+ &__accept-message {
+ color: $response-content-type-controls-accept-header-small-font-color;
+ font-size: .7em;
+ }
+
+ &__title {
+ display: block;
+ margin-bottom: 0.2em;
+ font-size: .7em;
+ }
+}
+
+.response-control-examples {
+ &__title {
+ display: block;
+ margin-bottom: 0.2em;
+ font-size: .7em;
}
- }
}
@keyframes blinker
diff --git a/src/style/_table.scss b/src/style/_table.scss
index 95414542..99c313c1 100644
--- a/src/style/_table.scss
+++ b/src/style/_table.scss
@@ -84,6 +84,8 @@ table
.parameters-col_description
{
+ width: 99%; // forces other columns to shrink to their content widths
+ margin-bottom: 2em;
input[type=text]
{
width: 100%;
@@ -100,6 +102,10 @@ table
font-size: 16px;
font-weight: normal;
+ // hack to give breathing room to the name column
+ // TODO: refactor all of this to flexbox
+ margin-right: .75em;
+
@include text_headline();
&.required
@@ -158,3 +164,12 @@ table
{
padding: 20px;
}
+
+
+.response-col_description {
+ width: 99%; // forces other columns to shrink to their content widths
+}
+
+.response-col_links {
+ min-width: 6em;
+}
diff --git a/src/style/_variables.scss b/src/style/_variables.scss
index 3ef325cd..8adf2dd8 100644
--- a/src/style/_variables.scss
+++ b/src/style/_variables.scss
@@ -127,12 +127,6 @@ $response-col-status-undocumented-font-color: $gray-300 !default;
$response-col-links-font-color: $gray-300 !default;
-$response-col-description-inner-markdown-font-color: $white !default;
-$response-col-description-inner-markdown-background-color: $gray-custom-1 !default;
-
-$response-col-description-inner-markdown-link-font-color: $color-primary !default;
-$response-col-description-inner-markdown-link-font-color-hover: $color-primary-hover !default;
-
$opblock-body-background-color: $gray-custom-1 !default;
$opblock-body-font-color: $white !default;
diff --git a/test/e2e-cypress/helpers/multiple-examples.js b/test/e2e-cypress/helpers/multiple-examples.js
new file mode 100644
index 00000000..4a98b519
--- /dev/null
+++ b/test/e2e-cypress/helpers/multiple-examples.js
@@ -0,0 +1,679 @@
+module.exports = {
+ ParameterPrimitiveTestCases,
+ RequestBodyPrimitiveTestCases,
+ ResponsePrimitiveTestCases,
+}
+
+function ParameterPrimitiveTestCases({
+operationDomId,
+ parameterName,
+ exampleA, // { value, key }
+ exampleB, // { value, key }
+ exampleC,
+ customUserInput,
+ customExpectedUrlSubstring,
+}) {
+ it("should render examples options without Modified Value by default", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ .get(operationDomId)
+ .click()
+ .get(`tr[data-param-name="${parameterName}"]`)
+ .find(".examples-select option")
+ .should("have.length", exampleC ? 3 : 2)
+ // Ensure the relevant input is disabled
+ .get(
+ `tr[data-param-name="${parameterName}"] input, tr[data-param-name="${parameterName}"] textarea`
+ )
+ .should("have.attr", "disabled")
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ .get(`.opblock-section-request-body`)
+ .find(".examples-select option")
+ .should("have.length", exampleC ? 3 : 2)
+ })
+
+ it("should set default static and Try-It-Out values based on the first member", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Assert on the static docs value
+ .get(
+ `tr[data-param-name="${parameterName}"] input,tr[data-param-name="${parameterName}"] textarea`
+ )
+ .should("have.value", exampleA.value)
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Assert on the Try-It-Out value
+ .get(
+ `tr[data-param-name="${parameterName}"] input,tr[data-param-name="${parameterName}"] textarea`
+ )
+ .should("have.value", exampleA.value)
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ .get(".request-url")
+ .contains(
+ exampleA.serializedValue || `?message=${escape(exampleA.value)}`
+ )
+ })
+
+ it("should set static and Try-It-Out values based on the second member", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Choose the second example
+ .get("table.parameters .examples-select > select")
+ .select(exampleB.key)
+ // Assert on the static docs value
+ .get(
+ `tr[data-param-name="${parameterName}"] input,tr[data-param-name="${parameterName}"] textarea`
+ )
+ .should("have.value", exampleB.value)
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Assert on the Try-It-Out value
+ .get(
+ `tr[data-param-name="${parameterName}"] input,tr[data-param-name="${parameterName}"] textarea`
+ )
+ .should("have.value", exampleB.value)
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ .get(".request-url")
+ .contains(
+ exampleB.serializedValue
+ ? `?${exampleB.serializedValue}`
+ : `?message=${escape(exampleB.value)}`
+ )
+ })
+
+ it("should handle user-entered values correctly", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Modify the input value
+ .get(
+ `tr[data-param-name="${parameterName}"] input,tr[data-param-name="${parameterName}"] textarea`
+ )
+ .clear()
+ .type(customUserInput)
+ // Assert on the active select menu item
+ .get("table.parameters .examples-select > select")
+ .find(":selected")
+ .should("have.text", "[Modified value]")
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ .get(".request-url")
+ .contains(
+ customExpectedUrlSubstring || `?message=${escape(customUserInput)}`
+ )
+ })
+
+ it("should retain user-entered values correctly", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Modify the input value
+ .get(
+ `tr[data-param-name="${parameterName}"] input,tr[data-param-name="${parameterName}"] textarea`
+ )
+ .clear()
+ .type(customUserInput)
+ // Select the first example
+ .get("table.parameters .examples-select > select")
+ .select(exampleA.key)
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ .get(".request-url")
+ .contains(
+ exampleA.serializedValue
+ ? `?${exampleA.serializedValue}`
+ : `?message=${escape(exampleA.value)}`
+ )
+ // Select the modified value
+ .get("table.parameters .examples-select > select")
+ .select("__MODIFIED__VALUE__")
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ .get(".request-url")
+ .contains(
+ customExpectedUrlSubstring || `?message=${escape(customUserInput)}`
+ )
+ })
+}
+
+function RequestBodyPrimitiveTestCases({
+ operationDomId,
+ exampleA, // { value, key, summary }
+ exampleB, // { value, key, summary }
+ exampleC,
+ customUserInput,
+ customUserInputExpectedCurlSubstring,
+ primaryMediaType = "text/plain",
+ secondaryMediaType = "text/plain+other",
+}) {
+ it("should render examples options without Modified Value by default", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ .get(operationDomId)
+ .click()
+ .get(`.opblock-section-request-body`)
+ .find(".examples-select option")
+ .should("have.length", exampleC ? 3 : 2)
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ .get(`.opblock-section-request-body`)
+ .find(".examples-select option")
+ .should("have.length", exampleC ? 3 : 2)
+ })
+
+ it("should set default static and Try-It-Out values based on the first member", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleA.value)
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Assert on the Try-It-Out value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.value", exampleA.value)
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the curl body
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(`-d "${exampleA.serializedValue || exampleA.value}"`)
+ })
+
+ it("should set default static and Try-It-Out values based on choosing the second member in static mode", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Choose the second example
+ .get(".opblock-section-request-body .examples-select > select")
+ .select(exampleB.key)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleB.value)
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Assert on the Try-It-Out value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.value", exampleB.value)
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(`-d "${exampleB.serializedValue || exampleB.value}"`)
+ })
+
+ it("should set default static and Try-It-Out values based on choosing the second member in Try-It-Out mode", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Choose the second example
+ .get(".opblock-section-request-body .examples-select > select")
+ .select(exampleB.key)
+ // Assert on the Try-It-Out value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.value", exampleB.value)
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(`-d "${exampleB.serializedValue || exampleB.value}"`)
+ // Switch to static docs
+ .get(".try-out__btn")
+ .click()
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleB.value)
+ })
+
+ it("should return the dropdown entry for an example when manually returning to its value", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleA.value)
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Assert on the Try-It-Out value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.value", exampleA.value)
+ // Clear the Try-It-Out value, replace it with custom value
+ .clear()
+ .type(customUserInput)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "[Modified value]")
+ // Modify the value again, going back to the example value
+ .get(`.opblock-section-request-body textarea`)
+ .clear()
+ .type(exampleA.value)
+ // Assert on the dropdown value returning to the example value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleA.summary)
+ })
+
+ it("should retain choosing a member in static docs when changing the media type", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Choose the second example
+ .get(".opblock-section-request-body .examples-select > select")
+ .select(exampleB.key)
+ // Change the media type
+ .get(".opblock-section-request-body .content-type")
+ .select(secondaryMediaType)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleB.value)
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Assert on the Try-It-Out value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.value", exampleB.value)
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(`-d "${exampleB.serializedValue || exampleB.value}"`)
+ })
+
+ it("should use the first example for the media type when changing the media type without prior interactions with the value", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Change the media type
+ .get(".opblock-section-request-body .content-type")
+ .select(secondaryMediaType)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleA.value)
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Assert on the Try-It-Out value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.value", exampleA.value)
+ // Execute the operation
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(`-d "${exampleA.serializedValue || exampleA.value}"`)
+ })
+
+ it("static mode toggling: mediaType -> example -> mediaType -> example", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Change the media type
+ .get(".opblock-section-request-body .content-type")
+ .select(secondaryMediaType)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleA.value)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleA.summary)
+
+ // Choose exampleB
+ .get(".opblock-section-request-body .examples-select > select")
+ .select(exampleB.key)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleB.value)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleB.summary)
+
+ // Change the media type
+ .get(".opblock-section-request-body .content-type")
+ .select(primaryMediaType)
+ // Assert that the static docs value didn't change
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleB.value)
+ // Assert that the dropdown value didn't change
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleB.summary)
+
+ // Choose exampleA
+ .get(".opblock-section-request-body .examples-select > select")
+ .select(exampleA.key)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body .microlight`)
+ .should("have.text", exampleA.value)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleA.summary)
+ })
+
+ it("Try-It-Out toggling: mediaType -> example -> mediaType -> example", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Change the media type
+ .get(".opblock-section-request-body .content-type")
+ .select(secondaryMediaType)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.text", exampleA.value)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleA.summary)
+
+ // Choose exampleB
+ .get(".opblock-section-request-body .examples-select > select")
+ .select(exampleB.key)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.text", exampleB.value)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleB.summary)
+
+ // Change the media type
+ .get(".opblock-section-request-body .content-type")
+ .select(primaryMediaType)
+ // Assert that the static docs value didn't change
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.text", exampleB.value)
+ // Assert that the dropdown value didn't change
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleB.summary)
+
+ // Choose exampleA
+ .get(".opblock-section-request-body .examples-select > select")
+ .select(exampleA.key)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.text", exampleA.value)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleA.summary)
+ })
+
+ it("Try-It-Out toggling and execution with modified values: mediaType -> modified value -> example -> mediaType -> example", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ // Expand the operation
+ .get(operationDomId)
+ .click()
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Change the media type
+ .get(".opblock-section-request-body .content-type")
+ .select(secondaryMediaType)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.text", exampleA.value)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleA.summary)
+
+ // Modify the value
+ .get(`.opblock-section-request-body textarea`)
+ .clear()
+ .type(customUserInput)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "[Modified value]")
+ // Fire the operation
+ .get(".execute")
+ .click()
+ // Assert on the curl body
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(
+ `-d "${customUserInputExpectedCurlSubstring || customUserInput}"`
+ )
+
+ // Choose exampleB
+ .get(".opblock-section-request-body .examples-select > select")
+ .select(exampleB.key)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.text", exampleB.value)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleB.summary)
+ // Fire the operation
+ .get(".execute")
+ .click()
+ // Assert on the curl body
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(`-d "${exampleB.serializedValue || exampleB.value}"`)
+
+ // Ensure the modified value is still accessible
+ .get(".opblock-section-request-body .examples-select > select")
+ .contains("[Modified value]")
+
+ // Change the media type to text/plain
+ .get(".opblock-section-request-body .content-type")
+ .select(primaryMediaType)
+ // Assert that the static docs value didn't change
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.text", exampleB.value)
+ // Assert that the dropdown value didn't change
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleB.summary)
+ // Fire the operation
+ .get(".execute")
+ .click()
+ // Assert on the curl body
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(`-d "${exampleB.serializedValue || exampleB.value}"`)
+
+ // Ensure the modified value is still accessible
+ .get(".opblock-section-request-body .examples-select > select")
+ .contains("[Modified value]")
+
+ // Choose exampleA
+ .get(".opblock-section-request-body .examples-select > select")
+ .select(exampleA.key)
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.text", exampleA.value)
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleA.summary)
+ // Fire the operation
+ .get(".execute")
+ .click()
+ // Assert on the curl body
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(`-d "${exampleA.serializedValue || exampleA.value}"`)
+
+ // Ensure the modified value is still the same value
+ .get(".opblock-section-request-body .examples-select > select")
+ .select("__MODIFIED__VALUE__")
+ // Assert on the static docs value
+ .get(`.opblock-section-request-body textarea`)
+ .should("have.text", customUserInput.replace(/{{}/g, "{"))
+ // Assert on the dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "[Modified value]")
+ // Fire the operation
+ .get(".execute")
+ .click()
+ // Assert on the curl body
+ // TODO: use an interceptor instead of curl
+ .get(".curl")
+ .contains(
+ `-d "${customUserInputExpectedCurlSubstring || customUserInput}"`
+ )
+ })
+
+ // TODO: Try-It-Out + Try-It-Out media type changes
+}
+
+function ResponsePrimitiveTestCases({
+ operationDomId,
+ exampleA, // { value, key, summary }
+ exampleB, // { value, key, summary }
+ exampleC, // { value, key, summary }
+}) {
+ it("should render the first example by default", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ .get(operationDomId)
+ .click()
+ .get(".responses-wrapper")
+ .within(() => {
+ cy.get(".examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleA.summary)
+ .get(".microlight")
+ .should("have.text", exampleA.value)
+ })
+ })
+ it("should render the second example", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ .get(operationDomId)
+ .click()
+ .get(".responses-wrapper")
+ .within(() => {
+ cy.get(".examples-select > select")
+ .select(exampleB.key)
+ .find(":selected")
+ .should("have.text", exampleB.summary)
+ .get(".microlight")
+ .should("have.text", exampleB.value)
+ })
+ })
+
+ it("should retain an example choice across media types if they share the same example", () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ .get(operationDomId)
+ .click()
+ .get(".responses-wrapper")
+ .within(() => {
+ cy
+ // Change examples
+ .get(".examples-select > select")
+ .select(exampleB.key)
+ // Assert against dropdown value
+ .find(":selected")
+ .should("have.text", exampleB.summary)
+ // Assert against example value
+ .get(".microlight")
+ .should("have.text", exampleB.value)
+
+ // Change media types
+ .get(".content-type")
+ .select("text/plain+other")
+ // Assert against dropdown value
+ .get(".examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleB.summary)
+ // Assert against example value
+ .get(".microlight")
+ .should("have.text", exampleB.value)
+ })
+ })
+ ;(exampleC ? it : it.skip)(
+ "should reset to the first example if the new media type lacks the current example",
+ () => {
+ cy.visit("/?url=/documents/features/multiple-examples-core.openapi.yaml")
+ .get(operationDomId)
+ .click()
+ .get(".responses-wrapper")
+ .within(() => {
+ cy
+ // Change media types
+ .get(".content-type")
+ .select("text/plain+other")
+ // Change examples
+ .get(".examples-select > select")
+ .select(exampleC.key)
+ // Assert against dropdown value
+ .find(":selected")
+ .should("have.text", exampleC.summary || exampleC.key)
+ // Assert against example value
+ .get(".microlight")
+ .should("have.text", exampleC.value)
+
+ // Change media types
+ .get(".content-type")
+ .select("text/plain")
+ // Assert against dropdown value
+ .get(".examples-select > select")
+ .find(":selected")
+ .should("have.text", exampleA.summary)
+ // Assert against example value
+ .get(".microlight")
+ .should("have.text", exampleA.value)
+ })
+ }
+ )
+}
diff --git a/test/e2e-cypress/static/documents/features/multiple-examples-core.openapi.yaml b/test/e2e-cypress/static/documents/features/multiple-examples-core.openapi.yaml
new file mode 100644
index 00000000..f6a39cee
--- /dev/null
+++ b/test/e2e-cypress/static/documents/features/multiple-examples-core.openapi.yaml
@@ -0,0 +1,400 @@
+openapi: 3.0.0
+info:
+ title: "Multiple Examples: Core Document"
+ description: |
+ This document has examples for straightforward usage of `examples` in...
+ * Parameter Object positions
+ * Response Object positions
+ * Request Body Object positions
+
+ It includes:
+ * cases for each JSON Schema type as an example value (except null) in each position
+ * variously-sized `examples` objects
+ * multi-paragraph descriptions within each example
+
+ It **does not** include the following out-of-scope items:
+ * usage of `examples` within `Parameter.content` or `Response.content`
+ * `externalValue` (might change)
+
+ It also lacks edge cases, which will be covered in the "Corner" Document:
+ * `examples` n=1, which presents an interesting UI problem w/ the dropdown
+ * `example` and `examples` both present
+ * example item value that doesn't match the input type
+ * e.g., `Parameter.type === "number"`, but `Parameter.examples.[key].value` is an object
+ * `null` as an example value
+ version: "1.0.2"
+paths:
+ /String:
+ post:
+ summary: "Bonus: contains two requestBody media types"
+ parameters:
+ - in: query
+ name: message
+ required: true
+ description: This parameter just so happens to have a one-line description.
+ schema:
+ type: string
+ examples:
+ StringExampleA:
+ $ref: '#/components/examples/StringExampleA'
+ StringExampleB:
+ $ref: '#/components/examples/StringExampleB'
+ requestBody:
+ description: the wonderful payload of my request
+ content:
+ text/plain:
+ schema:
+ type: string
+ examples:
+ StringExampleA:
+ $ref: '#/components/examples/StringExampleA'
+ StringExampleB:
+ $ref: '#/components/examples/StringExampleB'
+ text/plain+other:
+ schema:
+ type: string
+ examples:
+ StringExampleA:
+ $ref: '#/components/examples/StringExampleA'
+ StringExampleB:
+ $ref: '#/components/examples/StringExampleB'
+ responses:
+ 200:
+ description: has two media types; the second has a third example!
+ content:
+ text/plain:
+ schema:
+ type: string
+ examples:
+ StringExampleA:
+ $ref: '#/components/examples/StringExampleA'
+ StringExampleB:
+ $ref: '#/components/examples/StringExampleB'
+ text/plain+other:
+ schema:
+ type: string
+ examples:
+ StringExampleA:
+ $ref: '#/components/examples/StringExampleA'
+ StringExampleB:
+ $ref: '#/components/examples/StringExampleB'
+ StringExampleC:
+ $ref: '#/components/examples/StringExampleC'
+ /Number:
+ post:
+ parameters:
+ - in: query
+ name: message
+ required: true
+ schema:
+ type: number
+ examples:
+ NumberExampleA:
+ $ref: '#/components/examples/NumberExampleA'
+ NumberExampleB:
+ $ref: '#/components/examples/NumberExampleB'
+ NumberExampleC:
+ $ref: '#/components/examples/NumberExampleC'
+ requestBody:
+ description: the wonderful payload of my request
+ content:
+ text/plain:
+ schema:
+ type: number
+ examples:
+ NumberExampleA:
+ $ref: '#/components/examples/NumberExampleA'
+ NumberExampleB:
+ $ref: '#/components/examples/NumberExampleB'
+ NumberExampleC:
+ $ref: '#/components/examples/NumberExampleC'
+ text/plain+other:
+ schema:
+ type: number
+ examples:
+ NumberExampleA:
+ $ref: '#/components/examples/NumberExampleA'
+ NumberExampleB:
+ $ref: '#/components/examples/NumberExampleB'
+ NumberExampleC:
+ $ref: '#/components/examples/NumberExampleC'
+ responses:
+ 200:
+ description: OK!
+ content:
+ text/plain:
+ schema:
+ type: number
+ examples:
+ NumberExampleA:
+ $ref: '#/components/examples/NumberExampleA'
+ NumberExampleB:
+ $ref: '#/components/examples/NumberExampleB'
+ text/plain+other:
+ schema:
+ type: number
+ examples:
+ NumberExampleA:
+ $ref: '#/components/examples/NumberExampleA'
+ NumberExampleB:
+ $ref: '#/components/examples/NumberExampleB'
+ NumberExampleC:
+ $ref: '#/components/examples/NumberExampleC'
+ /Boolean:
+ post:
+ parameters:
+ - in: query
+ name: message
+ required: true
+ schema:
+ type: boolean
+ examples:
+ BooleanExampleA:
+ $ref: '#/components/examples/BooleanExampleA'
+ BooleanExampleB:
+ $ref: '#/components/examples/BooleanExampleB'
+ requestBody:
+ description: the wonderful payload of my request
+ content:
+ text/plain:
+ schema:
+ type: boolean
+ examples:
+ BooleanExampleA:
+ $ref: '#/components/examples/BooleanExampleA'
+ BooleanExampleB:
+ $ref: '#/components/examples/BooleanExampleB'
+ text/plain+other:
+ schema:
+ type: boolean
+ examples:
+ BooleanExampleA:
+ $ref: '#/components/examples/BooleanExampleA'
+ BooleanExampleB:
+ $ref: '#/components/examples/BooleanExampleB'
+ responses:
+ 200:
+ description: OK!
+ content:
+ text/plain:
+ schema:
+ type: boolean
+ examples:
+ BooleanExampleA:
+ $ref: '#/components/examples/BooleanExampleA'
+ BooleanExampleB:
+ $ref: '#/components/examples/BooleanExampleB'
+ text/plain+other:
+ schema:
+ type: boolean
+ examples:
+ BooleanExampleA:
+ $ref: '#/components/examples/BooleanExampleA'
+ BooleanExampleB:
+ $ref: '#/components/examples/BooleanExampleB'
+ /Array:
+ post:
+ parameters:
+ - in: query
+ name: message
+ required: true
+ schema:
+ type: array
+ items: {} # intentionally empty; don't want to assert on the items
+ examples:
+ ArrayExampleA:
+ $ref: '#/components/examples/ArrayExampleA'
+ ArrayExampleB:
+ $ref: '#/components/examples/ArrayExampleB'
+ ArrayExampleC:
+ $ref: '#/components/examples/ArrayExampleC'
+ requestBody:
+ description: the wonderful payload of my request
+ content:
+ application/json:
+ schema:
+ type: array
+ items: {} # intentionally empty; don't want to assert on the items
+ examples:
+ ArrayExampleA:
+ $ref: '#/components/examples/ArrayExampleA'
+ ArrayExampleB:
+ $ref: '#/components/examples/ArrayExampleB'
+ ArrayExampleC:
+ $ref: '#/components/examples/ArrayExampleC'
+ responses:
+ 200:
+ description: OK!
+ content:
+ application/json:
+ schema:
+ type: array
+ items: {} # intentionally empty; don't want to assert on the items
+ examples:
+ ArrayExampleA:
+ $ref: '#/components/examples/ArrayExampleA'
+ ArrayExampleB:
+ $ref: '#/components/examples/ArrayExampleB'
+ ArrayExampleC:
+ $ref: '#/components/examples/ArrayExampleC'
+ /Object:
+ post:
+ parameters:
+ - in: query
+ name: data
+ required: true
+ schema:
+ type: object
+ examples:
+ ObjectExampleA:
+ $ref: '#/components/examples/ObjectExampleA'
+ ObjectExampleB:
+ $ref: '#/components/examples/ObjectExampleB'
+ requestBody:
+ description: the wonderful payload of my request
+ content:
+ application/json:
+ schema:
+ type: object
+ examples:
+ ObjectExampleA:
+ $ref: '#/components/examples/ObjectExampleA'
+ ObjectExampleB:
+ $ref: '#/components/examples/ObjectExampleB'
+ text/plain+other:
+ schema:
+ type: object
+ examples:
+ ObjectExampleA:
+ $ref: '#/components/examples/ObjectExampleA'
+ ObjectExampleB:
+ $ref: '#/components/examples/ObjectExampleB'
+ responses:
+ 200:
+ description: OK!
+ content:
+ application/json:
+ schema:
+ type: object
+ examples:
+ ObjectExampleA:
+ $ref: '#/components/examples/ObjectExampleA'
+ ObjectExampleB:
+ $ref: '#/components/examples/ObjectExampleB'
+ text/plain+other:
+ schema:
+ type: object
+ examples:
+ ObjectExampleA:
+ $ref: '#/components/examples/ObjectExampleA'
+ ObjectExampleB:
+ $ref: '#/components/examples/ObjectExampleB'
+components:
+ examples:
+ StringExampleA:
+ value: "hello world"
+ summary: Don't just string me along...
+ description: |
+ A string in C is actually a character array. As an individual character variable can store only one character, we need an array of characters to store strings. Thus, in C string is stored in an array of characters. Each character in a string occupies one location in an array. The null character ‘\0’ is put after the last character. This is done so that program can tell when the end of the string has been reached.
+
+ For example, the string “Hello” is stored as follows...
+
+ 
+
+ Since the string contains 5 characters. it requires a character array of size 6 to store it. the last character in a string is always a NULL('\0') character. Always keep in mind that the '\0' is not included in the length if the string, so here the length of the string is 5 only. Notice above that the indexes of the string starts from 0 not one so don't confuse yourself with index and length of string.
+
+ Thus, in C, a string is a one-dimensional array of characters terminated a null character. The terminating null character is important. In fact, a string not terminated by ‘\0’ is not really a string, but merely a collection of characters.
+ StringExampleB:
+ value: "The quick brown fox jumps over the lazy dog"
+ summary: "I'm a pangram!"
+ description: |
+ A pangram (Greek: παν γράμμα, pan gramma, "every letter") or holoalphabetic sentence is a sentence using every letter of a given alphabet at least once. Pangrams have been used to display typefaces, test equipment, and develop skills in handwriting, calligraphy, and keyboarding.
+
+ The best-known English pangram is "The quick brown fox jumps over the lazy dog". It has been used since at least the late 19th century, was utilized by Western Union to test Telex / TWX data communication equipment for accuracy and reliability, and is now used by a number of computer programs (most notably the font viewer built into Microsoft Windows) to display computer fonts.
+
+ Pangrams exist in practically every alphabet-based language. An example from German is _Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich_, which contains all letters, including every umlaut (ä, ö, ü) plus the ß. It has been used since before 1800.
+
+ In a sense, the pangram is the opposite of the lipogram, in which the aim is to omit one or more letters.
+
+ A perfect pangram contains every letter of the alphabet only once and
+ can be considered an anagram of the alphabet. The only perfect pangrams
+ that are known either use abbreviations, such as "Mr Jock, TV quiz PhD,
+ bags few lynx", or use words so obscure that the phrase is hard to
+ understand, such as "Cwm fjord bank glyphs vext quiz", where cwm is a
+ loan word from the Welsh language meaning a steep-sided valley, and vext
+ is an uncommon way to spell vexed.
+ StringExampleC:
+ value: "JavaScript rules"
+ summary: "A third example, for use in special places..."
+ NumberExampleA:
+ value: 7710263025
+ summary: "World population"
+ description: |
+ In demographics, the world population is the total number of humans currently living, and was estimated to have reached 7.7 billion people as of April 2019. It took over 200,000 years of human history for the world's population to reach 1 billion; and only 200 years more to reach 7 billion.
+
+ World population has experienced continuous growth since the end of the Great Famine of 1315–1317 and the Black Death in 1350, when it was near 370 million. The highest population growth rates – global population increases above 1.8% per year – occurred between 1955 and 1975, peaking to 2.1% between 1965 and 1970. The growth rate has declined to 1.2% between 2010 and 2015 and is projected to decline further in the course of the 21st century. However, the global population is still growing and is projected to reach about 10 billion in 2050 and more than 11 billion in 2100.
+
+ Total annual births were highest in the late 1980s at about 139 million, and as of 2011 were expected to remain essentially constant at a level of 135 million, while deaths numbered 56 million per year and were expected to increase to 80 million per year by 2040. The median age of the world's population was estimated to be 30.4 years in 2018.
+ NumberExampleB:
+ value: 9007199254740991
+ summary: "Number.MAX_SAFE_INTEGER"
+ description: |
+ The `MAX_SAFE_INTEGER` constant has a value of `9007199254740991` (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between `-(2^53 - 1)` and `2^53 - 1`.
+
+ Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to `true`, which is mathematically incorrect. See `Number.isSafeInteger()` for more information.
+
+ Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a `Number` object you created.
+ NumberExampleC:
+ # `description` and `summary` intentionally omitted
+ value: 0
+ BooleanExampleA:
+ value: true
+ summary: The truth will set you free
+ description: |
+ In some programming languages, any expression can be evaluated in a context that expects a Boolean data type. Typically (though this varies by programming language) expressions like the number zero, the empty string, empty lists, and null evaluate to false, and strings with content (like "abc"), other numbers, and objects evaluate to true. Sometimes these classes of expressions are called "truthy" and "falsey".
+ BooleanExampleB:
+ # `description` intentionally omitted
+ value: false
+ summary: Friends don't lie to friends
+ ArrayExampleA:
+ value: [a, b, c]
+ summary: A lowly array of strings
+ description: |
+ In computer science, a list or sequence is an abstract data type that represents a countable number of ordered values, where the same value may occur more than once. An instance of a list is a computer representation of the mathematical concept of a finite sequence; the (potentially) infinite analog of a list is a stream.[1]:§3.5 Lists are a basic example of containers, as they contain other values. If the same value occurs multiple times, each occurrence is considered a distinct item.
+ ArrayExampleB:
+ value: [1, 2, 3, 4]
+ summary: A lowly array of numbers
+ description: |
+ Many programming languages provide support for list data types, and have special syntax and semantics for lists and list operations. A list can often be constructed by writing the items in sequence, separated by commas, semicolons, and/or spaces, within a pair of delimiters such as parentheses '()', brackets '[]', braces '{}', or angle brackets '<>'. Some languages may allow list types to be indexed or sliced like array types, in which case the data type is more accurately described as an array. In object-oriented programming languages, lists are usually provided as instances of subclasses of a generic "list" class, and traversed via separate iterators. List data types are often implemented using array data structures or linked lists of some sort, but other data structures may be more appropriate for some applications. In some contexts, such as in Lisp programming, the term list may refer specifically to a linked list rather than an array.
+
+ In type theory and functional programming, abstract lists are usually defined inductively by two operations: nil that yields the empty list, and cons, which adds an item at the beginning of a list.
+ ArrayExampleC:
+ # `summary` intentionally omitted
+ value: []
+ description: An empty array value should clear the current value
+ ObjectExampleA:
+ value:
+ firstName: Kyle
+ lastName: Shockey
+ email: kyle.shockey@smartbear.com
+ summary: A user's contact info
+ description: Who is this guy, anyways?
+ ObjectExampleB:
+ value:
+ name: Abbey
+ type: kitten
+ color: calico
+ gender: female
+ age: 11 weeks
+ summary: A wonderful kitten's info
+ description: |
+ Today’s domestic cats are physically very similar to their wild
+ ancestors. “Domestic cats and wildcats share a majority of their
+ characteristics,” Lyons says, but there are a few key differences:
+ wildcats were and are typically larger than their domestic kin, with
+ brown, tabby-like fur. “Wildcats have to have camouflage that’s going to
+ keep them very inconspicuous in the wild,” Lyons says. “So you can’t
+ have cats with orange and white running around—they’re going to be
+ snatched up by their predators.” As cats were domesticated, they began
+ to be selected and bred for more interesting colorations, thus giving us
+ today’s range of beautiful cat breeds.
diff --git a/test/e2e-cypress/tests/features/multiple-examples-core.js b/test/e2e-cypress/tests/features/multiple-examples-core.js
new file mode 100644
index 00000000..eff42090
--- /dev/null
+++ b/test/e2e-cypress/tests/features/multiple-examples-core.js
@@ -0,0 +1,642 @@
+/**
+ * @prettier
+ */
+
+ const {
+ ParameterPrimitiveTestCases,
+ RequestBodyPrimitiveTestCases,
+ ResponsePrimitiveTestCases,
+} = require("../../helpers/multiple-examples")
+describe("OpenAPI 3.0 Multiple Examples - core features", () => {
+ describe("/String", () => {
+ describe("in a parameter", () => {
+ ParameterPrimitiveTestCases({
+ operationDomId: "#operations-default-post_String",
+ parameterName: "message",
+ exampleA: {
+ key: "StringExampleA",
+ value: "hello world",
+ },
+ exampleB: {
+ key: "StringExampleB",
+ value: "The quick brown fox jumps over the lazy dog",
+ },
+ customUserInput: "OpenAPIs.org <3",
+ })
+ })
+ describe("in a Request Body", () => {
+ RequestBodyPrimitiveTestCases({
+ operationDomId: "#operations-default-post_String",
+ exampleA: {
+ key: "StringExampleA",
+ value: "hello world",
+ serializedValue: "hello world",
+ summary: "Don't just string me along...",
+ },
+ exampleB: {
+ key: "StringExampleB",
+ value: "The quick brown fox jumps over the lazy dog",
+ serializedValue: "The quick brown fox jumps over the lazy dog",
+ summary: "I'm a pangram!",
+ },
+ customUserInput: "OpenAPIs.org <3",
+ })
+ })
+ describe("in a Response", () => {
+ ResponsePrimitiveTestCases({
+ operationDomId: "#operations-default-post_String",
+ exampleA: {
+ key: "StringExampleA",
+ value: "hello world",
+ summary: "Don't just string me along...",
+ },
+ exampleB: {
+ key: "StringExampleB",
+ value: "The quick brown fox jumps over the lazy dog",
+ summary: "I'm a pangram!",
+ },
+ exampleC: {
+ key: "StringExampleC",
+ value: "JavaScript rules",
+ summary: "A third example, for use in special places...",
+ },
+ })
+ })
+ })
+ describe("/Number", () => {
+ describe("in a parameter", () => {
+ ParameterPrimitiveTestCases({
+ operationDomId: "#operations-default-post_Number",
+ parameterName: "message",
+ exampleA: {
+ key: "NumberExampleA",
+ value: "7710263025",
+ },
+ exampleB: {
+ key: "NumberExampleB",
+ value: "9007199254740991",
+ },
+ exampleC: {
+ key: "NumberExampleC",
+ value: "0",
+ },
+ customUserInput: "9001",
+ })
+ })
+ describe("in a Request Body", () => {
+ RequestBodyPrimitiveTestCases({
+ operationDomId: "#operations-default-post_Number",
+ exampleA: {
+ key: "NumberExampleA",
+ value: "7710263025",
+ summary: "World population",
+ },
+ exampleB: {
+ key: "NumberExampleB",
+ value: "9007199254740991",
+ summary: "Number.MAX_SAFE_INTEGER",
+ },
+ exampleC: {
+ key: "NumberExampleC",
+ value: "0",
+ },
+ customUserInput: "1337",
+ })
+ })
+ describe("in a Response", () => {
+ ResponsePrimitiveTestCases({
+ operationDomId: "#operations-default-post_Number",
+ exampleA: {
+ key: "NumberExampleA",
+ value: "7710263025",
+ summary: "World population",
+ },
+ exampleB: {
+ key: "NumberExampleB",
+ value: "9007199254740991",
+ summary: "Number.MAX_SAFE_INTEGER",
+ },
+ exampleC: {
+ key: "NumberExampleC",
+ value: "0",
+ },
+ })
+ })
+ })
+ describe("/Boolean", () => {
+ describe("in a parameter", () => {
+ it("should render and apply the first example and value by default", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Boolean")
+ .click()
+ // Assert on the initial dropdown value
+ .get("table.parameters .examples-select > select")
+ .find(":selected")
+ .should("have.text", "The truth will set you free")
+ // Assert on the initial JsonSchemaForm value
+ .get(".parameters-col_description > select")
+ .should("have.attr", "disabled")
+ .get(".parameters-col_description > select")
+ .find(":selected")
+ .should("have.text", "true")
+ // Execute
+ .get(".try-out__btn")
+ .click()
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ .get(".request-url")
+ .contains(`?message=true`)
+ })
+ it("should render and apply the second value when chosen", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Boolean")
+ .click()
+ // Set the dropdown value, then assert on it
+ .get("table.parameters .examples-select > select")
+ .select("BooleanExampleB")
+ .find(":selected")
+ .should("have.text", "Friends don't lie to friends")
+ // Set the JsonSchemaForm value, then assert on it
+ .get(".parameters-col_description > select")
+ .find(":selected")
+ .should("have.text", "false")
+ // Execute
+ .get(".try-out__btn")
+ .click()
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ .get(".request-url")
+ .contains(`?message=false`)
+ })
+ it("should track value changes against valid examples", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Boolean")
+ .click()
+ .get(".try-out__btn")
+ .click()
+ // Set the JsonSchemaForm value, then assert on it
+ .get(".parameters-col_description > select")
+ .select("false")
+ .find(":selected")
+ .should("have.text", "false")
+ // Assert on the dropdown value
+ .get("table.parameters .examples-select > select")
+ .find(":selected")
+ .should("have.text", "Friends don't lie to friends")
+ // Execute
+ .get(".execute")
+ .click()
+ // Assert on the request URL
+ .get(".request-url")
+ .contains(`?message=false`)
+ })
+ })
+ describe("in a Request Body", () => {
+ RequestBodyPrimitiveTestCases({
+ operationDomId: "#operations-default-post_Boolean",
+ exampleA: {
+ key: "BooleanExampleA",
+ value: "true",
+ summary: "The truth will set you free",
+ },
+ exampleB: {
+ key: "BooleanExampleB",
+ value: "false",
+ summary: "Friends don't lie to friends",
+ },
+ customUserInput: "tralse",
+ })
+ })
+ describe("in a Response", () => {
+ it("should render and apply the first example and value by default", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Boolean")
+ .click()
+ // Assert on the initial dropdown value
+ .get(".responses-wrapper .examples-select > select")
+ .find(":selected")
+ .should("have.text", "The truth will set you free")
+ // Assert on the example value
+ .get(".example.microlight")
+ .should("have.text", "true")
+ })
+ it("should render and apply the second value when chosen", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Boolean")
+ .click()
+ // Set the dropdown value, then assert on it
+ .get(".responses-wrapper .examples-select > select")
+ .select("BooleanExampleB")
+ .find(":selected")
+ .should("have.text", "Friends don't lie to friends")
+ // Assert on the example value
+ .get(".example.microlight")
+ .should("have.text", "false")
+ })
+ })
+ })
+ describe("/Array", () => {
+ describe("in a Parameter", () => {
+ it("should have the first example's array entries by default", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ .get(".json-schema-form-item > input")
+ .then(inputs => {
+ expect(inputs.map((i, el) => el.value).toArray()).to.deep.equal([
+ "a",
+ "b",
+ "c",
+ ])
+ })
+ .get(".parameters-col_description .examples-select > select")
+ .find(":selected")
+ .should("have.text", "A lowly array of strings")
+ })
+ it("should switch to the second array's entries via dropdown", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ .get(".parameters-col_description .examples-select > select")
+ .select("ArrayExampleB")
+ .get(".json-schema-form-item > input")
+ .then(inputs => {
+ expect(inputs.map((i, el) => el.value).toArray()).to.deep.equal([
+ "1",
+ "2",
+ "3",
+ "4",
+ ])
+ })
+ .get(".parameters-col_description .examples-select > select")
+ .find(":selected")
+ .should("have.text", "A lowly array of numbers")
+ })
+ it("should not allow modification of values in static mode", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ .get(".parameters-col_description .examples-select > select")
+ .select("ArrayExampleB")
+ // Add a new item
+ .get(".json-schema-form-item > input")
+ .should("have.attr", "disabled")
+ })
+ it("should allow modification of values in Try-It-Out", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ .get(".try-out__btn")
+ .click()
+ .get(".parameters-col_description .examples-select > select")
+ .select("ArrayExampleB")
+ // Add a new item
+ .get(".json-schema-form-item-add")
+ .click()
+ .get(".json-schema-form-item:last-of-type > input")
+ .type("5")
+ // Assert against the input fields
+ .get(".json-schema-form-item > input")
+ .then(inputs => {
+ expect(inputs.map((i, el) => el.value).toArray()).to.deep.equal([
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ ])
+ })
+ .get(".parameters-col_description .examples-select > select")
+ .find(":selected")
+ .should("have.text", "[Modified value]")
+ })
+
+ it("should retain a modified value, and support returning to it", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ .get(".try-out__btn")
+ .click()
+ .get(".parameters-col_description .examples-select > select")
+ .select("ArrayExampleB")
+ // Add a new item
+ .get(".json-schema-form-item-add")
+ .click()
+ .get(".json-schema-form-item:last-of-type > input")
+ .type("5")
+ // Reset to an example
+ .get(".parameters-col_description .examples-select > select")
+ .select("ArrayExampleB")
+ // Assert against the input fields
+ .get(".json-schema-form-item > input")
+ .then(inputs => {
+ expect(inputs.map((i, el) => el.value).toArray()).to.deep.equal([
+ "1",
+ "2",
+ "3",
+ "4",
+ ])
+ })
+ .get(".parameters-col_description .examples-select > select")
+ .find(":selected")
+ .should("have.text", "A lowly array of numbers")
+ // Return to the modified value
+ .get(".parameters-col_description .examples-select > select")
+ .select("__MODIFIED__VALUE__")
+ // Assert that our modified value is back
+ .get(".json-schema-form-item > input")
+ .then(inputs => {
+ expect(inputs.map((i, el) => el.value).toArray()).to.deep.equal([
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ ])
+ })
+ .get(".parameters-col_description .examples-select > select")
+ .find(":selected")
+ .should("have.text", "[Modified value]")
+ })
+ })
+ describe("in a Request Body", () => {
+ it("should have the first example's array entries by default", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ // Check HighlightCode value
+ .get(".opblock-section-request-body .highlight-code")
+ .should("have.text", JSON.stringify(["a", "b", "c"], null, 2))
+ // Check dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "A lowly array of strings")
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Check textarea value
+ .get(".opblock-section-request-body textarea")
+ .should("have.value", JSON.stringify(["a", "b", "c"], null, 2))
+ // Check dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "A lowly array of strings")
+ })
+ it("should switch to the second array's entries via dropdown", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ .get(".opblock-section-request-body .examples-select > select")
+ .select("ArrayExampleB")
+ .get(".opblock-section-request-body .highlight-code")
+ .should("have.text", JSON.stringify([1, 2, 3, 4], null, 2))
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "A lowly array of numbers")
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Check textarea value
+ .get(".opblock-section-request-body textarea")
+ .should("have.text", JSON.stringify([1, 2, 3, 4], null, 2))
+ // Check dropdown value
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "A lowly array of numbers")
+ })
+ it("should allow modification of values", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Choose the second example
+ .get(".opblock-section-request-body .examples-select > select")
+ .select("ArrayExampleB")
+ // Change the value
+ .get(".opblock-section-request-body textarea")
+ .type(`{leftarrow}{leftarrow},{enter} 5`)
+ // Check that [Modified value] is displayed in dropdown
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "[Modified value]")
+ // Check textarea value
+ .get(".opblock-section-request-body textarea")
+ .should("have.text", JSON.stringify([1, 2, 3, 4, 5], null, 2))
+ })
+
+ it("should retain a modified value, and support returning to it", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ // Switch to Try-It-Out
+ .get(".try-out__btn")
+ .click()
+ // Choose the second example as the example to start with
+ .get(".opblock-section-request-body .examples-select > select")
+ .select("ArrayExampleB")
+ // Change the value
+ .get(".opblock-section-request-body textarea")
+ .type(`{leftarrow}{leftarrow},{enter} 5`)
+ // Check that [Modified value] is displayed in dropdown
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "[Modified value]")
+ // Check textarea value
+ .get(".opblock-section-request-body textarea")
+ .should("have.text", JSON.stringify([1, 2, 3, 4, 5], null, 2))
+ // Choose the second example
+ .get(".opblock-section-request-body .examples-select > select")
+ .select("ArrayExampleB")
+ // Check that the example is displayed in dropdown
+ .get(".opblock-section-request-body .examples-select > select")
+ .find(":selected")
+ .should("have.text", "A lowly array of numbers")
+ // Check textarea value
+ .get(".opblock-section-request-body textarea")
+ .should("have.text", JSON.stringify([1, 2, 3, 4], null, 2))
+ // Switch back to the modified value
+ .get(".opblock-section-request-body .examples-select > select")
+ .select("__MODIFIED__VALUE__")
+ // Check textarea value
+ .get(".opblock-section-request-body textarea")
+ .should("have.text", JSON.stringify([1, 2, 3, 4, 5], null, 2))
+ })
+ })
+ describe("in a Response", () => {
+ it("should render and apply the first example and value by default", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ // Assert on the initial dropdown value
+ .get(".responses-wrapper .examples-select > select")
+ .find(":selected")
+ .should("have.text", "A lowly array of strings")
+ // Assert on the example value
+ .get(".example.microlight")
+ .should("have.text", JSON.stringify(["a", "b", "c"], null, 2))
+ })
+ it("should render and apply the second value when chosen", () => {
+ cy.visit(
+ "/?url=/documents/features/multiple-examples-core.openapi.yaml"
+ )
+ .get("#operations-default-post_Array")
+ .click()
+ // Set the dropdown value, then assert on it
+ .get(".responses-wrapper .examples-select > select")
+ .select("ArrayExampleB")
+ .find(":selected")
+ .should("have.text", "A lowly array of numbers")
+ // Assert on the example value
+ .get(".example.microlight")
+ .should("have.text", JSON.stringify([1, 2, 3, 4], null, 2))
+ })
+ })
+ })
+ describe("/Object", () => {
+ describe("in a Parameter", () => {
+ ParameterPrimitiveTestCases({
+ operationDomId: "#operations-default-post_Object",
+ parameterName: "data",
+ customUserInput: `{{} "openapiIsCool": true }`,
+ customExpectedUrlSubstring: "?openapiIsCool=true",
+ exampleA: {
+ key: "ObjectExampleA",
+ serializedValue:
+ "firstName=Kyle&lastName=Shockey&email=kyle.shockey%40smartbear.com",
+ value: JSON.stringify(
+ {
+ firstName: "Kyle",
+ lastName: "Shockey",
+ email: "kyle.shockey@smartbear.com",
+ },
+ null,
+ 2
+ ),
+ },
+ exampleB: {
+ key: "ObjectExampleB",
+ serializedValue:
+ "name=Abbey&type=kitten&color=calico&gender=female&age=11%20weeks",
+ value: JSON.stringify(
+ {
+ name: "Abbey",
+ type: "kitten",
+ color: "calico",
+ gender: "female",
+ age: "11 weeks",
+ },
+ null,
+ 2
+ ),
+ },
+ })
+ })
+ describe("in a Request Body", () => {
+ RequestBodyPrimitiveTestCases({
+ operationDomId: "#operations-default-post_Object",
+ primaryMediaType: "application/json",
+ // ↓ not a typo, Cypress requires escaping { when using `cy.type`
+ customUserInput: `{{} "openapiIsCool": true }`,
+ customExpectedUrlSubstring: "?openapiIsCool=true",
+ customUserInputExpectedCurlSubstring: `{\\"openapiIsCool\\":true}`,
+ exampleA: {
+ key: "ObjectExampleA",
+ serializedValue: `{\\"firstName\\":\\"Kyle\\",\\"lastName\\":\\"Shockey\\",\\"email\\":\\"kyle.shockey@smartbear.com\\"}`,
+ value: JSON.stringify(
+ {
+ firstName: "Kyle",
+ lastName: "Shockey",
+ email: "kyle.shockey@smartbear.com",
+ },
+ null,
+ 2
+ ),
+ summary: "A user's contact info",
+ },
+ exampleB: {
+ key: "ObjectExampleB",
+ serializedValue: `{\\"name\\":\\"Abbey\\",\\"type\\":\\"kitten\\",\\"color\\":\\"calico\\",\\"gender\\":\\"female\\",\\"age\\":\\"11 weeks\\"}`,
+ value: JSON.stringify(
+ {
+ name: "Abbey",
+ type: "kitten",
+ color: "calico",
+ gender: "female",
+ age: "11 weeks",
+ },
+ null,
+ 2
+ ),
+ summary: "A wonderful kitten's info",
+ },
+ })
+ })
+ describe("in a Response", () => {
+ ResponsePrimitiveTestCases({
+ operationDomId: "#operations-default-post_Object",
+ exampleA: {
+ key: "ObjectExampleA",
+ value: JSON.stringify(
+ {
+ firstName: "Kyle",
+ lastName: "Shockey",
+ email: "kyle.shockey@smartbear.com",
+ },
+ null,
+ 2
+ ),
+ summary: "A user's contact info",
+ },
+ exampleB: {
+ key: "ObjectExampleB",
+ value: JSON.stringify(
+ {
+ name: "Abbey",
+ type: "kitten",
+ color: "calico",
+ gender: "female",
+ age: "11 weeks",
+ },
+ null,
+ 2
+ ),
+ summary: "A wonderful kitten's info",
+ },
+ })
+ })
+ })
+})
diff --git a/webpack-hot-dev-server.config.js b/webpack-hot-dev-server.config.js
index 5ca1b041..49fb6adc 100644
--- a/webpack-hot-dev-server.config.js
+++ b/webpack-hot-dev-server.config.js
@@ -41,8 +41,8 @@ const rules = [
module.exports = require("./make-webpack-config")(rules, {
_special: {
separateStylesheets: false,
+ sourcemaps: true,
},
- devtool: "eval-source-map",
entry: {
"swagger-ui-bundle": [
"./src/polyfills",
|