JimLiu/baoyu-skills / skills/baoyu-diagram
baoyu-diagram
FlaggedCreate professional diagrams with configurable dark/light theme via CSS custom properties. Use this skill whenever the user asks for any kind of technical or conceptual diagram, visualization of a system, process flow, data flow, component relationship, network topology, decision tree, org chart, state machine, or any visual representation of structure/logic/process. Also trigger when the user says "画个图" "画一个架构图" "diagram" "flowchart" "sequence diagram" "draw me a ..." or uploads content and asks to visualize it. Outputs a dark-theme SVG, a light-theme SVG, and a @2x PNG of each.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 15.8 KB |
| references/architecture.md | markdown | 3.1 KB |
| references/flowchart.md | markdown | 2.3 KB |
| references/sequence.md | markdown | 3.9 KB |
| references/structural.md | markdown | 3.8 KB |
| scripts/bun.lock | other | 8.1 KB |
| scripts/flatten-vars.ts | script | 1.3 KB |
| scripts/main.ts | script | 5.3 KB |
| scripts/package.json | manifest | 104 B |
| scripts/theme-switch.ts | script | 7.1 KB |
| scripts/themes.test.ts | script | 2.9 KB |
| scripts/themes.ts | script | 4.1 KB |
| themes/dark.json | config | 958 B |
| themes/light.json | config | 978 B |
scripts/theme-switch.ts
View on GitHub#!/usr/bin/env bun
/**
* theme-switch.ts — Switch SVG theme between dark and light by replacing CSS custom property definitions.
*
* This script reads an SVG file, finds the `:root { ... }` block containing CSS custom property
* definitions, and replaces them with the target theme's color values. All `var(--variable)`
* references in the SVG markup remain unchanged — only the definitions are swapped.
*
* Usage:
* bun theme-switch.ts <svg-path> --theme=<name> [--output=<path>] [--validate]
*
* Themes are JSON files in {skillDir}/themes/ (e.g. dark.json, light.json).
* Each file is a flat object mapping CSS custom property names (keys starting
* with `--`) to color values; other keys (e.g. "description") are ignored.
* Add a new .json file there to create a custom theme, then use --theme=<name>.
*
* Example:
* bun theme-switch.ts diagram.svg --theme=light
* bun theme-switch.ts diagram.svg --theme=light --output=diagram-light.svg
* bun theme-switch.ts diagram.svg --theme=my-brand
*/
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { DEFAULT_THEME, listThemes, loadTheme as loadThemeFile } from './themes.ts';
import { resolve, dirname } from 'path';
// ─── Theme Loading ──────────────────────────────────────────────────────
// Shared with flatten-vars.ts and main.ts — see themes.ts.
function loadTheme(name: string): Record<string, string> {
try {
return loadThemeFile(name);
} catch (e) {
console.error(`Error: ${e instanceof Error ? e.message : e}`);
process.exit(1);
}
}
// ─── Core Logic ──────────────────────────────────────────────────────────────
/**
* Apply a theme to SVG content by replacing CSS custom property definitions
* inside the `:root { ... }` block within a `<style>` element.
*/
function applyTheme(svgContent: string, vars: Record<string, string>): string {
// Build the replacement :root block
const rootLines = Object.entries(vars)
.map(([key, value]) => ` ${key}: ${value};`)
.join('\n');
const newRootBlock = `:root {\n${rootLines}\n}`;
// Replace the :root { ... } block in the <style> element
// Pattern matches :root { ... } including multiline content
const rootBlockRegex = /:root\s*\{[^}]*\}/s;
if (rootBlockRegex.test(svgContent)) {
return svgContent.replace(rootBlockRegex, newRootBlock);
}
// Fallback: if no :root block found, check if there's a <style> tag and inject one
if (svgContent.includes('<style>')) {
const injectedRoot = `:root {\n${Object.entries(vars)
.map(([key, value]) => ` ${key}: ${value};`)
.join('\n')}\n}`;
return svgContent.replace('<style>', `<style>${injectedRoot}`);
}
// Last fallback: warn the user that the SVG doesn't follow the expected format
console.warn(
'Warning: No :root block or <style> element found in SVG. ' +
'The SVG may not have CSS custom properties defined. ' +
'Please ensure the SVG includes a <style>:root { ... } block.'
);
return svgContent;
}
/**
* Validate that all CSS variable references in the SVG match defined variables.
* Helps catch typos or missing variable definitions.
*/
function validateVariables(svgContent: string, vars: Record<string, string>): string[] {
const definedVars = new Set(Object.keys(vars));
const referencedVars = new Set<string>();
// Find all var(--xxx) references
const varRefRegex = /var\(--([^)]+)\)/g;
let match;
while ((match = varRefRegex.exec(svgContent)) !== null) {
referencedVars.add(`--${match[1]}`);
}
const missing = [...referencedVars].filter(v => !definedVars.has(v));
return missing;
}
// ─── CLI Entry Point ─────────────────────────────────────────────────────────
function parseArgs(argv: string[]): {
svgPath?: string;
theme?: string;
output?: string;
validate?: boolean;
} {
const args = argv.slice(2); // skip node and script path
const result: any = {};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
// Positional argument (svg path)
if (!arg.startsWith('--') && !result.svgPath) {
result.svgPath = arg;
continue;
}
// --theme=<name> or --theme <name> (any theme in {skillDir}/themes/)
if (arg.startsWith('--theme=')) {
result.theme = arg.split('=')[1];
} else if (arg === '--theme' && args[i + 1]) {
result.theme = args[++i];
}
// --output=path
if (arg.startsWith('--output=')) {
result.output = arg.split('=')[1];
} else if (arg === '--output' && args[i + 1]) {
result.output = args[++i];
}
// --validate
if (arg === '--validate') {
result.validate = true;
}
}
return result;
}
function main(): void {
const args = parseArgs(process.argv);
// Validate inputs
if (!args.svgPath) {
console.error('Usage: theme-switch.ts <svg-path> [--theme=<name>] [--output=<path>] [--validate]');
console.error('');
console.error('Arguments:');
console.error(' <svg-path> Path to the input SVG file');
console.error(` --theme=<name> Target theme from {skillDir}/themes/ (default: dark; available: ${listThemes().join(', ') || 'none'})`);
console.error(' --output=<path> Custom output path');
console.error(' --validate Check for undefined CSS variable references');
process.exit(1);
}
const theme: string = args.theme || DEFAULT_THEME;
const themeVars = loadTheme(theme);
const svgPath = resolve(args.svgPath);
if (!existsSync(svgPath)) {
console.error(`Error: File not found: ${svgPath}`);
process.exit(1);
}
if (!svgPath.endsWith('.svg')) {
console.error('Error: Input file must be a .svg file');
process.exit(1);
}
// Read SVG
const svgContent = readFileSync(svgPath, 'utf-8');
// Optional validation
if (args.validate) {
const missing = validateVariables(svgContent, themeVars);
if (missing.length > 0) {
console.error('Warning: The following CSS variables are referenced but not defined:');
missing.forEach(v => console.error(` - ${v}`));
console.error('');
console.error('Defined variables:');
Object.keys(themeVars).forEach(v => console.error(` - ${v}`));
process.exit(1);
}
console.log('Validation passed: all CSS variable references are defined.');
}
// Apply theme
const result = applyTheme(svgContent, themeVars);
// Determine output path
const outputDir = args.output ? dirname(args.output) : dirname(svgPath);
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
const outputPath = args.output || svgPath.replace('.svg', `.${theme}.svg`);
writeFileSync(outputPath, result, 'utf-8');
console.log(`Theme "${theme}" applied successfully: ${outputPath}`);
console.log(` Source: ${svgPath}`);
console.log(` Variables replaced: ${Object.keys(themeVars).length}`);
}
main();
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation). | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |