redoc/src/standalone.tsx

81 lines
1.9 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
2018-01-22 21:30:53 +03:00
import { render } from 'react-dom';
import { RedocStandalone } from './components/RedocStandalone';
2018-01-22 21:30:53 +03:00
import { querySelector } from './utils/dom';
2018-03-06 14:12:49 +03:00
export { Redoc, AppStore } from './index';
export const version = __REDOC_VERSION__;
export const revision = __REDOC_REVISION__;
function attributesMap(element: Element) {
2018-01-22 21:30:53 +03:00
const res = {};
const elAttrs = element.attributes;
// tslint:disable-next-line
for (let i = 0; i < elAttrs.length; i++) {
2018-01-22 21:30:53 +03:00
const attrib = elAttrs[i];
res[attrib.name] = attrib.value;
}
return res;
}
function parseOptionsFromElement(element: Element) {
const attrMap = attributesMap(element);
const res = {};
2018-01-22 21:30:53 +03:00
for (const attrName in attrMap) {
const optionName = attrName.replace(/-(.)/g, (_, $1) => $1.toUpperCase());
res[optionName] = attrMap[attrName];
// TODO: normalize options
}
return res;
}
export function init(
specOrSpecUrl: string | any,
options: any = {},
element: Element | null = querySelector('redoc'),
) {
if (element === null) {
throw new Error('"element" argument is not provided and <redoc> tag is not found on the page');
}
let specUrl: string | undefined;
let spec: object | undefined;
2017-11-20 16:02:35 +03:00
if (typeof specOrSpecUrl === 'string') {
specUrl = specOrSpecUrl;
} else if (typeof specOrSpecUrl === 'object') {
spec = specOrSpecUrl;
}
render(
React.createElement(
RedocStandalone,
{
2017-11-20 16:02:35 +03:00
spec,
specUrl,
options: { ...options, ...parseOptionsFromElement(element) },
},
['Loading...'],
),
element,
);
}
/**
* autoinit ReDoc if <redoc> tag is found on the page with "spec-url" attr
*/
function autoInit() {
const element = querySelector('redoc');
if (!element) {
return;
}
const specUrl = element.getAttribute('spec-url');
if (specUrl) {
init(specUrl, {}, element);
}
}
autoInit();