Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
jonaslagoni committed Sep 12, 2023
1 parent 293cd27 commit 7825a49
Show file tree
Hide file tree
Showing 10 changed files with 84 additions and 94 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ test/output
output
sample
coverage
__transpiled
33 changes: 20 additions & 13 deletions components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,37 @@ import { includeFile, generateBase64Favicon, renderSpec, stringifySpec, stringif
/**
* @param {{asyncapi: AsyncAPIDocumentInterface, params: any}} param0
*/
export function Index({ asyncapi, params }) {
export function Index({ asyncapi, params = {} }) {
const favicon = generateBase64Favicon(params);
let asyncapiScript = `<script src="js/asyncapi-ui.min.js" type="application/javascript"></script>`;
if(params?.singleFile) {
asyncapiScript = `<script type="text/javascript">
${includeFile('template/js/asyncapi-ui.min.js')}
</script>`;
}
let styling = `<link href="css/global.min.css" rel="stylesheet">
<link href="css/asyncapi.min.css" rel="stylesheet">`;
if(params?.singleFile) {
styling = `<style type="text/css">
${includeFile("template/css/global.min.css")}
${includeFile("template/css/asyncapi.min.css")}
</style>`;
}
return (`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
${params.baseHref && `<base href="${params.baseHref}">`}
${params?.baseHref && `<base href="${params.baseHref}">`}
<title>${asyncapi.info().title()} ${asyncapi.info().version()} documentation</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/x-icon" href="${generateBase64Favicon(params)}" />
${params.singleFile && `<style type="text/css">
${includeFile("template/css/global.min.css")}
${includeFile("template/css/asyncapi.min.css")}
</style>`}
${!params.singleFile && `<link href="css/global.min.css" rel="stylesheet">
<link href="css/asyncapi.min.css" rel="stylesheet">`}
<link rel="icon" type="image/x-icon" href="${favicon}" />
${styling}
</head>
<body>
<div id="root">${renderSpec(asyncapi, params)}</div>
${params.singleFile && ` <script type="text/javascript">
{{ "template/js/asyncapi-ui.min.js" | includeFile | safe }}
</script>`}
${!params.singleFile && `<script src="js/asyncapi-ui.min.js" type="application/javascript"></script>`}
${asyncapiScript}
<script>
const schema = ${stringifySpec(asyncapi)};
Expand Down
31 changes: 12 additions & 19 deletions helpers/all.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ const fs = require('fs');
const path = require('path');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const fetch = require('node-fetch');
const fetch = require('sync-fetch');
const { default: AsyncApiComponent, hljs } = require('@asyncapi/react-component');
const { stringify } = require('@asyncapi/parser');

const filter = module.exports;

function isJsonObject(o) {
return o && typeof o === 'object' && !Array.isArray(o);
}
Expand Down Expand Up @@ -35,7 +33,7 @@ function mergeInto(from, to) {
/**
* Prepares configuration for component.
*/
function prepareConfiguration(params = {}) {
export function prepareConfiguration(params = {}) {
const config = { show: { sidebar: true }, sidebar: { showOperations: 'byDefault' } };
// Apply config override
if (params.config) {
Expand Down Expand Up @@ -70,7 +68,7 @@ let initLanguages = false;
/**
* Load all language configurations from highlight.js
*/
function loadLanguagesConfig() {
export function loadLanguagesConfig() {
if (initLanguages === true) {
return;
}
Expand All @@ -91,12 +89,11 @@ function loadLanguagesConfig() {

initLanguages = true;
}
filter.loadLanguagesConfig = loadLanguagesConfig;

/**
* Generate Base64 value from favicon
*/
async function generateBase64Favicon(params) {
export async function generateBase64Favicon(params) {
const favicon = params.favicon;

// generate Base64 of AsyncAPI logo
Expand All @@ -106,9 +103,9 @@ async function generateBase64Favicon(params) {

try {
// Attempt to fetch favicon
const response = await fetch(favicon);
const response = fetch(favicon);
if (response.status == 200) {
const buffer = await response.buffer()
const buffer = response.buffer()
return "data:image/x-icon;base64," + buffer.toString('base64');
}
} catch (fetchErr) {
Expand All @@ -122,42 +119,38 @@ async function generateBase64Favicon(params) {
}
}
}
filter.generateBase64Favicon = generateBase64Favicon;

/**
* More safe function to include content of given file than default Nunjuck's `include`.
* Attaches raw file's content instead of executing it - problem with some attached files in template.
*/
function includeFile(pathFile) {
export function includeFile(pathFile) {
const pathToFile = path.resolve(__dirname, '../', pathFile);
return fs.readFileSync(pathToFile);
}
filter.includeFile = includeFile;

/**
* Stringifies the specification with escaping circular refs
* and annotates that specification is parsed.
*/
function stringifySpec(asyncapi) {
export function stringifySpec(asyncapi) {
return stringify(asyncapi);
}
filter.stringifySpec = stringifySpec;

/**
* Stringifies prepared configuration for component.
*/
function stringifyConfiguration(params) {
export function stringifyConfiguration(params) {
return JSON.stringify(prepareConfiguration(params));
}
filter.stringifyConfiguration = stringifyConfiguration;

/**
* Renders AsyncApi component by given AsyncAPI spec and with corresponding template configuration.
*/
function renderSpec(asyncapi, params) {
export function renderSpec(asyncapi, params) {
loadLanguagesConfig();
const config = prepareConfiguration(params);

const component = React.createElement(AsyncApiComponent, { schema: asyncapi, config: prepareConfiguration(params) });
const component = React.createElement(AsyncApiComponent, { schema: asyncapi, config });
return ReactDOMServer.renderToString(component);
}
filter.renderSpec = renderSpec;
17 changes: 14 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
"homepage": "https://github.com/asyncapi/html-template#readme",
"scripts": {
"lint": "echo \"No linter specified yet\"",
"develop": "npm run generate:assets && ag https://raw.githubusercontent.com/asyncapi/generator/v1.1.5/test/docs/dummy.yml ./ -o test/output --force-write --watch-template",
"//develop:install": "Force ag to install your local html-template source code",
"develop": "npm run generate:assets && node ./node_modules/@asyncapi/generator/cli.js https://raw.githubusercontent.com/asyncapi/generator/v1.1.5/test/docs/dummy.yml ./ -o test/output --force-write --watch-template",
"develop:install": " npm run develop -- --install",
"generate:assets": "npm run copy:sources && npm run generate:readme:toc",
"generate:readme:toc": "markdown-toc -i README.md",
Expand All @@ -39,11 +38,13 @@
"highlight.js": "10.7.3",
"node-fetch": "^2.6.7",
"puppeteer": "^14.1.0",
"rimraf": "^3.0.2"
"react-dom": "^17.0.2",
"rimraf": "^3.0.2",
"sync-fetch": "^0.5.2"
},
"devDependencies": {
"@asyncapi/parser": "^3.0.0-next-major-spec.2",
"@asyncapi/generator": "asyncapi/generator#add-v3-support",
"@asyncapi/parser": "^3.0.0-next-major-spec.2",
"cross-env": "^7.0.3",
"jest": "^26.6.3",
"jest-esm-transformer": "^1.0.0",
Expand Down
2 changes: 1 addition & 1 deletion scripts/copy-sources.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* Script that copies all given files from `node_modules` to the `template` folder.
* It is runned every time it package is published.
* It is run every time the package is published.
* This way we have an up to date sources to render the template.
*/

Expand Down
2 changes: 1 addition & 1 deletion template/css/asyncapi.min.css

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion template/index.html.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { File } from '@asyncapi/generator-react-sdk';
import { Index } from '../components';
import { Index } from '../components/index';

export default function({ asyncapi, params = {} }) {
return (
Expand Down
49 changes: 8 additions & 41 deletions template/js/asyncapi-ui.min.js

Large diffs are not rendered by default.

32 changes: 21 additions & 11 deletions test/helpers/all.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { hljs } from '@asyncapi/react-component';
import { AsyncAPIDocument } from "@asyncapi/parser";
import { createAsyncAPIDocument } from "@asyncapi/parser";

import {
includeFile,
Expand Down Expand Up @@ -55,26 +55,36 @@ describe('Helpers', () => {
'x-parser-circular-props': ['bar'],
}
schema.properties.bar = schema;
const doc = new AsyncAPIDocument({ asyncapi: '2.0.0', components: { schemas: { dummySchema: schema } }});
const doc = createAsyncAPIDocument({
semver: {
major: 2,
minor: 0,
patch: 0,
},
parsed: { asyncapi: '2.0.0', components: { schemas: { dummySchema: schema } }},
});

const expected = `{"asyncapi":"2.0.0","components":{"schemas":{"dummySchema":{"type":"object","properties":{"foo":{"type":"string","x-parser-schema-id":"<anonymous-schema-1>"},"bar":"$ref:$.components.schemas.dummySchema"},"x-parser-schema-id":"dummySchema","x-parser-circular-props":["bar"]}}},"x-parser-spec-parsed":true,"x-parser-spec-stringified":true}`;
const expected = `{\n \"asyncapi\": \"2.0.0\",\n \"components\": {\n \"schemas\": {\n \"dummySchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"foo\": {\n \"type\": \"string\"\n },\n \"bar\": \"$ref:$.components.schemas.dummySchema\"\n },\n \"x-parser-schema-id\": \"parsedDoc\",\n \"x-parser-circular-props\": [\n \"bar\"\n ]\n }\n }\n },\n \"x-parser-spec-stringified\": true\n}`;
const expectedParsed = {
asyncapi: '2.0.0',
asyncapi: "2.0.0",
components: {
schemas: {
dummySchema: {
type: 'object',
type: "object",
properties: {
foo: { type: 'string', 'x-parser-schema-id': '<anonymous-schema-1>' },
bar: '$ref:$.components.schemas.dummySchema',
foo: {
type: "string",
},
bar: "$ref:$.components.schemas.dummySchema",
},
'x-parser-schema-id': 'dummySchema',
'x-parser-circular-props': ['bar'],
"x-parser-schema-id": "parsedDoc",
"x-parser-circular-props": [
"bar",
],
},
},
},
'x-parser-spec-parsed': true,
'x-parser-spec-stringified': true,
"x-parser-spec-stringified": true,
};

const result = stringifySpec(doc);
Expand Down

0 comments on commit 7825a49

Please sign in to comment.