ClaudeMods
☰
KO
● — 명 접속 중 · 조회 — 회
후원프로젝트 제출
GitHub 저장소 · 작성자 galElmalah

mermaid-draw

Claude Code의 Mermaid 다이어그램: Claude가 작성하는 모든 ```mermaid 블록은 트랜스크립트에서 펜스가 있던 위치에 컬러 박스 아트로 그려집니다. 함수 훅(얼리 액세스)과 대화형 터미널이 필요합니다.

galElmalah@galElmalah

galElmalah/claude-mods/tree/main/claude-mermaid

번역 완료

이 mod 소개

mermaid-draw

Claude Code의 Mermaid 다이어그램. Claude가 작성하는 모든 ```mermaid 블록은 트랜스크립트에서 펜스가 있던 위치에 컬러 박스 아트로 그려집니다. 토큰이 전혀 들지 않습니다: 플러그인은 로컬에서 그리며, 화면에 다른 것은 나타나지 않습니다 — 창도, 버튼도 없습니다.

❯ how does a prompt become a reply?

⏺ A prompt flows through understanding and a decision point before a reply.

  ┌────────┐     ┌────────────┐     ◇────────────◇     ┌───────┐
  │        │     │            │     │            │     │       │
  │ Prompt ├────►│ Understand ├────►│ Use Tools? ├─Yes►│ Reply │
  │        │     │            │     │            │     │       │
  └────────┘     └────────────┘     ◇────────────◇     └───────┘

순서도, 상태, 시퀀스, 클래스 및 ER 다이어그램과 xy 차트가 그려집니다. 다른 종류(간트, 파이, 마인드맵 등)는 펜스를 유지합니다. 상하 순서도 또는 상태 다이어그램은 적합하고 아무것도 잃지 않을 때 왼쪽에서 오른쪽으로 배치됩니다 (터미널에서는 행이 소중합니다: 30행 대신 5행). 그리고 상태 다이어그램의 [*] 시작과 끝은 렌더러가 빈 상자로 그리기 때문에 생략됩니다.

모드: Claude Code 함수 훅 위에 구축된 플러그인으로, TypeScript가 Claude Code 자체 프로세스 내에서 실행됩니다. 얼리 액세스이므로 아래의 환경 변수가 필요하며 API는 릴리스 간에 변경될 수 있습니다.

요구 사항

  • Claude Code 2.1.270 이상, CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 포함.
  • 박스 그리기 문자를 가진 글꼴이 있는 대화형 터미널 세션 (없으면 /mermaid ascii on). claude -p에서는 아무것도 그려지지 않습니다.

빠른 시작

  1. ~/.claude/settings.json에서 함수 훅을 켭니다:

    { "env": { "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1" } }
    

    또는 한 세션의 경우: CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude.

  2. 클론에서 플러그인을 로드합니다(저장소 자체의 .claude/settings.json 은 그 안에서 시작된 세션의 변수를 설정합니다):

    git clone https://github.com/galElmalah/claude-mods
    cd claude-mods
    claude --plugin-dir claude-mermaid
    

    또는 저장소의 마켓플레이스 gal-mods에서 설치합니다:

    claude plugin marketplace add galElmalah/claude-mods
    claude plugin install mermaid-draw@gal-mods
    
  3. Claude에게 다이어그램을 요청합니다. 답변에 그려집니다.

claude-mermaid@claude-mods에서 업그레이드하시나요? 마이그레이션 지침을 따르세요.

사용

| 명령 | 기능 | | --- | --- | | /mermaid | 현재 설정을 표시합니다 | | /mermaid ascii on\|off | 박스 그리기 글리프 대신 일반 +--| 아트를 사용합니다(기본값 꺼짐) | | /mermaid color on\|off | 테두리는 청록색, 화살표는 노란색, 선은 흐리게 합니다(기본값 켜짐) | | /mermaid lr on\|off | 아무것도 잃지 않을 때 상하 순서도와 상태 다이어그램을 왼쪽에서 오른쪽으로 배치합니다(기본값 켜짐) | | /mermaid reset | 기본값으로 다시 설정합니다 |

