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

Stimulus hmr #6

Merged
merged 4 commits into from
Nov 21, 2023
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## v6.3.0

- stimulus HMR
- fix bug : stimulus restart vite dev server when controllers.json is updated
- split vite-plugin-symfony into 2 plugins `vite-plugin-symfony-entrypoints` and `vite-plugin-symfony-stimulus`.
- add new tests to vite-plugin-symfony
- doc : add mermaid charts

## v6.2.0

- fix #77 support Vite 5.x
Expand Down
2 changes: 2 additions & 0 deletions docs/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ node_modules/
.vitepress/dist/
.vscode/
.local/

graphs/
4 changes: 4 additions & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { defineConfig } from 'vitepress';
import { fileURLToPath, URL } from 'node:url';
import { renderMermaidGraphsPlugin } from './mermaid'

// https://vitepress.dev/reference/site-config
export default defineConfig({
vite: {
plugins: [
renderMermaidGraphsPlugin()
],
resolve: {
alias: [
{
Expand Down
3 changes: 3 additions & 0 deletions docs/.vitepress/mermaid.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"themeCSS": "* { line-height: 1.5; } span.edgeLabel { padding: 2px 5px; }"
}
84 changes: 84 additions & 0 deletions docs/.vitepress/mermaid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { exec } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFile, writeFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import type { Plugin, PluginOption } from 'vite';
import { mkdir, readdir } from 'node:fs/promises'

export async function getFilesInDirectory(directory: URL): Promise<string[]> {
return (await readdir(directory)).filter(file => file[0] !== '.');
}


const execPromise = promisify(exec);
const graphsDirectory = new URL('graphs/', import.meta.url);

const mermaidRegExp = /^```mermaid\n([\S\s]*?)\n```/gm;
const greaterThanRegExp = /&gt;/g;
const styleTagRegExp = /<style>[\S\s]*?<\/style>/gm;
const configFileURL = new URL('mermaid.config.json', import.meta.url);
const puppeteerConfigFileURL = new URL('puppeteer-config.json', import.meta.url);

export function renderMermaidGraphsPlugin(): Plugin {
const existingGraphFileNamesPromise = mkdir(graphsDirectory, { recursive: true })
.then(() => getFilesInDirectory(graphsDirectory))
.then(files => new Set(files.filter(name => name.endsWith('.svg'))));
const existingGraphsByName = new Map<string, Promise<string>>();

async function renderGraph(codeBlock: string, outFile: string) {
const existingGraphFileNames = await existingGraphFileNamesPromise;
const outFileURL = new URL(outFile, graphsDirectory);
if (!existingGraphFileNames.has(outFile)) {
const inFileURL = new URL(`${outFile}.mmd`, graphsDirectory);
await writeFile(inFileURL, codeBlock);
const { stdout, stderr } = await execPromise(
`npx mmdc --configFile ${fileURLToPath(
configFileURL
)} --puppeteerConfigFile ${fileURLToPath(puppeteerConfigFileURL)} --input ${fileURLToPath(
inFileURL
)} --output ${fileURLToPath(outFileURL)}`
);
if (stderr.trim()) console.log(stderr.trim());
if (stdout.trim()) console.log(stdout.trim());
}
const outFileContent = await readFile(outFileURL, 'utf8');
// Styles need to be placed top-level, so we extract them and then
// prepend them, separated with a line-break
const extractedStyles: string[] = [];
const baseGraph = outFileContent
// We need to replace some HTML entities
.replace(greaterThanRegExp, '>')
.replace(styleTagRegExp, styleTag => {
extractedStyles.push(styleTag);
return '';
});
console.log('Extracted styles from mermaid chart:', extractedStyles.length);
return `${extractedStyles.join('')}\n${baseGraph}`;
}

return {
enforce: 'pre',
name: 'render-mermaid-charts',
async transform(code, id) {
if (id.endsWith('.md')) {
const renderedGraphs: string[] = [];
const mermaidCodeBlocks: string[] = [];
let match: RegExpExecArray | null = null;
while ((match = mermaidRegExp.exec(code)) !== null) {
mermaidCodeBlocks.push(match[1]);
}
await Promise.all(
mermaidCodeBlocks.map(async (codeBlock, index) => {
const outFile = `${createHash('sha256').update(codeBlock).digest('base64url')}.svg`;
if (!existingGraphsByName.has(outFile)) {
existingGraphsByName.set(outFile, renderGraph(codeBlock, outFile));
}
renderedGraphs[index] = await existingGraphsByName.get(outFile)!;
})
);
return code.replace(mermaidRegExp, () => renderedGraphs.shift()!);
}
}
};
}
3 changes: 3 additions & 0 deletions docs/.vitepress/puppeteer-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"args": ["--no-sandbox"]
}
1 change: 1 addition & 0 deletions docs/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
2 changes: 2 additions & 0 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"author": "Hugues Tavernier",
"license": "ISC",
"devDependencies": {
"@mermaid-js/mermaid-cli": "^10.6.1",
"@typescript-eslint/eslint-plugin": "^6.11.0",
"@typescript-eslint/parser": "^6.11.0",
"eslint": "^8.53.0",
Expand All @@ -24,6 +25,7 @@
"prettier": "^3.1.0",
"sass": "^1.69.5",
"typescript": "5.2.2",
"vite": "^4",
"vitepress": "1.0.0-rc.25"
},
"type": "module"
Expand Down
Loading
Loading