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: add runnable code snippets #608

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions docusaurus.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ module.exports = {
require.resolve('docusaurus-plugin-segment'),
['./src/_plugins/google-tag-manager', { id: 'GTM-59XXGSG' }],
['./src/_plugins/alltius', { id: 'alltius' }],
'./src/_plugins/stacksjs-deps',
[
'docusaurus-plugin-openapi',
{
Expand Down
32 changes: 32 additions & 0 deletions src/_plugins/stacksjs-deps/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
module.exports = async function stacksJsDepsPlugin(_context, options) {
return {
name: 'stacksjs-deps-plugin',
injectHtmlTags() {
return {
postBodyTags: [
`
<script type="importmap" id="importmap">
{
"imports": {
"@stacks/common": "https://esm.sh/@stacks/[email protected]",
"@stacks/transactions": "https://esm.sh/@stacks/[email protected]",
"@stacks/network": "https://esm.sh/@stacks/[email protected]",
"@stacks/encryption": "https://esm.sh/@stacks/[email protected]",
"@stacks/profile": "https://esm.sh/@stacks/[email protected]",
"@stacks/auth": "https://esm.sh/@stacks/[email protected]",
"@stacks/storage": "https://esm.sh/@stacks/[email protected]",
"@stacks/wallet-sdk": "https://esm.sh/@stacks/[email protected]",
"@stacks/blockchain-api-client": "https://esm.sh/@stacks/[email protected]",
"@stacks/stacking": "https://esm.sh/@stacks/[email protected]",
"@stacks/connect": "https://esm.sh/@stacks/[email protected]",
"@noble/hashes/sha256": "https://esm.sh/@noble/[email protected]/sha256",
"crypto": "https://esm.sh/[email protected]",
"zone-file": "https://esm.sh/[email protected]"
}
}
</script>`,
],
};
},
};
};
102 changes: 102 additions & 0 deletions src/theme/CodeBlock/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import React, { useRef, useState } from 'react';
import CodeBlock from '@theme-original/CodeBlock';

const IMPORT_LINES_REGEX = /^import\s*(?:(?:(?:[\w*\s{},]*)\s*from)?\s*['"].+['"])?.*?(?:;|$)/gm;

export default function CodeBlockWrapper(props) {
const ref = useRef(null);

const run = () => {
const oldConsoleLog = console.log;
const oldConsoleError = console.error;

console.log = (...args) => {
ref.current.innerHTML += args.map(argToHtml()).join('');
};
console.error = (...args) => {
ref.current.innerHTML += args
.map(argToHtml('text-red-900 bg-red-100 text-red-50 dark:bg-red-950'))
.join('');
};

const uuid = crypto?.randomUUID() ?? 'uuid';
document.addEventListener(`scriptExecuted-${uuid}`, () => {
console.log = oldConsoleLog;
console.error = oldConsoleError;
document.head.removeChild(script);
});

const importStatements = props.children.match(IMPORT_LINES_REGEX)?.join('\n') || '';
const code = props.children.replace(IMPORT_LINES_REGEX, '');

const script = document.createElement('script');
script.setAttribute('type', 'module');
script.innerHTML = `
${importStatements};
try {
${code};
} catch(e) {
console.error(e);
}
document.dispatchEvent(new CustomEvent('scriptExecuted-${uuid}'));
`;
document.head.appendChild(script);
};

const isRunnable = props.metastring?.includes('run') ?? false;
if (!isRunnable) return <CodeBlock {...props} />;

return (
<>
<div className="relative">
<CodeBlock {...props} />
<button onClick={run} className="absolute right-2 bottom-2">
Run ▶︎
</button>
</div>
<div ref={ref} />
</>
);
}

function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}

function argToHtml(className = '') {
return arg => {
let value;
if (arg instanceof Error) {
value = escapeHtml(
JSON.stringify({ ...arg, message: arg.message, stack: arg.stack }, null, 2)
);
} else if (typeof arg === 'object') {
try {
value = escapeHtml(
JSON.stringify(
arg,
(key, value) => {
return typeof value === 'bigint' ? value.toString() : value;
},
2
)
);
} catch {
value = escapeHtml(arg);
}
} else if (typeof arg === 'string') {
value = escapeHtml(arg);
} else {
value = escapeHtml('' + arg);
}
const currentDate = new Date();
const formattedTime = currentDate.toISOString().split('T')[1].replace('Z', '').slice(0, -2);
const timeTag = "<span style='color: rgb(151 149 149)'>" + formattedTime + ' </span>';
return `<pre style="white-space:pre-wrap;" class="${className}">${timeTag}${value}</pre>`;
};
}
Loading