설정은 이미 화면에 있는 다이어그램을 다시 그립니다. 설정은 세션 간에 플러그인의 저장소에 유지됩니다.

작동 방식

  • hooks/register.ts는 훅 모듈입니다. AssistantMessage의 ui.render를 훅합니다. 터미널에서 색상이 켜져 있으면 자체 트리를 반환합니다(산문에는 Markdown, 다이어그램 각 줄마다 하나의 Text, 색상은 span의 props로). Claude Code 2.1.287부터 재작성된 props.text에 이스케이프 시퀀스가 없을 수 있기 때문입니다. 그렇지 않으면 닫힌 각 mermaid 펜스를 일반 아트의 텍스트 펜스로 바꿉니다. 또한 /mermaid에 대한 command.run도 훅합니다.
  • hooks/diagrams.ts는 순수한 부분입니다. 펜스 찾기, 렌더링, 가로 레이아웃 선택(위에서 아래로 렌더링한 모든 단어가 살아남을 때만 유지됩니다. 렌더러가 반대 방향으로 달리는 엣지의 레이블을 덮어쓸 수 있기 때문입니다), 너비에 맞추기, 직렬화. bun test가 이를 커버합니다.
  • hooks/vendor/mermaid-ascii.js는 beautiful-mermaid의 ASCII 렌더러로, scripts/build-vendor.mjs에 의해 번들됩니다(훅 모듈은 Node 없이 실행되며 패키지를 가져올 수 없습니다). 렌더러는 ANSI만 출력하므로, 센티널 색상 테마에 대해 truecolor로 실행되고 이스케이프는 역할(테두리, 선, 화살표, 텍스트)로 디코딩된 다음 터미널 자체의 16색 팔레트로 색칠되어 밝은 테마와 어두운 테마 모두 읽을 수 있습니다.
  • 번들은 한 가지를 패치합니다. 업스트림의 A* 엣지 라우터는 무한 그리드를 검색하므로, 엣지의 대상을 펜스로 둘러싼 그래프는 약 25초 동안 실행되고 Map maximum size exceeded로 죽었으며, 이는 훅의 전체 예산을 태울 것입니다. 벤더링된 사본은 검색을 제한하고 직선 세그먼트로 폴백하므로 동일한 그래프가 약 60ms에 그려집니다. 렌더링된 아트는 소스와 글리프 세트별로 캐시됩니다. 훅은 첫 번째 그리기 후 몇 밀리초 안에 안정됩니다.

개발

npm install                 # esbuild, beautiful-mermaid, aimock, bun types
npm run build:vendor        # rebuilds hooks/vendor/mermaid-ascii.js
npm test                    # unit tests of hooks/diagrams.ts
npm run test:plugin         # render-hook tests in Claude Code's plugin test kit
npm run test:e2e            # the plugin inside a real Claude Code (below)
npm run typecheck           # against ../.claude/types (run /plugin-types first)
npm run validate            # what the engine sees the module hook and call

타입 검사에는 Claude Code 빌드의 선언이 필요합니다. 저장소 루트에서 함수 훅을 켜고 세션을 열고 /plugin-types를 실행하면 git에서 무시되는 .claude/types/가 작성됩니다.

플러그인 테스트 키트와 Bun은 서로 다른 런타임을 사용합니다. test:plugin은 훅과 키트 테스트를 임시 플러그인 폴더에 복사하므로 Claude의 러너가 Bun 테스트를 로드하려고 하지 않습니다. npm run test:all은 두 스위트와 엔드투엔드 테스트를 각각의 러너로 실행합니다.

엔드투엔드 테스트

