Creates inject-mermaid.sh to apply mermaid.js CDN injection to HTML files that contain mermaid code blocks. This can be called independently or integrated into deployment scripts. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
61 lines
1.7 KiB
Bash
Executable file
61 lines
1.7 KiB
Bash
Executable file
#!/usr/bin/env bash
|
|
# Injects mermaid.js script into HTML files that contain mermaid code blocks.
|
|
# Usage: inject-mermaid.sh <html_directory>
|
|
|
|
HTML_DIR="${1:-.}"
|
|
|
|
inject_mermaid() {
|
|
local html_file="$1"
|
|
python3 - "$html_file" << 'PYEOF'
|
|
import sys
|
|
|
|
path = sys.argv[1]
|
|
snippet = """\
|
|
<script type="module">
|
|
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
|
|
document.querySelectorAll('code.language-mermaid').forEach(el => {
|
|
const div = document.createElement('div');
|
|
div.className = 'mermaid';
|
|
div.textContent = el.textContent;
|
|
el.closest('pre').replaceWith(div);
|
|
});
|
|
mermaid.initialize({ startOnLoad: true, theme: 'dark' });
|
|
</script>"""
|
|
|
|
with open(path, encoding='utf-8') as f:
|
|
content = f.read()
|
|
|
|
# Skip if already injected
|
|
if 'mermaid.esm' in content:
|
|
sys.exit(0)
|
|
|
|
# Skip if no mermaid blocks
|
|
if 'language-mermaid' not in content:
|
|
sys.exit(0)
|
|
|
|
new_content = content.replace('</body>', snippet + '\n</body>', 1)
|
|
if new_content == content:
|
|
print(f"Warning: </body> not found in {path}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
with open(path, 'w', encoding='utf-8') as f:
|
|
f.write(new_content)
|
|
PYEOF
|
|
}
|
|
|
|
# Find and process all HTML files in the directory
|
|
if command -v python3 &>/dev/null; then
|
|
for html_file in "$HTML_DIR"/*.html; do
|
|
[ -f "$html_file" ] || continue
|
|
[ "$(basename "$html_file")" = "index.html" ] && continue
|
|
|
|
if grep -q 'language-mermaid' "$html_file" 2>/dev/null; then
|
|
if ! grep -q 'mermaid.esm' "$html_file" 2>/dev/null; then
|
|
inject_mermaid "$html_file" && echo " Injected mermaid.js into $(basename "$html_file")"
|
|
fi
|
|
fi
|
|
done
|
|
else
|
|
echo "Warning: python3 not found — skipping mermaid injection"
|
|
exit 1
|
|
fi
|