跪拜 Guibai
← Back to the summary

Nine AI-Generated Diagrams to Decode Any Frontend Codebase

Whether you're just starting a new project or have been handed a legacy codebase, you face the same challenge—tens of thousands of lines of code, documentation that's either missing or outdated, and you have to figure it out on your own.

How do you get started?

I've seen two typical ways to fail. One is to let AI do it all—dump the code in and ask for a summary. The AI gives you a nice-sounding overview that seems reasonable, but you haven't verified anything, so you have zero confidence. The second is more subtle: you bury yourself in reading the code line by line, starting from the entry file. By day three you still haven't left the components directory, getting more and more lost in the details.

The root problem is the same for both: diving into details before building a global skeleton. Either you let AI dive in for you, or you dive in yourself.

My approach is the opposite—build the skeleton first, then fill in the flesh. Let AI draw the diagrams for you, and you verify, question, and supplement against those diagrams. If a diagram is wrong, you'll know immediately where it's wrong; if it's right, the entire project now has a coordinate system. When you later dive into details, you'll always know where you are.

Talk is cheap. Below I'll run through the source code of ant-design-pro for real—it's a complete admin system with routing, permissions, state management, and an API layer. It has everything you'd expect. Clone it and follow along.

First, pull the project locally:

git clone https://github.com/ant-design/ant-design-pro.git
cd ant-design-pro

The diagramming tool I use is Codex; Claude Code works too, depending on your preference. All the diagrams below were generated by Codex. See the results for yourself.


Diagram 1: Frontend Architecture Diagram

First things first: figure out what this project looks like. Don't rush into details; build the skeleton first.

Analyze the project source code and help me draw an overall architecture diagram for this frontend project.

## Layering Rules
- Layer according to [Component Layer (UI)], [Router Layer], [State Management Layer (Store/Context)], and [API Request Layer (Service)]
- Granularity: module-level only, do not expand specific implementation details. Each module must be labeled with its name and a one-sentence core responsibility.
- Infrastructure: build tools, deployment solutions, CI/CD, etc., go into a separate box (Infrastructure), don't expand details.

## Output
- Save as ./docs/frontend-architecture.svg

The result for ant-design-pro looks like this—four clear layers, with routing, state management, and the API layer each in their place:

Once this diagram is drawn, you can see the project's overall architecture at a glance—it's a panoramic view.

I've stepped on a landmine here: AI likes to draw the Infrastructure box as large as the core layers, stealing the spotlight. If it comes out wrong, just say "make Infrastructure smaller and put it in the corner." One sentence fixes it.


Diagram 2: Module Dependency Diagram

The architecture diagram shows "what it looks like"; this diagram shows "who depends on whom internally." The most valuable prompt in the entire set.

Analyze the import relationships among the project's internal source modules and generate a module dependency topology diagram.

## Analysis Rules
- Scan all internal import statements in source files (based on tsconfig paths aliases)
- Drill down to sub-module granularity (two levels after the alias), merge leaf nodes with no out-degree
- Control the number of nodes to 10~20, label each node with the module name + one-sentence responsibility
- Build an adjacency list, use DFS to detect bidirectional edges and minimal cycles, annotate the cyclic dependency count
- Highlight cyclic dependencies with bold red dashed lines, attach a statistical summary and details of cyclic pairs at the bottom

## Output
- ./docs/module-deps.svg

All the dependency relationships between ant-design-pro's modules are exposed once this diagram is generated:

Where cyclic dependencies hide, which module is everyone's "foundation," how many things are affected if you touch one module—it's all in this diagram. The industry has a vivid term for this: Blast Radius. The two or three most-depended-upon modules are the high-risk foundations; the leaf nodes with the fewest dependents are the safest entry points.

For example—if the diagram reveals that src/utils actually depends on src/pages/Login in reverse, that's a classic "sewer backflow." Utils should be the lowest, cleanest module, yet it depends on a business page in reverse. This kind of dependency is a wild pointer left over from history. When refactoring, don't touch it first; first figure out why this path exists, then seal it off.


Diagram 3: Interaction Sequence Diagram

The skeleton is clear. Next question: how does the business actually run? Pick the most important feature and trace it from entry to exit. In ant-design-pro, I chose user login—nothing strings together a system's skeleton better than login. Forms, validation, API, state management, route navigation—one chain touches everything.

For the project's core feature [Feature Name, e.g., User Login / Large File Upload], use global code search to retrieve real code and reconstruct its complete execution chain.

## Chain Coverage
- Start from the user triggering an action, fully trace: UI component event → API request call → Store/Global state update → View reactive rendering

## Annotation Rules
- Clearly annotate the component name, method name/Hook name, and core data passed at each step

## Output
- Save as ./docs/sequence-[FeatureName].svg