tests/e2e는 tmux 창에서 실제 대화형 Claude Code를 구동하며, 그 응답은 aimock(로컬 포트의 Anthropic-API 모의 객체이고 ANTHROPIC_BASE_URL이 이를 가리킴)에 의해 스크립트되고, 플러그인은 체크아웃에서 --plugin-dir로 로드됩니다. 각 테스트는 프롬프트를 보내고, 화면에 무언가가 표시되기를 기다리고, 캡처된 텍스트에 대해 단언하며, 색상이 중요한 경우 -e를 사용합니다. 그려지는 모든 종류, 색상, 한 응답에 두 개의 다이어그램, 그려지지 않는 종류, 예전에 멈추던 밀집 그래프, 목록 항목 내부의 펜스, 옆으로 눕힌 레이아웃, 모든 /mermaid 형식, 그리고 아트에 비해 너무 좁은 터미널을 다룹니다. PATH에 tmux와 claude가 필요하고, 체크아웃이 Claude Code가 신뢰하는 폴더여야 합니다. 그렇지 않으면 건너뜁니다. 약 10초.

hooks/에 대한 편집은 실행 중인 --plugin-dir 세션에 핫 리로드됩니다. --debug-file /tmp/mermaid.log로 Claude를 시작하면 엔진이 무엇을 거부했는지 볼 수 있습니다.

제한

  • beautiful-mermaid가 그리지 않는 종류(gantt, pie, mindmap, gitGraph, journey, timeline, quadrant, C4, …)는 펜스를 유지합니다.
  • 트랜스크립트보다 넓은 아트는 오른쪽에서 …로 잘리고, 얼마나 초과했는지 알려주는 줄이 붙습니다. 터미널을 더 넓게 만드세요.
  • 색상은 터미널에서만 그려집니다. 데스크톱, VS Code, 모바일에서는 일반 아트가 표시됩니다. 다이어그램 사이의 산문이 10000자를 넘는 (하나의 Markdown 요소 상한) 응답도 일반으로 그려집니다.

라이선스

MIT.

설치

먼저 작성자의 README에서 marketplace와 플러그인 이름을 확인하세요. 저장소 구조에 따라 명령어가 달라질 수 있습니다.

claude plugin marketplace add galElmalah/claude-mods
claude plugin install mermaid-draw@gal-mods
원문 / README

mermaid-draw

