Merge remote-tracking branch 'upstream/master'

This commit is contained in:
David Oram 2018-08-23 06:37:56 +12:00
commit f2b09f5a5e
53 changed files with 1248 additions and 1152 deletions

View File

@ -1,3 +1,16 @@
<a name="2.0.0-alpha.37"></a>
# [2.0.0-alpha.37](https://github.com/Rebilly/ReDoc/compare/v2.0.0-alpha.36...v2.0.0-alpha.37) (2018-08-22)
### Bug Fixes
* do not inherit title in allOf ([720e282](https://github.com/Rebilly/ReDoc/commit/720e282)), closes [#601](https://github.com/Rebilly/ReDoc/issues/601)
* fix crash on empty media object ([fb21212](https://github.com/Rebilly/ReDoc/commit/fb21212)), closes [#608](https://github.com/Rebilly/ReDoc/issues/608)
* make http badges font-based instead of inline png ([5d84bd4](https://github.com/Rebilly/ReDoc/commit/5d84bd4))
* use correct parent section for security definition ([f903406](https://github.com/Rebilly/ReDoc/commit/f903406))
<a name="2.0.0-alpha.36"></a>
# [2.0.0-alpha.36](https://github.com/Rebilly/ReDoc/compare/v2.0.0-alpha.35...v2.0.0-alpha.36) (2018-08-11)

View File

@ -29,8 +29,11 @@ const tsLoader = env => ({
const babelLoader = mode => ({
loader: 'babel-loader',
options: {
generatorOpts: {
decoratorsBeforeExport: true,
},
plugins: compact([
'@babel/plugin-syntax-typescript',
['@babel/plugin-syntax-typescript', { isTSX: true }],
['@babel/plugin-syntax-decorators', { legacy: true }],
'@babel/plugin-syntax-jsx',
mode !== 'production' ? 'react-hot-loader/babel' : undefined,
@ -113,6 +116,7 @@ export default (env: { playground?: boolean; bench?: boolean } = {}, { mode }) =
instance: 'ts2js-transpiler-only',
compilerOptions: {
allowJs: true,
declaration: false,
},
},
},

View File

@ -12,13 +12,14 @@ describe('Menu', () => {
it('should sync active menu items while scroll', () => {
cy.contains('h1', 'Introduction')
.scrollIntoView()
.get('[role=menuitem].active:not(.-depth0)')
.get('[role=menuitem].active')
.should('have.text', 'Introduction');
cy.contains('h2', 'Add a new pet to the store')
.scrollIntoView()
.get('[role=menuitem].active:not(.-depth0)')
.should('have.length', 2)
.wait(100)
.get('[role=menuitem].active')
.children()
.last()
.should('have.text', 'Add a new pet to the store')
.should('be.visible');

View File

@ -1,6 +1,6 @@
{
"name": "redoc",
"version": "2.0.0-alpha.36",
"version": "2.0.0-alpha.37",
"description": "ReDoc",
"repository": {
"type": "git",
@ -51,31 +51,31 @@
"license-check": "license-checker --production --onlyAllow 'MIT;ISC;Apache-2.0;BSD;BSD-2-Clause;BSD-3-Clause' --summary"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.47",
"@babel/plugin-syntax-decorators": "7.0.0-beta.47",
"@babel/plugin-syntax-jsx": "7.0.0-beta.47",
"@babel/plugin-syntax-typescript": "7.0.0-beta.47",
"@babel/core": "7.0.0-rc.1",
"@babel/plugin-syntax-decorators": "7.0.0-rc.1",
"@babel/plugin-syntax-jsx": "7.0.0-rc.1",
"@babel/plugin-syntax-typescript": "7.0.0-rc.1",
"@cypress/webpack-preprocessor": "2.0.1",
"@types/chai": "4.1.4",
"@types/dompurify": "^0.0.31",
"@types/enzyme": "^3.1.11",
"@types/enzyme-to-json": "^1.5.0",
"@types/jest": "^23.1.6",
"@types/enzyme": "^3.1.13",
"@types/enzyme-to-json": "^1.5.2",
"@types/jest": "^23.3.1",
"@types/json-pointer": "^1.0.30",
"@types/lodash": "^4.14.112",
"@types/lunr": "^2.1.5",
"@types/lodash": "^4.14.116",
"@types/lunr": "^2.1.6",
"@types/mark.js": "^8.11.1",
"@types/marked": "^0.4.0",
"@types/prismjs": "^1.6.4",
"@types/prop-types": "^15.5.3",
"@types/react": "^16.4.6",
"@types/react-dom": "^16.0.6",
"@types/prop-types": "^15.5.5",
"@types/react": "^16.4.11",
"@types/react-dom": "^16.0.7",
"@types/react-hot-loader": "^4.1.0",
"@types/react-tabs": "^1.0.2",
"@types/react-tabs": "^1.0.5",
"@types/tapable": "1.0.4",
"@types/webpack": "^4.4.6",
"@types/webpack": "^4.4.10",
"@types/webpack-env": "^1.13.0",
"@types/yargs": "^11.1.0",
"@types/yargs": "^11.1.1",
"babel-loader": "8.0.0-beta.2",
"babel-plugin-styled-components": "^1.5.1",
"beautify-benchmark": "^0.2.4",
@ -85,37 +85,37 @@
"core-js": "^2.5.7",
"coveralls": "^3.0.2",
"css-loader": "^1.0.0",
"cypress": "~3.0.2",
"cypress": "~3.1.0",
"deploy-to-gh-pages": "^1.3.6",
"enzyme": "^3.1.1",
"enzyme-adapter-react-16": "^1.0.4",
"enzyme": "^3.4.3",
"enzyme-adapter-react-16": "^1.2.0",
"enzyme-to-json": "^3.3.4",
"fork-ts-checker-webpack-plugin": "^0.4.3",
"fork-ts-checker-webpack-plugin": "0.4.3",
"html-webpack-plugin": "^3.1.0",
"jest": "^23.4.1",
"license-checker": "^20.1.0",
"jest": "^23.5.0",
"license-checker": "^20.2.0",
"lodash": "^4.17.10",
"mobx": "^4.3.1",
"prettier": "^1.13.7",
"prettier": "^1.14.2",
"prettier-eslint": "^8.8.2",
"puppeteer": "^1.6.0",
"puppeteer": "^1.7.0",
"raf": "^3.4.0",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"rimraf": "^2.6.2",
"shelljs": "^0.8.1",
"source-map-loader": "^0.2.1",
"style-loader": "^0.21.0",
"source-map-loader": "^0.2.4",
"style-loader": "^0.22.1",
"swagger2openapi": "^3.2.8",
"ts-jest": "^23.0.0",
"ts-loader": "4.4.2",
"ts-node": "^7.0.0",
"tslint": "^5.7.0",
"ts-jest": "23.0.1",
"ts-loader": "4.5.0",
"ts-node": "^7.0.1",
"tslint": "^5.11.0",
"tslint-react": "^3.4.0",
"typescript": "^3.0.0-dev.20180712",
"webpack": "^4.16.1",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.1",
"typescript": "^3.0.1",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5",
"webpack-node-externals": "^1.6.0",
"workerize-loader": "^1.0.3",
"yaml-js": "^0.2.3"
@ -128,26 +128,26 @@
"dependencies": {
"classnames": "^2.2.6",
"decko": "^1.2.0",
"dompurify": "^1.0.6",
"dompurify": "^1.0.7",
"eventemitter3": "^3.0.0",
"json-pointer": "^0.6.0",
"json-schema-ref-parser": "^5.1.1",
"lunr": "^2.3.0",
"json-schema-ref-parser": "^5.1.2",
"lunr": "^2.3.2",
"mark.js": "^8.11.1",
"marked": "0.3.18",
"memoize-one": "^4.0.0",
"mobx-react": "^5.2.3",
"openapi-sampler": "1.0.0-beta.13",
"mobx-react": "^5.2.5",
"openapi-sampler": "1.0.0-beta.14",
"perfect-scrollbar": "^1.4.0",
"polished": "^1.9.3",
"prismjs": "^1.15.0",
"prop-types": "^15.6.2",
"react-dropdown": "^1.3.0",
"react-hot-loader": "^4.3.3",
"react-dropdown": "^1.6.1",
"react-hot-loader": "^4.3.4",
"react-tabs": "^2.0.0",
"slugify": "^1.2.1",
"slugify": "^1.3.1",
"stickyfill": "^1.1.1",
"styled-components": "^3.3.3",
"styled-components": "^3.4.2",
"tslib": "^1.9.3"
},
"resolutions": {
@ -162,7 +162,7 @@
],
"jest": {
"transform": {
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
"^.+\\.tsx?$": "ts-jest"
},
"setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.ts",
"testPathIgnorePatterns": [

View File

@ -1,5 +1,10 @@
import * as React from 'react';
import { StoreConsumer } from '../components/StoreBuilder';
import styled, { css } from '../styled-components';
import { HistoryService } from '../services';
// tslint:disable-next-line
export const linkifyMixin = className => css`
${className} {
@ -27,6 +32,42 @@ export const linkifyMixin = className => css`
}
`;
export const ShareLink = styled.a`
const isModifiedEvent = event =>
!!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
export class Link extends React.Component<{ to: string; className?: string; children?: any }> {
navigate = (history: HistoryService, event) => {
if (
!event.defaultPrevented && // onClick prevented default
event.button === 0 && // ignore everything but left clicks
!isModifiedEvent(event) // ignore clicks with modifier keys
) {
event.preventDefault();
history.replace(this.props.to);
}
};
render() {
return (
<StoreConsumer>
{store => (
<a
className={this.props.className}
href={store!.menu.history.linkForId(this.props.to)}
onClick={this.navigate.bind(this, store!.menu.history)}
>
{this.props.children}
</a>
)}
</StoreConsumer>
);
}
}
const StyledShareLink = styled(Link)`
${linkifyMixin('&')};
`;
export function ShareLink(props: { to: string }) {
return <StyledShareLink to={props.to} />;
}

View File

@ -1,19 +1,44 @@
import styled, { media } from '../styled-components';
import { SECTION_ATTR } from '../services/MenuStore';
import styled, { media, withProps } from '../styled-components';
export const MiddlePanel = styled.div`
width: calc(100% - ${props => props.theme.rightPanel.width});
padding: ${props => props.theme.spacing.unit * 8}px;
padding: 0 ${props => props.theme.spacing.unit * 8}px;
${media.lessThan('medium')`
width: 100%;
`};
`;
export const Section = withProps<{ underlined?: boolean }>(
styled.div.attrs({
[SECTION_ATTR]: props => props.id,
} as any),
)`
padding: ${props => props.theme.spacing.unit * 8}px 0;
${props =>
(props.underlined &&
`
position: relative;
&:not(:last-of-type):after {
position: absolute;
bottom: 0;
width: 100%;
display: block;
content: '';
border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}
`) ||
''}
`;
export const RightPanel = styled.div`
width: ${props => props.theme.rightPanel.width};
color: #fafbfc;
background-color: ${props => props.theme.rightPanel.backgroundColor};
padding: ${props => props.theme.spacing.unit * 8}px;
padding: 0 ${props => props.theme.spacing.unit * 8}px;
${media.lessThan('medium')`
width: 100%;
@ -27,6 +52,7 @@ export const DarkRightPanel = RightPanel.extend`
export const Row = styled.div`
display: flex;
width: 100%;
padding: 0;
${media.lessThan('medium')`
flex-direction: column;

View File

@ -2,6 +2,8 @@ import * as React from 'react';
import PerfectScrollbarType, * as PerfectScrollbarNamespace from 'perfect-scrollbar';
import psStyles from 'perfect-scrollbar/css/perfect-scrollbar.css';
import { OptionsContext } from '../components/OptionsProvider';
import styled, { injectGlobal } from '../styled-components';
/*
@ -18,11 +20,13 @@ const StyledScrollWrapper = styled.div`
position: relative;
`;
export class PerfectScrollbar extends React.Component<{
export interface PerfectScrollbarProps {
options?: PerfectScrollbarType.Options;
className?: string;
updateFn: (fn) => void;
}> {
updateFn?: (fn) => void;
}
export class PerfectScrollbar extends React.Component<PerfectScrollbarProps> {
private _container: HTMLElement;
private inst: PerfectScrollbarType;
@ -49,7 +53,9 @@ export class PerfectScrollbar extends React.Component<{
render() {
const { children, className, updateFn } = this.props;
updateFn(this.componentDidUpdate.bind(this));
if (updateFn) {
updateFn(this.componentDidUpdate.bind(this));
}
return (
<StyledScrollWrapper className={`scrollbar-container ${className}`} innerRef={this.handleRef}>
@ -58,3 +64,26 @@ export class PerfectScrollbar extends React.Component<{
);
}
}
export function PerfectScrollbarWrap(
props: PerfectScrollbarProps & { children: JSX.Element[] | JSX.Element },
) {
return (
<OptionsContext.Consumer>
{options =>
!options.nativeScrollbars ? (
<PerfectScrollbar {...props}>{props.children}</PerfectScrollbar>
) : (
<div
style={{
overflow: 'auto',
msOverflowStyle: '-ms-autohiding-scrollbar',
}}
>
{props.children}
</div>
)
}
</OptionsContext.Consumer>
);
}

View File

@ -1,22 +0,0 @@
import * as React from 'react';
import { MiddlePanel, Row } from '../../common-elements/';
import { Markdown } from '../Markdown/Markdown';
export interface ApiDescriptionProps {
description: string;
}
export class ApiDescription extends React.PureComponent<ApiDescriptionProps> {
render() {
const { description } = this.props;
return (
<Row>
<MiddlePanel>
<Markdown source={description} />
</MiddlePanel>
</Row>
);
}
}

View File

@ -3,8 +3,8 @@ import * as React from 'react';
import { AppStore } from '../../services/AppStore';
import { MiddlePanel, Row } from '../../common-elements/';
import { MiddlePanel, Row, Section } from '../../common-elements/';
import { Markdown } from '../Markdown/Markdown';
import { StyledMarkdownBlock } from '../Markdown/styled.elements';
import {
ApiHeader,
@ -70,43 +70,46 @@ export class ApiInfo extends React.Component<ApiInfoProps> {
null;
return (
<Row>
<MiddlePanel className="api-info">
<ApiHeader>
{info.title} <span>({info.version})</span>
</ApiHeader>
{!hideDownloadButton && (
<p>
Download OpenAPI specification:
<DownloadButton
download={downloadFilename}
target="_blank"
href={downloadLink}
onClick={this.handleDownloadClick}
>
Download
</DownloadButton>
</p>
)}
<StyledMarkdownBlock>
{((info.license || info.contact || info.termsOfService) && (
<InfoSpanBoxWrap>
<InfoSpanBox>
{email} {website} {license} {terms}
</InfoSpanBox>
</InfoSpanBoxWrap>
)) ||
null}
{(externalDocs && (
<Section>
<Row>
<MiddlePanel className="api-info">
<ApiHeader>
{info.title} <span>({info.version})</span>
</ApiHeader>
{!hideDownloadButton && (
<p>
<a href={externalDocs.url}>{externalDocs.description || externalDocs.url}</a>
Download OpenAPI specification:
<DownloadButton
download={downloadFilename}
target="_blank"
href={downloadLink}
onClick={this.handleDownloadClick}
>
Download
</DownloadButton>
</p>
)) ||
null}
</StyledMarkdownBlock>
</MiddlePanel>
</Row>
)}
<StyledMarkdownBlock>
{((info.license || info.contact || info.termsOfService) && (
<InfoSpanBoxWrap>
<InfoSpanBox>
{email} {website} {license} {terms}
</InfoSpanBox>
</InfoSpanBoxWrap>
)) ||
null}
{(externalDocs && (
<p>
<a href={externalDocs.url}>{externalDocs.description || externalDocs.url}</a>
</p>
)) ||
null}
</StyledMarkdownBlock>
<Markdown source={store.spec.info.description} />
</MiddlePanel>
</Row>
</Section>
);
}
}

View File

@ -1,2 +1 @@
export { ApiDescription } from './ApiDescription';
export { ApiInfo } from './ApiInfo';

View File

@ -1,47 +1,28 @@
import { observer } from 'mobx-react';
import * as React from 'react';
import { SECTION_ATTR } from '../../services/MenuStore';
import { Markdown } from '../Markdown/Markdown';
import { AdvancedMarkdown } from '../Markdown/AdvancedMarkdown';
import { H1, H2, MiddlePanel, Row, ShareLink } from '../../common-elements';
import { MDXComponentMeta } from '../../services/MarkdownRenderer';
import { H1, H2, MiddlePanel, Row, Section, ShareLink } from '../../common-elements';
import { ContentItemModel } from '../../services/MenuBuilder';
import { GroupModel, OperationModel } from '../../services/models';
import { Operation } from '../Operation/Operation';
import { SecurityDefs } from '../SecuritySchemes/SecuritySchemes';
import { StoreConsumer } from '../StoreBuilder';
@observer
export class ContentItems extends React.Component<{
items: ContentItemModel[];
allowedMdComponents?: Dict<MDXComponentMeta>;
}> {
static defaultProps = {
allowedMdComponents: {
'security-definitions': {
component: SecurityDefs,
propsSelector: _store => ({
securitySchemes: _store!.spec.securitySchemes,
}),
},
},
};
render() {
const items = this.props.items;
if (items.length === 0) {
return null;
}
return items.map(item => (
<ContentItem item={item} key={item.id} allowedMdComponents={this.props.allowedMdComponents} />
));
return items.map(item => <ContentItem item={item} key={item.id} />);
}
}
export interface ContentItemProps {
item: ContentItemModel;
allowedMdComponents?: Dict<MDXComponentMeta>;
}
@observer
@ -67,39 +48,37 @@ export class ContentItem extends React.Component<ContentItemProps> {
throw new Error('Unknown item type');
}
return [
<div key="section" {...{ [SECTION_ATTR]: item.id }}>
{content}
</div>,
(item as any).items && <ContentItems key="content" items={(item as any).items} />,
];
return (
<>
<Section id={item.id} underlined={item.type === 'operation'}>
{content}
</Section>
{item.items && <ContentItems items={item.items} />}
</>
);
}
}
const middlePanelWrap = component => <MiddlePanel>{component}</MiddlePanel>;
@observer
export class SectionItem extends React.Component<ContentItemProps> {
render() {
const { name, description, level } = this.props.item as GroupModel;
const components = this.props.allowedMdComponents;
const Header = level === 2 ? H2 : H1;
return (
<Row>
<MiddlePanel>
<Header>
<ShareLink href={'#' + this.props.item.id} />
{name}
</Header>
{components ? (
<StoreConsumer>
{store => (
<Markdown source={description || ''} allowedComponents={components} store={store} />
)}
</StoreConsumer>
) : (
<Markdown source={description || ''} />
)}
</MiddlePanel>
</Row>
<>
<Row>
<MiddlePanel>
<Header>
<ShareLink to={this.props.item.id} />
{name}
</Header>
</MiddlePanel>
</Row>
<AdvancedMarkdown source={description || ''} htmlWrap={middlePanelWrap} />
</>
);
}
}

View File

@ -28,7 +28,14 @@ export class FieldDetails extends React.PureComponent<FieldProps> {
<div>
<TypePrefix>{schema.typePrefix}</TypePrefix>
<TypeName>{schema.displayType}</TypeName>
{schema.displayFormat && <TypeFormat> &lt;{schema.displayFormat}&gt; </TypeFormat>}
{schema.displayFormat && (
<TypeFormat>
{' '}
&lt;
{schema.displayFormat}
&gt;{' '}
</TypeFormat>
)}
{schema.title && <TypeTitle> ({schema.title}) </TypeTitle>}
<ConstraintsView constraints={schema.constraints} />
{schema.nullable && <NullableLabel> Nullable </NullableLabel>}

View File

@ -0,0 +1,48 @@
import * as React from 'react';
import { AppStore, MarkdownRenderer, RedocNormalizedOptions } from '../../services';
import { BaseMarkdownProps } from './Markdown';
import { SanitizedMarkdownHTML } from './SanitizedMdBlock';
import { OptionsConsumer } from '../OptionsProvider';
import { StoreConsumer } from '../StoreBuilder';
export interface AdvancedMarkdownProps extends BaseMarkdownProps {
htmlWrap?: (part: JSX.Element) => JSX.Element;
}
export class AdvancedMarkdown extends React.Component<AdvancedMarkdownProps> {
render() {
return (
<OptionsConsumer>
{options => (
<StoreConsumer>{store => this.renderWithOptionsAndStore(options, store)}</StoreConsumer>
)}
</OptionsConsumer>
);
}
renderWithOptionsAndStore(options: RedocNormalizedOptions, store?: AppStore) {
const { source, htmlWrap = i => i } = this.props;
if (!store) {
throw new Error('When using componentes in markdown, store prop must be provided');
}
const renderer = new MarkdownRenderer(options);
const parts = renderer.renderMdWithComponents(source);
if (!parts.length) {
return null;
}
return parts.map((part, idx) => {
if (typeof part === 'string') {
return React.cloneElement(
htmlWrap(<SanitizedMarkdownHTML html={part} inline={false} dense={false} />),
{ key: idx },
);
}
return <part.component key={idx} {...{ ...part.attrs, ...part.propsSelector(store) }} />;
});
}
}

View File

@ -1,103 +1,35 @@
import * as React from 'react';
import * as DOMPurify from 'dompurify';
import { AppStore, MarkdownRenderer, MDXComponentMeta } from '../../services';
import { OptionsContext } from '../OptionsProvider';
import { StyledMarkdownBlock } from './styled.elements';
const StyledMarkdownSpan = StyledMarkdownBlock.withComponent('span');
import { MarkdownRenderer } from '../../services';
import { SanitizedMarkdownHTML } from './SanitizedMdBlock';
export interface StylingMarkdownProps {
dense?: boolean;
inline?: boolean;
}
export interface BaseMarkdownProps extends StylingMarkdownProps {
export interface BaseMarkdownProps {
sanitize?: boolean;
store?: AppStore;
}
const sanitize = (untrustedSpec, html) => (untrustedSpec ? DOMPurify.sanitize(html) : html);
function SanitizedMarkdownHTML(props: StylingMarkdownProps & { html: string }) {
const Wrap = props.inline ? StyledMarkdownSpan : StyledMarkdownBlock;
return (
<OptionsContext.Consumer>
{options => (
<Wrap
className={'redoc-markdown'}
dangerouslySetInnerHTML={{
__html: sanitize(options.untrustedSpec, props.html),
}}
{...props}
/>
)}
</OptionsContext.Consumer>
);
}
export interface MarkdownProps extends BaseMarkdownProps {
allowedComponents?: Dict<MDXComponentMeta>;
source: string;
}
export type MarkdownProps = BaseMarkdownProps &
StylingMarkdownProps & {
source: string;
className?: string;
};
export class Markdown extends React.Component<MarkdownProps> {
constructor(props: MarkdownProps) {
super(props);
if (props.allowedComponents && props.inline) {
throw new Error('Markdown Component: "inline" mode doesn\'t support "components"');
}
}
render() {
const { source, allowedComponents, store, inline, dense } = this.props;
if (allowedComponents && !store) {
throw new Error('When using componentes in markdown, store prop must be provided');
}
const { source, inline, dense, className } = this.props;
const renderer = new MarkdownRenderer();
if (allowedComponents) {
return (
<AdvancedMarkdown
parts={renderer.renderMdWithComponents(source, allowedComponents)}
{...this.props}
/>
);
} else {
return (
<SanitizedMarkdownHTML html={renderer.renderMd(source)} inline={inline} dense={dense} />
);
}
}
}
export interface AdvancedMarkdownProps extends BaseMarkdownProps {
parts: Array<string | MDXComponentMeta>;
}
export class AdvancedMarkdown extends React.Component<AdvancedMarkdownProps> {
render() {
const { inline, dense, store, parts } = this.props;
if (!parts.length) {
return null;
}
return (
<>
{parts.map(
(part, idx) =>
typeof part === 'string' ? (
<SanitizedMarkdownHTML html={part} inline={inline} dense={dense} key={idx} />
) : (
<part.component key={idx} {...{ ...part.attrs, ...part.propsSelector(store) }} />
),
)}
</>
<SanitizedMarkdownHTML
html={renderer.renderMd(source)}
inline={inline}
dense={dense}
className={className}
/>
);
}
}

View File

@ -0,0 +1,30 @@
import * as DOMPurify from 'dompurify';
import * as React from 'react';
import { OptionsConsumer } from '../OptionsProvider';
import { StylingMarkdownProps } from './Markdown';
import { StyledMarkdownBlock } from './styled.elements';
const StyledMarkdownSpan = StyledMarkdownBlock.withComponent('span');
const sanitize = (untrustedSpec, html) => (untrustedSpec ? DOMPurify.sanitize(html) : html);
export function SanitizedMarkdownHTML(
props: StylingMarkdownProps & { html: string; className?: string },
) {
const Wrap = props.inline ? StyledMarkdownSpan : StyledMarkdownBlock;
return (
<OptionsConsumer>
{options => (
<Wrap
className={'redoc-markdown ' + (props.className || '')}
dangerouslySetInnerHTML={{
__html: sanitize(options.untrustedSpec, props.html),
}}
{...props}
/>
)}
</OptionsConsumer>
);
}

View File

@ -23,20 +23,10 @@ const OperationRow = Row.extend`
contain: content;
overflow: hidden;
position: relative;
&:after {
position: absolute;
bottom: 0;
width: 100%;
display: block;
content: '';
border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}
`;
const Description = styled(Markdown)`
margin-bottom: ${({ theme }) => theme.spacing.unit * 8};
margin-bottom: ${({ theme }) => theme.spacing.unit * 6}px;
`;
export interface OperationProps {
@ -55,7 +45,7 @@ export class Operation extends React.Component<OperationProps> {
<OperationRow>
<MiddlePanel>
<H2>
<ShareLink href={'#' + operation.id} />
<ShareLink to={operation.id} />
{summary} {deprecated && <Badge type="warning"> Deprecated </Badge>}
</H2>
{options.pathInMiddlePanel && <Endpoint operation={operation} inverted={true} />}

View File

@ -34,7 +34,9 @@ export class MediaTypeSamples extends React.Component<PayloadSamplesProps> {
return (
<SmallTabs>
<TabList>
{examplesNames.map(name => <Tab key={name}> {examples[name].summary || name} </Tab>)}
{examplesNames.map(name => (
<Tab key={name}> {examples[name].summary || name} </Tab>
))}
</TabList>
{examplesNames.map(name => (
<TabPanel key={name}>{sampleView(examples[name].value)}</TabPanel>

View File

@ -2,12 +2,12 @@ import * as PropTypes from 'prop-types';
import * as React from 'react';
import { ThemeProvider } from '../../styled-components';
import { OptionsProvider } from '../OptionsProvider';
import { AppStore } from '../../services';
import { ApiDescription, ApiInfo } from '../ApiInfo/';
import { ApiInfo } from '../ApiInfo/';
import { ApiLogo } from '../ApiLogo/ApiLogo';
import { ContentItems } from '../ContentItems/ContentItems';
import { OptionsProvider } from '../OptionsProvider';
import { SideMenu } from '../SideMenu/SideMenu';
import { StickyResponsiveSidebar } from '../StickySidebar/StickyResponsiveSidebar';
import { ApiContentWrap, BackgroundStub, RedocWrap } from './styled.elements';
@ -57,7 +57,6 @@ export class Redoc extends React.Component<RedocProps> {
</StickyResponsiveSidebar>
<ApiContentWrap className="api-content">
<ApiInfo store={store} />
<ApiDescription description={store.spec.info.description} />
<ContentItems items={menu.items as any} />
</ApiContentWrap>
<BackgroundStub />

View File

@ -33,7 +33,8 @@ export class RedocStandalone extends React.PureComponent<RedocStandaloneProps> {
}
return null;
},
options: PropTypes.object,
options: PropTypes.any,
onLoaded: PropTypes.any,
};
render() {

View File

@ -7,6 +7,7 @@ import { MenuItem } from '../SideMenu/MenuItem';
import { MarkerService } from '../../services/MarkerService';
import { SearchResult } from '../../services/SearchWorker.worker';
import { PerfectScrollbarWrap } from '../../common-elements/perfect-scrollbar';
import {
ClearIcon,
SearchIcon,
@ -135,21 +136,27 @@ export class SearchBox extends React.PureComponent<SearchBoxProps, SearchBoxStat
onChange={this.search}
/>
{results.length > 0 && (
<SearchResultsBox data-role="search:results">
{results.map((res, idx) => (
<MenuItem
item={Object.create(res.item, {
active: {
value: idx === activeItemIdx,
},
})}
onActivate={this.props.onActivate}
withoutChildren={true}
key={res.item.id}
data-role="search:result"
/>
))}
</SearchResultsBox>
<PerfectScrollbarWrap
options={{
wheelPropagation: false,
}}
>
<SearchResultsBox data-role="search:results">
{results.map((res, idx) => (
<MenuItem
item={Object.create(res.item, {
active: {
value: idx === activeItemIdx,
},
})}
onActivate={this.props.onActivate}
withoutChildren={true}
key={res.item.id}
data-role="search:result"
/>
))}
</SearchResultsBox>
</PerfectScrollbarWrap>
)}
</SearchWrap>
);

View File

@ -24,7 +24,7 @@ export const SearchInput = styled.input.attrs({
outline: none;
`;
export const SearchIcon = styled((props: any) => (
export const SearchIcon = styled((props: { className?: string }) => (
<svg
className={props.className}
version="1.1"
@ -58,7 +58,6 @@ export const SearchResultsBox = styled.div`
margin-top: 10px;
line-height: 1.4;
font-size: 0.9em;
overflow: auto;
${MenuItemLabel} {
padding-top: 6px;

View File

@ -3,7 +3,7 @@ import * as React from 'react';
import styled from '../../styled-components';
import { UnderlinedHeader } from '../../common-elements/headers';
import { Link, UnderlinedHeader } from '../../common-elements/';
import { SecurityRequirementModel } from '../../services/models/SecurityRequirement';
import { linksCss } from '../Markdown/styled.elements';
@ -70,9 +70,11 @@ export class SecurityRequirement extends React.PureComponent<SecurityRequirement
{security.schemes.map(scheme => {
return (
<SecurityRequirementAndWrap key={scheme.id}>
<a href={'#' + scheme.sectionId}>{scheme.id}</a>
<Link to={scheme.sectionId}>{scheme.id}</Link>
{scheme.scopes.length > 0 && ' ('}
{scheme.scopes.map(scope => <ScopeName key={scope}>{scope}</ScopeName>)}
{scheme.scopes.map(scope => (
<ScopeName key={scope}>{scope}</ScopeName>
))}
{scheme.scopes.length > 0 && ') '}
</SecurityRequirementAndWrap>
);
@ -82,20 +84,23 @@ export class SecurityRequirement extends React.PureComponent<SecurityRequirement
}
}
const AuthHeaderColumn = styled.td``;
const AuthHeaderColumn = styled.div`
flex: 1;
`;
const SecuritiesColumn = styled.td`
const SecuritiesColumn = styled.div`
width: ${props => props.theme.schema.defaultDetailsWidth};
`;
const AuthHeader = UnderlinedHeader.extend`
display: inline-block;
margin: 0;
`;
const Table = styled.table`
const Wrap = styled.div`
width: 100%;
border-collapse: collapse;
font-size: inherit;
display: flex;
margin: 1em 0;
`;
export interface SecurityRequirementsProps {
@ -109,20 +114,16 @@ export class SecurityRequirements extends React.PureComponent<SecurityRequiremen
return null;
}
return (
<Table>
<tbody>
<tr>
<AuthHeaderColumn>
<AuthHeader>Authorizations: </AuthHeader>
</AuthHeaderColumn>
<SecuritiesColumn>
{securities.map((security, idx) => (
<SecurityRequirement key={idx} security={security} />
))}
</SecuritiesColumn>
</tr>
</tbody>
</Table>
<Wrap>
<AuthHeaderColumn>
<AuthHeader>Authorizations: </AuthHeader>
</AuthHeaderColumn>
<SecuritiesColumn>
{securities.map((security, idx) => (
<SecurityRequirement key={idx} security={security} />
))}
</SecuritiesColumn>
</Wrap>
);
}
}

View File

@ -2,7 +2,7 @@ import * as React from 'react';
import { SecuritySchemesModel } from '../../services/models';
import { H2, ShareLink } from '../../common-elements';
import { H2, MiddlePanel, Row, Section, ShareLink } from '../../common-elements';
import { OpenAPISecurityScheme } from '../../types';
import { Markdown } from '../Markdown/Markdown';
import { StyledMarkdownBlock } from '../Markdown/styled.elements';
@ -66,12 +66,12 @@ export interface SecurityDefsProps {
export class SecurityDefs extends React.PureComponent<SecurityDefsProps> {
render() {
return (
<div>
{this.props.securitySchemes.schemes.map(scheme => (
<div data-section-id={scheme.sectionId} key={scheme.id}>
return this.props.securitySchemes.schemes.map(scheme => (
<Section id={scheme.sectionId} key={scheme.id}>
<Row>
<MiddlePanel>
<H2>
<ShareLink href={'#' + scheme.sectionId} />
<ShareLink to={scheme.sectionId} />
{scheme.id}
</H2>
<Markdown source={scheme.description || ''} />
@ -118,9 +118,9 @@ export class SecurityDefs extends React.PureComponent<SecurityDefsProps> {
</tbody>
</table>
</StyledMarkdownBlock>
</div>
))}
</div>
);
</MiddlePanel>
</Row>
</Section>
));
}
}

View File

@ -3,6 +3,7 @@ import * as React from 'react';
import { ShelfIcon } from '../../common-elements/shelfs';
import { IMenuItem, OperationModel } from '../../services';
import { shortenHTTPVerb } from '../../utils/openapi';
import { MenuItems } from './MenuItems';
import { MenuItemLabel, MenuItemLi, MenuItemTitle, OperationBadge } from './styled.elements';
@ -51,7 +52,7 @@ export class MenuItem extends React.Component<MenuItemProps> {
{item.type === 'operation' ? (
<OperationMenuItemContent {...this.props} item={item as OperationModel} />
) : (
<MenuItemLabel depth={item.depth} active={item.active || item.expanded} type={item.type}>
<MenuItemLabel depth={item.depth} active={item.active} type={item.type}>
<MenuItemTitle title={item.name}>
{item.name}
{this.props.children}
@ -93,7 +94,7 @@ class OperationMenuItemContent extends React.Component<OperationMenuItemContentP
active={item.active}
deprecated={item.deprecated}
>
<OperationBadge type={item.httpVerb} />
<OperationBadge type={item.httpVerb}>{shortenHTTPVerb(item.httpVerb)}</OperationBadge>
<MenuItemTitle width="calc(100% - 32px)">
{item.name}
{this.props.children}

View File

@ -1,11 +1,10 @@
import { observer } from 'mobx-react';
import * as React from 'react';
import { OptionsContext } from '../OptionsProvider';
import { IMenuItem, MenuStore } from '../../services/MenuStore';
import { MenuItems } from './MenuItems';
import { PerfectScrollbar } from '../../common-elements/perfect-scrollbar';
import { PerfectScrollbarWrap } from '../../common-elements/perfect-scrollbar';
import { RedocAttribution } from './styled.elements';
@observer
@ -15,31 +14,20 @@ export class SideMenu extends React.Component<{ menu: MenuStore; className?: str
render() {
const store = this.props.menu;
return (
<OptionsContext.Consumer>
{options =>
options.nativeScrollbars ? (
<MenuItems
className={this.props.className}
style={{
overflow: 'auto',
msOverflowStyle: '-ms-autohiding-scrollbar',
}}
items={store.items}
onActivate={this.activate}
root={true}
/>
) : (
<PerfectScrollbar updateFn={this.saveScrollUpdate} className={this.props.className}>
<MenuItems items={store.items} onActivate={this.activate} root={true} />
<RedocAttribution>
<a target="_blank" href="https://github.com/Rebilly/ReDoc">
Documentation Powered by ReDoc
</a>
</RedocAttribution>
</PerfectScrollbar>
)
}
</OptionsContext.Consumer>
<PerfectScrollbarWrap
updateFn={this.saveScrollUpdate}
className={this.props.className}
options={{
wheelPropagation: false,
}}
>
<MenuItems items={store.items} onActivate={this.activate} root={true} />
<RedocAttribution>
<a target="_blank" href="https://github.com/Rebilly/ReDoc">
Documentation Powered by ReDoc
</a>
</RedocAttribution>
</PerfectScrollbarWrap>
);
}

View File

@ -8,59 +8,55 @@ export const OperationBadge = withProps<{ type: string }>(styled.span).attrs({
})`
width: 26px;
display: inline-block;
height: ${props => props.theme.typography.code.fontSize};;
height: ${props => props.theme.typography.code.fontSize};
line-height: ${props => props.theme.typography.code.fontSize};
background-color: #333;
border-radius: 3px;
vertical-align: top;
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAACgCAMAAADZ0KclAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAZQTFRF////////VXz1bAAAAAJ0Uk5T/wDltzBKAAAA80lEQVR42uSWSwLCIAxEX+5/aa2QZBJw5UIt9QMdRqSPEAAw/TyvqzZf150NzdXL49qreXwXjeqz9bqN1tgJl/KLyaVrrL7K7gx+1vlNMqy+helOO4rfBGYZiEkq1ubQ3DeKvc97Et+d+e01vIZlLZZqb1WNJFd8ZKYsmv4Hh3H2fDgjMUI5WSExjiEZs7rEZ5T+/jQn9lhgsw53j/e9MQtxqPsbZY54M5fNl/MY/f1s7NbRSkYlYjc0KPsWMrmhIU9933ywxDiSE+upYNH8TdusUotllNvcAUzfnE/NC4OSYyklQhpdl9E4Tw0Cm4/G9xBgAO7VCkjWLOMfAAAAAElFTkSuQmCC");
background-repeat: no-repeat;
background-position: 6px 4px;
text-indent: -9000px;
font-size: 7px;
font-family: Verdana; // web-safe
color: white;
text-transform: uppercase;
text-align: center;
font-weight: bold;
vertical-align: middle;
margin-right: 6px;
margin-top: 2px;
&.get {
background-position: 8px -12px;
background-color: ${props => props.theme.colors.http.get};
}
&.post {
background-position: 6px 4px;
background-color: ${props => props.theme.colors.http.post};
}
&.put {
background-position: 8px -28px;
background-color: ${props => props.theme.colors.http.put};
}
&.options {
background-position: 4px -148px;
background-color: ${props => props.theme.colors.http.options};
}
&.patch {
background-position: 4px -114px;
background-color: ${props => props.theme.colors.http.patch};
}
&.delete {
background-position: 4px -44px;
background-color: ${props => props.theme.colors.http.delete};
}
&.basic {
background-position: 5px -79px;
background-color: ${props => props.theme.colors.http.basic};
}
&.link {
background-position: 4px -131px;
background-color: ${props => props.theme.colors.http.link};
}
&.head {
background-position: 6px -102px;
background-color: ${props => props.theme.colors.http.head};
}
`;
@ -120,13 +116,15 @@ export const MenuItemLabel = withProps<{
active: boolean;
deprecated?: boolean;
type?: string;
}>(styled.label).attrs({
role: 'menuitem',
className: props =>
classnames('-depth' + props.depth, {
active: props.active,
}),
})`
}>(
styled.label.attrs({
role: 'menuitem',
className: props =>
classnames('-depth' + props.depth, {
active: props.active,
}),
}),
)`
cursor: pointer;
color: ${props =>
props.active ? props.theme.colors.primary.main : props.theme.colors.text.primary};
@ -164,9 +162,10 @@ export const MenuItemTitle = withProps<{ width?: string }>(styled.span)`
`;
export const RedocAttribution = styled.div`
${({ theme }) => `
font-size: 0.8em;
margin-top: ${({ theme }) => `${theme.spacing.unit * 2}px`};
padding: ${({ theme }) => `0 ${theme.spacing.unit * 4}px`};
margin-top: ${theme.spacing.unit * 2}px;
padding: 0 ${theme.spacing.unit * 4}px;
text-align: left;
opacity: 0.7;
@ -174,9 +173,10 @@ export const RedocAttribution = styled.div`
a,
a:visited,
a:hover {
color: ${({ theme }) => theme.colors.text.primary} !important;
color: ${theme.colors.text.primary} !important;
border-top: 1px solid #e1e1e1;
padding-top: 10px;
padding: ${theme.spacing.unit}px 0;
display: block;
}
`};
`;

View File

@ -1,7 +1,6 @@
export * from './RedocStandalone';
export * from './Redoc/Redoc';
export * from './ApiInfo/ApiInfo';
export * from './ApiInfo/ApiDescription';
export * from './ApiLogo/ApiLogo';
export * from './ContentItems/ContentItems';
export { ApiContentWrap, BackgroundStub, RedocWrap } from './Redoc/styled.elements';

View File

@ -1,5 +1,5 @@
export * from './components';
export { MiddlePanel, Row, RightPanel } from './common-elements/';
export { MiddlePanel, Row, RightPanel, Section } from './common-elements/';
export * from './services';
export * from './utils';

View File

@ -2,7 +2,7 @@ import { observe } from 'mobx';
import { OpenAPISpec } from '../types';
import { loadAndBundleSpec } from '../utils/loadAndBundleSpec';
import { HistoryService } from './HistoryService';
import { history } from './HistoryService';
import { MarkerService } from './MarkerService';
import { MenuStore } from './MenuStore';
import { SpecStore } from './models';
@ -10,6 +10,9 @@ import { RedocNormalizedOptions, RedocRawOptions } from './RedocNormalizedOption
import { ScrollService } from './ScrollService';
import { SearchStore } from './SearchStore';
import { SecurityDefs } from '../components/SecuritySchemes/SecuritySchemes';
import { SECURITY_DEFINITIONS_COMPONENT_NAME } from '../utils/openapi';
export interface StoreState {
menu: {
activeItemIdx: number;
@ -64,14 +67,14 @@ export class AppStore {
createSearchIndex: boolean = true,
) {
this.rawOptions = options;
this.options = new RedocNormalizedOptions(options);
this.options = new RedocNormalizedOptions(options, DEFAULT_OPTIONS);
this.scroll = new ScrollService(this.options);
// update position statically based on hash (in case of SSR)
MenuStore.updateOnHash(HistoryService.hash, this.scroll);
MenuStore.updateOnHistory(history.currentId, this.scroll);
this.spec = new SpecStore(spec, specUrl, this.options);
this.menu = new MenuStore(this.spec, this.scroll);
this.menu = new MenuStore(this.spec, this.scroll, history);
if (!this.options.disableSearch) {
this.search = new SearchStore();
@ -86,7 +89,7 @@ export class AppStore {
}
onDidMount() {
this.menu.updateOnHash();
this.menu.updateOnHistory();
this.updateMarkOnMenu(this.menu.activeItemIdx);
}
@ -137,3 +140,14 @@ export class AppStore {
this.marker.mark();
}
}
const DEFAULT_OPTIONS: RedocRawOptions = {
allowedMdComponents: {
[SECURITY_DEFINITIONS_COMPONENT_NAME]: {
component: SecurityDefs,
propsSelector: (store: AppStore) => ({
securitySchemes: store.spec.securitySchemes,
}),
},
},
};

View File

@ -4,11 +4,7 @@ import { IS_BROWSER } from '../utils/';
const EVENT = 'hashchange';
function isSameHash(a: string, b: string): boolean {
return a === b || '#' + a === b || a === '#' + b;
}
export class IntHistoryService {
export class HistoryService {
private _emiter;
constructor() {
@ -16,8 +12,15 @@ export class IntHistoryService {
this.bind();
}
get hash(): string {
return IS_BROWSER ? window.location.hash : '';
get currentId(): string {
return IS_BROWSER ? window.location.hash.substring(1) : '';
}
linkForId(id: string) {
if (!id) {
return '';
}
return '#' + id;
}
subscribe(cb): () => void {
@ -26,7 +29,7 @@ export class IntHistoryService {
}
emit = () => {
this._emiter.emit(EVENT, this.hash);
this._emiter.emit(EVENT, this.currentId);
};
bind() {
@ -43,26 +46,32 @@ export class IntHistoryService {
@bind
@debounce
update(hash: string | null, rewriteHistory: boolean = false) {
if (hash == null || isSameHash(hash, this.hash)) {
replace(id: string | null, rewriteHistory: boolean = false) {
if (!IS_BROWSER) {
return;
}
if (id == null || id === this.currentId) {
return;
}
if (rewriteHistory) {
if (IS_BROWSER) {
window.history.replaceState(null, '', window.location.href.split('#')[0] + '#' + hash);
}
window.history.replaceState(
null,
'',
window.location.href.split('#')[0] + this.linkForId(id),
);
return;
}
if (IS_BROWSER) {
window.history.pushState(null, '', window.location.href.split('#')[0] + '#' + hash);
}
window.history.pushState(null, '', window.location.href.split('#')[0] + this.linkForId(id));
this.emit();
}
}
export const HistoryService = new IntHistoryService();
export const history = new HistoryService();
if (module.hot) {
module.hot.dispose(() => {
HistoryService.dispose();
history.dispose();
});
}

View File

@ -2,6 +2,7 @@ import * as marked from 'marked';
import { highlight, safeSlugify } from '../utils';
import { AppStore } from './AppStore';
import { RedocNormalizedOptions } from './RedocNormalizedOptions';
const renderer = new marked.Renderer();
@ -12,7 +13,7 @@ marked.setOptions({
},
});
export const LEGACY_REGEXP = '^\\s*<!-- ReDoc-Inject:\\s+?{component}\\s+?-->\\s*$';
export const LEGACY_REGEXP = '^\\s*<!-- ReDoc-Inject:\\s+?<{component}\\s*?/?>\\s+?-->\\s*$';
export const MDX_COMPONENT_REGEXP = '^\\s*<{component}\\s*?/>\\s*$';
export const COMPONENT_REGEXP = '(?:' + LEGACY_REGEXP + '|' + MDX_COMPONENT_REGEXP + ')';
@ -35,13 +36,21 @@ export function buildComponentComment(name: string) {
}
export class MarkdownRenderer {
static containsComponent(rawText: string, componentName: string) {
const anyCompRegexp = new RegExp(
COMPONENT_REGEXP.replace(/{component}/g, componentName),
'gmi',
);
return anyCompRegexp.test(rawText);
}
headings: MarkdownHeading[] = [];
currentTopHeading: MarkdownHeading;
private headingEnhanceRenderer: marked.Renderer;
private originalHeadingRule: typeof marked.Renderer.prototype.heading;
constructor() {
constructor(public options?: RedocNormalizedOptions) {
this.headingEnhanceRenderer = new marked.Renderer();
this.originalHeadingRule = this.headingEnhanceRenderer.heading.bind(
this.headingEnhanceRenderer,
@ -140,15 +149,17 @@ export class MarkdownRenderer {
// TODO: rewrite this completelly! Regexp-based 👎
// Use marked ecosystem
renderMdWithComponents(
rawText: string,
components: Dict<MDXComponentMeta>,
): Array<string | MDXComponentMeta> {
renderMdWithComponents(rawText: string): Array<string | MDXComponentMeta> {
const components = this.options && this.options.allowedMdComponents;
if (!components || Object.keys(components).length === 0) {
return [this.renderMd(rawText)];
}
const componentDefs: string[] = [];
const names = '(?:' + Object.keys(components).join('|') + ')';
const anyCompRegexp = new RegExp(
COMPONENT_REGEXP.replace(/{component}/g, '(<?' + names + '.*?)'),
COMPONENT_REGEXP.replace(/{component}/g, '(' + names + '.*?)'),
'gmi',
);
let match = anyCompRegexp.exec(rawText);
@ -189,10 +200,6 @@ function parseComponent(
componentName?: string;
attrs: any;
} {
if (htmlTag.startsWith('<')) {
return legacyParse(htmlTag);
}
const match = /([\w_-]+)(\s+[\w_-]+\s*={[^}]*?})*/.exec(htmlTag);
if (match === null || match.length <= 1) {
return { componentName: undefined, attrs: {} };
@ -216,20 +223,3 @@ function parseComponent(
attrs,
};
}
function legacyParse(
htmlTag: string,
): {
componentName?: string;
attrs: any;
} {
const match = /<([\w_-]+).*?>/.exec(htmlTag);
if (match === null || match.length <= 1) {
return { componentName: undefined, attrs: {} };
}
const componentName = match[1];
return {
componentName,
attrs: {}, // TODO
};
}

View File

@ -1,5 +1,9 @@
import { OpenAPIOperation, OpenAPIParameter, OpenAPISpec, OpenAPITag, Referenced } from '../types';
import { isOperationName } from '../utils';
import {
isOperationName,
SECURITY_DEFINITIONS_COMPONENT_NAME,
setSecuritySchemePrefix,
} from '../utils';
import { MarkdownRenderer } from './MarkdownRenderer';
import { GroupModel, OperationModel } from './models';
import { OpenAPIParser } from './OpenAPIParser';
@ -38,7 +42,7 @@ export class MenuBuilder {
const items: ContentItemModel[] = [];
const tagsMap = MenuBuilder.getTagsWithOperations(spec);
items.push(...MenuBuilder.addMarkdownItems(spec.info.description || ''));
items.push(...MenuBuilder.addMarkdownItems(spec.info.description || '', options));
if (spec['x-tagGroups']) {
items.push(
...MenuBuilder.getTagGroupsItems(parser, undefined, spec['x-tagGroups'], tagsMap, options),
@ -53,8 +57,11 @@ export class MenuBuilder {
* extracts items from markdown description
* @param description - markdown source
*/
static addMarkdownItems(description: string): ContentItemModel[] {
const renderer = new MarkdownRenderer();
static addMarkdownItems(
description: string,
options: RedocNormalizedOptions,
): ContentItemModel[] {
const renderer = new MarkdownRenderer(options);
const headings = renderer.extractHeadings(description || '');
const mapHeadingsDeep = (parent, items, depth = 1) =>
@ -64,6 +71,14 @@ export class MenuBuilder {
if (heading.items) {
group.items = mapHeadingsDeep(group, heading.items, depth + 1);
}
if (
MarkdownRenderer.containsComponent(
group.description || '',
SECURITY_DEFINITIONS_COMPONENT_NAME,
)
) {
setSecuritySchemePrefix(group.id + '/');
}
return group;
});

View File

@ -2,10 +2,10 @@ import { action, observable } from 'mobx';
import { querySelector } from '../utils/dom';
import { SpecStore } from './models';
import { HistoryService } from './HistoryService';
import { history as historyInst, HistoryService } from './HistoryService';
import { ScrollService } from './ScrollService';
import { flattenByProp, normalizeHash } from '../utils';
import { flattenByProp, SECURITY_SCHEMES_SECTION_PREFIX } from '../utils';
import { GROUP_DEPTH } from './MenuBuilder';
export type MenuItemGroupType = 'group' | 'tag' | 'section';
@ -42,22 +42,24 @@ export class MenuStore {
* Statically try update scroll position
* Used before hydrating from server-side rendered html to scroll page faster
*/
static updateOnHash(hash: string = HistoryService.hash, scroll: ScrollService) {
if (!hash) {
static updateOnHistory(id: string = historyInst.currentId, scroll: ScrollService) {
if (!id) {
return;
}
scroll.scrollIntoViewBySelector(`[${SECTION_ATTR}="${normalizeHash(hash)}"]`);
scroll.scrollIntoViewBySelector(`[${SECTION_ATTR}="${id}"]`);
}
/**
* active item absolute index (when flattened). -1 means nothing is selected
*/
@observable activeItemIdx: number = -1;
@observable
activeItemIdx: number = -1;
/**
* whether sidebar with menu is opened or not
*/
@observable sideBarOpened: boolean = false;
@observable
sideBarOpened: boolean = false;
items: IMenuItem[];
flatItems: IMenuItem[];
@ -73,8 +75,8 @@ export class MenuStore {
* @param spec [SpecStore](#SpecStore) which contains page content structure
* @param scroll scroll service instance used by this menu
*/
constructor(spec: SpecStore, public scroll: ScrollService) {
this.items = spec.operationGroups;
constructor(spec: SpecStore, public scroll: ScrollService, public history: HistoryService) {
this.items = spec.contentItems;
this.flatItems = flattenByProp(this.items || [], 'items');
this.flatItems.forEach((item, idx) => (item.absoluteIdx = idx));
@ -84,7 +86,7 @@ export class MenuStore {
subscribe() {
this._unsubscribe = this.scroll.subscribe(this.updateOnScroll);
this._hashUnsubscribe = HistoryService.subscribe(this.updateOnHash);
this._hashUnsubscribe = this.history.subscribe(this.updateOnHistory);
}
@action
@ -132,22 +134,24 @@ export class MenuStore {
/**
* update active items on hash change
* @param hash current hash
* @param id current hash
*/
updateOnHash = (hash: string = HistoryService.hash): boolean => {
if (!hash) {
return false;
updateOnHistory = (id: string = this.history.currentId) => {
if (!id) {
return;
}
let item: IMenuItem | undefined;
hash = normalizeHash(hash);
item = this.flatItems.find(i => i.id === hash);
item = this.flatItems.find(i => i.id === id);
if (item) {
this.activateAndScroll(item, false);
} else {
this.scroll.scrollIntoViewBySelector(`[${SECTION_ATTR}="${hash}"]`);
if (id.startsWith(SECURITY_SCHEMES_SECTION_PREFIX)) {
item = this.flatItems.find(i => SECURITY_SCHEMES_SECTION_PREFIX.startsWith(i.id));
this.activate(item);
}
this.scroll.scrollIntoViewBySelector(`[${SECTION_ATTR}="${id}"]`);
}
return item !== undefined;
};
/**
@ -173,13 +177,13 @@ export class MenuStore {
/**
* activate menu item
* @param item item to activate
* @param updateHash [true] whether to update location hash
* @param updateLocation [true] whether to update location
* @param rewriteHistory [false] whether to rewrite browser history (do not create new enrty)
*/
@action
activate(
item: IMenuItem | undefined,
updateHash: boolean = true,
updateLocation: boolean = true,
rewriteHistory: boolean = false,
) {
if ((this.activeItem && this.activeItem.id) === (item && item.id)) {
@ -187,7 +191,7 @@ export class MenuStore {
}
this.deactivate(this.activeItem);
if (!item) {
HistoryService.update('', rewriteHistory);
this.history.replace('', rewriteHistory);
return;
}
@ -198,8 +202,8 @@ export class MenuStore {
}
this.activeItemIdx = item.absoluteIdx!;
if (updateHash) {
HistoryService.update(item.id, rewriteHistory);
if (updateLocation) {
this.history.replace(item.id, rewriteHistory);
}
item.activate();
@ -226,10 +230,14 @@ export class MenuStore {
* @see MenuStore.activate
*/
@action.bound
activateAndScroll(item: IMenuItem | undefined, updateHash?: boolean, rewriteHistory?: boolean) {
activateAndScroll(
item: IMenuItem | undefined,
updateLocation?: boolean,
rewriteHistory?: boolean,
) {
// item here can be a copy from search results so find corresponding item from menu
const menuItem = (item && this.getItemById(item.id)) || item;
this.activate(menuItem, updateHash, rewriteHistory);
this.activate(menuItem, updateLocation, rewriteHistory);
this.scrollToActive();
if (!menuItem || !menuItem.items.length) {
this.closeSidebar();

View File

@ -4,8 +4,8 @@ import { OpenAPIRef, OpenAPISchema, OpenAPISpec, Referenced } from '../types';
import { appendToMdHeading, IS_BROWSER } from '../utils/';
import { JsonPointer } from '../utils/JsonPointer';
import { isNamedDefinition } from '../utils/openapi';
import { buildComponentComment, COMPONENT_REGEXP, MDX_COMPONENT_REGEXP } from './MarkdownRenderer';
import { isNamedDefinition, SECURITY_DEFINITIONS_COMPONENT_NAME } from '../utils/openapi';
import { buildComponentComment, MarkdownRenderer } from './MarkdownRenderer';
import { RedocNormalizedOptions } from './RedocNormalizedOptions';
export type MergedOpenAPISchema = OpenAPISchema & { parentRefs?: string[] };
@ -74,16 +74,8 @@ export class OpenAPIParser {
) {
// Automatically inject Authentication section with SecurityDefinitions component
const description = spec.info.description || '';
const legacySecurityRegexp = new RegExp(
COMPONENT_REGEXP.replace('{component}', '<security-definitions>'),
'mi',
);
const securityRegexp = new RegExp(
MDX_COMPONENT_REGEXP.replace('{component}', 'security-definitions'),
'mi',
);
if (!legacySecurityRegexp.test(description) && !securityRegexp.test(description)) {
const comment = buildComponentComment('security-definitions');
if (!MarkdownRenderer.containsComponent(description, SECURITY_DEFINITIONS_COMPONENT_NAME)) {
const comment = buildComponentComment(SECURITY_DEFINITIONS_COMPONENT_NAME);
spec.info.description = appendToMdHeading(description, 'Authentication', comment);
}
}
@ -264,7 +256,9 @@ export class OpenAPIParser {
if (subSchemaRef) {
receiver.parentRefs!.push(subSchemaRef);
if (receiver.title === undefined && isNamedDefinition(subSchemaRef)) {
receiver.title = JsonPointer.baseName(subSchemaRef);
// this is not so correct behaviour. comented out for now
// ref: https://github.com/Rebilly/ReDoc/issues/601
// receiver.title = JsonPointer.baseName(subSchemaRef);
}
}
}

View File

@ -2,6 +2,8 @@ import defaultTheme, { ResolvedThemeInterface, resolveTheme, ThemeInterface } fr
import { querySelector } from '../utils/dom';
import { isNumeric, mergeObjects } from '../utils/helpers';
import { MDXComponentMeta } from './MarkdownRenderer';
export interface RedocRawOptions {
theme?: ThemeInterface;
scrollYOffset?: number | string | (() => number);
@ -17,6 +19,8 @@ export interface RedocRawOptions {
disableSearch?: boolean | string;
unstable_ignoreMimeParameters?: boolean;
allowedMdComponents?: Dict<MDXComponentMeta>;
}
function argValueToBoolean(val?: string | boolean): boolean {
@ -98,9 +102,11 @@ export class RedocNormalizedOptions {
/* tslint:disable-next-line */
unstable_ignoreMimeParameters: boolean;
allowedMdComponents: Dict<MDXComponentMeta>;
constructor(raw: RedocRawOptions) {
constructor(raw: RedocRawOptions, defaults: RedocRawOptions = {}) {
let hook;
raw = { ...defaults, ...raw };
if (raw.theme && raw.theme.extensionsHook) {
hook = raw.theme.extensionsHook;
raw.theme.extensionsHook = undefined;
@ -120,5 +126,7 @@ export class RedocNormalizedOptions {
this.disableSearch = argValueToBoolean(raw.disableSearch);
this.unstable_ignoreMimeParameters = argValueToBoolean(raw.unstable_ignoreMimeParameters);
this.allowedMdComponents = raw.allowedMdComponents || {};
}
}

View File

@ -13,7 +13,7 @@ export class SpecStore {
info: ApiInfoModel;
externalDocs?: OpenAPIExternalDocumentation;
operationGroups: ContentItemModel[];
contentItems: ContentItemModel[];
securitySchemes: SecuritySchemesModel;
constructor(
@ -24,8 +24,7 @@ export class SpecStore {
this.parser = new OpenAPIParser(spec, specUrl, options);
this.info = new ApiInfoModel(this.parser);
this.externalDocs = this.parser.spec.externalDocs;
this.operationGroups = MenuBuilder.buildStructure(this.parser, this.options);
this.contentItems = MenuBuilder.buildStructure(this.parser, this.options);
this.securitySchemes = new SecuritySchemesModel(this.parser);
}
}

View File

@ -1,9 +1,21 @@
import { MarkdownRenderer } from '../MarkdownRenderer';
import { MarkdownRenderer, MDXComponentMeta } from '../MarkdownRenderer';
import { RedocNormalizedOptions } from '../RedocNormalizedOptions';
const TestComponent = () => null;
describe('Markdown renderer', () => {
let renderer: MarkdownRenderer;
beforeEach(() => {
renderer = new MarkdownRenderer();
renderer = new MarkdownRenderer(
new RedocNormalizedOptions({
allowedMdComponents: {
'security-definitions': {
component: TestComponent,
propsSelector: () => ({}),
},
},
}),
);
});
test('should return a level-1 heading even though only level-2 is present', () => {
@ -19,4 +31,33 @@ describe('Markdown renderer', () => {
expect(headings[0].items).toBeDefined();
expect(headings[0].items).toHaveLength(1);
});
test('renderMdWithComponents should work with legacy syntax', () => {
const source = 'Hello!\n<!-- ReDoc-Inject: <security-definitions> -->\nBye';
const parts = renderer.renderMdWithComponents(source);
expect(parts).toHaveLength(3);
expect(parts[0]).toEqual('<p>Hello!</p>\n');
expect(typeof parts[1]).toEqual('object');
expect((parts[1] as MDXComponentMeta).component).toEqual(TestComponent);
expect(parts[2]).toEqual('<p>Bye</p>\n');
});
test('renderMdWithComponents should work with mdx-like syntax', () => {
const source = 'Hello!\n<security-definitions/>\nBye';
const parts = renderer.renderMdWithComponents(source);
expect(parts).toHaveLength(3);
expect(parts[0]).toEqual('<p>Hello!</p>\n');
expect(typeof parts[1]).toEqual('object');
expect((parts[1] as MDXComponentMeta).component).toBe(TestComponent);
expect(parts[2]).toEqual('<p>Bye</p>\n');
});
test('renderMdWithComponents should parse attribute names', () => {
const source = '<security-definitions pointer={"test"}/>';
const parts = renderer.renderMdWithComponents(source);
expect(parts).toHaveLength(1);
const part = parts[0] as MDXComponentMeta;
expect(part.component).toBe(TestComponent);
expect(part.attrs).toEqual({ pointer: 'test' });
});
});

View File

@ -1,25 +1,38 @@
import { HistoryService } from '../HistoryService';
import { history } from '../HistoryService';
describe('History service', () => {
test('should be an instance', () => {
expect(typeof HistoryService).not.toBe('function');
expect(HistoryService.subscribe).toBeDefined();
expect(typeof history).not.toBe('function');
expect(history.subscribe).toBeDefined();
});
test('History subscribe', () => {
const fn = jest.fn();
HistoryService.subscribe(fn);
HistoryService.emit();
history.subscribe(fn);
history.emit();
expect(fn).toHaveBeenCalled();
});
test('History subscribe should return unsubsribe function', () => {
const fn = jest.fn();
const unsubscribe = HistoryService.subscribe(fn);
HistoryService.emit();
const unsubscribe = history.subscribe(fn);
history.emit();
expect(fn).toHaveBeenCalled();
unsubscribe();
HistoryService.emit();
history.emit();
expect(fn).toHaveBeenCalledTimes(1);
});
test('currentId should return correct id', () => {
window.location.hash = '#testid';
expect(history.currentId).toEqual('testid');
});
test('should return correct link for id', () => {
expect(history.linkForId('testid')).toEqual('#testid');
});
test('should return empty link for empty id', () => {
expect(history.linkForId('')).toEqual('');
});
});

View File

@ -10,7 +10,8 @@ import { SchemaModel } from './Schema';
* Field or Parameter model ready to be used by components
*/
export class FieldModel {
@observable expanded: boolean = false;
@observable
expanded: boolean = false;
schema: SchemaModel;
name: string;

View File

@ -21,8 +21,10 @@ export class GroupModel implements IMenuItem {
parent?: GroupModel;
externalDocs?: OpenAPIExternalDocumentation;
@observable active: boolean = false;
@observable expanded: boolean = false;
@observable
active: boolean = false;
@observable
expanded: boolean = false;
depth: number;
level: number;

View File

@ -14,7 +14,8 @@ import { RedocNormalizedOptions } from '../RedocNormalizedOptions';
export class MediaContentModel {
mediaTypes: MediaTypeModel[];
@observable activeMimeIdx = 0;
@observable
activeMimeIdx = 0;
/**
* @param isRequestType needed to know if skipe RO/RW fields in objects

View File

@ -56,7 +56,7 @@ export class MediaTypeModel {
value: sample,
};
}
} else {
} else if (this.schema) {
this.examples = {
default: new ExampleModel(parser, {
value: Sampler.sample(

View File

@ -40,9 +40,12 @@ export class OperationModel implements IMenuItem {
depth: number;
@observable ready?: boolean = true;
@observable active: boolean = false;
@observable expanded: boolean = false;
@observable
ready?: boolean = true;
@observable
active: boolean = false;
@observable
expanded: boolean = false;
//#endregion
pointer: string;

View File

@ -9,7 +9,8 @@ import { FieldModel } from './Field';
import { MediaContentModel } from './MediaContent';
export class ResponseModel {
@observable expanded: boolean;
@observable
expanded: boolean;
content?: MediaContentModel;
code: string;

View File

@ -48,7 +48,8 @@ export class SchemaModel {
oneOf?: SchemaModel[];
oneOfType: string;
discriminatorProp: string;
@observable activeOneOf: number = 0;
@observable
activeOneOf: number = 0;
rawSchema: OpenAPISchema;
schema: MergedOpenAPISchema;

View File

@ -1,5 +1,5 @@
import { OpenAPISecurityRequirement, OpenAPISecurityScheme } from '../../types';
import { SECURITY_SCHEMES_SECTION } from '../../utils/openapi';
import { SECURITY_SCHEMES_SECTION_PREFIX } from '../../utils/openapi';
import { OpenAPIParser } from '../OpenAPIParser';
export interface SecurityScheme extends OpenAPISecurityScheme {
@ -27,7 +27,7 @@ export class SecurityRequirementModel {
return {
...scheme,
id,
sectionId: SECURITY_SCHEMES_SECTION + id,
sectionId: SECURITY_SCHEMES_SECTION_PREFIX + id,
scopes,
};
})

View File

@ -1,5 +1,5 @@
import { OpenAPISecurityScheme, Referenced } from '../../types';
import { SECURITY_SCHEMES_SECTION } from '../../utils/openapi';
import { SECURITY_SCHEMES_SECTION_PREFIX } from '../../utils/openapi';
import { OpenAPIParser } from '../OpenAPIParser';
export class SecuritySchemeModel {
@ -25,7 +25,7 @@ export class SecuritySchemeModel {
constructor(parser: OpenAPIParser, id: string, scheme: Referenced<OpenAPISecurityScheme>) {
const info = parser.deref(scheme);
this.id = id;
this.sectionId = SECURITY_SCHEMES_SECTION + id;
this.sectionId = SECURITY_SCHEMES_SECTION_PREFIX + id;
this.type = info.type;
this.description = info.description || '';
if (info.type === 'apiKey') {

View File

@ -24,10 +24,6 @@ export function html2Str(html: string): string {
.join(' ');
}
export function normalizeHash(hash: string): string {
return hash.startsWith('#') ? hash.substr(1) : hash;
}
// scrollIntoViewIfNeeded polyfill
if (typeof Element !== 'undefined' && !(Element as any).prototype.scrollIntoViewIfNeeded) {

View File

@ -16,6 +16,7 @@ import 'prismjs/components/prism-php.js';
import 'prismjs/components/prism-python.js';
import 'prismjs/components/prism-ruby.js';
import 'prismjs/components/prism-scala.js';
import 'prismjs/components/prism-sql.js';
import 'prismjs/components/prism-swift.js';
const DEFAULT_LANG = 'clike';

View File

@ -275,4 +275,14 @@ export function normalizeServers(
});
}
export const SECURITY_SCHEMES_SECTION = 'section/Authentication/';
export const SECURITY_DEFINITIONS_COMPONENT_NAME = 'security-definitions';
export let SECURITY_SCHEMES_SECTION_PREFIX = 'section/Authentication/';
export function setSecuritySchemePrefix(prefix: string) {
SECURITY_SCHEMES_SECTION_PREFIX = prefix;
}
export const shortenHTTPVerb = verb =>
({
delete: 'del',
options: 'opts',
}[verb] || verb);

View File

@ -88,8 +88,11 @@ export default (env: { standalone?: boolean } = {}, { mode }) => ({
{
loader: 'babel-loader',
options: {
generatorOpts: {
decoratorsBeforeExport: true,
},
plugins: [
'@babel/plugin-syntax-typescript',
['@babel/plugin-syntax-typescript', { isTSX: true }],
['@babel/plugin-syntax-decorators', { legacy: true }],
'@babel/plugin-syntax-jsx',
[
@ -114,6 +117,7 @@ export default (env: { standalone?: boolean } = {}, { mode }) => ({
transpileOnly: true,
compilerOptions: {
allowJs: true,
declaration: false,
},
},
},

1218
yarn.lock

File diff suppressed because it is too large Load Diff