I specifically compared once—with the same prompt, the sequence diagram generated with and without "global code search for real code" were two completely different things. Without it, the AI hallucinated an entire chain out of thin air, even drawing non-existent APIs convincingly. At first glance, it looked real. With it added, every step could be matched against the source code.


Diagram 4: Data Model Diagram

ant-design-pro uses Umi's model plugin for state management. Each page has its own model, and there's a global userModel managing login state. If you try to figure out this architecture by just flipping through code without drawing a diagram, just understanding how data flows between userModel and each page model is enough to give you a headache. After drawing this diagram, it's a ten-minute job.

Deeply parse the state management or context definition files in the project (e.g., src/stores or src/contexts), analyze and sort out the core data models.

## Diagram Content
- Draw a data model relationship diagram, clearly annotating the state fields, core Actions, and their data types for each Model/Store

## Relationship Mapping
- Use lines to mark reference, composition, or derivation dependency relationships between Models/Stores

## Output
- Save as ./docs/data-model.svg

A side note—for TypeScript projects, also throw the core type files from the types/ or interfaces/ directory at the AI. Type definitions themselves are a data map. After the AI reads the types and then draws the data model diagram, the accuracy jumps significantly.


Diagram 5: State Machine Diagram

For the state machine diagram, I chose the login form to run. Why? After a dozen projects, I've found the login page is a disaster zone for state bugs—verification code countdowns, password error prompts, token expiration redirects, network disconnection retries. When there are many states, it's easy to miss one. This diagram flattens all transition paths. Which state is missing, which branch is omitted—a single glance and they're all red flags.

Deeply parse the source code of component [ComponentName/PageName], extract all state variables that control its core interactions.

## Coverage of Transitions
- Fully draw the state transition diagram, must cover core states like idle, loading, success, error, and edge-case exception branches

## Trigger Conditions
- On each state transition line, clearly annotate the action or event name that triggers the transition

## Output
- Save as ./docs/state-[ComponentName].svg


Diagram 6: Page Route Flow Diagram

ant-design-pro's route configuration is in config/routes.ts. Dozens of page nodes plus nested routes and permission guards—one diagram clarifies it all.

Analyze the route configuration file (e.g., router/index.ts or similar route table definition), sort out the site-wide page navigation logic.

## Nodes and Edges
- Each route page as a node, arrows point in the navigation direction, lines must note the navigation method (declarative link, programmatic navigation, or redirect)

## Guard Annotation
- For route nodes or global interception points with mounted route guards (BeforeEach / Guards), use a different color to highlight and distinguish them

## Output
- Save as ./docs/route-flow.svg

This diagram has a hidden use—on a new hire's first day, giving them this diagram is better than giving them the code. I've tried it. Ten minutes looking at the diagram helps a newcomer more than an hour flipping through code.


Diagram 7: Permission Route Guard Diagram

ant-design-pro's permission system lives in src/access.ts and the route guards. Login state checks, role permissions, page-level and button-level control—these are the most painful troubleshooting points in real business scenarios.

Analyze the core code related to permission verification in the project (e.g., permission.ts, auth.ts, and route interceptors).

## Flow Nodes
- Starting from a user initiating a page access, fully draw the decision tree: Login state check → Role judgment → Specific permission verification → Final pass or intercept

## Branch Destinations
- Decision nodes must state the verification logic, interception branches must clearly mark the redirect destination (e.g., redirect to /login or /403)

## Output
- Save as ./docs/auth-guard.svg


Diagram 8: External Dependency Diagram

I pull out this diagram every year before a major version upgrade—which dependencies are foundational, which are dependencies of dependencies. One look tells you the upgrade order.

Comprehensively analyze package.json, .env configuration files (e.g., .env.production), and README.md to help me sort out all external dependencies of this frontend project.

## Classification
Strictly divide all external dependencies into the following three categories:
- Core Frameworks & Heavy Dependencies (e.g., React/Vue ecosystem, UI component libraries, global/local state management, image processing libraries, etc.)
- Middleware & Infrastructure (e.g., build tools Vite/Webpack, unit testing frameworks Vitest, Node/BFF layer, Docker configuration, etc.)
- External APIs & Third-party Services (e.g., LLM APIs, customer service systems, monitoring/analytics services, etc.)

## Visual Presentation
- Draw as an architecture relationship diagram, using different colors to highlight and distinguish each category of dependency

## Output
- Save as ./docs/external-deps.svg


Diagram 9: Component Lifecycle Diagram

Pick a page in ant-design-pro that you modify most often, and let AI draw its complete lifecycle—from mount to unmount, when side effects run, when data loads, what Props updates trigger.

For the project's core component [ComponentName], draw its complete lifecycle from mount to unmount and an asynchronous execution sequence diagram.

## Key Nodes
- Must include Props updates, useEffect/watch execution order, Suspense pending state, ErrorBoundary error catching, and the timing of component lazy load asynchronous loading

## Execution Flow
- Clearly mark the trigger conditions for each phase and the execution order of side effects