Mermaid diagrams in Claude Code. Every ```mermaid block Claude writes is drawn as box art, in colour, right where the fence was in the transcript. Nothing costs a token: the plugin draws locally, and nothing else appears on screen — no pane, no buttons.

❯ how does a prompt become a reply?

⏺ A prompt flows through understanding and a decision point before a reply.

  ┌────────┐     ┌────────────┐     ◇────────────◇     ┌───────┐
  │        │     │            │     │            │     │       │
  │ Prompt ├────►│ Understand ├────►│ Use Tools? ├─Yes►│ Reply │
  │        │     │            │     │            │     │       │
  └────────┘     └────────────┘     ◇────────────◇     └───────┘

Flowcharts, state, sequence, class and ER diagrams and xy charts are drawn; other kinds (gantt, pie, mindmap, …) keep their fence. A top-down flowchart or state diagram is laid out left to right when that fits and loses nothing (rows are dear in a terminal: 5 rows instead of 30), and a state diagram's [*] start and end, which the renderer draws as empty boxes, are left out.

A mod: a plugin built on Claude Code function hooks, TypeScript that runs inside Claude Code's own process. Early access, so it needs the environment variable below and the API can change between releases.

Requirements

  • Claude Code 2.1.270 or later with CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1.
  • An interactive terminal session with a font that has box-drawing characters (/mermaid ascii on for one that does not). Nothing draws in claude -p.

Quick start

  1. Turn function hooks on, in ~/.claude/settings.json:

    { "env": { "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1" } }
    

    Or for one session: CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude.

  2. Load the plugin from a clone (the repo's own .claude/settings.json sets the variable for sessions started inside it):

    git clone https://github.com/galElmalah/claude-mods
    cd claude-mods
    claude --plugin-dir claude-mermaid
    

    Or install it from the repo's marketplace, gal-mods:

    claude plugin marketplace add galElmalah/claude-mods
    claude plugin install mermaid-draw@gal-mods
    
  3. Ask Claude for a diagram. It is drawn in the reply.

Upgrading from claude-mermaid@claude-mods? Follow the migration instructions.

Use

| command | what it does | | --- | --- | | /mermaid | shows the current settings | | /mermaid ascii on\|off | plain +--| art instead of box-drawing glyphs (default off) | | /mermaid color on\|off | borders cyan, arrows yellow, lines dim (default on) | | /mermaid lr on\|off | lay top-down flowcharts and state diagrams out left to right when nothing is lost (default on) | | /mermaid reset | the defaults again |

A setting redraws the diagrams already on screen. Settings are kept in the plugin's store across sessions.

How it works

  • hooks/register.ts is the hooks module. It hooks ui.render of AssistantMessage: with colour on, on the terminal, it returns a tree of its own (Markdown for the prose, one Text per diagram line, the colours as props on its spans), since a rewritten props.text may carry no escape sequence from Claude Code 2.1.287 on; otherwise it swaps each closed mermaid fence for a text fence of plain art. It also hooks command.run for /mermaid.
  • hooks/diagrams.ts is the pure part: finding fences, rendering, choosing the sideways layout (kept only when every word of the top-down render survives, since the renderer can overwrite the label of an edge that runs back the other way), fitting to a width, serializing. bun test covers it.
  • hooks/vendor/mermaid-ascii.js is beautiful-mermaid's ASCII renderer bundled by scripts/build-vendor.mjs (hooks modules run with no Node and cannot import packages). The renderer only emits ANSI, so it is run in truecolor against a theme of sentinel colours and the escapes are decoded back into roles (border, line, arrow, text), then coloured for the terminal's own 16-colour palette so light and dark themes both read.
  • The bundle patches one thing: upstream's A* edge router searches an unbounded grid, so a graph that fences an edge's target in ran for ~25 s and died on Map maximum size exceeded, which would burn the hook's whole budget. The vendored copy caps the search and falls back to a straight segment, so the same graph draws in ~60 ms. Rendered art is cached per source and glyph set; a hook settles in a few ms after the first draw.

Develop

npm install                 # esbuild, beautiful-mermaid, aimock, bun types
npm run build:vendor        # rebuilds hooks/vendor/mermaid-ascii.js
npm test                    # unit tests of hooks/diagrams.ts
npm run test:plugin         # render-hook tests in Claude Code's plugin test kit
npm run test:e2e            # the plugin inside a real Claude Code (below)
npm run typecheck           # against ../.claude/types (run /plugin-types first)
npm run validate            # what the engine sees the module hook and call

Typechecking needs the declarations of your Claude Code build: open a session in the repository root with function hooks on and run /plugin-types, which writes the git-ignored .claude/types/.

The plugin test kit and Bun use different runtimes. test:plugin copies the hooks and kit tests into a temporary plugin folder so Claude's runner does not try to load the Bun tests. npm run test:all runs both suites and the end-to-end tests with their respective runners.

End-to-end tests

tests/e2e drives a real interactive Claude Code in a tmux pane, its replies scripted by aimock (an Anthropic-API mock on a local port, ANTHROPIC_BASE_URL pointed at it), the plugin loaded from the checkout with --plugin-dir. Each test sends a prompt, waits for the screen to show a thing, and asserts on the captured text, with -e where colour matters. It covers every drawn kind, colours, two diagrams in one reply, an undrawn kind, the dense graph that used to hang, a fence inside a list item, the sideways layout, every /mermaid form, and a terminal too narrow for the art. Needs tmux and claude on PATH, and the checkout to be a folder Claude Code trusts; skipped otherwise. About 10 s.

Edits to hooks/ hot-reload into a running --plugin-dir session. Start Claude with --debug-file /tmp/mermaid.log to see what the engine refused.

Limits

  • Kinds beautiful-mermaid does not draw (gantt, pie, mindmap, gitGraph, journey, timeline, quadrant, C4, …) keep their fence.
  • Art wider than the transcript is cut at the right with … and a line saying by how much; make the terminal wider.
  • Colours are drawn on the terminal alone; desktop, VS Code and mobile show plain art. A reply whose prose between diagrams runs past 10000 characters (one Markdown element's cap) is drawn plain too.

License

MIT.

비슷한 프로젝트