Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Use fence for sandbox data #48

Merged
merged 1 commit into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/includer/ui/endpoint.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import stringify from 'json-stringify-safe';
import RefsService from '../services/refs';
import {dump} from 'js-yaml';

import {
COOKIES_SECTION_NAME,
Expand Down Expand Up @@ -114,7 +115,7 @@
bodyStr = JSON.stringify(prepareSampleObject(requestBody?.schema ?? {}), null, 2);
}

const props = JSON.stringify({
const props = dump({
pathParams,
searchParams,
headers,
Expand All @@ -127,7 +128,7 @@
host: host ?? '',
});

return block(['{% openapi sandbox %}', props, '{% end openapi sandbox %}']);
return block(['```openapi-sandbox\n' + props + '\n```']);
}

function request(data: Endpoint) {
Expand Down Expand Up @@ -216,7 +217,7 @@
const {type = 'schema', schema} = obj;
const sectionTitle = title(3)('Body');

let result: any[] = [sectionTitle];

Check warning on line 220 in src/includer/ui/endpoint.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

Unexpected any. Specify a different type

if (isPrimitive(schema.type)) {
result = [
Expand Down
99 changes: 17 additions & 82 deletions src/plugin/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,98 +1,33 @@
import type StateBlock from 'markdown-it/lib/rules_block/state_block';
import type Token from 'markdown-it/lib/token';
import type {MarkdownItPluginCb} from '@diplodoc/transform/lib/plugins/typings';
import {escape} from 'html-escaper';
import {load} from 'js-yaml';

const startMark = '{% openapi sandbox %}';
const endMark = '{% end openapi sandbox %}';

function parserOpenAPISandboxBlock(state: StateBlock, start: number, end: number, silent: boolean) {
let firstLine,
lastLine,
next,
lastPos,
found = false,
pos = state.bMarks[start] + state.tShift[start],
max = state.eMarks[start];

if (pos + startMark.length > max) {
return false;
}

if (state.src.slice(pos, pos + startMark.length) !== startMark) {
return false;
}

pos += startMark.length;
firstLine = state.src.slice(pos, max);

if (silent) {
return true;
}

if (firstLine.slice(-endMark.length) === endMark) {
firstLine = firstLine.slice(0, -endMark.length);
found = true;
}

for (next = start; !found; ) {
next++;

if (next >= end) {
break;
}

pos = state.bMarks[next] + state.tShift[next];
max = state.eMarks[next];

if (pos < max && state.tShift[next] < state.blkIndent) {
// non-empty line with negative indent should stop the list:
break;
}
function isSandboxBlock(token: Token) {
return token.type === 'fence' && token.info.match(/^\s*openapi-sandbox(\s*|$)/);
}

if (state.src.slice(pos, max).slice(-endMark.length) === endMark) {
lastPos = state.src.slice(0, max).lastIndexOf(endMark);
lastLine = state.src.slice(pos, lastPos);
found = true;
}
function applyTransforms({tokens}: {tokens: Token[]}) {
const blocks = tokens.filter(isSandboxBlock);

if (blocks.length) {
blocks.forEach((token) => {
token.type = 'openapi_sandbox_block';
token.tag = 'div';
token.attrSet('class', 'yfm-openapi-sandbox-js');
token.attrSet('data-props', encodeURIComponent(JSON.stringify(load(token.content))));
token.content = '';
});
}

state.line = next + 1;

const token = state.push('openapi_sandbox_block', 'openapi_sandbox', 0);
token.block = true;
token.content =
(firstLine ? firstLine + '\n' : '') +
state.getLines(start + 1, next, state.tShift[start], true) +
(lastLine ? lastLine : '');
token.map = [start, state.line];
token.markup = startMark;
return true;
}

const openapiSandboxBlock = (jsonString: string) => {
try {
const props = escape(jsonString);

return `<div class="yfm-sandbox-js" data-props="${props}"></div>`;
} catch (error) {
console.log(error);
return jsonString;
}
};

const openapiSandboxRenderer = (tokens: Token[], idx: number) => {
return openapiSandboxBlock(tokens[idx].content);
};

const openapiSandboxPlugin: MarkdownItPluginCb = (md) => {
try {
md.block.ruler.before('meta', 'openapi_sandbox_block', parserOpenAPISandboxBlock);
md.core.ruler.after('fence', 'openapi-sandbox', applyTransforms);
} catch (e) {
md.block.ruler.push('openapi_sandbox_block', parserOpenAPISandboxBlock);
md.core.ruler.push('openapi-sandbox', applyTransforms);
}

md.renderer.rules.openapi_sandbox_block = openapiSandboxRenderer;
};

export function transform() {
Expand Down
5 changes: 2 additions & 3 deletions src/runtime/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, {useEffect, useState} from 'react';
import {createPortal} from 'react-dom';
import {unescape} from 'html-escaper';

import {Sandbox} from './sandbox';

Expand All @@ -10,7 +9,7 @@
const [sandbox, setSandbox] = useState<HTMLElement | null>(null);

useEffect(() => {
document.addEventListener('click', (event: any) => {

Check warning on line 12 in src/runtime/index.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

Unexpected any. Specify a different type
if (!event?.target?.closest('.openapi')) {
return;
}
Expand All @@ -34,19 +33,19 @@
}, []);

useEffect(() => {
setSandbox(document.querySelector<HTMLElement>('.yfm-sandbox-js'));
setSandbox(document.querySelector<HTMLElement>('.yfm-openapi-sandbox-js'));
});

if (!sandbox || !sandbox.dataset.props) {
return null;
}

try {
const props = JSON.parse(unescape(sandbox.dataset.props));
const props = JSON.parse(decodeURIComponent(sandbox.dataset.props));

return createPortal(<Sandbox {...props} />, sandbox);
} catch (error) {
console.log(error);

Check warning on line 48 in src/runtime/index.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

Unexpected console statement

return null;
}
Expand Down
Loading