## Output
- Save as ./docs/lifecycle-[ComponentName].svg

Honestly, this diagram is mostly unused. But once, when I was troubleshooting a bug where "the page keeps sending requests after navigating away," I searched for half an hour without finding the root cause. Later, I had AI draw this lifecycle diagram, and within ten minutes I pinpointed it: a missing unsubscribe in a useEffect cleanup function.


Summarizing the Nine Diagrams

Diagram Name Core Purpose What It Revealed in ant-design-pro
Frontend Architecture See at a glance if the four-layer skeleton is malformed Config → Pages → Data Models → Services, cleanly layered
Module Dependency Uncover cyclic dependencies, see who is whose foundation The dependency web among page/model/service
Interaction Sequence Trace a full chain from trigger to render Complete login chain trace, caller and callee at each step
Data Model Understand where data lives, who uses it, how it flows The reference relationship web of userModel and page models
State Machine Flatten all state transitions, find missing branches Login form: 6 state nodes, 9 transition edges
Route Flow Page navigation map, which nodes guards hang on Topology of dozens of route nodes + nested guards
Permission Guard Decision tree, who gets blocked at which node access.ts three-state judgment + route-level permission branches
External Dependencies Must-see before version upgrades, distinguish critical from cosmetic React + Umi + antd core iron triangle + plugins
Lifecycle Quick reference manual for async bug hunting Complete sequence from mount to unmount for a core page

Saving to docs/ Is Just the Beginning

The nine diagrams are drawn, but just saving them into docs/ is only the first step. My habit now is—create a CLAUDE.md or .cursor/rules file in the project root, and write the paths to the nine diagrams and a brief project summary into it. AI loads it automatically on startup. Subsequent code suggestions and problem analysis will all be based on the understanding you've accumulated. Next conversation, it won't ask "what does this project do" again; the map is already imprinted in its mind.

Appendix: Diagramming Skin for Domestic Models

Codex and Claude Code produce fairly stable diagram outputs, but if you're using domestic models, the default diagrams often have text overflow, card overlap, and messy layouts. In this case, you need to attach an extra visual specification to tell the AI how to control card sizes and prevent text overflow.

Just append the following prompt to any diagram prompt:

# Architecture Diagram Universal Skin Specification

## Canvas and Font
- Canvas background uniformly uses #F8FAFC, pure white or pure gray is forbidden
- Global text uses deep blue-black #0F172A, module titles 11-12px bold, responsibility descriptions 9px regular
- Description text must use low-saturation dark colors with a hue, pure gray is strictly forbidden

## Card Width Adaptation
- Fixed width for all cards is forbidden. Dynamically calculate width based on the longest single line of text within the card
- Text pixel estimation: English/Symbols × 5.5px, Chinese/Chinese punctuation × 11px
- Final card width = Text pixel value + 40px (including left and right padding)
- Fixed horizontal spacing between cards: 14px

## Card Height Determined by Line Count
- Description text is forbidden from being a single non-wrapping line; it must automatically wrap based on the card's available width
- Total lines = Math.ceil(Total text pixels / Available width)
- Card height = 32px (title area) + Total lines × 13px (per line height + line spacing)
- For multi-line text, use SVG foreignObject tags wrapping HTML divs, with height dynamically calculated by the above formula

## Visual Details
- Outer large container border-radius: 8px, inner small card border-radius: 6px
- Large container has a 56px wide solid-color sidebar on the left, with white bold centered text

Final Words

Don't expect AI to draw it perfectly in one go. It might miss critical asynchronous chains, draw dependency directions in reverse, or treat deprecated modules as core. AI only reads code; it can't read what's outside the code—historical baggage, implicit constraints, the special integration logic in Old Wang's head. It knows none of this.

Architecture decisions, business judgments, risk assessments—don't offload these to AI; it can't handle them. But flipping through code, sorting out relationships, drawing diagrams—these are grunt work, and AI is much faster than you. Divide the work clearly; don't get it backwards.

Diagrams aren't done once they're drawn. They're done once they're saved into docs/. But a word of caution—the larger the project, the more nodes there are. The first diagram AI draws will likely be a crowded mess or missing things. Don't expect a one-shot success; have AI adjust it. Tell it "this area is too crowded, split it up," "you missed the xxx module, add it," "this arrow direction is reversed." Iterating three to five rounds is normal. I also tweaked ant-design-pro several times before getting a presentable version.

Three months later, less than half of the understanding in your brain will remain, but the diagrams in the docs will always be there. The next person who takes over, opening it up and seeing these nine diagrams, will find it more useful than you explaining for three hours.


Don't just watch me run it. Try it on the project your company is working on right now. Drop in the 9 prompts one by one. Feel free to leave a comment in the section below.

Welcome to follow my public account: 深入浅出AI

55663d977f57f6cc6e888942ff5a99bb.jpg