diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index ed7646b..e9f97f9 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -8,7 +8,7 @@ "skills": "./skills/", "interface": { "displayName": "QGraphFlow", - "shortDescription": "Architecture and flow diagrams: eleven kinds of interactive software diagrams from source, configuration and documents", + "shortDescription": "Architecture and flow diagrams: nine kinds of interactive software diagrams from source, configuration and documents", "longDescription": "Generate flow, architecture, sequence, ER, deployment, class, state, use-case and data-flow diagrams from CodeGraph or raw repository evidence; deliver an offline HTML viewer and an auditable graph.json with in-page SVG and PNG download.", "developerName": "Max Zheng", "category": "Productivity", diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 118d206..187f0c9 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -11,6 +11,7 @@ on: - 'skills/q-flow/scripts/**' - 'skills/q-flow/assets/**' - 'docs/pages/**' + - 'scripts/showcase-changes.mjs' - '.github/workflows/pages.yml' pull_request: paths: @@ -19,6 +20,7 @@ on: - 'skills/q-flow/scripts/**' - 'skills/q-flow/assets/**' - 'docs/pages/**' + - 'scripts/showcase-changes.mjs' - '.github/workflows/pages.yml' workflow_dispatch: @@ -42,6 +44,13 @@ jobs: node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json site/jeepay/zh-CN --repo-root output/jeepay-source node skills/q-flow/scripts/validate-graph.mjs site/jeepay/zh-CN/graph.json --repo-root output/jeepay-source cp docs/pages/index.html site/index.html + - name: Generate the update comparison shown in the README clip + run: | + for locale in zh-CN en; do + node scripts/showcase-changes.mjs "$locale" "output/changes-$locale" + node skills/q-flow/scripts/generate-viewer.mjs "output/changes-$locale/current.graph.json" "site/jeepay/changes/$locale" --compare "output/changes-$locale/earlier.graph.json" --repo-root output/jeepay-source + node skills/q-flow/scripts/validate-graph.mjs "site/jeepay/changes/$locale/graph.json" --repo-root output/jeepay-source + done - uses: actions/upload-pages-artifact@v5 with: path: site diff --git a/.github/workflows/publish-github-npm.yml b/.github/workflows/publish-github-npm.yml index 8d20fef..726a417 100644 --- a/.github/workflows/publish-github-npm.yml +++ b/.github/workflows/publish-github-npm.yml @@ -52,7 +52,7 @@ jobs: node verified/node_modules/@supermax92/qgraphflow/skills/q-flow/scripts/validate-graph.mjs examples/jeepay/flowchart.graph.json --input-only node verified/node_modules/@supermax92/qgraphflow/skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/flowchart.graph.json output/order # Generate the complete real-source Jeepay collection with the installed package. - node verified/node_modules/@supermax92/qgraphflow/skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/eleven + node verified/node_modules/@supermax92/qgraphflow/skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay - uses: actions/setup-node@v7 with: node-version: '22' diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..a9b8a5b --- /dev/null +++ b/README.en.md @@ -0,0 +1,301 @@ +
+ +

QGraphFlow

+ +### Turn complex code into diagrams you can explore. + +Follow the path. Inspect the evidence. Share one offline file. + +💡 Inspired by Cocoon-AI/architecture-diagram-generator — thanks to the original author for the idea. + +[中文](README.md) · [English](README.en.md) + +[Live demo](https://supermax92.github.io/qgraphflow/) · [Getting started](#getting-started) · [Client installation](#installation-guide) · [Report an issue](https://github.com/supermax92/qgraphflow/issues) · [MIT](LICENSE) + +
+ +![Jeepay multi-view interaction demo: component relationship architecture, sequence and ER diagrams](https://github.com/supermax92/qgraphflow/releases/download/showcase-v3/jeepay.en.hero.gif) + +Real Jeepay source: component names stay readable with the whole diagram on screen, each card opens on its source line, and one file switches between component relationship architecture, sequence and ER diagrams. [Watch the MP4](https://github.com/supermax92/qgraphflow/releases/download/showcase-v3/jeepay.en.hero.mp4) + +*Nine diagram types: component relationship architecture, flowchart, sequence, ER, deployment, class, state, use case and data flow.* + +QGraphFlow turns source code, schemas, configuration and requirements into interactive software diagrams, with evidence you can inspect and an offline HTML file you can share. + +**What sets it apart:** nine diagram types from one skill, an evidence kind on every relationship and the source line behind each code-backed one, automatic layout, editing in the page, and no network requests from the plugin scripts or the Viewer itself. + +![Code changes marked on the diagram: the added component framed in green, the renamed call in blue, this update listed on the right](https://github.com/supermax92/qgraphflow/releases/download/showcase-v3/jeepay.en.changes.gif) + +When the code changes, the diagram shows what changed: `generate --compare` checks against the previous version, marks added, changed and removed elements on the diagram and lists them under "This update", each with its source. The earlier version in this demo is fictional, made to show all three marks. [Try it online](https://supermax92.github.io/qgraphflow/jeepay/changes/en/) · [Watch the MP4](https://github.com/supermax92/qgraphflow/releases/download/showcase-v3/jeepay.en.changes.mp4) + +```bash +npx skills add supermax92/qgraphflow +``` + +One command installs the skill for Claude Code, Codex, Cursor and Qoder; the [installation guide](#installation-guide) covers the plugin installations and the other clients. + +- **Explore:** search, zoom and pan; inspect responsibilities and upstream/downstream relationships. + +- **Verify:** inspect nodes and edges for source files, lines, symbols and explicitly marked uncertainty. + +- **Edit:** unlock the layout, change text and move elements; reset when needed. + +- **Share:** open offline HTML or export the complete diagram as SVG / PNG. + +The real-source [Jeepay corpus](examples/jeepay) contains all nine views used by CI and the live demo. + +## Getting started + +After installation, open your application project in the client and select the `q-flow` skill. These examples use Claude Code's `/q-flow`; in Codex, use the `$q-flow` or `$qgraphflow:q-flow` entry actually provided by your client. Not installed yet? Read the [installation guide](#installation-guide) first. + +### 1. Empty input: Not sure where to start + +Invoke the skill without adding a request: + +```text +/q-flow +``` + +The skill guides you to choose the part to analyze and the question the diagram should answer. Drawing starts once the necessary information is clear. + +### 2. Ask about capabilities: Learn what it can draw + +```text +/q-flow What types of diagrams can you draw? What questions does each type answer? I have just taken over a project; introduce your capabilities and suggest a starting point. +``` + +Learn what the nine diagram types are for, then decide whether to explore project structure, call order, data relationships or something else. + +### 3. Vague input: Only a general goal + +```text +/q-flow Help me draw this project. I want to understand it as quickly as possible. +``` + +You do not need to specify a diagram type first. The skill selects a suitable view based on the project and your goal, and asks follow-up questions when necessary information is missing. + +### 4. Precise input: Define the scope and request drawing details + +Replace the business names and steps below with flows that actually exist in your project: + +```text +/q-flow Analyze the order creation flow in the current project and generate a sequence diagram in Chinese. +Cover the request entry point, pricing, stock reservation, payment authorization and order persistence. +Retain the synchronous calls, asynchronous messages, paired returns, activation bars, conditional branches, retries and failure compensation that actually exist in the source. Do not omit details for brevity. +Mark the source files and line numbers for components and calls, and save the result to docs/qgraphflow/order-sequence/. +``` + +State the subject, question, level of detail and output location clearly to start directly. The diagram retains only facts supported by evidence. + +### 5. Refine further: Expand part of the previous diagram + +After the result is generated, continue in the same conversation: + +```text +/q-flow Expand the stock reservation step in the previous sequence diagram into a separate flowchart in Chinese. +Show all branches for stock validation, successful reservation, retryable failures, the retry limit and stock release. Follow the source code and add no steps absent from it. +``` + +Start with the overall picture, then explore one step in depth. You can also request more detail in an existing diagram or verify its relationships. + +## Installation guide + +You need Node.js 22 or later and a plugin-capable client with model access configured. + +### Quick install + +```bash +npx skills add supermax92/qgraphflow +``` + +Tested with `skills` 1.7.0 for Claude Code, Codex, Cursor and Qoder. It asks which clients to install to; `-a claude-code` names one, and `-g` installs for your user instead of the current project. The skill installs as `q-flow`, without the `qgraphflow:` prefix of the plugin installations below. + +To install it as a plugin instead, follow the steps below. [Qoder Desktop](#qoder-desktop) users can install from the marketplace and skip step 1. + +### 1. Download the plugin + +Get the plugin from npmjs.com; no account, login or token is needed. Create a separate directory outside your application project: + +```bash +mkdir qgraphflow-install +cd qgraphflow-install +npm install qgraphflow --ignore-scripts +cd node_modules/qgraphflow +``` + +You are now in the plugin root. **Downloading through npm does not automatically install the plugin in your client;** continue with step 2. The package also provides the `qgraphflow` command used in [Keep diagrams in sync with code](#keep-diagrams-in-sync-with-code). + +Run the following terminal commands from **the plugin root containing `skills/`**. + +### 2. Install in your client + +#### Codex App / CLI + +Codex CLI must be installed and available in your terminal: + +```bash +codex plugin marketplace add . +codex plugin add qgraphflow@supermax92 +``` + +Start a new session, type `$`, and select `qgraphflow:q-flow`. + +#### Claude Code + +```bash +claude plugin marketplace add ./ +claude plugin install qgraphflow@supermax92 --scope user +``` + +Start a new session and enter `/q-flow` (or the fully qualified `/qgraphflow:q-flow`). + +#### Qoder CLI + +```bash +qodercli plugins install . +``` + +Start a new session and select `q-flow`. + +#### Qoder Desktop + +**Recommended:** Open **Settings → Plugins → Marketplace**, search for **QGraphFlow** or **代码图谱可视化**, and install the plugin. Start a new session and select `q-flow`. + +For local installation, complete step 1, then open **Settings → Plugins → Custom → Import** and import the complete plugin root directory. Start a new session and select `q-flow`. + +#### Cursor + +Copy everything in the plugin root, including hidden files, into: + +```text +~/.cursor/plugins/local/qgraphflow/ +``` + +Confirm that `.cursor-plugin/plugin.json` exists there, reload the window, and find `q-flow` in **Customize**. Back up any previous version first; do not mix old and new files. + +### 3. Start using it + +Open your application project in the client, start a new session and select the skill. Describe your request using the [Getting started](#getting-started) examples. Open the generated HTML in your browser. + +Building it yourself? See the [source build instructions](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). + +## Quick usage + +These examples use `$qgraphflow:q-flow` in Codex. If your client shows `$q-flow`, select that entry instead. For other clients, use the skill entry described above. + +**Not sure where to begin?** Invoke the skill and choose the subject and question when prompted. + +```text +$qgraphflow:q-flow +``` + +**Already have a goal?** Say which part to draw and what you want to understand. You do not need to choose a diagram type first. + +### Example 1: Understand the architecture + +```text +$qgraphflow:q-flow Analyze the current project and generate an architecture diagram in Chinese, showing the responsibilities of the main modules, dependencies and system boundaries. +``` + +Useful when joining a project and learning its overall structure. + +### Example 2: Trace a business flow + +```text +$qgraphflow:q-flow Analyze order creation and generate a sequence diagram in Chinese, showing the call order for pricing, stock reservation, payment and order persistence, and mark failure branches. +``` + +Replace order creation and its steps with your project's actual flow. Continue in the same conversation: + +```text +$qgraphflow:q-flow Expand the stock reservation step in the previous diagram into a separate flowchart in Chinese, showing success and failure handling. +``` + +Results go under `docs/qgraphflow/` by default. Open `index.html` to explore, edit and export; `graph.json` retains the graph data. Each view is also written as an SVG (`diagram.svg`, or `diagram--.svg` for several views) that you can embed as an image in a README, pull request or wiki. + +After editing in the page, **More → Save changes** in Chrome or Edge rewrites the page, `graph.json` and the SVGs in place once you pick the diagram's folder. Other browsers save `graph.json` only: put it in the folder and regenerate the page and SVGs with `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. + +
+Run the nine-view Jeepay source example + +Select your Jeepay source checkout to verify the evidence: + +```bash +export JEEPAY_REPO_ROOT="" +node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" +node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" +``` + +Open `output/jeepay/index.html`; its nine SVGs are in the same directory. See the [corpus README](examples/jeepay) for the source revision and refresh procedure. + +
+ +## Keep diagrams in sync with code + +A diagram generated with a repository root records where each component is defined, the line behind each code-backed relationship (a call, a foreign key) and a fingerprint of every file it points into. Validating it with `--repo-root` lets lines that only moved pass and fails when the code behind the diagram changed: a recorded line was rewritten, a call was removed, new code touches a drawn component that no relationship covers, or a name the diagram uses is gone. The error shows the old and new code and names the elements and text to update. Add this job to your CI; it needs no build, login or token, and full history (`fetch-depth: 0`) lets it compare against those fingerprints: + +```yaml +name: Diagrams +on: [push, pull_request] +jobs: + diagrams: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: actions/setup-node@v7 + with: + node-version: '22' + - run: | + for graph in docs/qgraphflow/*/graph.json; do + npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } + done + exit ${failed:-0} +``` + +To see the impact on the pull request, add `--changes changes.md` to the validate line and post the file when it fails, for example `gh pr comment "$PR" --body-file changes.md` (needs `pull-requests: write`). It lists, per view, the elements each change touches, the file and line, and the old and new code. The page regenerated after `--fix` also marks those elements and lists the changes beside the key points. + +When it fails, ask the skill to refresh that diagram: + +```text +$qgraphflow:q-flow CI says docs/qgraphflow/order-sequence is out of date. Refresh it. +``` + +The skill realigns every anchor, lists each change in the graph's `meta.sourceDrift`, updates only the elements those items name and regenerates the page and SVGs with your edited positions and text kept. It does not redraw the diagram. + +Add `--compare HEAD` when regenerating to see what a refresh changed: the page colors added and changed elements, lists removed ones beside the key points, and leaves `graph.json` untouched. + +## What each of the nine diagram types answers + +| View · PNG | Main question | Example scope | +| --- | --- | --- | +| Component relationship architecture | Which responsibility boundaries collaborate in the system? | Channels, transaction orchestration, pricing, risk, stock, payment, orders, events and fulfillment | +| Flowchart | How does each decision point branch and converge? | Stock shortage, risk rejection, compensation for payment failure and successful commit | +| Sequence | In what order does a request make calls and receive returns? | Successful checkout main flow and asynchronous OrderPaid | +| ER | How does core data relate? | Cart, orders, items, payments, stock reservations and parcels | +| Deployment | Where are runtime units placed and how are they connected? | Edge, Kubernetes, data services, payment and warehouse/logistics networks | +| Class | How do domain objects and code contracts depend on each other? | Checkout application service, Order and four ports | +| State | Which events and guards advance an order? | Payment, fulfillment, cancellation, refund and closure | +| Use case | What capabilities does each actor have? | Buyer, merchant, warehouse and customer support | +| Data flow | What transformations and stores do data assets pass through? | Cart, transaction decisions, order events, warehouse/logistics and delivery receipts | + +This is a concept model demonstrating QGraphFlow, not a particular e-commerce repository. The example `graph.json` invents no source paths and marks relationship evidence as `inference`. Real project diagrams need traceable source, DDL, configuration, tests and accepted requirements. + +## Develop and contribute + +```bash +npm ci --prefix skills/q-flow/assets/viewer +npm run build --prefix skills/q-flow/assets/viewer +node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs +``` + +Development needs Node.js 22 or later, npm, tar, zip and unzip. Include a minimal redacted graph, client/browser versions and reproduction steps in issue reports. + +Reference documentation (English): [Evidence sources](skills/q-flow/references/evidence-sources.md) · [Graph data format](skills/q-flow/references/graph-schema.md) · [Guided intake](skills/q-flow/references/guided-intake.md) · [Viewer development and acceptance](skills/q-flow/references/viewer-development.md) · [Visual conventions](skills/q-flow/references/visual-contract.md) + +## License and attribution + +[MIT](LICENSE) · [Third-party notices](THIRD_PARTY_NOTICES.md) + +QGraphFlow is an independent MIT-licensed project. The scenarios in this document are conceptual examples and do not represent any real company's production architecture. diff --git a/README.md b/README.md index 9ba5579..cf170ed 100644 --- a/README.md +++ b/README.md @@ -2,121 +2,119 @@

QGraphFlow

-### Turn complex code into diagrams you can explore. +### 把复杂代码,变成可以探索的图。 -Follow the path. Inspect the evidence. Share one offline file. +跟随路径,查看证据,用一个离线文件分享。 -💡 Inspired by Cocoon-AI/architecture-diagram-generator — thanks to the original author for the idea. +💡 灵感来自 Cocoon-AI/architecture-diagram-generator,感谢原作者的启发。 -[English](README.md) · [中文](docs/readme/README.zh-CN.md) · [Русский](docs/readme/README.ru.md) · [Português](docs/readme/README.pt.md) · [日本語](docs/readme/README.ja.md) · [Deutsch](docs/readme/README.de.md) · [Español](docs/readme/README.es.md) +[中文](README.md) · [English](README.en.md) -[Live demo](https://supermax92.github.io/qgraphflow/) · [Getting started](#getting-started) · [Client installation](#installation-guide) · [Report an issue](https://github.com/supermax92/qgraphflow/issues) · [MIT](LICENSE) +[在线演示](https://supermax92.github.io/qgraphflow/) · [快速入门](#快速入门) · [客户端安装](#安装指南) · [反馈问题](https://github.com/supermax92/qgraphflow/issues) · [MIT](LICENSE) -*Eleven diagram types: platform capability architecture, engineering layer architecture, component relationship architecture, flowchart, sequence, ER, deployment, class, state, use case and data flow.* +![Jeepay 多视图交互演示:组件关系架构图、时序图与 ER 图](https://github.com/supermax92/qgraphflow/releases/download/showcase-v3/jeepay.zh-CN.hero.gif) -QGraphFlow turns source code, schemas, configuration and requirements into interactive software diagrams, with evidence you can inspect and an offline HTML file you can share. +以 Jeepay 真实源码为例:整图缩小后仍能读出组件名,点开卡片就是对应的源码行,同一个文件里切换组件关系、时序与 ER 图。[观看 MP4](https://github.com/supermax92/qgraphflow/releases/download/showcase-v3/jeepay.zh-CN.hero.mp4) -**What sets it apart:** eleven diagram types from one skill, an evidence kind on every relationship and the source line behind each code-backed one, automatic layout, editing in the page, and no network requests from the plugin scripts or the Viewer itself. +*支持九类图:【组件关系架构图、流程图、时序图、ER 图、部署图、类图、状态图、用例图、数据流图】* -![Jeepay multi-view interaction demo: component relationship architecture, sequence and ER diagrams](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) +QGraphFlow 从源码、数据结构、配置和需求生成交互式软件图,让关系有据可查,并将结果交付为可分享的离线 HTML。 -Using real Jeepay source code, switch between component relationship architecture, sequence and ER diagrams to explore components and call relationships. [View full-size GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) +**差异在哪:** 一个技能覆盖九类图,每条关系都标明证据类别,有代码支撑的关系还记录对应的源码行,自动布局,能直接在页面里编辑,插件脚本和 Viewer 本身不发任何网络请求。 -**Complex sequence diagram showcase** +![代码改动标到图上:新增组件带绿框,改名的调用带蓝框,右侧列出本次更新](https://github.com/supermax92/qgraphflow/releases/download/showcase-v3/jeepay.zh-CN.changes.gif) -![Complex sequence diagram drawn step by step: participants, lifelines, messages, activation bars and nested combined fragments](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -A fictional e-commerce scenario contains 9 participants, 29 messages and 6 combined fragments, covering stock retries, nested branches, parallel processing, failure compensation and asynchronous callbacks. The animation progressively reveals the generated diagram to show its structure and details. [View full-size GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) +代码变了,图上直接标出变了什么:`generate --compare` 对比上一版,把新增、改动和删除的元素标在图上,并列在右侧"本次更新"里,每一项都能点开看源码出处。演示里的上一版是虚构的,用来展示三种标记。[在线体验](https://supermax92.github.io/qgraphflow/jeepay/changes/zh-CN/) · [观看 MP4](https://github.com/supermax92/qgraphflow/releases/download/showcase-v3/jeepay.zh-CN.changes.mp4) ```bash npx skills add supermax92/qgraphflow ``` -One command installs the skill for Claude Code, Codex, Cursor and Qoder; the [installation guide](#installation-guide) covers the plugin installations and the other clients. +一条命令即可为 Claude Code、Codex、Cursor 和 Qoder 装好技能;以插件方式安装和其他客户端见[安装指南](#安装指南)。 -- **Explore:** search, zoom and pan; inspect responsibilities and upstream/downstream relationships. +- **探索:** 搜索定位、缩放和平移画布,查看组件职责与上下游关系。 -- **Verify:** inspect nodes and edges for source files, lines, symbols and explicitly marked uncertainty. +- **核验:** 从节点或连线查看详情,核对源码文件、行号、符号和明确标注的不确定性。 -- **Edit:** unlock the layout, change text and move elements; reset when needed. +- **编辑:** 解锁后修改文字、移动元素;不满意时一键重置。 -- **Share:** open offline HTML or export the complete diagram as SVG / PNG. +- **分享:** 打开离线 HTML,或将完整图导出为 SVG / PNG。 -The real-source [Jeepay corpus](examples/jeepay) contains all eleven views used by CI and the live demo. +基于真实源码的 [Jeepay 语料](examples/jeepay)包含 CI 和在线演示用到的全部九个视图。 -## Getting started +## 快速入门 -After installation, open your application project in the client and select the `q-flow` skill. These examples use Claude Code's `/q-flow`; in Codex, use the `$q-flow` or `$qgraphflow:q-flow` entry actually provided by your client. Not installed yet? Read the [installation guide](#installation-guide) first. +安装后,在客户端打开你的业务项目,选择 `q-flow` 技能。以下以 Claude Code 的 `/q-flow` 为例;Codex 中使用客户端实际提供的 `$q-flow` 或 `$qgraphflow:q-flow` 入口。还未安装?先看[安装指南](#安装指南)。 -### 1. Empty input: Not sure where to start +### 1. 空白输入:不知道从哪里开始 -Invoke the skill without adding a request: +只调用技能,不附加需求: ```text /q-flow ``` -The skill guides you to choose the part to analyze and the question the diagram should answer. Drawing starts once the necessary information is clear. +技能会引导你选择要分析的部分,以及希望图回答的问题;必要信息明确后开始绘图。 -### 2. Ask about capabilities: Learn what it can draw +### 2. 询问能力:先了解能画什么 ```text -/q-flow What types of diagrams can you draw? What questions does each type answer? I have just taken over a project; introduce your capabilities and suggest a starting point. +/q-flow 你能绘制哪些类型的图?每类图适合回答什么问题?我刚接手一个项目,请先介绍能力并建议一个起点。 ``` -Learn what the eleven diagram types are for, then decide whether to explore project structure, call order, data relationships or something else. +先了解九类图的用途,再决定看项目结构、调用顺序、数据关系还是其他内容。 -### 3. Vague input: Only a general goal +### 3. 模糊输入:只有一个大致目标 ```text -/q-flow Help me draw this project. I want to understand it as quickly as possible. +/q-flow 帮我画一下这个项目,我想尽快看懂它。 ``` -You do not need to specify a diagram type first. The skill selects a suitable view based on the project and your goal, and asks follow-up questions when necessary information is missing. +不用先指定图类型。技能会根据项目和你的目标确定合适的视图,缺少必要信息时再追问。 -### 4. Precise input: Define the scope and request drawing details +### 4. 精准输入:明确范围并要求绘制细节 -Replace the business names and steps below with flows that actually exist in your project: +将下面的业务名称和步骤替换成项目中实际存在的流程: ```text -/q-flow Analyze the order creation flow in the current project and generate a sequence diagram in Chinese. -Cover the request entry point, pricing, stock reservation, payment authorization and order persistence. -Retain the synchronous calls, asynchronous messages, paired returns, activation bars, conditional branches, retries and failure compensation that actually exist in the source. Do not omit details for brevity. -Mark the source files and line numbers for components and calls, and save the result to docs/qgraphflow/order-sequence/. +/q-flow 分析当前项目的订单创建流程,生成中文时序图。 +覆盖请求入口、价格计算、库存预占、支付授权和订单落库。 +保留源码中实际存在的同步调用、异步消息、成对返回、激活条、条件分支、重试和失败补偿,不要为了简洁省略细节。 +标明组件与调用的源码文件和行号,将结果保存到 docs/qgraphflow/order-sequence/。 ``` -State the subject, question, level of detail and output location clearly to start directly. The diagram retains only facts supported by evidence. +把对象、问题、详细程度和输出位置说清楚,就能直接开始;图中只保留有证据支持的事实。 -### 5. Refine further: Expand part of the previous diagram +### 5. 继续细化:展开上一张图的局部 -After the result is generated, continue in the same conversation: +在生成结果后,于同一对话中继续: ```text -/q-flow Expand the stock reservation step in the previous sequence diagram into a separate flowchart in Chinese. -Show all branches for stock validation, successful reservation, retryable failures, the retry limit and stock release. Follow the source code and add no steps absent from it. +/q-flow 展开上一张时序图中的库存预占步骤,单独生成中文流程图。 +完整展示库存校验、预占成功、可重试失败、重试上限和释放库存的分支,以源码为准,不添加代码中没有的步骤。 ``` -Start with the overall picture, then explore one step in depth. You can also request more detail in an existing diagram or verify its relationships. +先看整体,再深入一个步骤;也可以继续要求补充已有图的细节或核验其中的关系。 -## Installation guide +## 安装指南 -You need Node.js 22 or later and a plugin-capable client with model access configured. +准备 Node.js 22 及以上版本,以及已配置好模型访问、支持插件功能的客户端。 -### Quick install +### 快速安装 ```bash npx skills add supermax92/qgraphflow ``` -Tested with `skills` 1.7.0 for Claude Code, Codex, Cursor and Qoder. It asks which clients to install to; `-a claude-code` names one, and `-g` installs for your user instead of the current project. The skill installs as `q-flow`, without the `qgraphflow:` prefix of the plugin installations below. +已用 `skills` 1.7.0 在 Claude Code、Codex、Cursor 和 Qoder 上实测。命令会询问装到哪些客户端;`-a claude-code` 可直接指定,`-g` 改为装到当前用户而不是当前项目。这样装上的技能名是 `q-flow`,不带下文插件安装方式里的 `qgraphflow:` 前缀。 -To install it as a plugin instead, follow the steps below. [Qoder Desktop](#qoder-desktop) users can install from the marketplace and skip step 1. +如需以插件方式安装,按以下步骤操作。[Qoder Desktop](#qoder-desktop) 可直接从插件商城安装,跳过第 1 步。 -### 1. Download the plugin +### 1. 下载插件 -Get the plugin from npmjs.com; no account, login or token is needed. Create a separate directory outside your application project: +从 npmjs.com 获取插件,无需账号、登录或令牌。在业务项目之外创建独立目录: ```bash mkdir qgraphflow-install @@ -125,22 +123,22 @@ npm install qgraphflow --ignore-scripts cd node_modules/qgraphflow ``` -You are now in the plugin root. **Downloading through npm does not automatically install the plugin in your client;** continue with step 2. The package also provides the `qgraphflow` command used in [Keep diagrams in sync with code](#keep-diagrams-in-sync-with-code). +此时已进入插件根目录。**npm 下载不会自动完成客户端安装**,请继续第 2 步。这个包还提供 `qgraphflow` 命令,[让图和代码保持同步](#让图和代码保持同步)一节会用到。 -Run the following terminal commands from **the plugin root containing `skills/`**. +以下终端命令均在**包含 `skills/` 的插件根目录**执行。 -### 2. Install in your client +### 2. 选择客户端安装 #### Codex App / CLI -Codex CLI must be installed and available in your terminal: +终端需已安装 Codex CLI: ```bash codex plugin marketplace add . codex plugin add qgraphflow@supermax92 ``` -Start a new session, type `$`, and select `qgraphflow:q-flow`. +新建会话,输入 `$`,选择 `qgraphflow:q-flow`。 #### Claude Code @@ -149,7 +147,7 @@ claude plugin marketplace add ./ claude plugin install qgraphflow@supermax92 --scope user ``` -Start a new session and enter `/q-flow` (or the fully qualified `/qgraphflow:q-flow`). +新建会话,输入 `/q-flow`(或完整名称 `/qgraphflow:q-flow`)。 #### Qoder CLI @@ -157,70 +155,70 @@ Start a new session and enter `/q-flow` (or the fully qualified `/qgraphflow:q-f qodercli plugins install . ``` -Start a new session and select `q-flow`. +新建会话,选择 `q-flow`。 #### Qoder Desktop -**Recommended:** Open **Settings → Plugins → Marketplace**, search for **QGraphFlow** or **代码图谱可视化**, and install the plugin. Start a new session and select `q-flow`. +**推荐:**打开 **Settings → Plugins → Marketplace**,搜索 **QGraphFlow** 或 **代码图谱可视化**,安装插件。新建会话,选择 `q-flow`。 -For local installation, complete step 1, then open **Settings → Plugins → Custom → Import** and import the complete plugin root directory. Start a new session and select `q-flow`. +如需本地安装,先完成第 1 步,再打开 **Settings → Plugins → Custom → Import**,导入完整的插件根目录。新建会话,选择 `q-flow`。 #### Cursor -Copy everything in the plugin root, including hidden files, into: +将插件根目录中的全部内容(含隐藏文件)复制到: ```text ~/.cursor/plugins/local/qgraphflow/ ``` -Confirm that `.cursor-plugin/plugin.json` exists there, reload the window, and find `q-flow` in **Customize**. Back up any previous version first; do not mix old and new files. +确认其中存在 `.cursor-plugin/plugin.json`,重新加载窗口,在 **Customize** 中找到 `q-flow`。若已有旧版本,先备份,勿混合新旧文件。 -### 3. Start using it +### 3. 开始使用 -Open your application project in the client, start a new session and select the skill. Describe your request using the [Getting started](#getting-started) examples. Open the generated HTML in your browser. +在客户端打开你的业务项目,新建会话并选择技能,按[快速入门](#快速入门)中的示例描述需求。生成后,用浏览器打开输出的 HTML。 -Building it yourself? See the [source build instructions](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). +需要自行构建?参见[源码构建说明](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally)。 -## Quick usage +## 快速使用 -These examples use `$qgraphflow:q-flow` in Codex. If your client shows `$q-flow`, select that entry instead. For other clients, use the skill entry described above. +以下以 Codex 的 `$qgraphflow:q-flow` 入口为例;如果客户端显示 `$q-flow`,请选择它实际提供的入口。其他客户端使用上方对应的技能入口。 -**Not sure where to begin?** Invoke the skill and choose the subject and question when prompted. +**不知道从哪里开始?** 直接调用,按提示选择要分析的部分和想了解的问题。 ```text $qgraphflow:q-flow ``` -**Already have a goal?** Say which part to draw and what you want to understand. You do not need to choose a diagram type first. +**目标已经明确?** 一句话说明“画哪个部分+想看什么”,无需先选择图类型。 -### Example 1: Understand the architecture +### 示例一:看懂项目架构 ```text -$qgraphflow:q-flow Analyze the current project and generate an architecture diagram in Chinese, showing the responsibilities of the main modules, dependencies and system boundaries. +$qgraphflow:q-flow 分析当前项目,生成中文架构图,展示主要模块的职责、依赖关系和系统边界。 ``` -Useful when joining a project and learning its overall structure. +适合初次接触项目,先了解整体结构。 -### Example 2: Trace a business flow +### 示例二:追踪业务调用 ```text -$qgraphflow:q-flow Analyze order creation and generate a sequence diagram in Chinese, showing the call order for pricing, stock reservation, payment and order persistence, and mark failure branches. +$qgraphflow:q-flow 分析订单创建流程,生成中文时序图,展示价格计算、库存预占、支付和订单落库的调用顺序,并标明失败分支。 ``` -Replace order creation and its steps with your project's actual flow. Continue in the same conversation: +将“订单创建”及相关步骤替换成项目中的实际业务流程。看完后,在同一对话中继续追问: ```text -$qgraphflow:q-flow Expand the stock reservation step in the previous diagram into a separate flowchart in Chinese, showing success and failure handling. +$qgraphflow:q-flow 展开上一张图中的库存预占步骤,单独生成中文流程图,展示成功与失败的处理流程。 ``` -Results go under `docs/qgraphflow/` by default. Open `index.html` to explore, edit and export; `graph.json` retains the graph data. Each view is also written as an SVG (`diagram.svg`, or `diagram--.svg` for several views) that you can embed as an image in a README, pull request or wiki. +结果默认保存在 `docs/qgraphflow/` 下:打开 `index.html` 即可交互查看、编辑和导出,`graph.json` 保留图数据。每个视图还会写出一份 SVG(`diagram.svg`,多视图时为 `diagram--.svg`),可以直接作为图片嵌进 README、PR 或 Wiki。 -After editing in the page, **More → Save changes** in Chrome or Edge rewrites the page, `graph.json` and the SVGs in place once you pick the diagram's folder. Other browsers save `graph.json` only: put it in the folder and regenerate the page and SVGs with `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. +在页面里编辑后,用 Chrome 或 Edge 执行「更多 → 保存修改」并选一次图所在的文件夹,即可原地重写页面、`graph.json` 和 SVG。其他浏览器只能保存 `graph.json`:把它放回该文件夹,再用 `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force` 重新生成页面和 SVG。
-Run the eleven-view Jeepay source example +运行基于 Jeepay 源码的九视图示例 -Select your Jeepay source checkout to verify the evidence: +指定本机的 Jeepay 源码目录来核验证据: ```bash export JEEPAY_REPO_ROOT="" @@ -228,13 +226,13 @@ node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.j node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" ``` -Open `output/jeepay/index.html`; its eleven SVGs are in the same directory. See the [corpus README](examples/jeepay) for the source revision and refresh procedure. +打开 `output/jeepay/index.html`,九个 SVG 在同一目录。源码版本和刷新步骤见[语料 README](examples/jeepay)。
-## Keep diagrams in sync with code +## 让图和代码保持同步 -A diagram generated with a repository root records where each component is defined and the line behind each code-backed relationship (a call, a foreign key). Validating it with `--repo-root` fails when a recorded file is gone, a line range no longer fits, or a recorded symbol has left its lines, and the error names the lines where the symbol is now. Add this job to your CI; it needs no build, login or token: +带仓库根目录生成的图会记下每个组件定义在哪里、每条有代码支撑的关系所在的那一行(调用、外键等),以及它指向的每个文件的内容指纹。用 `--repo-root` 校验时,只是挪了位置的行会自动对上、照常通过;只有图背后的代码真的变了才会失败:记录的那一行被改写、某个调用被删掉、新代码碰到了图里画的组件却没有对应的关系,或者图里用到的名字已经不存在。错误里会给出改动前后的代码,并指出要更新的元素和文字。把下面这个任务加进 CI,不需要构建、登录或令牌;拉取完整历史(`fetch-depth: 0`)才能和这些指纹比对: ```yaml name: Diagrams @@ -244,6 +242,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - uses: actions/setup-node@v7 with: node-version: '22' @@ -254,33 +254,35 @@ jobs: exit ${failed:-0} ``` -When it fails, ask the skill to refresh that diagram: +想在 PR 里直接看到受影响的地方,就在 validate 那一行加上 `--changes changes.md`,失败时把这个文件贴成评论,例如 `gh pr comment "$PR" --body-file changes.md`(需要 `pull-requests: write` 权限)。它按视图列出每处改动碰到的元素、文件和行号,以及改动前后的代码。执行 `--fix` 后重新生成的页面也会标出这些元素,并在要点旁列出这些改动。 + +失败后,让技能刷新这张图: ```text -$qgraphflow:q-flow CI says docs/qgraphflow/order-sequence is out of date. Refresh it. +$qgraphflow:q-flow CI 提示 docs/qgraphflow/order-sequence 的图过时了,刷新一下。 ``` -The skill moves anchors whose symbol it finds once, corrects only the anchors still reported, and regenerates the page and SVGs with your edited positions and text kept. It does not redraw the diagram. +技能会把所有锚点对齐到当前代码,把每处改动列进图的 `meta.sourceDrift`,只更新这些条目指出的元素,再保留你调整过的位置和文字,重新生成页面和 SVG;不会重画整张图。 -## What each of the eleven diagram types answers +重新生成时加上 `--compare HEAD`,就能看出这次刷新改了什么:页面把新增和改动的元素着色,在要点旁列出删掉的元素,`graph.json` 不受影响。 -| View · PNG | Main question | Example scope | +## 九类图各自回答什么 + +| 视图 · PNG | 主要问题 | 本示例范围 | | --- | --- | --- | -| Platform capability architecture | What capabilities does the platform provide? | Capability zones and matrices | -| Engineering layer architecture | How is the engineering code organized? | Engineering layers and shared support | -| Component relationship architecture | Which responsibility boundaries collaborate in the system? | Channels, transaction orchestration, pricing, risk, stock, payment, orders, events and fulfillment | -| Flowchart | How does each decision point branch and converge? | Stock shortage, risk rejection, compensation for payment failure and successful commit | -| Sequence | In what order does a request make calls and receive returns? | Successful checkout main flow and asynchronous OrderPaid | -| ER | How does core data relate? | Cart, orders, items, payments, stock reservations and parcels | -| Deployment | Where are runtime units placed and how are they connected? | Edge, Kubernetes, data services, payment and warehouse/logistics networks | -| Class | How do domain objects and code contracts depend on each other? | Checkout application service, Order and four ports | -| State | Which events and guards advance an order? | Payment, fulfillment, cancellation, refund and closure | -| Use case | What capabilities does each actor have? | Buyer, merchant, warehouse and customer support | -| Data flow | What transformations and stores do data assets pass through? | Cart, transaction decisions, order events, warehouse/logistics and delivery receipts | - -This is a concept model demonstrating QGraphFlow, not a particular e-commerce repository. The example `graph.json` invents no source paths and marks relationship evidence as `inference`. Real project diagrams need traceable source, DDL, configuration, tests and accepted requirements. - -## Develop and contribute +| 组件关系架构图 | 系统由哪些责任边界协作? | 渠道、交易编排、价格、风控、库存、支付、订单、事件与履约 | +| 流程图 | 每个决策点如何分支和收敛? | 缺货、风控拒绝、支付失败补偿与成功提交 | +| 时序图 | 一次请求按什么顺序调用和返回? | 成功结算主链及异步 OrderPaid | +| ER 图 | 核心数据如何关联? | 购物车、订单、明细、支付、库存预占和包裹 | +| 部署图 | 运行单元放在哪里、怎样连接? | 边缘、Kubernetes、数据服务、支付和仓配网络 | +| 类图 | 领域对象和代码契约怎样依赖? | Checkout 应用服务、Order 与四个端口 | +| 状态图 | 订单受哪些事件和守卫条件推进? | 支付、履约、取消、退款和关闭 | +| 用例图 | 每类参与者拥有哪些能力? | 买家、商家、仓库与客服 | +| 数据流图 | 数据资产经过哪些变换和存储? | 购物车、交易决策、订单事件、仓配和物流回执 | + +这是用于展示 QGraphFlow 能力的概念模型,不对应某个电商仓库。`graph.json` 不伪造源码路径,关系证据统一标记为 `inference`;对真实项目绘图时,应改用源码、DDL、配置、测试和已接受需求中的可追溯证据。 + +## 开发与参与 ```bash npm ci --prefix skills/q-flow/assets/viewer @@ -288,24 +290,12 @@ npm run build --prefix skills/q-flow/assets/viewer node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs ``` -Development needs Node.js 22 or later, npm, tar, zip and unzip. Include a minimal redacted graph, client/browser versions and reproduction steps in issue reports. +开发需要 Node.js 22 及以上版本、npm、tar、zip 和 unzip。反馈问题时,请附最小脱敏图数据、客户端和浏览器版本,以及复现步骤。 -Reference documentation (English): [Evidence sources](skills/q-flow/references/evidence-sources.md) · [Graph data format](skills/q-flow/references/graph-schema.md) · [Guided intake](skills/q-flow/references/guided-intake.md) · [Viewer development and acceptance](skills/q-flow/references/viewer-development.md) · [Visual conventions](skills/q-flow/references/visual-contract.md) +参考文档(英文):[证据来源](skills/q-flow/references/evidence-sources.md) · [图数据格式](skills/q-flow/references/graph-schema.md) · [需求引导](skills/q-flow/references/guided-intake.md) · [Viewer 开发与验收](skills/q-flow/references/viewer-development.md) · [图形表达约定](skills/q-flow/references/visual-contract.md) -## License and attribution +## 许可证与归属 -[MIT](LICENSE) · [Third-party notices](THIRD_PARTY_NOTICES.md) - -QGraphFlow is an independent MIT-licensed project. The scenarios in this document are conceptual examples and do not represent any real company's production architecture. - -## Architecture overviews - -Architecture now includes component relations, platform capabilities and engineering layers. Describe the subject and question; the skill chooses the template. Requested collections can contain multiple architecture views with independent edits. - -```text -$qgraphflow:q-flow Analyze this project's platform capabilities and business integration methods, and generate a platform capability overview in Chinese. -$qgraphflow:q-flow Analyze the organization and component layers of the current project, and generate Chinese overviews of the whole project and a cross-section of one component. -$qgraphflow:q-flow Generate an English platform capability overview of this project and show how application modules integrate. -``` +[MIT](LICENSE) · [第三方声明](THIRD_PARTY_NOTICES.md) -See [examples/jeepay](examples/jeepay) for real-source platform, engineering and component relationship architecture views. Unlock an overview to reorder cards within a layer or edit text. Save keeps all views; reset restores only the current one. +QGraphFlow 是采用 MIT 许可证的独立项目。本文场景为概念示例,不代表任何真实公司的生产架构。 diff --git a/docs/clients.de.md b/docs/clients.de.md deleted file mode 100644 index 8524f03..0000000 --- a/docs/clients.de.md +++ /dev/null @@ -1,74 +0,0 @@ -# Installationsanleitung - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[Zurück zur README](readme/README.de.md) - -Qoder Desktop kann das Plugin aus dem Marketplace installieren; dann entfällt Schritt 1 (siehe den Abschnitt unten). Die übrigen Clients installieren das Plugin-Paket von npmjs.com. - -Du benötigst Node.js 22 oder neuer (mit npm) und einen Client mit eingerichtetem Modellzugriff. - -## Schnellinstallation - -```bash -npx skills add supermax92/qgraphflow -``` - -Installiert den Skill `q-flow` für Claude Code, Codex, Cursor und Qoder (getestet mit `skills` 1.7.0) und fragt, in welche Clients installiert werden soll. Für die Installation als Plugin den folgenden Schritten folgen. - -## 1. Plugin über npm herunterladen - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Lege das Verzeichnis außerhalb deines Anwendungsprojekts an; Konto, Anmeldung oder Token sind nicht nötig. Danach befindest du dich im Plugin-Stammverzeichnis. Der Download über npm installiert das Plugin nicht im Client; fahre mit Schritt 2 fort. Um noch nicht veröffentlichten Code zu installieren, siehe die [Anleitung zum Bauen aus dem Quellcode](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## 2. Im Client installieren - -Führe die folgenden Befehle im Plugin-Stammverzeichnis aus Schritt 1 (`qgraphflow-install/node_modules/qgraphflow`) aus, nicht im Verzeichnis deines eigenen Anwendungsprojekts. - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Hier registriert `marketplace add` nur eine lokale Installationsquelle; eine Veröffentlichung im öffentlichen Marktplatz ist nicht erforderlich. Siehe die [offizielle OpenAI-Dokumentation](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli). - -Starte eine neue Sitzung, gib `$` ein und wähle `qgraphflow:q-flow` aus (verwende den tatsächlich im Client angezeigten Namen). - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Starte eine neue Sitzung und gib `/q-flow` (oder den vollständigen Namen `/qgraphflow:q-flow`) ein. - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -Starte eine neue Sitzung und wähle `q-flow` aus. - -### Qoder Desktop - -**Empfohlen:** Öffne **Settings → Plugins → Marketplace**, suche nach **QGraphFlow** oder **代码图谱可视化** und installiere das Plugin. Starte eine neue Sitzung und wähle `q-flow`. - -Für eine lokale Installation führe zuerst Schritt 1 aus. Öffne dann **Settings → Plugins → Custom → Import** und importiere das vollständige Plugin-Stammverzeichnis. Lade den Client neu und wähle `q-flow`. - -### Cursor - -Kopiere den gesamten Inhalt des Plugin-Stammverzeichnisses, einschließlich versteckter Dateien, nach `~/.cursor/plugins/local/qgraphflow/`. Sichere ein vorhandenes Verzeichnis zuerst; vermische keine alten und neuen Dateien. - -Prüfe, ob das Manifest unter `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json` liegt. Lade das Fenster neu und wähle unter Customize → Plugins / Skills den Skill `q-flow` aus. - -Diese lokale Methode wurde mit Cursor 3.19.13 getestet. Prüfe bei anderen Versionen, ob Plugin und Skill angezeigt werden. diff --git a/docs/clients.es.md b/docs/clients.es.md deleted file mode 100644 index a537a04..0000000 --- a/docs/clients.es.md +++ /dev/null @@ -1,74 +0,0 @@ -# Guía de instalación - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[Volver al README](readme/README.es.md) - -Qoder Desktop permite instalar el complemento desde su Marketplace y omitir el paso 1 (consulta su sección más abajo). Los demás clientes instalan el paquete del complemento obtenido de npmjs.com. - -Necesitas Node.js 22 o posterior (con npm) y un cliente con acceso al modelo configurado. - -## Instalación rápida - -```bash -npx skills add supermax92/qgraphflow -``` - -Instala la habilidad `q-flow` en Claude Code, Codex, Cursor y Qoder (probado con `skills` 1.7.0) y pregunta en qué clientes instalar. Para instalar el complemento, sigue los pasos siguientes. - -## 1. Descargar el complemento con npm - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Crea el directorio fuera del proyecto de tu aplicación; no se necesita cuenta, inicio de sesión ni token. Ahora estás en la raíz del complemento. La descarga mediante npm no instala el complemento en el cliente; continúa con el paso 2. Para instalar código aún no publicado, consulta las [instrucciones de compilación desde el código fuente](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## 2. Instalar en el cliente - -Ejecuta los siguientes comandos desde la raíz del complemento a la que entraste en el paso 1 (`qgraphflow-install/node_modules/qgraphflow`), no desde el directorio de tu propio proyecto. - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Aquí, `marketplace add` solo registra una fuente de instalación local; no requiere publicar el complemento en un marketplace público. Consulta la [documentación oficial de OpenAI](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli). - -Inicia una sesión nueva, escribe `$` y selecciona `qgraphflow:q-flow` (usa el nombre que muestre tu cliente). - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Inicia una sesión nueva y escribe `/q-flow` (o el nombre completo `/qgraphflow:q-flow`). - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -Inicia una sesión nueva y selecciona `q-flow`. - -### Qoder Desktop - -**Recomendado:** Abre **Settings → Plugins → Marketplace**, busca **QGraphFlow** o **代码图谱可视化** e instala el complemento. Inicia una sesión nueva y selecciona `q-flow`. - -Para una instalación local, completa primero el paso 1. Después abre **Settings → Plugins → Custom → Import** e importa el directorio raíz completo del complemento. Recarga el cliente y selecciona `q-flow`. - -### Cursor - -Copia todo el contenido de la raíz del complemento, incluidos los archivos ocultos, a `~/.cursor/plugins/local/qgraphflow/`. Si el directorio ya existe, haz una copia de seguridad antes; no mezcles archivos antiguos y nuevos. - -Comprueba que el manifiesto esté en `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json`. Recarga la ventana y selecciona `q-flow` en Customize → Plugins / Skills. - -Este método local se probó en Cursor 3.19.13. En otras versiones, comprueba que aparezcan tanto el complemento como la habilidad. diff --git a/docs/clients.ja.md b/docs/clients.ja.md deleted file mode 100644 index cff8b35..0000000 --- a/docs/clients.ja.md +++ /dev/null @@ -1,74 +0,0 @@ -# インストールガイド - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[README に戻る](readme/README.ja.md) - -Qoder Desktop ではマーケットプレイスからインストールでき、手順 1 は不要です(下記の該当項を参照)。その他のクライアントでは、npmjs.com から取得したプラグインパッケージをインストールします。 - -Node.js 22 以降(npm を含む)と、モデルへのアクセスを設定済みのクライアントが必要です。 - -## クイックインストール - -```bash -npx skills add supermax92/qgraphflow -``` - -Claude Code、Codex、Cursor、Qoder にスキル `q-flow` を導入します(`skills` 1.7.0 で実測済み)。導入先のクライアントを尋ねられます。プラグインとして導入する場合は、次の手順に従ってください。 - -## 1. npm からプラグインをダウンロード - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -ディレクトリは業務プロジェクトの外に作成します。アカウント、ログイン、トークンは不要です。これでプラグインのルートディレクトリに移動できました。npm でダウンロードしてもクライアントへのインストールは自動では行われないため、手順 2 に進んでください。未リリースのコードをインストールする場合は、[ソースからのビルド手順](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally)を参照してください。 - -## 2. クライアントにインストール - -以下のコマンドは、自分の業務プロジェクトではなく、手順 1 で移動したプラグインのルートディレクトリ(`qgraphflow-install/node_modules/qgraphflow`)で実行します。 - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -ここでの `marketplace add` はローカルのインストール元を登録するだけで、公開マーケットプレイスへの掲載は不要です。[OpenAI 公式ドキュメント](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli)を参照してください。 - -新しいセッションを開始し、`$` を入力して `qgraphflow:q-flow` を選択します(クライアントに実際に表示される名前を使用してください)。 - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -新しいセッションを開始し、`/q-flow`(または完全名 `/qgraphflow:q-flow`)を入力します。 - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -新しいセッションを開始し、`q-flow` を選択します。 - -### Qoder Desktop - -**推奨:** **Settings → Plugins → Marketplace** を開き、**QGraphFlow** または **代码图谱可视化** を検索してインストールします。新しいセッションを開始し、`q-flow` を選択します。 - -ローカルインストールの場合は手順 1 を完了し、**Settings → Plugins → Custom → Import** を開いて、プラグインのルートディレクトリ全体をインポートします。再読み込み後、`q-flow` を選択します。 - -### Cursor - -プラグインのルートディレクトリの内容を隠しファイルも含めてすべて `~/.cursor/plugins/local/qgraphflow/` にコピーします。既存のディレクトリがある場合は先にバックアップし、新旧のファイルを混在させないでください。 - -マニフェストが `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json` にあることを確認します。ウィンドウを再読み込みし、Customize → Plugins / Skills で `q-flow` を選択します。 - -このローカル方式は Cursor 3.19.13 で検証済みです。他のバージョンでは、プラグインとスキルが表示されることを確認してください。 diff --git a/docs/clients.md b/docs/clients.md index 4308b01..3bee4ab 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -1,8 +1,8 @@ # Installation guide -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) +[English](clients.md) · [中文](clients.zh-CN.md) -[Back to README](../README.md) +[Back to README](../README.en.md) Qoder Desktop can install the plugin from its marketplace and skip step 1 (see its section below). The other clients install the plugin package from npmjs.com. diff --git a/docs/clients.pt.md b/docs/clients.pt.md deleted file mode 100644 index be22326..0000000 --- a/docs/clients.pt.md +++ /dev/null @@ -1,74 +0,0 @@ -# Guia de instalação - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[Voltar ao README](readme/README.pt.md) - -O Qoder Desktop pode instalar o plugin pelo Marketplace e pular a etapa 1 (veja a seção correspondente abaixo). Os demais clientes instalam o pacote do plugin obtido no npmjs.com. - -Você precisa de Node.js 22 ou posterior (com npm) e de um cliente com acesso ao modelo configurado. - -## Instalação rápida - -```bash -npx skills add supermax92/qgraphflow -``` - -Instala a habilidade `q-flow` no Claude Code, Codex, Cursor e Qoder (testado com `skills` 1.7.0) e pergunta em quais clientes instalar. Para instalar o plugin, siga as etapas abaixo. - -## 1. Baixar o plugin pelo npm - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Crie o diretório fora do projeto da sua aplicação; não é preciso conta, login nem token. Agora você está na raiz do plugin. Baixar pelo npm não instala o plugin no cliente; continue na etapa 2. Para instalar código ainda não lançado, consulte as [instruções de compilação a partir do código-fonte](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## 2. Instalar no cliente - -Execute os comandos abaixo na raiz do plugin aberta na etapa 1 (`qgraphflow-install/node_modules/qgraphflow`), não no diretório do seu próprio projeto. - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Aqui, `marketplace add` apenas registra uma fonte de instalação local; não exige publicação em um marketplace público. Consulte a [documentação oficial da OpenAI](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli). - -Inicie uma nova sessão, digite `$` e selecione `qgraphflow:q-flow` (use o nome exibido pelo seu cliente). - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Inicie uma nova sessão e digite `/q-flow` (ou o nome completo `/qgraphflow:q-flow`). - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -Inicie uma nova sessão e selecione `q-flow`. - -### Qoder Desktop - -**Recomendado:** Abra **Settings → Plugins → Marketplace**, pesquise **QGraphFlow** ou **代码图谱可视化** e instale o plugin. Inicie uma nova sessão e selecione `q-flow`. - -Para uma instalação local, conclua primeiro a etapa 1. Depois, abra **Settings → Plugins → Custom → Import** e importe o diretório raiz completo do plugin. Recarregue o cliente e selecione `q-flow`. - -### Cursor - -Copie todo o conteúdo da raiz do plugin, incluindo arquivos ocultos, para `~/.cursor/plugins/local/qgraphflow/`. Se o diretório já existir, faça um backup antes; não misture arquivos antigos e novos. - -Confirme que o manifesto está em `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json`. Recarregue a janela e selecione `q-flow` em Customize → Plugins / Skills. - -Esse método local foi testado no Cursor 3.19.13. Em outras versões, confirme que o plugin e a habilidade aparecem. diff --git a/docs/clients.ru.md b/docs/clients.ru.md deleted file mode 100644 index ade4691..0000000 --- a/docs/clients.ru.md +++ /dev/null @@ -1,74 +0,0 @@ -# Руководство по установке - -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) - -[Вернуться к README](readme/README.ru.md) - -В Qoder Desktop плагин можно установить из Marketplace и пропустить шаг 1 (см. соответствующий раздел ниже). Остальные клиенты устанавливают пакет плагина с npmjs.com. - -Нужны Node.js 22 или новее (с npm) и клиент с настроенным доступом к модели. - -## Быстрая установка - -```bash -npx skills add supermax92/qgraphflow -``` - -Устанавливает навык `q-flow` для Claude Code, Codex, Cursor и Qoder (проверено с `skills` 1.7.0) и спрашивает, в какие клиенты устанавливать. Чтобы установить плагин, выполните шаги ниже. - -## 1. Скачать плагин из npm - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Создайте каталог вне своего рабочего проекта; учётная запись, вход и токен не нужны. Теперь вы в корневом каталоге плагина. Загрузка через npm не устанавливает плагин в клиент — перейдите к шагу 2. Чтобы установить ещё не выпущенный код, см. [инструкции по сборке из исходников](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## 2. Установить в клиент - -Выполняйте команды ниже из корневого каталога плагина, в который вы перешли на шаге 1 (`qgraphflow-install/node_modules/qgraphflow`), а не из каталога вашего приложения. - -### Codex App / CLI - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Здесь `marketplace add` только регистрирует локальный источник установки; публикация в маркетплейсе не требуется. См. [официальную документацию OpenAI](https://developers.openai.com/plugins/build/plugins#add-a-marketplace-from-the-cli). - -Начните новый сеанс, введите `$` и выберите `qgraphflow:q-flow` (используйте имя, которое показывает ваш клиент). - -### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Начните новый сеанс и введите `/q-flow` (или полное имя `/qgraphflow:q-flow`). - -### Qoder CLI - -```bash -qodercli plugins install . -``` - -Начните новый сеанс и выберите `q-flow`. - -### Qoder Desktop - -**Рекомендуется:** Откройте **Settings → Plugins → Marketplace**, найдите **QGraphFlow** или **代码图谱可视化** и установите плагин. Начните новый сеанс и выберите `q-flow`. - -Для локальной установки выполните шаг 1, затем откройте **Settings → Plugins → Custom → Import** и импортируйте весь корневой каталог плагина. Перезагрузите клиент и выберите `q-flow`. - -### Cursor - -Скопируйте всё содержимое корневого каталога плагина, включая скрытые файлы, в `~/.cursor/plugins/local/qgraphflow/`. Если каталог уже существует, сначала сделайте резервную копию; не смешивайте старые и новые файлы. - -Убедитесь, что манифест находится по адресу `~/.cursor/plugins/local/qgraphflow/.cursor-plugin/plugin.json`. Перезагрузите окно и выберите `q-flow` в Customize → Plugins / Skills. - -Этот способ локальной установки проверялся в Cursor 3.19.13. В других версиях убедитесь, что плагин и навык отображаются. diff --git a/docs/clients.zh-CN.md b/docs/clients.zh-CN.md index 5f2290e..607e648 100644 --- a/docs/clients.zh-CN.md +++ b/docs/clients.zh-CN.md @@ -1,8 +1,8 @@ # 安装指南 -[English](clients.md) · [中文](clients.zh-CN.md) · [Русский](clients.ru.md) · [Português](clients.pt.md) · [日本語](clients.ja.md) · [Deutsch](clients.de.md) · [Español](clients.es.md) +[English](clients.md) · [中文](clients.zh-CN.md) -[返回 README](readme/README.zh-CN.md) +[返回 README](../README.md) Qoder Desktop 可从插件商城安装,跳过第 1 步(见下方对应小节)。其他客户端安装从 npmjs.com 下载的插件包。 diff --git a/docs/distribution.md b/docs/distribution.md index 9773e8a..0dc793e 100644 --- a/docs/distribution.md +++ b/docs/distribution.md @@ -27,7 +27,7 @@ Use new output directories. Packaging refuses to overwrite existing outputs. `np ## Publish only after confirmation 1. Confirm the GitHub repository URL, commit author name/email, commit message, and the changes to include. `main` accepts changes only through a pull request (ruleset `main-pr-required-no-bypass`); commit on a branch, open the pull request and merge it once CI is green. -2. Keep the media Releases `showcase-v1` (historical) and `showcase-v2` (current README recordings) separate from software `v0.0.7`. Their attachments stay on GitHub until their removal is confirmed separately; do not move old tags or mark a media-only Release as the latest software release. +2. Keep the media Releases `showcase-v1`, `showcase-v2` (historical) and `showcase-v3` (current README recordings, made with `scripts/record-showcase.mjs`) separate from software `v0.0.7`. Their attachments stay on GitHub until their removal is confirmed separately; do not move old tags or mark a media-only Release as the latest software release. 3. The READMEs link the real-source Jeepay corpus. Public examples and smoke tests use this corpus; historical sample recordings are no longer linked. 4. Re-run checks, commit the confirmed source changes, and merge them into `main` through the pull request. Do not force-push or mirror-push. Media must not enter the commit; Codex's private `refs/codex/` snapshots are not release refs. 5. Build runtime archives from the confirmed commit, record their SHA-256 checksums, verify the extracted package, and attach them to software Release `v0.0.7`. GitHub's automatic **Source code** archives are full source snapshots, not the slim plugin installer. @@ -42,7 +42,7 @@ Track marketplace releases separately from GitHub Releases and npm packages. For ## Online demo -`.github/workflows/pages.yml` checks out the Jeepay revision recorded in `examples/jeepay/source.json`, builds all eleven coordinate-free views with the committed prebuilt Viewer and verifies their source anchors with `--repo-root`. It serves `site/jeepay/zh-CN/` and uses `docs/pages/index.html` as the home page. The page folder also serves its `graph.json` and SVGs. +`.github/workflows/pages.yml` checks out the Jeepay revision recorded in `examples/jeepay/source.json`, builds all nine coordinate-free views with the committed prebuilt Viewer and verifies their source anchors with `--repo-root`. It serves `site/jeepay/zh-CN/` and uses `docs/pages/index.html` as the home page. `scripts/showcase-changes.mjs` derives an earlier version of the component relations view, and `generate-viewer.mjs --compare` marks what changed in `site/jeepay/changes/zh-CN/` and `site/jeepay/changes/en/`; the README `changes` clip records the same comparison. The page folder also serves its `graph.json` and SVGs. Pull requests that touch the examples, the generator, the prebuilt Viewer, `docs/pages/` or the workflow run the build as a smoke test; pushes to `main` also deploy it. The site is uploaded as a Pages artifact and never enters a branch, and a failed build leaves the previous deployment online. Before the first deployment, set **Settings → Pages → Build and deployment → Source** to **GitHub Actions**. diff --git a/docs/pages/index.html b/docs/pages/index.html index d68d15d..60b934b 100644 --- a/docs/pages/index.html +++ b/docs/pages/index.html @@ -14,8 +14,10 @@

QGraphFlow

-

以 Jeepay 公开源码、Maven 配置、DDL 和 Compose 为依据,查看十一类可追溯的软件图形。

-打开 Jeepay 十一类图平台能力、工程分层、组件关系、流程、时序、ER、部署、类、状态、用例和数据流。可搜索、编辑、核验来源并导出。 +

以 Jeepay 公开源码、Maven 配置、DDL 和 Compose 为依据,查看九类可追溯的软件图形。

+打开 Jeepay 九类图组件关系、流程、时序、ER、部署、类、状态、用例和数据流。可搜索、编辑、核验来源并导出。 +代码变了,图上标出变了什么组件关系架构图对比上一版:新增、改动和删除的元素直接标在图上,并列在右侧"本次更新"里。 +

English version of the update comparison

这些图展示源码和配置声明;容器运行及支付渠道接入状态未作验证。

项目源码与安装说明 diff --git a/docs/readme/README.de.md b/docs/readme/README.de.md deleted file mode 100644 index daac308..0000000 --- a/docs/readme/README.de.md +++ /dev/null @@ -1,311 +0,0 @@ -
- -

QGraphFlow

- -### Aus komplexem Code werden Diagramme zum Erkunden. - -Pfade verfolgen. Belege prüfen. Eine Offline-Datei teilen. - -💡 Inspiriert von Cocoon-AI/architecture-diagram-generator – vielen Dank für die Anregung. - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[Online-Demo](https://supermax92.github.io/qgraphflow/) · [Erste Schritte](#erste-schritte) · [Client-Installation](#installationsanleitung) · [Problem melden](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*Elf Diagrammarten: Plattformfähigkeitsarchitektur, Architektur der Engineering-Schichten, Komponentenbeziehungsarchitektur, Flussdiagramm, Sequenz, ER, Bereitstellung, Klasse, Zustand, Anwendungsfall und Datenfluss.* - -QGraphFlow erzeugt interaktive Softwarediagramme aus Quellcode, Datenstrukturen, Konfiguration und Anforderungen. Beziehungen bleiben überprüfbar; das Ergebnis lässt sich als Offline-HTML teilen. - -**Was es auszeichnet:** elf Diagrammarten in einem Skill, eine Belegart für jede Beziehung und die Quellzeile hinter jeder durch Code gestützten, automatisches Layout, Bearbeiten direkt auf der Seite und keine Netzwerkanfragen von den Plugin-Skripten oder dem Viewer selbst. - -![Interaktive Jeepay-Demo mit mehreren Ansichten: Komponentenbeziehungsarchitektur, Sequenz- und ER-Diagramme](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -Wechsle anhand des echten Jeepay-Quellcodes zwischen Komponentenbeziehungsarchitektur, Sequenz- und ER-Diagrammen, um Komponenten und Aufrufbeziehungen zu erkunden. [GIF in Originalgröße ansehen](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**Präsentation eines komplexen Sequenzdiagramms** - -![Schrittweises Zeichnen eines komplexen Sequenzdiagramms: Teilnehmer, Lebenslinien, Nachrichten, Aktivierungsbalken und verschachtelte kombinierte Fragmente](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -Ein fiktives E-Commerce-Szenario enthält 9 Teilnehmer, 29 Nachrichten und 6 kombinierte Fragmente mit Bestandswiederholungen, verschachtelten Zweigen, paralleler Verarbeitung, Fehlerkompensation und asynchronen Rückrufen. Die Animation zeigt das erzeugte Diagramm schrittweise und macht seine Struktur und Details sichtbar. [GIF in Originalgröße ansehen](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -Ein Befehl installiert den Skill für Claude Code, Codex, Cursor und Qoder; die Installation als Plugin und weitere Clients beschreibt die [Installationsanleitung](#installationsanleitung). - -- **Erkunden:** suchen, zoomen und verschieben; Verantwortlichkeiten sowie ein- und ausgehende Beziehungen verstehen. - -- **Prüfen:** Dateien, Zeilen, Symbole und ausdrücklich gekennzeichnete Unsicherheiten an Knoten und Kanten untersuchen. - -- **Bearbeiten:** Layout entsperren, Texte ändern und Elemente verschieben; bei Bedarf zurücksetzen. - -- **Teilen:** Offline-HTML öffnen oder das vollständige Diagramm als SVG / PNG exportieren. - -Der auf echtem Quellcode beruhende [Jeepay-Korpus](../../examples/jeepay) enthält alle elf Ansichten, die CI und die Online-Demo verwenden. - -## Erste Schritte - -Öffne nach der Installation dein Geschäftsprojekt im Client und wähle den Skill `q-flow`. Die Beispiele verwenden `/q-flow` in Claude Code; in Codex verwendest du den Eintrag `$q-flow` oder `$qgraphflow:q-flow`, den dein Client tatsächlich anbietet. Noch nicht installiert? Lies zuerst die [Installationsanleitung](#installationsanleitung). - -### 1. Leere Eingabe: Du weißt nicht, wo du anfangen sollst - -Rufe den Skill ohne zusätzliche Anforderungen auf: - -```text -/q-flow -``` - -Der Skill hilft dir, den zu analysierenden Teil und die Frage auszuwählen, die das Diagramm beantworten soll. Sobald die nötigen Informationen geklärt sind, beginnt das Zeichnen. - -### 2. Nach Fähigkeiten fragen: Erfahren, was er zeichnen kann - -```text -/q-flow Welche Diagrammarten kannst du zeichnen? Welche Fragen beantwortet jede Art? Ich habe gerade ein Projekt übernommen; stelle deine Fähigkeiten vor und schlage einen Einstieg vor. -``` - -Lerne zuerst die Einsatzgebiete der elf Diagrammarten kennen. Entscheide dann, ob du Projektstruktur, Aufrufreihenfolge, Datenbeziehungen oder etwas anderes betrachten möchtest. - -### 3. Vage Eingabe: Nur ein grobes Ziel - -```text -/q-flow Hilf mir, dieses Projekt zu zeichnen. Ich möchte es möglichst schnell verstehen. -``` - -Du musst vorher keine Diagrammart angeben. Der Skill bestimmt anhand des Projekts und deines Ziels eine passende Ansicht und fragt nach, wenn notwendige Informationen fehlen. - -### 4. Präzise Eingabe: Umfang festlegen und Zeichnungsdetails anfordern - -Ersetze die folgenden Geschäftsbegriffe und Schritte durch Abläufe, die tatsächlich in deinem Projekt vorkommen: - -```text -/q-flow Analysiere die Bestellerstellung im aktuellen Projekt und erzeuge ein Sequenzdiagramm auf Chinesisch. -Berücksichtige den Anfrageeingang, die Preisberechnung, Bestandsreservierung, Zahlungsautorisierung und Speicherung der Bestellung. -Erhalte die synchronen Aufrufe, asynchronen Nachrichten, gepaarten Rückgaben, Aktivierungsbalken, bedingten Zweige, Wiederholungen und Fehlerkompensationen, die tatsächlich im Quellcode vorkommen. Lasse keine Details zugunsten der Kürze weg. -Kennzeichne Quelldateien und Zeilennummern der Komponenten und Aufrufe und speichere das Ergebnis unter docs/qgraphflow/order-sequence/. -``` - -Benenne Gegenstand, Frage, Detailgrad und Ausgabeort klar, damit es direkt losgehen kann. Das Diagramm enthält nur durch Belege gestützte Fakten. - -### 5. Weiter verfeinern: Einen Teil des letzten Diagramms vertiefen - -Fahre nach der Erzeugung des Ergebnisses im selben Gespräch fort: - -```text -/q-flow Vertiefe die Bestandsreservierung aus dem letzten Sequenzdiagramm als separates Flussdiagramm auf Chinesisch. -Zeige sämtliche Zweige für Bestandsprüfung, erfolgreiche Reservierung, wiederholbare Fehler, Wiederholungslimit und Bestandsfreigabe. Halte dich an den Quellcode und füge keine dort fehlenden Schritte hinzu. -``` - -Betrachte zuerst das Ganze und vertiefe dann einen Schritt. Du kannst auch weitere Details für ein vorhandenes Diagramm anfordern oder seine Beziehungen prüfen. - -## Installationsanleitung - -Benötigt werden Node.js 22 oder neuer und ein Client mit Plugin-Unterstützung und eingerichtetem Modellzugriff. - -### Schnellinstallation - -```bash -npx skills add supermax92/qgraphflow -``` - -Getestet mit `skills` 1.7.0 für Claude Code, Codex, Cursor und Qoder. Der Befehl fragt, in welche Clients installiert werden soll; `-a claude-code` gibt einen direkt an, `-g` installiert für den eigenen Benutzer statt für das aktuelle Projekt. Der Skill heißt danach `q-flow`, ohne das Präfix `qgraphflow:` der Plugin-Installationen unten. - -Für die Installation als Plugin den folgenden Schritten folgen. [Qoder Desktop](#qoder-desktop) kann das Plugin direkt aus dem Marketplace installieren; Schritt 1 entfällt. - -### 1. Plugin herunterladen - -Das Plugin von npmjs.com beziehen, ohne Konto, Anmeldung oder Token. Ein eigenes Verzeichnis außerhalb des Anwendungsprojekts erstellen: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Nun befindet man sich im Plugin-Stammverzeichnis. **Der Download über npm installiert das Plugin nicht automatisch im Client;** mit Schritt 2 fortfahren. Das Paket stellt außerdem den Befehl `qgraphflow` bereit, den [Diagramme mit dem Code synchron halten](#diagramme-mit-dem-code-synchron-halten) verwendet. - -Alle folgenden Terminalbefehle im **Plugin-Stammverzeichnis mit `skills/`** ausführen. - -### 2. Im gewünschten Client installieren - -#### Codex App / CLI - -Codex CLI muss installiert und im Terminal verfügbar sein: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Eine neue Sitzung starten, `$` eingeben und `qgraphflow:q-flow` auswählen. - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Eine neue Sitzung starten und `/q-flow` (oder den vollständigen Namen `/qgraphflow:q-flow`) eingeben. - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -Eine neue Sitzung starten und `q-flow` auswählen. - -#### Qoder Desktop - -**Empfohlen:** Öffne **Settings → Plugins → Marketplace**, suche nach **QGraphFlow** oder **代码图谱可视化** und installiere das Plugin. Starte eine neue Sitzung und wähle `q-flow`. - -Für eine lokale Installation führe zuerst Schritt 1 aus. Öffne dann **Settings → Plugins → Custom → Import** und importiere das vollständige Plugin-Stammverzeichnis. Starte eine neue Sitzung und wähle `q-flow`. - -#### Cursor - -Den gesamten Inhalt des Plugin-Stammverzeichnisses einschließlich versteckter Dateien hierhin kopieren: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -Prüfen, ob dort `.cursor-plugin/plugin.json` vorhanden ist, das Fenster neu laden und `q-flow` unter **Customize** suchen. Eine vorhandene ältere Version zuerst sichern; alte und neue Dateien nicht vermischen. - -### 3. Loslegen - -Öffne dein Geschäftsprojekt im Client, starte eine neue Sitzung und wähle den Skill. Beschreibe deine Anforderungen anhand der Beispiele unter [Erste Schritte](#erste-schritte). Öffne das erzeugte HTML im Browser. - -Selbst bauen? Siehe [Anleitung zum Bauen aus dem Quellcode](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## Schnell verwenden - -Die Beispiele verwenden `$qgraphflow:q-flow` in Codex. Zeigt der Client `$q-flow`, diesen Eintrag wählen. In anderen Clients den oben beschriebenen Skill-Aufruf verwenden. - -**Noch kein Ausgangspunkt?** Den Skill aufrufen und auf Nachfrage Gegenstand und Fragestellung auswählen. - -```text -$qgraphflow:q-flow -``` - -**Das Ziel steht fest?** Beschreiben, welchen Teil das Diagramm zeigen und welche Frage es beantworten soll. Die Diagrammart muss nicht vorab gewählt werden. - -### Beispiel 1: Projektarchitektur verstehen - -```text -$qgraphflow:q-flow Analysiere dieses Projekt und erstelle ein chinesisches Architekturdiagramm mit Verantwortlichkeiten der Module, Abhängigkeiten und Systemgrenzen. -``` - -Geeignet, um sich erstmals einen Überblick über ein Projekt zu verschaffen. - -### Beispiel 2: Einen Geschäftsablauf verfolgen - -```text -$qgraphflow:q-flow Analysiere die Bestellerstellung und erstelle ein chinesisches Sequenzdiagramm für Preisberechnung, Bestandsreservierung, Zahlung und Speicherung der Bestellung, einschließlich Fehlerzweigen. -``` - -Bestellerstellung und Schritte durch den tatsächlichen Projektablauf ersetzen. Im selben Gespräch weiterfragen: - -```text -$qgraphflow:q-flow Vertiefe die Bestandsreservierung aus dem letzten Diagramm als separates chinesisches Flussdiagramm mit Erfolgs- und Fehlerbehandlung. -``` - -Ergebnisse landen standardmäßig unter `docs/qgraphflow/`. `index.html` zum Erkunden, Bearbeiten und Exportieren öffnen; `graph.json` enthält die Diagrammdaten. Jede Ansicht wird außerdem als SVG geschrieben (`diagram.svg`, bei mehreren Ansichten `diagram--.svg`), das sich als Bild in eine README, einen Pull Request oder ein Wiki einbinden lässt. - -Nach Änderungen auf der Seite schreibt **Mehr → Änderungen speichern** in Chrome oder Edge Seite, `graph.json` und SVGs direkt zurück, sobald der Diagrammordner einmal gewählt ist. Andere Browser speichern nur `graph.json`: die Datei in den Ordner legen und Seite und SVGs mit `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force` neu erzeugen. - -
-Das Jeepay-Quellcodebeispiel mit elf Ansichten ausführen - -Wähle deine lokale Jeepay-Quellcodekopie, um die Belege zu prüfen: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Öffne `output/jeepay/index.html`; die elf SVGs liegen im selben Verzeichnis. Die Quellcoderevision und das Aktualisierungsverfahren stehen in der [Korpus-README](../../examples/jeepay). - -
- -## Diagramme mit dem Code synchron halten - -Ein mit Repository-Wurzel erzeugtes Diagramm hält fest, wo jede Komponente definiert ist, und die Zeile hinter jeder durch Code gestützten Beziehung (ein Aufruf, ein Fremdschlüssel). Die Prüfung mit `--repo-root` schlägt fehl, wenn eine erfasste Datei fehlt, ein Zeilenbereich nicht mehr in die Datei passt oder ein erfasstes Symbol seine Zeilen verlassen hat; die Meldung nennt die Zeilen, in denen das Symbol jetzt steht. Diesen Job in die CI aufnehmen; er braucht keinen Build, keine Anmeldung und kein Token: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -Schlägt er fehl, den Skill bitten, dieses Diagramm zu aktualisieren: - -```text -$qgraphflow:q-flow Laut CI ist docs/qgraphflow/order-sequence veraltet. Bitte aktualisieren. -``` - -Der Skill verschiebt Anker, deren Symbol er genau einmal in der Datei findet, korrigiert nur die weiterhin gemeldeten Anker und erzeugt Seite und SVGs neu, wobei bearbeitete Positionen und Texte erhalten bleiben. Er zeichnet das Diagramm nicht neu. - -## Welche Fragen die elf Diagrammarten beantworten - -| Ansicht · PNG | Hauptfrage | Umfang des Beispiels | -| --- | --- | --- | -| Plattformfähigkeitsarchitektur | Welche Fähigkeiten bietet die Plattform? | Fähigkeitsbereiche und Matrizen | -| Architektur der Engineering-Schichten | Wie ist der Projektcode organisiert? | Engineering-Schichten und gemeinsame Unterstützung | -| Komponentenbeziehungsarchitektur | Welche Verantwortungsgrenzen arbeiten im System zusammen? | Kanäle, Transaktionsorchestrierung, Preise, Risiko, Bestand, Zahlung, Bestellungen, Ereignisse und Auftragsabwicklung | -| Flussdiagramm | Wie verzweigt und vereinigt sich jeder Entscheidungspunkt? | Fehlbestand, Risikoablehnung, Kompensation bei Zahlungsfehlern und erfolgreicher Commit | -| Sequenz | In welcher Reihenfolge führt eine Anfrage Aufrufe aus und erhält Rückgaben? | Hauptpfad eines erfolgreichen Kaufabschlusses und asynchrones OrderPaid | -| ER | Wie hängen die Kerndaten zusammen? | Warenkorb, Bestellungen, Positionen, Zahlungen, Bestandsreservierungen und Pakete | -| Bereitstellung | Wo werden Laufzeiteinheiten platziert und wie sind sie verbunden? | Randnetz, Kubernetes, Datendienste, Zahlung und Lager-/Logistiknetze | -| Klasse | Wie hängen Domänenobjekte und Codeverträge voneinander ab? | Checkout-Anwendungsdienst, Order und vier Ports | -| Zustand | Welche Ereignisse und Wächterbedingungen treiben eine Bestellung voran? | Zahlung, Auftragsabwicklung, Stornierung, Erstattung und Abschluss | -| Anwendungsfall | Welche Fähigkeiten besitzt jeder Akteur? | Käufer, Händler, Lager und Kundendienst | -| Datenfluss | Welche Transformationen und Speicher durchlaufen Datenbestände? | Warenkorb, Transaktionsentscheidungen, Bestellereignisse, Lager/Logistik und Lieferbelege | - -Dies ist ein Konzeptmodell zur Demonstration von QGraphFlow, kein konkretes E-Commerce-Repository. Die Beispieldatei `graph.json` erfindet keine Quellpfade und kennzeichnet Beziehungen mit `inference`. Echte Projektdiagramme benötigen nachvollziehbaren Quellcode, DDL, Konfiguration, Tests und akzeptierte Anforderungen. - -## Entwickeln und beitragen - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -Erforderlich sind Node.js 22 oder neuer, npm, tar, zip und unzip. Fehlerberichte sollten ein minimales anonymisiertes Diagramm, Client- und Browserversion sowie Reproduktionsschritte enthalten. - -Referenzdokumentation (Englisch): [Belegquellen](../../skills/q-flow/references/evidence-sources.md) · [Diagrammformat](../../skills/q-flow/references/graph-schema.md) · [Geführte Bedarfsklärung](../../skills/q-flow/references/guided-intake.md) · [Viewer-Entwicklung und Abnahme](../../skills/q-flow/references/viewer-development.md) · [Diagrammgestaltung](../../skills/q-flow/references/visual-contract.md) - -## Lizenz und Zuordnung - -[MIT](../../LICENSE) · [Drittanbieterhinweise](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow ist ein unabhängiges Projekt unter MIT-Lizenz. Die Szenarien in diesem Dokument sind konzeptionelle Beispiele und stellen keine Produktionsarchitektur eines realen Unternehmens dar. - -## Architekturübersichten - -Architektur umfasst jetzt Komponentenbeziehungen, Plattformfähigkeiten und Engineering-Schichten. Beschreibe den Gegenstand und die Frage; der Skill wählt die Vorlage. Angeforderte Sammlungen können mehrere Architekturansichten mit unabhängigen Bearbeitungen enthalten. - -```text -$qgraphflow:q-flow Analysiere die Plattformfähigkeiten und die geschäftlichen Integrationswege des aktuellen Projekts und erzeuge eine Übersicht der Plattformfähigkeiten auf Chinesisch. -$qgraphflow:q-flow Analysiere die Organisation des aktuellen Projekts und seine Komponentenschichten und erzeuge chinesische Übersichten des Gesamtprojekts und eines Komponentenquerschnitts. -$qgraphflow:q-flow Erzeuge eine englische Übersicht der Plattformfähigkeiten dieses Projekts und zeige, wie sich Anwendungsmodule integrieren. -``` - -Siehe [examples/jeepay](../../examples/jeepay) für quellenbasierte Architekturansichten zu Plattform, Engineering und Komponentenbeziehungen. Entsperre eine Übersicht, um Karten innerhalb einer Schicht neu anzuordnen oder Texte zu bearbeiten. Speichern erhält alle Ansichten; Zurücksetzen stellt nur die aktuelle wieder her. diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md deleted file mode 100644 index 0ee215c..0000000 --- a/docs/readme/README.es.md +++ /dev/null @@ -1,311 +0,0 @@ -
- -

QGraphFlow

- -### Convierte código complejo en diagramas que puedes explorar. - -Sigue el recorrido. Comprueba las evidencias. Comparte un archivo sin conexión. - -💡 Inspirado en Cocoon-AI/architecture-diagram-generator; gracias por la idea. - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[Demo en línea](https://supermax92.github.io/qgraphflow/) · [Primeros pasos](#primeros-pasos) · [Instalación por cliente](#guía-de-instalación) · [Informar de un problema](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*Once tipos de diagramas: arquitectura de capacidades de la plataforma, arquitectura por capas de ingeniería, arquitectura de relaciones entre componentes, diagrama de flujo, secuencia, ER, despliegue, clases, estados, casos de uso y flujo de datos.* - -QGraphFlow genera diagramas de software interactivos a partir del código, los esquemas, la configuración y los requisitos. Permite comprobar las relaciones y compartir el resultado como HTML sin conexión. - -**Qué lo distingue:** once tipos de diagrama en una sola habilidad, un tipo de evidencia en cada relación y la línea de código detrás de cada una respaldada por código, diseño automático, edición en la propia página y ninguna solicitud de red de los scripts del complemento ni del propio Viewer. - -![Demostración interactiva de varias vistas de Jeepay: arquitectura de relaciones entre componentes, secuencia y ER](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -Con el código fuente real de Jeepay, alterna entre diagramas de arquitectura de relaciones entre componentes, secuencia y ER para explorar componentes y relaciones de llamadas. [Ver GIF a tamaño original](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**Presentación de un diagrama de secuencia complejo** - -![Dibujo gradual de un diagrama de secuencia complejo: participantes, líneas de vida, mensajes, barras de activación y fragmentos combinados anidados](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -Un escenario ficticio de comercio electrónico contiene 9 participantes, 29 mensajes y 6 fragmentos combinados, con reintentos de inventario, ramas anidadas, procesamiento paralelo, compensación de fallos y callbacks asíncronos. La animación muestra gradualmente el diagrama generado para presentar su estructura y sus detalles. [Ver GIF a tamaño original](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -Un solo comando instala la habilidad para Claude Code, Codex, Cursor y Qoder; la instalación como complemento y los demás clientes están en la [guía de instalación](#guía-de-instalación). - -- **Explorar:** buscar, ampliar y desplazar el lienzo; consultar responsabilidades y relaciones entrantes y salientes. - -- **Verificar:** inspeccionar nodos y conexiones para revisar archivos, líneas, símbolos e incertidumbres explícitas. - -- **Editar:** desbloquear el diseño, cambiar textos y mover elementos; restablecer cuando sea necesario. - -- **Compartir:** abrir el HTML sin conexión o exportar el diagrama completo a SVG / PNG. - -El [corpus de Jeepay](../../examples/jeepay), basado en código fuente real, contiene las once vistas utilizadas por CI y la demostración online. - -## Primeros pasos - -Tras la instalación, abre tu proyecto de negocio en el cliente y selecciona la habilidad `q-flow`. Los ejemplos usan `/q-flow` de Claude Code; en Codex, usa la entrada `$q-flow` o `$qgraphflow:q-flow` que ofrezca tu cliente. ¿Todavía no lo has instalado? Consulta primero la [guía de instalación](#guía-de-instalación). - -### 1. Entrada vacía: No sabes por dónde empezar - -Invoca la habilidad sin añadir una petición: - -```text -/q-flow -``` - -La habilidad te guía para elegir la parte que analizar y la pregunta que debe responder el diagrama. Empieza a dibujar cuando la información necesaria está clara. - -### 2. Preguntar por las capacidades: Saber qué puede dibujar - -```text -/q-flow ¿Qué tipos de diagramas puedes dibujar? ¿Qué preguntas responde cada tipo? Acabo de hacerme cargo de un proyecto; presenta tus capacidades y sugiere un punto de partida. -``` - -Conoce primero los usos de los once tipos de diagramas y decide después si quieres ver la estructura del proyecto, el orden de llamadas, las relaciones de datos u otro contenido. - -### 3. Entrada vaga: Solo tienes un objetivo general - -```text -/q-flow Ayúdame a dibujar este proyecto. Quiero entenderlo lo antes posible. -``` - -No necesitas indicar primero el tipo de diagrama. La habilidad determina una vista adecuada según el proyecto y tu objetivo, y pregunta cuando falta información necesaria. - -### 4. Entrada precisa: Definir el alcance y pedir detalles del dibujo - -Sustituye los nombres de negocio y los pasos siguientes por procesos que existan realmente en tu proyecto: - -```text -/q-flow Analiza el proceso de creación de pedidos del proyecto actual y genera un diagrama de secuencia en chino. -Incluye la entrada de solicitudes, el cálculo de precios, la reserva de inventario, la autorización de pago y la persistencia del pedido. -Conserva las llamadas síncronas, mensajes asíncronos, retornos emparejados, barras de activación, ramas condicionales, reintentos y compensaciones de fallos que existan realmente en el código. No omitas detalles por brevedad. -Indica los archivos y números de línea del código de los componentes y llamadas, y guarda el resultado en docs/qgraphflow/order-sequence/. -``` - -Define claramente el objeto, la pregunta, el nivel de detalle y la ubicación de salida para empezar directamente. El diagrama conserva solo hechos respaldados por evidencia. - -### 5. Seguir refinando: Ampliar una parte del diagrama anterior - -Una vez generado el resultado, continúa en la misma conversación: - -```text -/q-flow Amplía el paso de reserva de inventario del diagrama de secuencia anterior en un diagrama de flujo independiente en chino. -Muestra todas las ramas de validación de inventario, reserva exitosa, fallos reintentables, límite de reintentos y liberación de inventario. Sigue el código fuente y no añadas pasos que no existan en él. -``` - -Mira primero el conjunto y profundiza después en un paso. También puedes pedir más detalles de un diagrama existente o verificar sus relaciones. - -## Guía de instalación - -Se necesitan Node.js 22 o posterior y un cliente compatible con complementos que tenga configurado el acceso al modelo. - -### Instalación rápida - -```bash -npx skills add supermax92/qgraphflow -``` - -Probado con `skills` 1.7.0 en Claude Code, Codex, Cursor y Qoder. El comando pregunta en qué clientes instalar; `-a claude-code` indica uno directamente y `-g` instala para el usuario en lugar del proyecto actual. La habilidad queda instalada como `q-flow`, sin el prefijo `qgraphflow:` de las instalaciones como complemento de más abajo. - -Para instalarla como complemento, seguir los pasos siguientes. En [Qoder Desktop](#qoder-desktop), puedes instalar desde el Marketplace y omitir el paso 1. - -### 1. Descargar el complemento - -Obtener el complemento desde npmjs.com, sin cuenta, inicio de sesión ni token. Crear un directorio independiente fuera del proyecto de la aplicación: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Ahora se está en la raíz del complemento. **La descarga mediante npm no instala automáticamente el complemento en el cliente**; continuar con el paso 2. El paquete también ofrece el comando `qgraphflow`, que se usa en [Mantener los diagramas sincronizados con el código](#mantener-los-diagramas-sincronizados-con-el-código). - -Ejecutar los comandos siguientes desde **la raíz del complemento, que contiene `skills/`**. - -### 2. Instalar en el cliente - -#### Codex App / CLI - -Codex CLI debe estar instalado y disponible en la terminal: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Iniciar una sesión nueva, escribir `$` y seleccionar `qgraphflow:q-flow`. - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Iniciar una sesión nueva y escribir `/q-flow` (o el nombre completo `/qgraphflow:q-flow`). - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -Iniciar una sesión nueva y seleccionar `q-flow`. - -#### Qoder Desktop - -**Recomendado:** Abre **Settings → Plugins → Marketplace**, busca **QGraphFlow** o **代码图谱可视化** e instala el complemento. Inicia una sesión nueva y selecciona `q-flow`. - -Para una instalación local, completa primero el paso 1. Después abre **Settings → Plugins → Custom → Import** e importa el directorio raíz completo del complemento. Inicia una sesión nueva y selecciona `q-flow`. - -#### Cursor - -Copiar todo el contenido de la raíz del complemento, incluidos los archivos ocultos, a: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -Comprobar que allí existe `.cursor-plugin/plugin.json`, recargar la ventana y buscar `q-flow` en **Customize**. Si hay una versión anterior, hacer una copia de seguridad antes; no mezclar archivos antiguos y nuevos. - -### 3. Empezar a usarlo - -Abre tu proyecto de negocio en el cliente, inicia una sesión nueva y selecciona la habilidad. Describe tu petición siguiendo los ejemplos de [Primeros pasos](#primeros-pasos). Abre el HTML generado en el navegador. - -¿Prefieres compilarlo? Consulta las [instrucciones de compilación desde el código fuente](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## Uso rápido - -Estos ejemplos usan `$qgraphflow:q-flow` en Codex. Si el cliente muestra `$q-flow`, seleccionar esa entrada. En los demás clientes, usar la forma de invocación indicada arriba. - -**¿No sabes por dónde empezar?** Invocar la habilidad y elegir el tema y la pregunta cuando lo solicite. - -```text -$qgraphflow:q-flow -``` - -**¿Ya tienes un objetivo?** Indicar qué parte quieres dibujar y qué quieres entender. No hace falta elegir antes el tipo de diagrama. - -### Ejemplo 1: Entender la arquitectura - -```text -$qgraphflow:q-flow Analiza este proyecto y crea un diagrama de arquitectura en chino que muestre responsabilidades de los módulos, dependencias y límites del sistema. -``` - -Útil para conocer la estructura general al llegar a un proyecto. - -### Ejemplo 2: Seguir un flujo de negocio - -```text -$qgraphflow:q-flow Analiza la creación de pedidos y genera un diagrama de secuencia en chino con cálculo de precios, reserva de inventario, pago y persistencia del pedido, incluidas las ramas de fallo. -``` - -Sustituir la creación de pedidos y sus pasos por el flujo real del proyecto. Continuar en la misma conversación: - -```text -$qgraphflow:q-flow Amplía la reserva de inventario del diagrama anterior en un diagrama de flujo independiente en chino, con el tratamiento de éxitos y fallos. -``` - -Los resultados se guardan bajo `docs/qgraphflow/` de forma predeterminada. Abrir `index.html` para explorar, editar y exportar; `graph.json` conserva los datos. Cada vista también se escribe como SVG (`diagram.svg`, o `diagram--.svg` cuando hay varias), que puede incrustarse como imagen en un README, una pull request o una wiki. - -Después de editar en la página, **Más → Guardar cambios** en Chrome o Edge reescribe en su sitio la página, `graph.json` y los SVG, tras elegir una vez la carpeta del diagrama. Otros navegadores solo guardan `graph.json`: colocarlo en la carpeta y volver a generar la página y los SVG con `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. - -
-Ejecutar el ejemplo de Jeepay con once vistas basado en código fuente - -Selecciona tu copia local del código fuente de Jeepay para verificar la evidencia: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Abre `output/jeepay/index.html`; sus once SVG están en el mismo directorio. Consulta el [README del corpus](../../examples/jeepay) para conocer la revisión del código fuente y el procedimiento de actualización. - -
- -## Mantener los diagramas sincronizados con el código - -Un diagrama generado con la raíz del repositorio registra dónde se define cada componente y la línea detrás de cada relación respaldada por código (una llamada, una clave foránea). La validación con `--repo-root` falla cuando falta un archivo registrado, un rango de líneas ya no cabe en el archivo o un símbolo registrado salió de sus líneas, y el error indica en qué líneas está ahora el símbolo. Añadir este trabajo a la CI; no necesita compilación, inicio de sesión ni token: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -Si falla, pedir a la habilidad que actualice ese diagrama: - -```text -$qgraphflow:q-flow La CI dice que docs/qgraphflow/order-sequence está desactualizado. Actualízalo. -``` - -La habilidad mueve los anclajes cuyo símbolo encuentra una sola vez en el archivo, corrige solo los que siguen fallando y vuelve a generar la página y los SVG conservando las posiciones y los textos editados. No redibuja el diagrama. - -## Qué responde cada uno de los once tipos de diagramas - -| Vista · PNG | Pregunta principal | Alcance del ejemplo | -| --- | --- | --- | -| Arquitectura de capacidades de la plataforma | ¿Qué capacidades ofrece la plataforma? | Zonas de capacidades y matrices | -| Arquitectura por capas de ingeniería | ¿Cómo se organiza el código del proyecto? | Capas de ingeniería y soporte compartido | -| Arquitectura de relaciones entre componentes | ¿Qué límites de responsabilidad colaboran en el sistema? | Canales, orquestación de transacciones, precios, riesgo, inventario, pago, pedidos, eventos y ejecución de pedidos | -| Diagrama de flujo | ¿Cómo se bifurca y converge cada decisión? | Falta de inventario, rechazo de riesgo, compensación de fallos de pago y confirmación exitosa | -| Secuencia | ¿En qué orden hace llamadas y recibe retornos una solicitud? | Flujo principal de compra exitosa y OrderPaid asíncrono | -| ER | ¿Cómo se relacionan los datos principales? | Carrito, pedidos, líneas, pagos, reservas de inventario y paquetes | -| Despliegue | ¿Dónde se ubican las unidades de ejecución y cómo se conectan? | Borde, Kubernetes, servicios de datos, pago y redes de almacén y logística | -| Clases | ¿Cómo dependen los objetos de dominio y los contratos del código? | Servicio de aplicación Checkout, Order y cuatro puertos | -| Estados | ¿Qué eventos y condiciones de guarda hacen avanzar un pedido? | Pago, ejecución del pedido, cancelación, reembolso y cierre | -| Casos de uso | ¿Qué capacidades tiene cada actor? | Comprador, comercio, almacén y atención al cliente | -| Flujo de datos | ¿Por qué transformaciones y almacenes pasan los activos de datos? | Carrito, decisiones de transacción, eventos de pedidos, almacén y logística y comprobantes de entrega | - -Este modelo conceptual demuestra QGraphFlow y no corresponde a un repositorio de comercio concreto. El ejemplo `graph.json` no inventa rutas de código y marca las evidencias de las relaciones como `inference`. Los diagramas reales necesitan código, DDL, configuración, pruebas y requisitos aceptados que se puedan rastrear. - -## Desarrollo y contribuciones - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -Se necesitan Node.js 22 o posterior, npm, tar, zip y unzip. Al informar de un problema, incluir un gráfico mínimo sin datos sensibles, versiones del cliente y navegador y pasos de reproducción. - -Documentación de referencia (en inglés): [Fuentes de evidencia](../../skills/q-flow/references/evidence-sources.md) · [Formato de gráficos](../../skills/q-flow/references/graph-schema.md) · [Consulta guiada](../../skills/q-flow/references/guided-intake.md) · [Desarrollo y aceptación del Viewer](../../skills/q-flow/references/viewer-development.md) · [Composición de diagramas](../../skills/q-flow/references/visual-contract.md) - -## Licencia y atribución - -[MIT](../../LICENSE) · [Avisos de terceros](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow es un proyecto independiente con licencia MIT. Los escenarios de este documento son ejemplos conceptuales y no representan la arquitectura de producción de ninguna empresa real. - -## Vistas generales de arquitectura - -La arquitectura incluye ahora relaciones entre componentes, capacidades de la plataforma y capas de ingeniería. Describe el objeto y la pregunta; la habilidad elige la plantilla. Las colecciones solicitadas pueden contener varias vistas de arquitectura con ediciones independientes. - -```text -$qgraphflow:q-flow Analiza las capacidades de la plataforma y las formas de integración de negocio del proyecto actual, y genera una vista general de capacidades de la plataforma en chino. -$qgraphflow:q-flow Analiza la organización del proyecto actual y sus capas de componentes, y genera vistas generales en chino del proyecto completo y de una sección de un componente. -$qgraphflow:q-flow Genera una vista general en inglés de las capacidades de la plataforma de este proyecto y muestra cómo se integran los módulos de aplicación. -``` - -Consulta [examples/jeepay](../../examples/jeepay) para ver las vistas de arquitectura de plataforma, ingeniería y relaciones entre componentes basadas en código fuente real. Desbloquea una vista general para reordenar tarjetas dentro de una capa o editar texto. Guardar conserva todas las vistas; restablecer restaura solo la actual. diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md deleted file mode 100644 index b122259..0000000 --- a/docs/readme/README.ja.md +++ /dev/null @@ -1,311 +0,0 @@ -
- -

QGraphFlow

- -### 複雑なコードを、探索できる図へ。 - -経路をたどり、根拠を確認し、ひとつのオフラインファイルで共有。 - -💡 Cocoon-AI/architecture-diagram-generator に着想を得ました。原作者に感謝します。 - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[オンラインデモ](https://supermax92.github.io/qgraphflow/) · [はじめに](#はじめに) · [クライアントへの導入](#インストールガイド) · [問題を報告](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*11 種類の図に対応:プラットフォーム機能アーキテクチャ図、エンジニアリング層アーキテクチャ図、コンポーネント関係アーキテクチャ図、フローチャート、シーケンス図、ER 図、配置図、クラス図、状態図、ユースケース図、データフロー図。* - -QGraphFlow はソースコード、データ構造、設定、要件から対話型のソフトウェア図を生成します。関係の根拠を確認し、共有可能なオフライン HTML として届けます。 - -**ここが違う:** 1 つのスキルで 11 種類の図、すべての関係に根拠の種別、コードで裏付けられた関係にはその根拠となるソース行、自動レイアウト、ページ上での編集。プラグインのスクリプトと Viewer 自体はネットワーク通信を一切行いません。 - -![Jeepay の複数ビュー操作デモ:コンポーネント関係アーキテクチャ図、シーケンス図、ER 図](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -Jeepay の実際のソースを例に、コンポーネント関係アーキテクチャ図、シーケンス図、ER 図を切り替えて、コンポーネントと呼び出し関係を探索します。 [原寸の GIF を見る](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**複雑なシーケンス図の紹介** - -![複雑なシーケンス図の段階的な描画:参加者、ライフライン、メッセージ、活性区間、入れ子の結合フラグメント](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -架空の EC シナリオに 9 人の参加者、29 件のメッセージ、6 個の結合フラグメントを含め、在庫の再試行、入れ子の分岐、並行処理、失敗時の補償、非同期コールバックを扱います。生成済みの図をアニメーションで段階的に表示し、複雑なシーケンス図の構造と詳細を紹介します。 [原寸の GIF を見る](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -1 つのコマンドで Claude Code、Codex、Cursor、Qoder にスキルを導入できます。プラグインとしての導入やほかのクライアントは[インストールガイド](#インストールガイド)を参照してください。 - -- **探索:** 検索・拡大縮小・パンで、責務と上流・下流の関係を確認。 - -- **検証:** ノードや接続線からファイル、行番号、シンボル、明示された不確実性を確認。 - -- **編集:** ロック解除後に文字や位置を変更。必要に応じてリセット。 - -- **共有:** オフライン HTML を開くか、図全体を SVG / PNG に出力。 - -実際のソースに基づく [Jeepay コーパス](../../examples/jeepay)には、CI とオンラインデモで使う 11 種類のビューがすべて含まれます。 - -## はじめに - -インストール後、クライアントで業務プロジェクトを開き、`q-flow` スキルを選択します。以下は Claude Code の `/q-flow` を使う例です。Codex ではクライアントが実際に提供する `$q-flow` または `$qgraphflow:q-flow` を使ってください。まだインストールしていない場合は、先に[インストールガイド](#インストールガイド)を参照してください。 - -### 1. 空の入力:どこから始めるか分からない - -要件を付けずにスキルだけを呼び出します。 - -```text -/q-flow -``` - -スキルが、分析する部分と図で答えてほしい問いの選択を案内します。必要な情報が明確になったら描画を始めます。 - -### 2. 機能を尋ねる:何を描けるか知る - -```text -/q-flow どの種類の図を描けますか?各種類はどのような問いに答えるのに適していますか?プロジェクトを引き継いだばかりなので、まず機能を紹介し、始める場所を提案してください。 -``` - -まず 11 種類の図の用途を知り、それからプロジェクト構造、呼び出し順序、データ関係など、何を見るかを決めます。 - -### 3. 曖昧な入力:大まかな目的だけがある - -```text -/q-flow このプロジェクトを図にしてください。できるだけ早く理解したいです。 -``` - -先に図の種類を指定する必要はありません。スキルがプロジェクトと目的に応じて適したビューを決め、必要な情報が不足している場合に質問します。 - -### 4. 正確な入力:範囲を明示して描画の詳細を求める - -次の業務名と手順を、プロジェクトに実際に存在するフローに置き換えてください。 - -```text -/q-flow 現在のプロジェクトの注文作成フローを分析し、中国語のシーケンス図を生成してください。 -リクエスト入口、価格計算、在庫引当、支払い承認、注文の永続化を含めてください。 -ソースに実際に存在する同期呼び出し、非同期メッセージ、対応する戻り、活性区間、条件分岐、再試行、失敗時の補償を残し、簡潔さのために詳細を省略しないでください。 -コンポーネントと呼び出しのソースファイルと行番号を示し、結果を docs/qgraphflow/order-sequence/ に保存してください。 -``` - -対象、問い、詳細度、出力先を明確に伝えると、そのまま開始できます。図には根拠のある事実だけを残します。 - -### 5. さらに詳しく:前の図の一部分を展開する - -結果の生成後、同じ会話で続けます。 - -```text -/q-flow 前のシーケンス図の在庫引当ステップを展開し、独立した中国語のフローチャートを生成してください。 -在庫確認、引当成功、再試行可能な失敗、再試行上限、在庫解放の分岐をすべて示してください。ソースコードに従い、コードにない手順は追加しないでください。 -``` - -まず全体を見てから、ひとつの手順を掘り下げます。既存の図の詳細追加や、関係の検証を続けて依頼することもできます。 - -## インストールガイド - -Node.js 22 以降と、プラグインに対応しモデルへのアクセスを設定済みのクライアントを用意してください。 - -### クイックインストール - -```bash -npx skills add supermax92/qgraphflow -``` - -`skills` 1.7.0 で Claude Code、Codex、Cursor、Qoder への導入を実測済みです。導入先のクライアントを尋ねられます。`-a claude-code` で直接指定でき、`-g` を付けると現在のプロジェクトではなくユーザー単位で導入します。この方法で導入したスキル名は `q-flow` で、下のプラグイン導入で付く `qgraphflow:` という接頭辞は付きません。 - -プラグインとして導入する場合は、次の手順に従ってください。[Qoder Desktop](#qoder-desktop) ではマーケットプレイスから直接インストールできるため、手順 1 は不要です。 - -### 1. プラグインをダウンロード - -npmjs.com からプラグインを取得します。アカウント、ログイン、トークンは不要です。業務プロジェクトの外に専用ディレクトリを作成します。 - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -これでプラグインのルートディレクトリに移動できました。**npm でダウンロードしても、クライアントへのインストールは自動では行われません。** 手順 2 に進んでください。このパッケージには `qgraphflow` コマンドも含まれ、[図とコードを同期させる](#図とコードを同期させる)で使います。 - -以下のコマンドはすべて、**`skills/` を含むプラグインのルートディレクトリ**で実行してください。 - -### 2. クライアントにインストール - -#### Codex App / CLI - -ターミナルで Codex CLI を使用できるよう、あらかじめインストールしてください。 - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -新しいセッションを開始し、`$` を入力して `qgraphflow:q-flow` を選択します。 - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -新しいセッションを開始し、`/q-flow`(または完全名 `/qgraphflow:q-flow`)を入力します。 - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -新しいセッションを開始し、`q-flow` を選択します。 - -#### Qoder Desktop - -**推奨:** **Settings → Plugins → Marketplace** を開き、**QGraphFlow** または **代码图谱可视化** を検索してインストールします。新しいセッションを開始し、`q-flow` を選択します。 - -ローカルインストールの場合は手順 1 を完了し、**Settings → Plugins → Custom → Import** を開いて、プラグインのルートディレクトリ全体をインポートします。新しいセッションで `q-flow` を選択します。 - -#### Cursor - -プラグインのルートディレクトリ内のすべてのファイル(隠しファイルを含む)を、次の場所にコピーします。 - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -その中に `.cursor-plugin/plugin.json` があることを確認し、ウィンドウを再読み込みして **Customize** で `q-flow` を探します。旧バージョンがある場合は先にバックアップし、新旧のファイルを混在させないでください。 - -### 3. 使い始める - -クライアントで業務プロジェクトを開き、新しいセッションでスキルを選択します。[はじめに](#はじめに)の例を参考に要件を伝えてください。生成後、出力された HTML をブラウザで開きます。 - -自分でビルドする場合は、[ソースからのビルド手順](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally)を参照してください。 - -## すぐに使う - -以下は Codex の `$qgraphflow:q-flow` を使う例です。クライアントに `$q-flow` と表示される場合は、その入口を選択してください。他のクライアントでは、上記の対応するスキルの呼び出し方を使います。 - -**どこから始めるか迷ったら:** スキルを呼び出し、案内に従って対象と知りたいことを選びます。 - -```text -$qgraphflow:q-flow -``` - -**目的が決まっているなら:** 「どの部分を描くか+何を知りたいか」を伝えます。先に図の種類を選ぶ必要はありません。 - -### 例1:プロジェクト構造を理解する - -```text -$qgraphflow:q-flow 現在のプロジェクトを分析し、主要モジュールの責務、依存関係、システム境界を示す中国語のアーキテクチャ図を作成してください。 -``` - -初めて触れるプロジェクトの全体像をつかむのに適しています。 - -### 例2:業務の呼び出しを追う - -```text -$qgraphflow:q-flow 注文作成フローを分析し、価格計算、在庫引当、支払い、注文保存の呼び出し順と失敗分岐を示す中国語のシーケンス図を作成してください。 -``` - -「注文作成」と各手順を実際の業務フローに置き換えてください。同じ会話で続けて依頼できます。 - -```text -$qgraphflow:q-flow 前の図の在庫引当を掘り下げ、成功時と失敗時の処理を示す中国語のフローチャートを別に作成してください。 -``` - -既定の保存先は `docs/qgraphflow/` 配下です。`index.html` を開いて探索・編集・出力でき、`graph.json` に図データが残ります。各ビューは SVG(`diagram.svg`、複数ビューでは `diagram--.svg`)としても書き出され、README、プルリクエスト、Wiki に画像として埋め込めます。 - -ページで編集したあと、Chrome または Edge で「その他 → 変更を保存」を実行し、図のフォルダーを一度選ぶと、ページ、`graph.json`、SVG がその場で書き換わります。ほかのブラウザーは `graph.json` だけを保存します。そのフォルダーに置いてから `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force` でページと SVG を再生成してください。 - -
-Jeepay のソースに基づく 11 ビューの例を実行する - -根拠を検証するため、ローカルの Jeepay ソースチェックアウトを指定してください。 - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -`output/jeepay/index.html` を開いてください。11 個の SVG も同じディレクトリにあります。ソースのリビジョンと更新手順は[コーパスの README](../../examples/jeepay)を参照してください。 - -
- -## 図とコードを同期させる - -リポジトリのルートを指定して生成した図には、各コンポーネントの定義位置と、コードで裏付けられた各関係を成立させている行(呼び出し、外部キーなど)が記録されます。`--repo-root` 付きで検証すると、記録したファイルがない、行範囲がファイルに収まらない、記録したシンボルが元の行範囲から外れた、のいずれかで失敗し、エラーにはシンボルの現在の行が示されます。次のジョブを CI に追加してください。ビルド、ログイン、トークンは不要です。 - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -失敗したら、スキルにその図の更新を頼みます。 - -```text -$qgraphflow:q-flow CI で docs/qgraphflow/order-sequence の図が古いと出ました。更新してください。 -``` - -スキルは、ファイル内で 1 か所だけ見つかったシンボルのアンカーを移し、なお失敗するアンカーだけを修正し、編集した位置と文字を保ったままページと SVG を再生成します。図を描き直すことはしません。 - -## 11 種類の図がそれぞれ答えること - -| ビュー · PNG | 主な問い | 本サンプルの範囲 | -| --- | --- | --- | -| プラットフォーム機能アーキテクチャ図 | プラットフォームにはどんな機能があるか? | 機能の区分とマトリクス | -| エンジニアリング層アーキテクチャ図 | プロジェクトのコードはどう構成されているか? | エンジニアリング層と共通の支援機能 | -| コンポーネント関係アーキテクチャ図 | システムのどの責務境界が協調するか? | チャネル、取引のオーケストレーション、価格、リスク、在庫、支払い、注文、イベント、注文履行 | -| フローチャート | 各判断点はどう分岐・合流するか? | 欠品、リスク拒否、支払い失敗時の補償、正常コミット | -| シーケンス図 | ひとつのリクエストはどの順序で呼び出しと戻りを行うか? | 決済成功の主経路と非同期 OrderPaid | -| ER 図 | 主要データはどう関連するか? | カート、注文、明細、支払い、在庫引当、荷物 | -| 配置図 | 実行単位をどこに置き、どう接続するか? | エッジ、Kubernetes、データサービス、支払い、倉庫配送ネットワーク | -| クラス図 | ドメインオブジェクトとコードの契約はどう依存するか? | Checkout アプリケーションサービス、Order、4 つのポート | -| 状態図 | どのイベントとガード条件が注文を進めるか? | 支払い、注文履行、取消、返金、終了 | -| ユースケース図 | 各参加者にはどんな機能があるか? | 購入者、店舗、倉庫、カスタマーサポート | -| データフロー図 | データ資産はどの変換と保存を経るか? | カート、取引判断、注文イベント、倉庫配送、配送受領記録 | - -これは QGraphFlow の機能を示す概念モデルで、特定の EC リポジトリに対応しません。サンプルの `graph.json` に架空のソースパスは入れず、関係の証拠を `inference` に統一しています。実際のプロジェクトでは、追跡可能なソース、DDL、設定、テスト、合意済み要件を使ってください。 - -## 開発と参加 - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -開発には Node.js 22 以降、npm、tar、zip、unzip が必要です。問題報告には、機密情報を除いた最小限の図データ、クライアントとブラウザーのバージョン、再現手順を添えてください。 - -リファレンス(英語):[証拠の出典](../../skills/q-flow/references/evidence-sources.md) · [図データ形式](../../skills/q-flow/references/graph-schema.md) · [対話による要件確認](../../skills/q-flow/references/guided-intake.md) · [Viewer の開発と受け入れ検証](../../skills/q-flow/references/viewer-development.md) · [図の構成](../../skills/q-flow/references/visual-contract.md) - -## ライセンスと帰属 - -[MIT](../../LICENSE) · [第三者の表示](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow は MIT ライセンスを採用する独立したプロジェクトです。本文のシナリオは概念例で、実在する企業の本番アーキテクチャを表しません。 - -## アーキテクチャの全体像 - -アーキテクチャには、コンポーネント関係、プラットフォーム機能、エンジニアリング層が含まれます。対象と問いを伝えると、スキルがテンプレートを選びます。依頼したコレクションには、個別に編集できる複数のアーキテクチャビューを含められます。 - -```text -$qgraphflow:q-flow 現在のプロジェクトのプラットフォーム機能と業務の接続方法を分析し、中国語のプラットフォーム機能全体図を生成してください。 -$qgraphflow:q-flow 現在のプロジェクト構成とコンポーネントの階層を分析し、プロジェクト全体とひとつのコンポーネント断面の中国語の全体図を生成してください。 -$qgraphflow:q-flow このプロジェクトのプラットフォーム機能の全体図を英語で生成し、アプリケーションモジュールがどのように統合されるかを示してください。 -``` - -実際のソースに基づくプラットフォーム、エンジニアリング、コンポーネント関係のアーキテクチャビューは [examples/jeepay](../../examples/jeepay)を参照してください。全体図のロックを解除すると、同じ層のカードの並べ替えや文字の編集ができます。保存は全ビューを保持し、リセットは現在のビューだけを戻します。 diff --git a/docs/readme/README.pt.md b/docs/readme/README.pt.md deleted file mode 100644 index 1bc62a6..0000000 --- a/docs/readme/README.pt.md +++ /dev/null @@ -1,311 +0,0 @@ -
- -

QGraphFlow

- -### Transforme código complexo em diagramas que você pode explorar. - -Siga o caminho. Confira as evidências. Compartilhe um arquivo offline. - -💡 Inspirado em Cocoon-AI/architecture-diagram-generator — agradecemos pela ideia. - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[Demonstração online](https://supermax92.github.io/qgraphflow/) · [Primeiros passos](#primeiros-passos) · [Instalação por cliente](#guia-de-instalação) · [Relatar problema](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*Onze tipos de diagrama: arquitetura de capacidades da plataforma, arquitetura em camadas de engenharia, arquitetura de relações entre componentes, fluxograma, sequência, ER, implantação, classes, estados, casos de uso e fluxo de dados.* - -QGraphFlow gera diagramas de software interativos a partir de código, esquemas, configuração e requisitos. As relações podem ser verificadas e o resultado é um HTML offline compartilhável. - -**O que o diferencia:** onze tipos de diagrama em uma só habilidade, o tipo de evidência de cada relação e a linha de código por trás de cada uma que o código sustenta, layout automático, edição na própria página e nenhuma requisição de rede dos scripts do plugin nem do próprio Viewer. - -![Demonstração interativa de várias vistas do Jeepay: arquitetura de relações entre componentes, sequência e ER](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -Com o código-fonte real do Jeepay, alterne entre diagramas de arquitetura de relações entre componentes, sequência e ER para explorar componentes e relações de chamadas. [Ver GIF no tamanho original](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**Apresentação de um diagrama de sequência complexo** - -![Desenho gradual de um diagrama de sequência complexo: participantes, linhas de vida, mensagens, barras de ativação e fragmentos combinados aninhados](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -Um cenário fictício de comércio eletrônico contém 9 participantes, 29 mensagens e 6 fragmentos combinados, com novas tentativas de estoque, ramos aninhados, processamento paralelo, compensação de falhas e callbacks assíncronos. A animação revela gradualmente o diagrama gerado para mostrar sua estrutura e seus detalhes. [Ver GIF no tamanho original](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -Um só comando instala a habilidade para Claude Code, Codex, Cursor e Qoder; a instalação como plugin e os demais clientes estão no [guia de instalação](#guia-de-instalação). - -- **Explorar:** pesquisar, ampliar e deslocar a tela; entender responsabilidades e relações de entrada e saída. - -- **Verificar:** inspecionar nós e conexões para conferir arquivos, linhas, símbolos e incertezas explícitas. - -- **Editar:** desbloquear o layout, alterar textos e mover elementos; redefinir quando necessário. - -- **Compartilhar:** abrir o HTML offline ou exportar o diagrama completo em SVG / PNG. - -O [corpus do Jeepay](../../examples/jeepay), baseado em código-fonte real, contém as onze vistas usadas pelo CI e pela demonstração online. - -## Primeiros passos - -Após a instalação, abra seu projeto de negócio no cliente e selecione a habilidade `q-flow`. Os exemplos usam `/q-flow` do Claude Code; no Codex, use a entrada `$q-flow` ou `$qgraphflow:q-flow` que seu cliente realmente oferece. Ainda não instalou? Consulte primeiro o [guia de instalação](#guia-de-instalação). - -### 1. Entrada vazia: Não sabe por onde começar - -Invoque a habilidade sem acrescentar uma solicitação: - -```text -/q-flow -``` - -A habilidade orienta você a escolher a parte a analisar e a pergunta que o diagrama deve responder. O desenho começa quando as informações necessárias estão claras. - -### 2. Perguntar sobre capacidades: Saber o que pode desenhar - -```text -/q-flow Quais tipos de diagrama você pode desenhar? Que perguntas cada tipo responde? Acabei de assumir um projeto; apresente suas capacidades e sugira um ponto de partida. -``` - -Conheça primeiro os usos dos onze tipos de diagrama e depois decida se quer explorar a estrutura do projeto, a ordem das chamadas, as relações de dados ou outro conteúdo. - -### 3. Entrada vaga: Apenas um objetivo geral - -```text -/q-flow Ajude-me a desenhar este projeto. Quero entendê-lo o mais rápido possível. -``` - -Não é necessário indicar primeiro o tipo de diagrama. A habilidade determina uma vista adequada com base no projeto e no seu objetivo, e pergunta quando faltam informações necessárias. - -### 4. Entrada precisa: Definir o escopo e pedir detalhes do desenho - -Substitua os nomes de negócio e os passos abaixo por fluxos que realmente existam no seu projeto: - -```text -/q-flow Analise o fluxo de criação de pedidos do projeto atual e gere um diagrama de sequência em chinês. -Inclua a entrada da solicitação, o cálculo de preços, a reserva de estoque, a autorização de pagamento e a persistência do pedido. -Mantenha as chamadas síncronas, mensagens assíncronas, retornos emparelhados, barras de ativação, ramificações condicionais, tentativas e compensações de falha que realmente existam no código. Não omita detalhes por brevidade. -Indique os arquivos e números de linha do código dos componentes e chamadas, e salve o resultado em docs/qgraphflow/order-sequence/. -``` - -Defina claramente o objeto, a pergunta, o nível de detalhe e o local de saída para começar diretamente. O diagrama mantém apenas fatos sustentados por evidências. - -### 5. Refinar mais: Expandir parte do diagrama anterior - -Após a geração do resultado, continue na mesma conversa: - -```text -/q-flow Expanda a etapa de reserva de estoque do diagrama de sequência anterior em um fluxograma separado em chinês. -Mostre todos os ramos de validação do estoque, reserva bem-sucedida, falhas que permitem nova tentativa, limite de tentativas e liberação de estoque. Siga o código-fonte e não adicione etapas ausentes dele. -``` - -Veja primeiro o todo e depois aprofunde uma etapa. Você também pode pedir mais detalhes de um diagrama existente ou verificar suas relações. - -## Guia de instalação - -Você precisa do Node.js 22 ou posterior e de um cliente com suporte a plugins e acesso ao modelo configurado. - -### Instalação rápida - -```bash -npx skills add supermax92/qgraphflow -``` - -Testado com `skills` 1.7.0 no Claude Code, Codex, Cursor e Qoder. O comando pergunta em quais clientes instalar; `-a claude-code` indica um diretamente e `-g` instala para o seu usuário em vez do projeto atual. A habilidade é instalada como `q-flow`, sem o prefixo `qgraphflow:` das instalações como plugin abaixo. - -Para instalar como plugin, siga as etapas abaixo. No [Qoder Desktop](#qoder-desktop), você pode instalar pelo Marketplace e pular a etapa 1. - -### 1. Baixe o plugin - -Obtenha o plugin no npmjs.com, sem conta, login nem token. Crie um diretório separado, fora do projeto da sua aplicação: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Agora você está na raiz do plugin. **Baixar pelo npm não instala automaticamente o plugin no cliente**; continue na etapa 2. O pacote também oferece o comando `qgraphflow`, usado em [Mantenha os diagramas em sincronia com o código](#mantenha-os-diagramas-em-sincronia-com-o-código). - -Execute os comandos abaixo na **raiz do plugin, que contém `skills/`**. - -### 2. Instale no seu cliente - -#### Codex App / CLI - -O Codex CLI precisa estar instalado e disponível no terminal: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Inicie uma nova sessão, digite `$` e selecione `qgraphflow:q-flow`. - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Inicie uma nova sessão e digite `/q-flow` (ou o nome completo `/qgraphflow:q-flow`). - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -Inicie uma nova sessão e selecione `q-flow`. - -#### Qoder Desktop - -**Recomendado:** Abra **Settings → Plugins → Marketplace**, pesquise **QGraphFlow** ou **代码图谱可视化** e instale o plugin. Inicie uma nova sessão e selecione `q-flow`. - -Para uma instalação local, conclua primeiro a etapa 1. Depois, abra **Settings → Plugins → Custom → Import** e importe o diretório raiz completo do plugin. Inicie uma nova sessão e selecione `q-flow`. - -#### Cursor - -Copie todo o conteúdo da raiz do plugin, incluindo os arquivos ocultos, para: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -Confirme que `.cursor-plugin/plugin.json` existe nesse local, recarregue a janela e encontre `q-flow` em **Customize**. Se houver uma versão anterior, faça backup primeiro; não misture arquivos antigos e novos. - -### 3. Comece a usar - -Abra seu projeto de negócio no cliente, inicie uma nova sessão e selecione a habilidade. Descreva sua solicitação seguindo os exemplos de [Primeiros passos](#primeiros-passos). Abra o HTML gerado no navegador. - -Quer compilar por conta própria? Consulte as [instruções de compilação do código-fonte](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## Uso rápido - -Os exemplos usam `$qgraphflow:q-flow` no Codex. Se o cliente mostrar `$q-flow`, selecione essa entrada. Nos demais clientes, use a forma de chamada da habilidade indicada acima. - -**Sem saber por onde começar?** Chame a habilidade e escolha o assunto e a pergunta quando solicitado. - -```text -$qgraphflow:q-flow -``` - -**Já tem um objetivo?** Diga qual parte deseja desenhar e o que quer entender. Não é preciso escolher o tipo de diagrama antes. - -### Exemplo 1: Entender a arquitetura - -```text -$qgraphflow:q-flow Analise este projeto e crie um diagrama de arquitetura em chinês com responsabilidades dos módulos, dependências e limites do sistema. -``` - -Útil para conhecer a estrutura geral ao entrar em um projeto. - -### Exemplo 2: Acompanhar um fluxo de negócio - -```text -$qgraphflow:q-flow Analise a criação de pedidos e gere um diagrama de sequência em chinês com cálculo de preços, reserva de estoque, pagamento e persistência do pedido, incluindo os ramos de falha. -``` - -Substitua a criação de pedidos e suas etapas pelo fluxo real do projeto. Continue na mesma conversa: - -```text -$qgraphflow:q-flow Expanda a reserva de estoque do diagrama anterior em um fluxograma separado em chinês, mostrando o tratamento de sucesso e falha. -``` - -Os resultados ficam em `docs/qgraphflow/` por padrão. Abra `index.html` para explorar, editar e exportar; `graph.json` mantém os dados do grafo. Cada vista também é gravada como SVG (`diagram.svg`, ou `diagram--.svg` quando há várias vistas), que pode ser incorporado como imagem em um README, pull request ou wiki. - -Depois de editar na página, **Mais → Salvar alterações** no Chrome ou no Edge regrava a página, o `graph.json` e os SVG no lugar, depois que você escolhe a pasta do diagrama uma vez. Outros navegadores salvam só o `graph.json`: coloque-o na pasta e gere de novo a página e os SVG com `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. - -
-Executar o exemplo do Jeepay com onze vistas baseado em código-fonte - -Selecione sua cópia local do código-fonte do Jeepay para verificar as evidências: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Abra `output/jeepay/index.html`; os onze SVG estão no mesmo diretório. Consulte o [README do corpus](../../examples/jeepay) para conhecer a revisão do código-fonte e o procedimento de atualização. - -
- -## Mantenha os diagramas em sincronia com o código - -Um diagrama gerado com a raiz do repositório registra onde cada componente é definido e a linha por trás de cada relação sustentada pelo código (uma chamada, uma chave estrangeira). A validação com `--repo-root` falha quando um arquivo registrado sumiu, um intervalo de linhas não cabe mais no arquivo ou um símbolo registrado saiu das suas linhas, e o erro indica as linhas em que o símbolo está agora. Adicione este job ao seu CI; ele não precisa de build, login nem token: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -Quando falhar, peça à habilidade para atualizar o diagrama: - -```text -$qgraphflow:q-flow O CI diz que docs/qgraphflow/order-sequence está desatualizado. Atualize-o. -``` - -A habilidade move as âncoras cujo símbolo aparece uma única vez no arquivo, corrige apenas as âncoras que ainda falham e gera de novo a página e os SVG, mantendo as posições e os textos que você editou. Ela não redesenha o diagrama. - -## O que cada um dos onze tipos de diagrama responde - -| Vista · PNG | Pergunta principal | Escopo do exemplo | -| --- | --- | --- | -| Arquitetura de capacidades da plataforma | Quais capacidades a plataforma oferece? | Zonas de capacidades e matrizes | -| Arquitetura em camadas de engenharia | Como o código do projeto é organizado? | Camadas de engenharia e suporte compartilhado | -| Arquitetura de relações entre componentes | Quais limites de responsabilidade colaboram no sistema? | Canais, orquestração de transações, preços, risco, estoque, pagamento, pedidos, eventos e execução de pedidos | -| Fluxograma | Como cada decisão se ramifica e converge? | Falta de estoque, recusa de risco, compensação de falha de pagamento e confirmação bem-sucedida | -| Sequência | Em que ordem uma solicitação faz chamadas e recebe retornos? | Fluxo principal de compra bem-sucedida e OrderPaid assíncrono | -| ER | Como os dados centrais se relacionam? | Carrinho, pedidos, itens, pagamentos, reservas de estoque e pacotes | -| Implantação | Onde ficam as unidades de execução e como se conectam? | Borda, Kubernetes, serviços de dados, pagamento e redes de armazém e logística | -| Classes | Como objetos de domínio e contratos do código dependem entre si? | Serviço de aplicação Checkout, Order e quatro portas | -| Estados | Quais eventos e condições de guarda fazem um pedido avançar? | Pagamento, execução do pedido, cancelamento, reembolso e encerramento | -| Casos de uso | Quais capacidades cada ator possui? | Comprador, lojista, depósito e atendimento | -| Fluxo de dados | Por quais transformações e armazenamentos os ativos de dados passam? | Carrinho, decisões de transação, eventos de pedidos, armazém e logística e comprovantes de entrega | - -Este modelo conceitual demonstra o QGraphFlow e não corresponde a um repositório de comércio específico. O exemplo `graph.json` não inventa caminhos de código e marca as evidências das relações como `inference`. Diagramas reais precisam de código, DDL, configuração, testes e requisitos aceitos rastreáveis. - -## Desenvolvimento e contribuição - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -São necessários Node.js 22 ou posterior, npm, tar, zip e unzip. Ao relatar problemas, inclua um grafo mínimo sem informações sensíveis, versões do cliente e navegador e passos de reprodução. - -Documentação de referência (em inglês): [Fontes de evidência](../../skills/q-flow/references/evidence-sources.md) · [Formato dos grafos](../../skills/q-flow/references/graph-schema.md) · [Consulta guiada](../../skills/q-flow/references/guided-intake.md) · [Desenvolvimento e aceitação do Viewer](../../skills/q-flow/references/viewer-development.md) · [Composição de diagramas](../../skills/q-flow/references/visual-contract.md) - -## Licença e atribuição - -[MIT](../../LICENSE) · [Avisos de terceiros](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow é um projeto independente sob a licença MIT. Os cenários deste documento são exemplos conceituais e não representam a arquitetura de produção de nenhuma empresa real. - -## Visões gerais de arquitetura - -A arquitetura agora inclui relações entre componentes, capacidades da plataforma e camadas de engenharia. Descreva o objeto e a pergunta; a habilidade escolhe o modelo. As coleções solicitadas podem conter várias vistas de arquitetura com edições independentes. - -```text -$qgraphflow:q-flow Analise as capacidades da plataforma e as formas de integração de negócio do projeto atual e gere uma visão geral de capacidades da plataforma em chinês. -$qgraphflow:q-flow Analise a organização do projeto atual e suas camadas de componentes e gere visões gerais em chinês do projeto inteiro e de uma seção de um componente. -$qgraphflow:q-flow Gere uma visão geral em inglês das capacidades da plataforma deste projeto e mostre como os módulos de aplicação se integram. -``` - -Consulte [examples/jeepay](../../examples/jeepay) para ver as vistas de arquitetura de plataforma, engenharia e relações entre componentes baseadas em código-fonte real. Desbloqueie uma visão geral para reordenar cartões dentro de uma camada ou editar textos. Salvar mantém todas as vistas; redefinir restaura apenas a atual. diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md deleted file mode 100644 index 39c7a23..0000000 --- a/docs/readme/README.ru.md +++ /dev/null @@ -1,311 +0,0 @@ -
- -

QGraphFlow

- -### Превратите сложный код в диаграммы для исследования. - -Проследите путь. Проверьте основания. Поделитесь одним автономным файлом. - -💡 Вдохновлено проектом Cocoon-AI/architecture-diagram-generator — спасибо за идею. - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[Онлайн-демо](https://supermax92.github.io/qgraphflow/) · [Первые шаги](#первые-шаги) · [Установка для клиентов](#установка) · [Сообщить о проблеме](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*Поддерживаются одиннадцать типов диаграмм: архитектура возможностей платформы, архитектура инженерных слоёв, архитектура связей компонентов, блок-схема, последовательность, ER, развёртывание, классы, состояния, варианты использования и поток данных.* - -QGraphFlow создаёт интерактивные диаграммы программных систем из кода, схем данных, конфигурации и требований. Основания связей можно проверить, а результат — передать как автономный HTML. - -**Чем отличается:** одиннадцать типов диаграмм в одном навыке, тип доказательства для каждой связи и строка кода за каждой связью, подтверждённой кодом, автоматическая раскладка, редактирование прямо на странице и никаких сетевых запросов ни от скриптов плагина, ни от самого Viewer. - -![Интерактивная демонстрация нескольких видов Jeepay: архитектура связей компонентов, последовательность и ER](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -На примере реального исходного кода Jeepay переключайтесь между архитектурой связей компонентов, диаграммой последовательности и ER, изучая компоненты и связи вызовов. [Посмотреть GIF в исходном размере](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.en.hero.gif) - -**Демонстрация сложной диаграммы последовательности** - -![Пошаговое рисование сложной диаграммы последовательности: участники, линии жизни, сообщения, полосы активации и вложенные комбинированные фрагменты](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -Вымышленный сценарий электронной торговли содержит 9 участников, 29 сообщений и 6 комбинированных фрагментов: повторные попытки резервирования, вложенные ветви, параллельную обработку, компенсацию сбоев и асинхронные обратные вызовы. Анимация постепенно показывает готовую диаграмму, раскрывая её структуру и детали. [Посмотреть GIF в исходном размере](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.en.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -Одна команда устанавливает навык для Claude Code, Codex, Cursor и Qoder; установка в виде плагина и другие клиенты описаны в разделе [Установка](#установка). - -- **Исследование:** поиск, масштабирование и перемещение холста; назначение компонентов, входящие и исходящие связи. - -- **Проверка:** файлы, строки, символы и явно обозначенная неопределённость в узлах и связях. - -- **Редактирование:** разблокировка расположения, изменение текста и перемещение элементов; сброс при необходимости. - -- **Обмен:** автономный HTML или экспорт всей диаграммы в SVG / PNG. - -Основанный на реальном коде [корпус Jeepay](../../examples/jeepay) содержит все одиннадцать видов, используемых CI и онлайн-демонстрацией. - -## Первые шаги - -После установки откройте свой рабочий проект в клиенте и выберите навык `q-flow`. Примеры используют `/q-flow` в Claude Code; в Codex используйте пункт `$q-flow` или `$qgraphflow:q-flow`, который действительно предлагает ваш клиент. Ещё не установили? Сначала прочитайте раздел [Установка](#установка). - -### 1. Пустой ввод: Не знаете, с чего начать - -Вызовите навык без дополнительных требований: - -```text -/q-flow -``` - -Навык поможет выбрать часть для анализа и вопрос, на который должна ответить диаграмма. Рисование начнётся, когда необходимая информация будет ясна. - -### 2. Вопрос о возможностях: Узнать, что можно нарисовать - -```text -/q-flow Какие типы диаграмм ты можешь рисовать? На какие вопросы отвечает каждый тип? Я только что принял проект; сначала расскажи о своих возможностях и предложи, с чего начать. -``` - -Сначала узнайте назначение одиннадцати типов диаграмм, затем решите, что изучать: структуру проекта, порядок вызовов, связи данных или что-то другое. - -### 3. Неопределённый ввод: Есть только общая цель - -```text -/q-flow Помоги нарисовать этот проект. Я хочу как можно быстрее его понять. -``` - -Не нужно заранее указывать тип диаграммы. Навык определит подходящий вид по проекту и вашей цели и задаст вопросы, если необходимой информации не хватает. - -### 4. Точный ввод: Задать границы и запросить детали рисунка - -Замените названия и шаги ниже процессами, которые действительно есть в вашем проекте: - -```text -/q-flow Проанализируй создание заказа в текущем проекте и создай диаграмму последовательности на китайском языке. -Включи точку входа запроса, расчёт цены, резервирование запасов, авторизацию платежа и сохранение заказа. -Сохрани синхронные вызовы, асинхронные сообщения, парные возвраты, полосы активации, условные ветви, повторные попытки и компенсацию сбоев, которые действительно есть в исходниках. Не опускай детали ради краткости. -Укажи исходные файлы и номера строк компонентов и вызовов и сохрани результат в docs/qgraphflow/order-sequence/. -``` - -Чётко задайте предмет, вопрос, уровень детализации и место вывода, чтобы начать сразу. Диаграмма сохраняет только факты, подтверждённые доказательствами. - -### 5. Дальнейшее уточнение: Раскрыть часть предыдущей диаграммы - -После получения результата продолжите в том же разговоре: - -```text -/q-flow Раскрой резервирование запасов из предыдущей диаграммы последовательности отдельной блок-схемой на китайском языке. -Покажи все ветви проверки запасов, успешного резервирования, повторяемых сбоев, предела повторных попыток и освобождения запасов. Следуй исходному коду и не добавляй отсутствующих в нём шагов. -``` - -Сначала рассмотрите целое, затем углубитесь в один шаг. Можно также запросить дополнительные детали существующей диаграммы или проверить её связи. - -## Установка - -Нужны Node.js 22 или новее и клиент с поддержкой плагинов и настроенным доступом к модели. - -### Быстрая установка - -```bash -npx skills add supermax92/qgraphflow -``` - -Проверено с `skills` 1.7.0 для Claude Code, Codex, Cursor и Qoder. Команда спросит, в какие клиенты устанавливать; `-a claude-code` задаёт клиент сразу, а `-g` устанавливает навык для пользователя, а не для текущего проекта. Навык устанавливается как `q-flow`, без префикса `qgraphflow:`, который дают способы установки плагина ниже. - -Чтобы установить его как плагин, выполните шаги ниже. В [Qoder Desktop](#qoder-desktop) можно установить плагин из Marketplace и пропустить шаг 1. - -### 1. Скачайте плагин - -Получите плагин с npmjs.com — без учётной записи, входа и токена. Создайте отдельный каталог вне своего рабочего проекта: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -Теперь вы в корневом каталоге плагина. **Загрузка через npm не устанавливает плагин в клиент автоматически** — перейдите к шагу 2. Пакет также даёт команду `qgraphflow`, которая используется в разделе [Синхронизация диаграмм с кодом](#синхронизация-диаграмм-с-кодом). - -Все команды ниже выполняйте из **корневого каталога плагина, содержащего `skills/`**. - -### 2. Установите в свой клиент - -#### Codex App / CLI - -В терминале должен быть доступен установленный Codex CLI: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -Начните новую сессию, введите `$` и выберите `qgraphflow:q-flow`. - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -Начните новую сессию и введите `/q-flow` (или полное имя `/qgraphflow:q-flow`). - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -Начните новую сессию и выберите `q-flow`. - -#### Qoder Desktop - -**Рекомендуется:** Откройте **Settings → Plugins → Marketplace**, найдите **QGraphFlow** или **代码图谱可视化** и установите плагин. Начните новый сеанс и выберите `q-flow`. - -Для локальной установки выполните шаг 1, затем откройте **Settings → Plugins → Custom → Import** и импортируйте весь корневой каталог плагина. Начните новый сеанс и выберите `q-flow`. - -#### Cursor - -Скопируйте всё содержимое корневого каталога плагина, включая скрытые файлы, в: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -Убедитесь, что там есть `.cursor-plugin/plugin.json`, перезагрузите окно и найдите `q-flow` в **Customize**. Если уже установлена старая версия, сначала сделайте резервную копию; не смешивайте старые и новые файлы. - -### 3. Начните работу - -Откройте свой рабочий проект в клиенте, начните новую сессию и выберите навык. Опишите требования по примерам в разделе [Первые шаги](#первые-шаги). После генерации откройте выходной HTML в браузере. - -Хотите собрать самостоятельно? См. [инструкции по сборке из исходников](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally). - -## Быстрое использование - -Примеры используют `$qgraphflow:q-flow` в Codex. Если клиент показывает `$q-flow`, выберите этот пункт. Для других клиентов используйте способ вызова навыка, указанный выше. - -**Не знаете, с чего начать?** Вызовите навык, затем выберите предмет и вопрос по подсказке. - -```text -$qgraphflow:q-flow -``` - -**Цель уже ясна?** Укажите, какую часть нарисовать и что требуется понять. Тип диаграммы заранее выбирать не нужно. - -### Пример 1: Понять архитектуру проекта - -```text -$qgraphflow:q-flow Проанализируй текущий проект и создай диаграмму архитектуры на китайском языке: обязанности модулей, зависимости и границы системы. -``` - -Подходит для первого знакомства с общей структурой проекта. - -### Пример 2: Проследить бизнес-процесс - -```text -$qgraphflow:q-flow Проанализируй создание заказа и создай диаграмму последовательности на китайском языке: расчёт цены, резерв запасов, оплата и сохранение заказа, включая ветки сбоев. -``` - -Замените создание заказа и его шаги реальным процессом проекта. Продолжите в том же разговоре: - -```text -$qgraphflow:q-flow Подробно раскрой резерв запасов из предыдущей диаграммы отдельной блок-схемой на китайском языке с обработкой успеха и сбоев. -``` - -По умолчанию результаты находятся в `docs/qgraphflow/`. Откройте `index.html` для исследования, редактирования и экспорта; `graph.json` хранит данные графа. Каждый вид также записывается как SVG (`diagram.svg`, а для нескольких видов — `diagram--.svg`), который можно встроить как изображение в README, pull request или вики. - -После правок на странице команда **Ещё → Сохранить изменения** в Chrome или Edge перезаписывает страницу, `graph.json` и SVG на месте, когда вы один раз выберете каталог диаграммы. Другие браузеры сохраняют только `graph.json`: положите его в этот каталог и пересоздайте страницу и SVG командой `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force`. - -
-Запустить пример Jeepay с одиннадцатью видами на основе исходного кода - -Выберите локальную копию исходников Jeepay для проверки доказательств: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Откройте `output/jeepay/index.html`; одиннадцать SVG находятся в том же каталоге. Версия исходников и процедура обновления описаны в [README корпуса](../../examples/jeepay). - -
- -## Синхронизация диаграмм с кодом - -Диаграмма, созданная с указанием корня репозитория, запоминает, где определён каждый компонент, и строку за каждой связью, подтверждённой кодом (вызов, внешний ключ). Проверка с `--repo-root` завершается ошибкой, если записанного файла больше нет, диапазон строк не помещается в файл или записанный символ ушёл из своих строк; в сообщении указано, в каких строках символ находится теперь. Добавьте эту задачу в CI — ей не нужны сборка, вход или токен: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -Если проверка не прошла, попросите навык обновить диаграмму: - -```text -$qgraphflow:q-flow CI сообщает, что диаграмма docs/qgraphflow/order-sequence устарела. Обнови её. -``` - -Навык переносит якоря, символ которых встречается в файле один раз, исправляет только якоря с оставшимися ошибками и пересоздаёт страницу и SVG, сохраняя ваши позиции и тексты. Заново диаграмму он не рисует. - -## На какие вопросы отвечает каждый из одиннадцати типов диаграмм - -| Вид · PNG | Главный вопрос | Область примера | -| --- | --- | --- | -| Архитектура возможностей платформы | Какие возможности есть у платформы? | Зоны возможностей и матрицы | -| Архитектура инженерных слоёв | Как организован код проекта? | Инженерные слои и общая поддержка | -| Архитектура связей компонентов | Какие границы ответственности взаимодействуют в системе? | Каналы, оркестрация транзакций, цены, риски, запасы, платежи, заказы, события и исполнение заказов | -| Блок-схема | Как ветвится и сходится каждая точка решения? | Нехватка запасов, отказ по риску, компенсация сбоя оплаты и успешная фиксация | -| Последовательность | В каком порядке запрос выполняет вызовы и получает возвраты? | Основной путь успешной покупки и асинхронный OrderPaid | -| ER | Как связаны основные данные? | Корзина, заказы, позиции, платежи, резервы запасов и посылки | -| Развёртывание | Где размещены единицы исполнения и как они соединены? | Периметр, Kubernetes, сервисы данных, платежи и складские/логистические сети | -| Классы | Как зависят объекты домена и контракты кода? | Прикладной сервис Checkout, Order и четыре порта | -| Состояния | Какие события и охранные условия продвигают заказ? | Оплата, исполнение, отмена, возврат денег и закрытие | -| Варианты использования | Какие возможности есть у каждого участника? | Покупатель, продавец, склад и поддержка клиентов | -| Поток данных | Через какие преобразования и хранилища проходят данные? | Корзина, решения по транзакциям, события заказов, склад/логистика и подтверждения доставки | - -Это концептуальная демонстрация QGraphFlow, а не модель конкретного торгового репозитория. Пример `graph.json` не выдумывает пути к коду и обозначает основания связей как `inference`. Диаграммы реальных проектов требуют прослеживаемых исходников, DDL, конфигурации, тестов и согласованных требований. - -## Разработка и участие - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -Нужны Node.js 22 или новее, npm, tar, zip и unzip. В сообщении о проблеме приложите минимальный граф без конфиденциальных данных, версии клиента и браузера и шаги воспроизведения. - -Справочная документация (на английском): [Источники оснований](../../skills/q-flow/references/evidence-sources.md) · [Формат графов](../../skills/q-flow/references/graph-schema.md) · [Уточнение запроса](../../skills/q-flow/references/guided-intake.md) · [Разработка и приёмка Viewer](../../skills/q-flow/references/viewer-development.md) · [Композиция диаграмм](../../skills/q-flow/references/visual-contract.md) - -## Лицензия и принадлежность - -[MIT](../../LICENSE) · [Уведомления третьих сторон](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow — независимый проект под лицензией MIT. Сценарии в этом документе являются концептуальными примерами и не представляют производственную архитектуру какой-либо реальной компании. - -## Обзоры архитектуры - -Архитектура теперь включает связи компонентов, возможности платформы и инженерные слои. Опишите предмет и вопрос; навык выберет шаблон. Запрошенные коллекции могут содержать несколько архитектурных видов с независимыми правками. - -```text -$qgraphflow:q-flow Проанализируй возможности платформы и способы бизнес-интеграции текущего проекта и создай обзор возможностей платформы на китайском языке. -$qgraphflow:q-flow Проанализируй организацию текущего проекта и слои компонентов и создай китайские обзоры всего проекта и среза одного компонента. -$qgraphflow:q-flow Создай обзор возможностей платформы этого проекта на английском языке и покажи, как интегрируются прикладные модули. -``` - -См. [examples/jeepay](../../examples/jeepay) для архитектурных видов платформы, инженерной организации и связей компонентов на основе реального кода. Разблокируйте обзор, чтобы менять порядок карточек в слое или редактировать текст. Сохранение удерживает все виды; сброс восстанавливает только текущий. diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md deleted file mode 100644 index 4367651..0000000 --- a/docs/readme/README.zh-CN.md +++ /dev/null @@ -1,311 +0,0 @@ -
- -

QGraphFlow

- -### 把复杂代码,变成可以探索的图。 - -跟随路径,查看证据,用一个离线文件分享。 - -💡 灵感来自 Cocoon-AI/architecture-diagram-generator,感谢原作者的启发。 - -[English](../../README.md) · [中文](../../docs/readme/README.zh-CN.md) · [Русский](../../docs/readme/README.ru.md) · [Português](../../docs/readme/README.pt.md) · [日本語](../../docs/readme/README.ja.md) · [Deutsch](../../docs/readme/README.de.md) · [Español](../../docs/readme/README.es.md) - -[在线演示](https://supermax92.github.io/qgraphflow/) · [快速入门](#快速入门) · [客户端安装](#安装指南) · [反馈问题](https://github.com/supermax92/qgraphflow/issues) · [MIT](../../LICENSE) - -
- -*支持十一类图:【平台能力架构图、工程分层架构图、组件关系架构图、流程图、时序图、ER 图、部署图、类图、状态图、用例图、数据流图】* - -QGraphFlow 从源码、数据结构、配置和需求生成交互式软件图,让关系有据可查,并将结果交付为可分享的离线 HTML。 - -**差异在哪:** 一个技能覆盖十一类图,每条关系都标明证据类别,有代码支撑的关系还记录对应的源码行,自动布局,能直接在页面里编辑,插件脚本和 Viewer 本身不发任何网络请求。 - -![Jeepay 多视图交互演示:组件关系架构图、时序图与 ER 图](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.zh-CN.hero.gif) - -以 Jeepay 真实源码为例,在组件关系架构图、时序图与 ER 图之间切换,探索组件与调用关系。[查看原尺寸 GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/jeepay.zh-CN.hero.gif) - -**复杂时序图展示** - -![复杂时序图逐步绘制:参与者、生命线、消息、激活条与嵌套组合片段](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.zh-CN.sequence-drawing.gif) - -虚构电商场景包含 9 个参与者、29 条消息和 6 个组合片段,覆盖库存重试、嵌套分支、并行处理、失败补偿与异步回调。动画逐步呈现已生成的图形,展示复杂时序图的结构与细节。[查看原尺寸 GIF](https://github.com/supermax92/qgraphflow/releases/download/showcase-v2/checkout.zh-CN.sequence-drawing.gif) - -```bash -npx skills add supermax92/qgraphflow -``` - -一条命令即可为 Claude Code、Codex、Cursor 和 Qoder 装好技能;以插件方式安装和其他客户端见[安装指南](#安装指南)。 - -- **探索:** 搜索定位、缩放和平移画布,查看组件职责与上下游关系。 - -- **核验:** 从节点或连线查看详情,核对源码文件、行号、符号和明确标注的不确定性。 - -- **编辑:** 解锁后修改文字、移动元素;不满意时一键重置。 - -- **分享:** 打开离线 HTML,或将完整图导出为 SVG / PNG。 - -The real-source [Jeepay corpus](../../examples/jeepay) contains all eleven views used by CI and the live demo. - -## 快速入门 - -安装后,在客户端打开你的业务项目,选择 `q-flow` 技能。以下以 Claude Code 的 `/q-flow` 为例;Codex 中使用客户端实际提供的 `$q-flow` 或 `$qgraphflow:q-flow` 入口。还未安装?先看[安装指南](#安装指南)。 - -### 1. 空白输入:不知道从哪里开始 - -只调用技能,不附加需求: - -```text -/q-flow -``` - -技能会引导你选择要分析的部分,以及希望图回答的问题;必要信息明确后开始绘图。 - -### 2. 询问能力:先了解能画什么 - -```text -/q-flow 你能绘制哪些类型的图?每类图适合回答什么问题?我刚接手一个项目,请先介绍能力并建议一个起点。 -``` - -先了解十一类图的用途,再决定看项目结构、调用顺序、数据关系还是其他内容。 - -### 3. 模糊输入:只有一个大致目标 - -```text -/q-flow 帮我画一下这个项目,我想尽快看懂它。 -``` - -不用先指定图类型。技能会根据项目和你的目标确定合适的视图,缺少必要信息时再追问。 - -### 4. 精准输入:明确范围并要求绘制细节 - -将下面的业务名称和步骤替换成项目中实际存在的流程: - -```text -/q-flow 分析当前项目的订单创建流程,生成中文时序图。 -覆盖请求入口、价格计算、库存预占、支付授权和订单落库。 -保留源码中实际存在的同步调用、异步消息、成对返回、激活条、条件分支、重试和失败补偿,不要为了简洁省略细节。 -标明组件与调用的源码文件和行号,将结果保存到 docs/qgraphflow/order-sequence/。 -``` - -把对象、问题、详细程度和输出位置说清楚,就能直接开始;图中只保留有证据支持的事实。 - -### 5. 继续细化:展开上一张图的局部 - -在生成结果后,于同一对话中继续: - -```text -/q-flow 展开上一张时序图中的库存预占步骤,单独生成中文流程图。 -完整展示库存校验、预占成功、可重试失败、重试上限和释放库存的分支,以源码为准,不添加代码中没有的步骤。 -``` - -先看整体,再深入一个步骤;也可以继续要求补充已有图的细节或核验其中的关系。 - -## 安装指南 - -准备 Node.js 22 及以上版本,以及已配置好模型访问、支持插件功能的客户端。 - -### 快速安装 - -```bash -npx skills add supermax92/qgraphflow -``` - -已用 `skills` 1.7.0 在 Claude Code、Codex、Cursor 和 Qoder 上实测。命令会询问装到哪些客户端;`-a claude-code` 可直接指定,`-g` 改为装到当前用户而不是当前项目。这样装上的技能名是 `q-flow`,不带下文插件安装方式里的 `qgraphflow:` 前缀。 - -如需以插件方式安装,按以下步骤操作。[Qoder Desktop](#qoder-desktop) 可直接从插件商城安装,跳过第 1 步。 - -### 1. 下载插件 - -从 npmjs.com 获取插件,无需账号、登录或令牌。在业务项目之外创建独立目录: - -```bash -mkdir qgraphflow-install -cd qgraphflow-install -npm install qgraphflow --ignore-scripts -cd node_modules/qgraphflow -``` - -此时已进入插件根目录。**npm 下载不会自动完成客户端安装**,请继续第 2 步。这个包还提供 `qgraphflow` 命令,[让图和代码保持同步](#让图和代码保持同步)一节会用到。 - -以下终端命令均在**包含 `skills/` 的插件根目录**执行。 - -### 2. 选择客户端安装 - -#### Codex App / CLI - -终端需已安装 Codex CLI: - -```bash -codex plugin marketplace add . -codex plugin add qgraphflow@supermax92 -``` - -新建会话,输入 `$`,选择 `qgraphflow:q-flow`。 - -#### Claude Code - -```bash -claude plugin marketplace add ./ -claude plugin install qgraphflow@supermax92 --scope user -``` - -新建会话,输入 `/q-flow`(或完整名称 `/qgraphflow:q-flow`)。 - -#### Qoder CLI - -```bash -qodercli plugins install . -``` - -新建会话,选择 `q-flow`。 - -#### Qoder Desktop - -**推荐:**打开 **Settings → Plugins → Marketplace**,搜索 **QGraphFlow** 或 **代码图谱可视化**,安装插件。新建会话,选择 `q-flow`。 - -如需本地安装,先完成第 1 步,再打开 **Settings → Plugins → Custom → Import**,导入完整的插件根目录。新建会话,选择 `q-flow`。 - -#### Cursor - -将插件根目录中的全部内容(含隐藏文件)复制到: - -```text -~/.cursor/plugins/local/qgraphflow/ -``` - -确认其中存在 `.cursor-plugin/plugin.json`,重新加载窗口,在 **Customize** 中找到 `q-flow`。若已有旧版本,先备份,勿混合新旧文件。 - -### 3. 开始使用 - -在客户端打开你的业务项目,新建会话并选择技能,按[快速入门](#快速入门)中的示例描述需求。生成后,用浏览器打开输出的 HTML。 - -需要自行构建?参见[源码构建说明](https://github.com/supermax92/qgraphflow/blob/main/docs/distribution.md#prepare-locally)。 - -## 快速使用 - -以下以 Codex 的 `$qgraphflow:q-flow` 入口为例;如果客户端显示 `$q-flow`,请选择它实际提供的入口。其他客户端使用上方对应的技能入口。 - -**不知道从哪里开始?** 直接调用,按提示选择要分析的部分和想了解的问题。 - -```text -$qgraphflow:q-flow -``` - -**目标已经明确?** 一句话说明“画哪个部分+想看什么”,无需先选择图类型。 - -### 示例一:看懂项目架构 - -```text -$qgraphflow:q-flow 分析当前项目,生成中文架构图,展示主要模块的职责、依赖关系和系统边界。 -``` - -适合初次接触项目,先了解整体结构。 - -### 示例二:追踪业务调用 - -```text -$qgraphflow:q-flow 分析订单创建流程,生成中文时序图,展示价格计算、库存预占、支付和订单落库的调用顺序,并标明失败分支。 -``` - -将“订单创建”及相关步骤替换成项目中的实际业务流程。看完后,在同一对话中继续追问: - -```text -$qgraphflow:q-flow 展开上一张图中的库存预占步骤,单独生成中文流程图,展示成功与失败的处理流程。 -``` - -结果默认保存在 `docs/qgraphflow/` 下:打开 `index.html` 即可交互查看、编辑和导出,`graph.json` 保留图数据。每个视图还会写出一份 SVG(`diagram.svg`,多视图时为 `diagram--.svg`),可以直接作为图片嵌进 README、PR 或 Wiki。 - -在页面里编辑后,用 Chrome 或 Edge 执行「更多 → 保存修改」并选一次图所在的文件夹,即可原地重写页面、`graph.json` 和 SVG。其他浏览器只能保存 `graph.json`:把它放回该文件夹,再用 `npx -y qgraphflow generate docs/qgraphflow//graph.json docs/qgraphflow/ --layout preserve --force` 重新生成页面和 SVG。 - -
-Run the eleven-view Jeepay source example - -Select your Jeepay source checkout to verify the evidence: - -```bash -export JEEPAY_REPO_ROOT="" -node skills/q-flow/scripts/validate-graph.mjs examples/jeepay/collection.graph.json --input-only --repo-root "$JEEPAY_REPO_ROOT" -node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" -``` - -Open `output/jeepay/index.html`; its eleven SVGs are in the same directory. See the [corpus README](../../examples/jeepay) for the source revision and refresh procedure. - -
- -## 让图和代码保持同步 - -带仓库根目录生成的图会记下每个组件定义在哪里,以及每条有代码支撑的关系所在的那一行(调用、外键等)。用 `--repo-root` 校验时,记录的文件不在了、行号超出文件,或记录的符号离开了原来的行范围,校验都会失败,并在错误里写出这个符号现在所在的行。把下面这个任务加进 CI,不需要构建、登录或令牌: - -```yaml -name: Diagrams -on: [push, pull_request] -jobs: - diagrams: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: | - for graph in docs/qgraphflow/*/graph.json; do - npx -y qgraphflow validate "$graph" --input-only --repo-root . || { echo "::error file=$graph::$graph failed validation"; failed=1; } - done - exit ${failed:-0} -``` - -失败后,让技能刷新这张图: - -```text -$qgraphflow:q-flow CI 提示 docs/qgraphflow/order-sequence 的图过时了,刷新一下。 -``` - -技能会把在文件里只找到一处的符号重新定位,只修改仍然报错的锚点,再保留你调整过的位置和文字,重新生成页面和 SVG;不会重画整张图。 - -## 十一类图各自回答什么 - -| 视图 · PNG | 主要问题 | 本示例范围 | -| --- | --- | --- | -| 平台能力架构图 | 平台具备哪些能力? | 能力分区与矩阵 | -| 工程分层架构图 | 工程代码怎样组织? | 工程层级与共享支撑 | -| 组件关系架构图 | 系统由哪些责任边界协作? | 渠道、交易编排、价格、风控、库存、支付、订单、事件与履约 | -| 流程图 | 每个决策点如何分支和收敛? | 缺货、风控拒绝、支付失败补偿与成功提交 | -| 时序图 | 一次请求按什么顺序调用和返回? | 成功结算主链及异步 OrderPaid | -| ER 图 | 核心数据如何关联? | 购物车、订单、明细、支付、库存预占和包裹 | -| 部署图 | 运行单元放在哪里、怎样连接? | 边缘、Kubernetes、数据服务、支付和仓配网络 | -| 类图 | 领域对象和代码契约怎样依赖? | Checkout 应用服务、Order 与四个端口 | -| 状态图 | 订单受哪些事件和守卫条件推进? | 支付、履约、取消、退款和关闭 | -| 用例图 | 每类参与者拥有哪些能力? | 买家、商家、仓库与客服 | -| 数据流图 | 数据资产经过哪些变换和存储? | 购物车、交易决策、订单事件、仓配和物流回执 | - -这是用于展示 QGraphFlow 能力的概念模型,不对应某个电商仓库。`graph.json` 不伪造源码路径,关系证据统一标记为 `inference`;对真实项目绘图时,应改用源码、DDL、配置、测试和已接受需求中的可追溯证据。 - -## 开发与参与 - -```bash -npm ci --prefix skills/q-flow/assets/viewer -npm run build --prefix skills/q-flow/assets/viewer -node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs -``` - -开发需要 Node.js 22 及以上版本、npm、tar、zip 和 unzip。反馈问题时,请附最小脱敏图数据、客户端和浏览器版本,以及复现步骤。 - -参考文档(英文):[证据来源](../../skills/q-flow/references/evidence-sources.md) · [图数据格式](../../skills/q-flow/references/graph-schema.md) · [需求引导](../../skills/q-flow/references/guided-intake.md) · [Viewer 开发与验收](../../skills/q-flow/references/viewer-development.md) · [图形表达约定](../../skills/q-flow/references/visual-contract.md) - -## 许可证与归属 - -[MIT](../../LICENSE) · [第三方声明](../../THIRD_PARTY_NOTICES.md) - -QGraphFlow 是采用 MIT 许可证的独立项目。本文场景为概念示例,不代表任何真实公司的生产架构。 - -## Architecture overviews / 架构总览 - -Architecture now includes component relations, platform capabilities and engineering layers. Describe the subject and question; the skill chooses the template. Requested collections can contain multiple architecture views with independent edits. - -```text -$qgraphflow:q-flow 分析当前项目的平台能力和业务接入方式,生成中文平台能力总览。 -$qgraphflow:q-flow 分析当前工程组织和组件分层,生成工程整体与一个组件剖面的中文总览。 -$qgraphflow:q-flow Generate an English platform capability overview of this project and show how application modules integrate. -``` - -See [examples/jeepay](../../examples/jeepay) for real-source platform, engineering and component relationship architecture views. Unlock an overview to reorder cards within a layer or edit text. Save keeps all views; reset restores only the current one. diff --git a/examples/jeepay/README.md b/examples/jeepay/README.md index b3d2b77..7a72acf 100644 --- a/examples/jeepay/README.md +++ b/examples/jeepay/README.md @@ -2,7 +2,7 @@ The only business dataset used by CI, Pages and package smoke tests is the public [Jeepay repository](https://github.com/jeequan/jeepay). `source.json` records the exact revision and SHA-256 of every referenced source file. No Java source, credentials or developer machine paths are distributed here. -The collection contains eleven views: platform capabilities, engineering layers, component relationships, unified-order flowchart and sequence, payment ER, Compose deployment, payment classes, order states, API use cases and unified-order data flow. All inputs contain facts and source anchors; generated coordinates and routing snapshots are deliberately excluded. +The collection contains nine views: component relationships, unified-order flowchart and sequence, payment ER, Compose deployment, payment classes, order states, API use cases and unified-order data flow. All inputs contain facts and source anchors; generated coordinates and routing snapshots are deliberately excluded. CI checks out the revision declared in `source.json`, verifies every node source and relationship site, and computes fresh layouts. Assertions cover preserved facts, valid notation and geometry, export, saving, cancellation and selected-view isolation. They do not lock a particular diagram's dimensions, node count, crossing count, candidate count or solver strategy. @@ -14,7 +14,7 @@ node --test tests/*.test.mjs skills/q-flow/scripts/*.test.mjs node skills/q-flow/scripts/generate-viewer.mjs examples/jeepay/collection.graph.json output/jeepay --repo-root "$JEEPAY_REPO_ROOT" ``` -To refresh the corpus after reviewing updated Jeepay source and updating its eleven diagrams under `docs/qgraphflow/`, run: +To refresh the corpus after reviewing updated Jeepay source and updating its nine diagrams under `docs/qgraphflow/`, run: ```bash node scripts/refresh-jeepay-fixtures.mjs "$JEEPAY_REPO_ROOT" diff --git a/examples/jeepay/capabilities.graph.json b/examples/jeepay/capabilities.graph.json deleted file mode 100644 index 94a696d..0000000 --- a/examples/jeepay/capabilities.graph.json +++ /dev/null @@ -1,270 +0,0 @@ -{ - "meta": { - "title": "Jeepay 平台能力架构", - "subtitle": "Jeepay 源码与配置证据", - "sourceRef": "jeequan/jeepay@e1ac9086d679826bab593f20431b7ecd292eb685", - "scope": "项目核心支付能力", - "diagramType": "architecture", - "locale": "zh-CN", - "notes": [ - "能力卡片以源码中的控制器和服务为准;退款、转账和分账是独立入口。", - "本图呈现能力与关键支撑,不代表所有能力均在同一请求链路中。" - ], - "architectureView": "capabilities", - "viewId": "jeepay-capabilities" - }, - "nodes": [ - { - "id": "unified", - "label": "UnifiedOrderController", - "kind": "business", - "module": "payment", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/UnifiedOrderController.java", - "lineStart": 44, - "lineEnd": 44, - "kind": "source" - }, - "subtitle": "统一下单入口", - "tags": [ - "core" - ], - "overviewText": [ - "校验商户签名后选择支付方式,生成支付订单。" - ] - }, - { - "id": "refund", - "label": "RefundOrderController", - "kind": "business", - "module": "refund", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/refund/RefundOrderController.java", - "lineStart": 57, - "lineEnd": 57, - "kind": "source" - }, - "subtitle": "退款订单入口", - "overviewText": [ - "面向已支付订单发起渠道退款。" - ] - }, - { - "id": "transfer", - "label": "TransferOrderController", - "kind": "business", - "module": "transfer", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/transfer/TransferOrderController.java", - "lineStart": 55, - "lineEnd": 55, - "kind": "source" - }, - "subtitle": "转账订单入口", - "overviewText": [ - "向渠道发起转账。" - ] - }, - { - "id": "division", - "label": "PayOrderDivisionExecController", - "kind": "business", - "module": "division", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/division/PayOrderDivisionExecController.java", - "lineStart": 57, - "lineEnd": 57, - "kind": "source" - }, - "subtitle": "分账执行入口", - "overviewText": [ - "按商户请求执行支付订单分账。" - ] - }, - { - "id": "process", - "label": "PayOrderProcessService", - "kind": "component", - "module": "payment", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 40, - "lineEnd": 40, - "kind": "source" - }, - "subtitle": "支付成功后的订单处理", - "overviewText": [ - "确认支付成功后处理订单业务。" - ] - }, - { - "id": "notify", - "label": "PayMchNotifyService", - "kind": "component", - "module": "notification", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayMchNotifyService.java", - "lineStart": 45, - "lineEnd": 45, - "kind": "source" - }, - "subtitle": "保存并推送商户通知", - "overviewText": [ - "保存通知记录并推送消息。" - ] - }, - { - "id": "channel", - "label": "IPaymentService", - "kind": "component", - "module": "channel", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/channel/IPaymentService.java", - "lineStart": 30, - "lineEnd": 30, - "kind": "source" - }, - "subtitle": "渠道支付接口契约", - "overviewText": [ - "定义渠道支付检查与支付调用。" - ] - }, - { - "id": "orderdb", - "label": "PayOrderService", - "kind": "data", - "module": "payment", - "source": { - "file": "jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/PayOrderService.java", - "lineStart": 49, - "lineEnd": 49, - "kind": "source" - }, - "subtitle": "支付订单持久化与条件更新", - "overviewText": [ - "持久化并按原状态条件更新订单。" - ] - } - ], - "edges": [ - { - "id": "c1", - "source": "unified", - "target": "channel", - "kind": "call", - "label": "调起渠道支付", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 205, - "lineEnd": 205 - } - }, - { - "id": "c2", - "source": "unified", - "target": "orderdb", - "kind": "data", - "label": "保存支付订单", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 201, - "lineEnd": 201 - } - }, - { - "id": "c3", - "source": "unified", - "target": "process", - "kind": "call", - "label": "处理支付结果", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 383, - "lineEnd": 383 - } - }, - { - "id": "c4", - "source": "process", - "target": "notify", - "kind": "call", - "label": "通知商户", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 60, - "lineEnd": 60 - } - }, - { - "id": "c5", - "source": "process", - "target": "orderdb", - "kind": "data", - "label": "查询订单", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 51, - "lineEnd": 51 - } - } - ], - "layout": { - "sections": [ - { - "id": "entry", - "title": "业务能力入口", - "mode": "grid", - "columns": 4, - "tone": "blue", - "items": [ - { - "nodeId": "unified" - }, - { - "nodeId": "refund" - }, - { - "nodeId": "transfer" - }, - { - "nodeId": "division" - } - ] - }, - { - "id": "core", - "title": "支付处理", - "mode": "row", - "tone": "green", - "items": [ - { - "nodeId": "channel" - }, - { - "nodeId": "process" - } - ] - }, - { - "id": "support", - "title": "订单与通知支撑", - "mode": "row", - "tone": "subtle", - "items": [ - { - "nodeId": "orderdb" - }, - { - "nodeId": "notify" - } - ] - } - ], - "direction": "down" - } -} diff --git a/examples/jeepay/collection.graph.json b/examples/jeepay/collection.graph.json index de7ec21..c46452f 100644 --- a/examples/jeepay/collection.graph.json +++ b/examples/jeepay/collection.graph.json @@ -1,552 +1,5 @@ { "diagrams": [ - { - "meta": { - "title": "Jeepay 平台能力架构", - "subtitle": "Jeepay 源码与配置证据", - "sourceRef": "jeequan/jeepay@e1ac9086d679826bab593f20431b7ecd292eb685", - "scope": "项目核心支付能力", - "diagramType": "architecture", - "locale": "zh-CN", - "notes": [ - "能力卡片以源码中的控制器和服务为准;退款、转账和分账是独立入口。", - "本图呈现能力与关键支撑,不代表所有能力均在同一请求链路中。" - ], - "architectureView": "capabilities", - "viewId": "jeepay-capabilities" - }, - "nodes": [ - { - "id": "unified", - "label": "UnifiedOrderController", - "kind": "business", - "module": "payment", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/UnifiedOrderController.java", - "lineStart": 44, - "lineEnd": 44, - "kind": "source" - }, - "subtitle": "统一下单入口", - "tags": [ - "core" - ], - "overviewText": [ - "校验商户签名后选择支付方式,生成支付订单。" - ] - }, - { - "id": "refund", - "label": "RefundOrderController", - "kind": "business", - "module": "refund", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/refund/RefundOrderController.java", - "lineStart": 57, - "lineEnd": 57, - "kind": "source" - }, - "subtitle": "退款订单入口", - "overviewText": [ - "面向已支付订单发起渠道退款。" - ] - }, - { - "id": "transfer", - "label": "TransferOrderController", - "kind": "business", - "module": "transfer", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/transfer/TransferOrderController.java", - "lineStart": 55, - "lineEnd": 55, - "kind": "source" - }, - "subtitle": "转账订单入口", - "overviewText": [ - "向渠道发起转账。" - ] - }, - { - "id": "division", - "label": "PayOrderDivisionExecController", - "kind": "business", - "module": "division", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/division/PayOrderDivisionExecController.java", - "lineStart": 57, - "lineEnd": 57, - "kind": "source" - }, - "subtitle": "分账执行入口", - "overviewText": [ - "按商户请求执行支付订单分账。" - ] - }, - { - "id": "process", - "label": "PayOrderProcessService", - "kind": "component", - "module": "payment", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 40, - "lineEnd": 40, - "kind": "source" - }, - "subtitle": "支付成功后的订单处理", - "overviewText": [ - "确认支付成功后处理订单业务。" - ] - }, - { - "id": "notify", - "label": "PayMchNotifyService", - "kind": "component", - "module": "notification", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayMchNotifyService.java", - "lineStart": 45, - "lineEnd": 45, - "kind": "source" - }, - "subtitle": "保存并推送商户通知", - "overviewText": [ - "保存通知记录并推送消息。" - ] - }, - { - "id": "channel", - "label": "IPaymentService", - "kind": "component", - "module": "channel", - "source": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/channel/IPaymentService.java", - "lineStart": 30, - "lineEnd": 30, - "kind": "source" - }, - "subtitle": "渠道支付接口契约", - "overviewText": [ - "定义渠道支付检查与支付调用。" - ] - }, - { - "id": "orderdb", - "label": "PayOrderService", - "kind": "data", - "module": "payment", - "source": { - "file": "jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/PayOrderService.java", - "lineStart": 49, - "lineEnd": 49, - "kind": "source" - }, - "subtitle": "支付订单持久化与条件更新", - "overviewText": [ - "持久化并按原状态条件更新订单。" - ] - } - ], - "edges": [ - { - "id": "c1", - "source": "unified", - "target": "channel", - "kind": "call", - "label": "调起渠道支付", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 205, - "lineEnd": 205 - } - }, - { - "id": "c2", - "source": "unified", - "target": "orderdb", - "kind": "data", - "label": "保存支付订单", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 201, - "lineEnd": 201 - } - }, - { - "id": "c3", - "source": "unified", - "target": "process", - "kind": "call", - "label": "处理支付结果", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/ctrl/payorder/AbstractPayOrderController.java", - "lineStart": 383, - "lineEnd": 383 - } - }, - { - "id": "c4", - "source": "process", - "target": "notify", - "kind": "call", - "label": "通知商户", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 60, - "lineEnd": 60 - } - }, - { - "id": "c5", - "source": "process", - "target": "orderdb", - "kind": "data", - "label": "查询订单", - "evidence": "source", - "site": { - "file": "jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java", - "lineStart": 51, - "lineEnd": 51 - } - } - ], - "layout": { - "sections": [ - { - "id": "entry", - "title": "业务能力入口", - "mode": "grid", - "columns": 4, - "tone": "blue", - "items": [ - { - "nodeId": "unified" - }, - { - "nodeId": "refund" - }, - { - "nodeId": "transfer" - }, - { - "nodeId": "division" - } - ] - }, - { - "id": "core", - "title": "支付处理", - "mode": "row", - "tone": "green", - "items": [ - { - "nodeId": "channel" - }, - { - "nodeId": "process" - } - ] - }, - { - "id": "support", - "title": "订单与通知支撑", - "mode": "row", - "tone": "subtle", - "items": [ - { - "nodeId": "orderdb" - }, - { - "nodeId": "notify" - } - ] - } - ], - "direction": "down" - } - }, - { - "meta": { - "title": "Jeepay 工程分层架构", - "subtitle": "Jeepay 源码与配置证据", - "sourceRef": "jeequan/jeepay@e1ac9086d679826bab593f20431b7ecd292eb685", - "scope": "Maven 模块与编译期依赖", - "diagramType": "architecture", - "locale": "zh-CN", - "notes": [ - "箭头表示 pom.xml 声明的模块依赖,不表示运行时 HTTP 调用。", - "jeepay-z-codegen 是独立代码生成模块,不在支付主干分层中。" - ], - "architectureView": "engineering", - "viewId": "jeepay-engineering" - }, - "nodes": [ - { - "id": "manager", - "label": "jeepay-manager", - "kind": "component", - "module": "manager", - "source": { - "file": "jeepay-manager/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "运营管理端应用模块" - ] - }, - { - "id": "merchant", - "label": "jeepay-merchant", - "kind": "component", - "module": "merchant", - "source": { - "file": "jeepay-merchant/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "商户管理端应用模块" - ] - }, - { - "id": "payment", - "label": "jeepay-payment", - "kind": "business", - "module": "payment", - "source": { - "file": "jeepay-payment/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "tags": [ - "core" - ], - "overviewText": [ - "统一支付网关应用模块" - ] - }, - { - "id": "service", - "label": "jeepay-service", - "kind": "component", - "module": "service", - "source": { - "file": "jeepay-service/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "数据库服务与持久化访问模块" - ] - }, - { - "id": "core", - "label": "jeepay-core", - "kind": "component", - "module": "core", - "source": { - "file": "jeepay-core/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "公共实体、模型与工具模块" - ] - }, - { - "id": "mq", - "label": "jeepay-components-mq", - "kind": "component", - "module": "mq", - "source": { - "file": "jeepay-components/jeepay-components-mq/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "消息队列抽象与实现模块" - ] - }, - { - "id": "oss", - "label": "jeepay-components-oss", - "kind": "component", - "module": "oss", - "source": { - "file": "jeepay-components/jeepay-components-oss/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "对象存储组件模块" - ] - } - ], - "edges": [ - { - "id": "e1", - "source": "manager", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-manager/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e2", - "source": "merchant", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-merchant/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e3", - "source": "payment", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 30, - "lineEnd": 30 - } - }, - { - "id": "e4", - "source": "payment", - "target": "mq", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 42, - "lineEnd": 42 - } - }, - { - "id": "e5", - "source": "payment", - "target": "oss", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 36, - "lineEnd": 36 - } - }, - { - "id": "e6", - "source": "service", - "target": "core", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-service/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e7", - "source": "mq", - "target": "core", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-components/jeepay-components-mq/pom.xml", - "lineStart": 25, - "lineEnd": 25 - } - } - ], - "layout": { - "sections": [ - { - "id": "app", - "title": "应用入口", - "mode": "grid", - "columns": 3, - "tone": "blue", - "items": [ - { - "nodeId": "manager" - }, - { - "nodeId": "merchant" - }, - { - "nodeId": "payment" - } - ] - }, - { - "id": "domain", - "title": "持久化与公共模型", - "mode": "stack", - "tone": "green", - "items": [ - { - "nodeId": "service" - }, - { - "nodeId": "core" - } - ] - }, - { - "id": "components", - "title": "可复用组件", - "mode": "row", - "tone": "lavender", - "items": [ - { - "nodeId": "mq" - }, - { - "nodeId": "oss" - } - ] - } - ], - "direction": "down" - } - }, { "meta": { "title": "Jeepay 支付组件关系架构", diff --git a/examples/jeepay/engineering.graph.json b/examples/jeepay/engineering.graph.json deleted file mode 100644 index 94f32a3..0000000 --- a/examples/jeepay/engineering.graph.json +++ /dev/null @@ -1,277 +0,0 @@ -{ - "meta": { - "title": "Jeepay 工程分层架构", - "subtitle": "Jeepay 源码与配置证据", - "sourceRef": "jeequan/jeepay@e1ac9086d679826bab593f20431b7ecd292eb685", - "scope": "Maven 模块与编译期依赖", - "diagramType": "architecture", - "locale": "zh-CN", - "notes": [ - "箭头表示 pom.xml 声明的模块依赖,不表示运行时 HTTP 调用。", - "jeepay-z-codegen 是独立代码生成模块,不在支付主干分层中。" - ], - "architectureView": "engineering", - "viewId": "jeepay-engineering" - }, - "nodes": [ - { - "id": "manager", - "label": "jeepay-manager", - "kind": "component", - "module": "manager", - "source": { - "file": "jeepay-manager/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "运营管理端应用模块" - ] - }, - { - "id": "merchant", - "label": "jeepay-merchant", - "kind": "component", - "module": "merchant", - "source": { - "file": "jeepay-merchant/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "商户管理端应用模块" - ] - }, - { - "id": "payment", - "label": "jeepay-payment", - "kind": "business", - "module": "payment", - "source": { - "file": "jeepay-payment/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "tags": [ - "core" - ], - "overviewText": [ - "统一支付网关应用模块" - ] - }, - { - "id": "service", - "label": "jeepay-service", - "kind": "component", - "module": "service", - "source": { - "file": "jeepay-service/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "数据库服务与持久化访问模块" - ] - }, - { - "id": "core", - "label": "jeepay-core", - "kind": "component", - "module": "core", - "source": { - "file": "jeepay-core/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "公共实体、模型与工具模块" - ] - }, - { - "id": "mq", - "label": "jeepay-components-mq", - "kind": "component", - "module": "mq", - "source": { - "file": "jeepay-components/jeepay-components-mq/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "消息队列抽象与实现模块" - ] - }, - { - "id": "oss", - "label": "jeepay-components-oss", - "kind": "component", - "module": "oss", - "source": { - "file": "jeepay-components/jeepay-components-oss/pom.xml", - "lineStart": 7, - "lineEnd": 7, - "kind": "config" - }, - "subtitle": "Maven 模块", - "overviewText": [ - "对象存储组件模块" - ] - } - ], - "edges": [ - { - "id": "e1", - "source": "manager", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-manager/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e2", - "source": "merchant", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-merchant/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e3", - "source": "payment", - "target": "service", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 30, - "lineEnd": 30 - } - }, - { - "id": "e4", - "source": "payment", - "target": "mq", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 42, - "lineEnd": 42 - } - }, - { - "id": "e5", - "source": "payment", - "target": "oss", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-payment/pom.xml", - "lineStart": 36, - "lineEnd": 36 - } - }, - { - "id": "e6", - "source": "service", - "target": "core", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-service/pom.xml", - "lineStart": 24, - "lineEnd": 24 - } - }, - { - "id": "e7", - "source": "mq", - "target": "core", - "kind": "depends", - "label": "Maven 依赖", - "evidence": "source", - "site": { - "file": "jeepay-components/jeepay-components-mq/pom.xml", - "lineStart": 25, - "lineEnd": 25 - } - } - ], - "layout": { - "sections": [ - { - "id": "app", - "title": "应用入口", - "mode": "grid", - "columns": 3, - "tone": "blue", - "items": [ - { - "nodeId": "manager" - }, - { - "nodeId": "merchant" - }, - { - "nodeId": "payment" - } - ] - }, - { - "id": "domain", - "title": "持久化与公共模型", - "mode": "stack", - "tone": "green", - "items": [ - { - "nodeId": "service" - }, - { - "nodeId": "core" - } - ] - }, - { - "id": "components", - "title": "可复用组件", - "mode": "row", - "tone": "lavender", - "items": [ - { - "nodeId": "mq" - }, - { - "nodeId": "oss" - } - ] - } - ], - "direction": "down" - } -} diff --git a/examples/jeepay/source.json b/examples/jeepay/source.json index 08e068c..bbc4944 100644 --- a/examples/jeepay/source.json +++ b/examples/jeepay/source.json @@ -32,16 +32,6 @@ "jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/PayOrderService.java": "1efb0a56a8fc8df768c85ef4edc4cd2ef99ca09049beded87407175e2c21db67" }, "views": [ - { - "id": "jeepay-capabilities", - "type": "architecture", - "architectureView": "capabilities" - }, - { - "id": "jeepay-engineering", - "type": "architecture", - "architectureView": "engineering" - }, { "id": "jeepay-relations", "type": "architecture", diff --git a/package.json b/package.json index 2266bcf..060f6eb 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "skills/q-flow/references/", "skills/q-flow/scripts/generate-viewer.mjs", "skills/q-flow/scripts/validate-graph.mjs", + "skills/q-flow/scripts/source-drift.mjs", "skills/q-flow/assets/viewer-dist/index.html", "skills/q-flow/assets/viewer/package.json", "skills/q-flow/assets/viewer/src/diagrams/", @@ -42,7 +43,7 @@ "THIRD_PARTY_NOTICES.md", "README.md", "docs/clients*.md", - "docs/readme/", + "README.en.md", "skills/q-flow/scripts/compile-layout.mjs", "skills/q-flow/scripts/compile-sequence.mjs", "skills/q-flow/assets/layout-dist/", @@ -51,18 +52,17 @@ "skills/q-flow/assets/viewer/src/layout-spacing.js", "skills/q-flow/assets/viewer/src/session-graph.js", "skills/q-flow/assets/viewer/src/view-identity.js", - "skills/q-flow/assets/viewer/src/architecture-overview.js", "skills/q-flow/assets/viewer/src/layout-quality.js", "skills/q-flow/assets/viewer/src/layout-policy.js", "skills/q-flow/assets/viewer/src/layout-compaction.js", "skills/q-flow/assets/viewer/src/route-clearance.js", "skills/q-flow/assets/viewer/src/export-svg.js", "skills/q-flow/assets/viewer/src/node-svg.js", - "skills/q-flow/assets/viewer/src/architecture-overview-theme.js", "skills/q-flow/assets/viewer/src/orthogonal-routing.js", "skills/q-flow/assets/viewer/src/layout-refinement.js", "skills/q-flow/assets/viewer/src/layout-templates.js", "skills/q-flow/assets/viewer/src/presentation-graph.js", + "skills/q-flow/assets/viewer/src/graph-diff.js", "skills/q-flow/assets/viewer/src/layout-semantics.js" ], "scripts": { diff --git a/scripts/record-showcase-hero.mjs b/scripts/record-showcase.mjs similarity index 53% rename from scripts/record-showcase-hero.mjs rename to scripts/record-showcase.mjs index a93dc91..bd68832 100644 --- a/scripts/record-showcase-hero.mjs +++ b/scripts/record-showcase.mjs @@ -1,8 +1,10 @@ #!/usr/bin/env node // Record the actual source-built Viewer with a cursor following real mouse input. // The cursor is recording-only; graph content, layout and generated HTML are never altered. -// Build/generate the three-view Jeepay collection before running this development helper. -// node scripts/record-showcase-hero.mjs --page --out +// Two clips, each generated here from the checked-in corpus with the current Viewer build: +// hero component relations (names readable at fit) → a card's source line → sequence → ER +// changes the page generate --compare writes: what this update added, changed and removed, then the new card's source +// node scripts/record-showcase.mjs --clip hero|changes --locale zh-CN|en --out [--preview] // PLAYWRIGHT_MODULE optionally points to an existing Playwright installation. import fs from 'node:fs'; import path from 'node:path'; @@ -12,25 +14,52 @@ import assert from 'node:assert/strict'; import { createRequire } from 'node:module'; import { spawnSync } from 'node:child_process'; import { parseArgs } from 'node:util'; +import { showcaseChanges } from './showcase-changes.mjs'; const require = createRequire(import.meta.url); const { values } = parseArgs({ options: { - page: { type: 'string' }, out: { type: 'string' }, + clip: { type: 'string', default: 'hero' }, locale: { type: 'string', default: 'zh-CN' }, out: { type: 'string' }, width: { type: 'string', default: '1440' }, height: { type: 'string', default: '900' }, fps: { type: 'string', default: '12' }, preview: { type: 'boolean', default: false }, } }); -if (!values.page || !values.out) throw new Error('Required: --page --out '); -const pagePath = path.resolve(values.page), out = path.resolve(values.out); +const { clip, locale } = values; +if (!values.out || !['hero', 'changes'].includes(clip) || !['zh-CN', 'en'].includes(locale)) throw new Error('Required: --clip hero|changes --locale zh-CN|en --out '); +const out = path.resolve(values.out), root = path.resolve(import.meta.dirname, '..'); const width = Number(values.width), height = Number(values.height), fps = Number(values.fps); for (const value of [width, height, fps]) assert.ok(Number.isInteger(value) && value > 0); -const graphPath = path.join(path.dirname(pagePath), 'graph.json'); + +// The three Jeepay views: Chinese from the corpus, English from its showcase translation. +const corpus = JSON.parse(fs.readFileSync(path.join(root, locale === 'en' ? 'examples/showcase/jeepay.en.hero.graph.json' : 'examples/jeepay/collection.graph.json'), 'utf8')); +const pick = id => structuredClone(corpus.diagrams.find(graph => graph.meta.viewId === id)); +const pageDir = path.join(out, `page-${clip}-${locale}`); +fs.rmSync(pageDir, { recursive: true, force: true }); fs.mkdirSync(pageDir, { recursive: true }); +const generate = (input, ...args) => { + const result = spawnSync(process.execPath, [path.join(root, 'skills/q-flow/scripts/generate-viewer.mjs'), input, pageDir, '--force', ...args], { encoding: 'utf8' }); + if (result.status !== 0) throw new Error(result.stderr || result.stdout); +}; +if (clip === 'hero') { + const input = path.join(out, `hero.${locale}.graph.json`); + fs.writeFileSync(input, JSON.stringify({ diagrams: ['jeepay-relations', 'jeepay-sequence', 'jeepay-er'].map(pick) })); + generate(input); +} else { + // The update the online demo also shows (scripts/showcase-changes.mjs): added, renamed and removed elements. + const { current, earlier } = showcaseChanges(locale); + const input = path.join(out, `changes.${locale}.graph.json`), before = path.join(out, `changes.${locale}.earlier.graph.json`); + fs.writeFileSync(input, JSON.stringify(current)); fs.writeFileSync(before, JSON.stringify(earlier)); + generate(input, '--compare', before); +} +const pagePath = path.join(pageDir, 'index.html'), graphPath = path.join(pageDir, 'graph.json'); const graphBytesBefore = fs.readFileSync(graphPath, 'utf8'); -const graphs = JSON.parse(graphBytesBefore).diagrams; -assert.deepEqual(graphs.map(graph => graph.meta.viewId), ['jeepay-relations', 'jeepay-sequence', 'jeepay-er']); +const saved = JSON.parse(graphBytesBefore), graphs = saved.diagrams ?? [saved]; const byId = Object.fromEntries(graphs.map(graph => [graph.meta.viewId, graph])); -const locale = graphs[0].meta.locale; -assert.ok(['en', 'zh-CN'].includes(locale), 'Supported recording languages: en, zh-CN'); assert.ok(graphs.every(graph => graph.meta.locale === locale)); +// Centre of the named elements in the generated layout, for camera moves that survive layout changes. +const centreOf = (id, ids) => { + const items = [...byId[id].nodes, ...(byId[id].groups ?? [])].filter(item => ids.includes(item.id)); + const left = Math.min(...items.map(node => node.position.x)), right = Math.max(...items.map(node => node.position.x + node.size.width)); + const top = Math.min(...items.map(node => node.position.y)), bottom = Math.max(...items.map(node => node.position.y + node.size.height)); + return { x: (left + right) / 2, y: (top + bottom) / 2, width: right - left, height: bottom - top }; +}; const ui = locale === 'en' ? { hideNotes: 'Hide key points', fit: 'Fit canvas', details: 'View details', hideDetails: 'Hide details' } : { hideNotes: '隐藏要点', fit: '适应画布', details: '查看详情', hideDetails: '隐藏右侧详情栏' }; @@ -40,11 +69,14 @@ const candidates = process.env.PLAYWRIGHT_MODULE ? [process.env.PLAYWRIGHT_MODUL 'playwright', ...fs.readdirSync(path.join(os.homedir(), '.npm/_npx')).sort() .map(name => path.join(os.homedir(), '.npm/_npx', name, 'node_modules/playwright')), ]; -let chromium; +// Playwright's own Chromium when downloaded, else CHROME_PATH or the installed Google Chrome. +const macChrome = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +let chromium, executablePath; for (const candidate of candidates) { - try { const api = require(candidate); if (fs.existsSync(api.chromium.executablePath())) { chromium = api.chromium; break; } } catch { /* try the next installed build */ } + try { chromium = require(candidate).chromium; break; } catch { /* try the next installed build */ } } -if (!chromium) throw new Error('An installed Playwright build with downloaded Chromium is required.'); +if (!chromium) throw new Error('An installed Playwright build is required (PLAYWRIGHT_MODULE).'); +if (!fs.existsSync(chromium.executablePath())) executablePath = process.env.CHROME_PATH ?? (fs.existsSync(macChrome) ? macChrome : undefined); const html = fs.readFileSync(pagePath); const server = http.createServer((request, response) => { if (new URL(request.url, 'http://localhost').pathname !== '/') { response.writeHead(404).end(); return; } @@ -52,7 +84,7 @@ const server = http.createServer((request, response) => { }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); let browser, frame = 0, time = 0; -const record = { width, height, fps, page: path.relative(path.resolve(import.meta.dirname, '..'), pagePath), +const record = { clip, locale, width, height, fps, page: path.relative(root, pagePath), commit: spawnSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).stdout.trim(), viewerSha256: (await import('node:crypto')).createHash('sha256').update(html).digest('hex'), sourceRef: graphs[0].meta.sourceRef, views: [], errors: [], remoteRequests: [], @@ -63,7 +95,7 @@ function encode(args) { if (result.status !== 0) throw new Error(result.stderr || 'ffmpeg failed'); } try { - browser = await chromium.launch(); + browser = await chromium.launch({ executablePath }); const context = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: 1, colorScheme: 'light', reducedMotion: 'no-preference' }); const page = await context.newPage(); @@ -78,6 +110,8 @@ try { const parkedPointer = { x: width - 110, y: Math.round(height * .66) }; let pointer = { ...parkedPointer }; async function installCursor() { + // Clicks made before filming leave no focus ring on the first frame. + await page.evaluate(() => document.activeElement?.blur()); await page.evaluate(() => { const element = document.createElement('div'); element.id = '__recording-cursor'; element.setAttribute('aria-hidden', 'true'); @@ -96,7 +130,7 @@ try { } async function moveTo(x, y) { const from = { ...pointer }; - const count = F(Math.min(.45, Math.max(.2, Math.hypot(x - from.x, y - from.y) / 3000))); + const count = F(Math.min(.35, Math.max(.15, Math.hypot(x - from.x, y - from.y) / 3500))); for (let i = 1; i <= count; i++) { const t = 1 - (1 - i / count) ** 3; pointer = { x: from.x + (x - from.x) * t, y: from.y + (y - from.y) * t }; @@ -134,12 +168,39 @@ try { window.__recordingAnimations ??= new Map(); for (const animation of document.getAnimations()) { if (!window.__recordingAnimations.has(animation)) window.__recordingAnimations.set(animation, now); - animation.pause(); animation.currentTime = now - window.__recordingAnimations.get(animation); + // A finite animation that has reached its end is finished, so its end events (transitionend) still fire. + const elapsed = now - window.__recordingAnimations.get(animation), end = animation.effect?.getComputedTiming().endTime; + if (Number.isFinite(end) && elapsed >= end) animation.finish(); + else { animation.pause(); animation.currentTime = elapsed; } } }, time); await page.screenshot({ path: path.join(framesDir, `frame-${String(frame++).padStart(4, '0')}.png`), scale: 'css' }); + if (frame === 1) startPhase = await flowPhase(); + } + // Where the looping line flow is, as a fraction of its period, so the last frame can meet the first. + let startPhase = null; + const flowPhase = () => page.evaluate(() => { + const flow = document.getAnimations().find(animation => animation.effect?.getComputedTiming().iterations === Infinity); + if (!flow) return null; + const { duration } = flow.effect.getComputedTiming(); + return { phase: (flow.currentTime % duration) / duration, duration }; + }); + async function alignFlow() { + if (!startPhase) return; + for (let i = 0; i <= Math.ceil(startPhase.duration / 1000 * fps); i++) { + const now = await flowPhase(); if (!now) return; + const gap = Math.abs(now.phase - startPhase.phase), apart = Math.min(gap, 1 - gap) * now.duration; + if (apart <= 500 / fps) { record.flowAlignedWithin = Math.round(apart); return; } + await capture(); + } } async function hold(seconds) { for (let i = 0; i < F(seconds); i++) await capture(); } + // Animations only advance with captured frames: keep filming until a panel that slides in is there. + async function until(locator, seconds = 1.5) { + for (let i = 0; i < F(seconds) && !(await locator.isVisible()); i++) await capture(); + if (!(await locator.isVisible())) await page.screenshot({ path: path.join(out, 'until-failed.png'), scale: 'css' }); + assert.ok(await locator.isVisible(), 'Expected element did not appear'); + } async function viewport() { return page.evaluate(() => window.__qgraphflowAutomation.getViewport()); } async function camera(x, y, zoom, seconds) { const from = await viewport(); @@ -188,40 +249,63 @@ try { await closeNotes(); await fit(); assert.equal(await page.locator('.react-flow__node[data-id]').count(), byId[id].nodes.length + (byId[id].groups?.length ?? 0)); } - await closeNotes(); await fit(); - await installCursor(); recording = true; - await mark('architecture-overview', { allNodes: true }); - await hold(.75); - await camera(470, 370, 1, .75); - await click(page.locator('.react-flow__node[data-id="abstract"] .diagram-node')); await settle(); - await hold(.4); - await click(page.getByRole('button', { name: ui.details, exact: true })); await settle(); - assert.match(await page.locator('.inspector .source-path').innerText(), /AbstractPayOrderController\.java/); - await camera(470, 370, .9, .4); - await hold(.5); await mark('architecture-evidence'); await hold(.75); - await click(page.getByRole('button', { name: ui.hideDetails, exact: true })); await settle(); - await fit(); await hold(.25); - await switchTo('jeepay-sequence'); - await mark('sequence-overview', { allNodes: true }); await hold(.5); - await camera(810, 390, .88, 1); await mark('sequence-order'); await hold(.75); - // Keep participant headers, the guarded fragment and all callback messages in one shot. - const callbackNodes = ['orders', 'channelapi', 'channel', 'callback', 'process', 'notify']; - const span = byId['jeepay-sequence'].nodes.filter(node => callbackNodes.includes(node.id)); - const left = Math.min(...span.map(node => node.position.x)), right = Math.max(...span.map(node => node.position.x + node.size.width)); - const top = Math.min(...span.map(node => node.position.y)), bottom = Math.max(...span.map(node => node.position.y + node.size.height)); - const callbackZoom = Math.min((width - 80) / (right - left), (height - 100) / (bottom - top)); - await camera((left + right) / 2, (top + bottom) / 2, callbackZoom, 1.15); - await mark('sequence-callback', { containedNodes: callbackNodes }); await hold(1); - await fit(); await hold(.25); - await switchTo('jeepay-er'); - await mark('er-overview', { allNodes: true }); await hold(.5); - await camera(1095, 900, .85, 1); await mark('er-fields'); await hold(1.25); - await click(page.locator('.react-flow__node[data-id="t_pay_order"] .diagram-node'), { position: { x: 180, y: 25 } }); await settle(); - assert.match(await page.locator('.node-card .card-source').innerText(), /init\.sql/); - await hold(.5); await mark('er-evidence'); await hold(.5); - await page.keyboard.press('Escape'); await settle(); await fit(); await hold(.25); - await switchTo('jeepay-relations'); await moveTo(parkedPointer.x, parkedPointer.y); await hold(.5); - assert.ok(record.cursor.clicks.length >= 10, 'Missing recorded mouse actions'); + if (clip === 'hero') { + await closeNotes(); await fit(); + await installCursor(); recording = true; + await mark('relations-overview', { allNodes: true }); + await hold(1); + const card = centreOf('jeepay-relations', ['abstract']); + await camera(card.x, card.y, 1, .75); await mark('relations-focus', { containedNodes: ['abstract'] }); + await click(page.locator('.react-flow__node[data-id="abstract"] .diagram-node')); await settle(); + await hold(.4); await mark('relations-selected'); + await click(page.getByRole('button', { name: ui.details, exact: true })); await settle(); + assert.match(await page.locator('.inspector .source-path').innerText(), /AbstractPayOrderController\.java/); + await hold(.5); await mark('relations-evidence'); await hold(1); + await click(page.getByRole('button', { name: ui.hideDetails, exact: true })); await settle(); + await fit(); await hold(.25); await mark('relations-back', { allNodes: true }); + await switchTo('jeepay-sequence'); + await mark('sequence-overview', { allNodes: true }); await hold(.75); + // Keep participant headers, the guarded fragment with its guard and all callback messages in one shot. + const callbackNodes = ['orders', 'channelapi', 'channel', 'callback', 'process', 'notify', 'success']; + const span = centreOf('jeepay-sequence', callbackNodes); + await camera(span.x, span.y, Math.min((width - 80) / span.width, (height - 100) / span.height), 1.15); + await mark('sequence-callback', { containedNodes: callbackNodes }); await hold(1.25); + await fit(); await hold(.25); await mark('sequence-back', { allNodes: true }); + await switchTo('jeepay-er'); + await mark('er-overview', { allNodes: true }); await hold(.5); + // The table is taller than the screen: open on its header, primary key and first fields. + const table = byId['jeepay-er'].nodes.find(node => node.id === 't_pay_order'); + await camera(table.position.x + table.size.width / 2, table.position.y + 420 / .9, .9, 1); await mark('er-fields'); await hold(1); + await click(page.locator('.react-flow__node[data-id="t_pay_order"] .diagram-node'), { position: { x: table.size.width * .9 / 2, y: 24 } }); await settle(); + assert.match(await page.locator('.node-card .card-source').innerText(), /init\.sql/); + await hold(.5); await mark('er-evidence'); await hold(.75); + await page.keyboard.press('Escape'); await settle(); await hold(.25); + await switchTo('jeepay-relations'); + } else { + // The side card lists the key points and then this update: added, changed, removed. The page opens with its first + // card selected; clear that so the clip starts where it ends. + await fit(); await page.keyboard.press('Escape'); await settle(); + await installCursor(); recording = true; + assert.equal(await page.locator('.graph-update .update-removed s').first().innerText(), 'PayOrderReconcileJob'); + await mark('changes-overview', { allNodes: true }); await hold(1.75); + // A listed element opens the details panel, which covers the list. The renamed call comes first, while the whole + // view is on screen; then the added component, which the camera moves to, with its source. + const hide = page.getByRole('button', { name: ui.hideDetails, exact: true }); + await click(page.locator('.graph-update .update-changed button').first()); await settle(); + const label = await page.locator('.edge-label[data-edge-id="r6"]').boundingBox(), panel = await page.locator('.inspector').boundingBox(); + assert.ok(label && label.x + label.width < panel.x && label.y > 0 && label.y + label.height < height, 'The renamed call stays in view beside the details'); + await hold(.5); await mark('changes-changed'); await hold(.5); + await click(hide); await settle(); + const added = page.locator('.graph-update .update-added button').first(); + await until(added); await click(added); await settle(); + assert.equal(await page.locator('.diagram-node.is-added').count(), 1); + assert.match(await page.locator('.inspector .source-path').innerText(), /PayMchNotifyService\.java/); + await hold(.5); await mark('changes-added'); await hold(1.25); + await click(hide); await settle(); + await page.keyboard.press('Escape'); await settle(); await fit(); + } + await moveTo(parkedPointer.x, parkedPointer.y); await hold(.5); await alignFlow(); await mark(`${clip}-end`, { allNodes: true }); + assert.ok(record.cursor.clicks.length >= (clip === 'hero' ? 10 : 4), 'Missing recorded mouse actions'); assert.deepEqual(record.errors, [], 'Browser runtime errors'); assert.deepEqual(record.remoteRequests, [], 'Viewer requested external resources'); assert.equal(fs.readFileSync(graphPath, 'utf8'), graphBytesBefore, 'Recording changed the generated graph'); @@ -229,8 +313,8 @@ try { const pattern = path.join(framesDir, 'frame-%04d.png'); const palette = path.join(out, 'palette.png'); encode(['-framerate', String(fps), '-i', pattern, '-vf', 'palettegen=stats_mode=diff:max_colors=256', palette]); - encode(['-framerate', String(fps), '-i', pattern, '-i', palette, '-lavfi', 'paletteuse=dither=bayer:bayer_scale=3:diff_mode=rectangle', '-loop', '0', path.join(out, `jeepay.${locale}.hero.gif`)]); - encode(['-framerate', String(fps), '-i', pattern, '-c:v', 'libx264', '-crf', '18', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', path.join(out, `jeepay.${locale}.hero.mp4`)]); + encode(['-framerate', String(fps), '-i', pattern, '-i', palette, '-lavfi', 'paletteuse=dither=bayer:bayer_scale=3:diff_mode=rectangle', '-loop', '0', path.join(out, `jeepay.${locale}.${clip}.gif`)]); + encode(['-framerate', String(fps), '-i', pattern, '-c:v', 'libx264', '-crf', '18', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', path.join(out, `jeepay.${locale}.${clip}.mp4`)]); } Object.assign(record, { frames: frame, seconds: frame / fps, framesDir }); fs.writeFileSync(path.join(out, 'record.json'), JSON.stringify(record, null, 2) + '\n'); diff --git a/scripts/refresh-jeepay-fixtures.mjs b/scripts/refresh-jeepay-fixtures.mjs index 237f788..783c282 100644 --- a/scripts/refresh-jeepay-fixtures.mjs +++ b/scripts/refresh-jeepay-fixtures.mjs @@ -9,8 +9,6 @@ const repo = process.argv[2]; if (!repo) throw new Error('Usage: node scripts/refresh-jeepay-fixtures.mjs '); const root = fs.realpathSync(repo), destination = path.resolve(import.meta.dirname, '../examples/jeepay'); const views = [ - ['capabilities', 'jeepay-platform-capability-architecture'], - ['engineering', 'jeepay-engineering-layer-architecture'], ['relations', 'jeepay-component-relation-architecture'], ['flowchart', 'jeepay-unified-order-flowchart'], ['sequence', 'jeepay-unified-order-sequence'], diff --git a/scripts/showcase-changes.mjs b/scripts/showcase-changes.mjs new file mode 100644 index 0000000..c9289cd --- /dev/null +++ b/scripts/showcase-changes.mjs @@ -0,0 +1,32 @@ +#!/usr/bin/env node +// The "this update" example shared by the README clip and the online demo: the Jeepay component relations view (the +// Chinese corpus or its English showcase translation) and a believable earlier version of it. In the earlier version +// the merchant notification does not exist yet, one call has its old name, and a retired reconciliation job is still +// there. The earlier version is derived, so it always matches the corpus. +// node scripts/showcase-changes.mjs zh-CN|en writes current.graph.json and earlier.graph.json +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = path.resolve(import.meta.dirname, '..'); + +export function showcaseChanges(locale) { + const file = locale === 'en' ? 'examples/showcase/jeepay.en.hero.graph.json' : 'examples/jeepay/collection.graph.json'; + const corpus = JSON.parse(fs.readFileSync(path.join(root, file), 'utf8')); + const current = structuredClone(corpus.diagrams.find(graph => graph.meta.viewId === 'jeepay-relations')), earlier = structuredClone(current); + earlier.nodes = earlier.nodes.filter(node => node.id !== 'notify'); + earlier.edges = earlier.edges.filter(edge => edge.source !== 'notify' && edge.target !== 'notify'); + earlier.edges.find(edge => edge.id === 'r6').label = locale === 'en' ? 'Save order' : '保存订单'; + earlier.nodes.push({ ...structuredClone(current.nodes.find(node => node.id === 'orders')), id: 'reconcile', label: 'PayOrderReconcileJob', subtitle: locale === 'en' ? 'Legacy reconciliation' : '旧版对账任务' }); + earlier.edges.push({ ...structuredClone(earlier.edges.find(edge => edge.id === 'r9')), id: 'r-reconcile', source: 'reconcile', label: locale === 'en' ? 'Reconcile orders' : '对账订单' }); + return { current, earlier }; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const [locale, directory] = process.argv.slice(2); + if (!['zh-CN', 'en'].includes(locale) || !directory) throw new Error('Usage: node scripts/showcase-changes.mjs zh-CN|en '); + const { current, earlier } = showcaseChanges(locale); + fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync(path.join(directory, 'current.graph.json'), `${JSON.stringify(current, null, 2)}\n`); + fs.writeFileSync(path.join(directory, 'earlier.graph.json'), `${JSON.stringify(earlier, null, 2)}\n`); +} diff --git a/skills/q-flow/SKILL.md b/skills/q-flow/SKILL.md index 17f28f6..5e81f61 100644 --- a/skills/q-flow/SKILL.md +++ b/skills/q-flow/SKILL.md @@ -25,9 +25,9 @@ For every ready request, apply [Granularity](references/graph-common.md#granular ## Author -Eleven templates: three architecture views (`meta.architectureView`: `capabilities`, `engineering`, `relations`) and eight other types below. +Nine templates, one per type: architecture is drawn as component relations, plus the eight other types below. -1. Choose `meta.diagramType` by intent: structure → `architecture`; decisions → `flowchart`; ordered calls → `sequence`; stored data → `er`; runtime placement → `deployment`; types → `class`; lifecycle → `state`; actors/capabilities → `usecase`; data movement → `dataflow`. Default to `architecture` when ambiguous. Architecture: platform capabilities / business integration → `capabilities`; engineering organization / component layers → `engineering`; component calls / dependencies → `relations`. Use one graph unless the user explicitly requests multiple views. +1. Choose `meta.diagramType` by intent: structure → `architecture`; decisions → `flowchart`; ordered calls → `sequence`; stored data → `er`; runtime placement → `deployment`; types → `class`; lifecycle → `state`; actors/capabilities → `usecase`; data movement → `dataflow`. Default to `architecture` when ambiguous. Use one graph unless the user explicitly requests multiple views. 2. Each view uses [graph-common.md](references/graph-common.md) and its matching page in [references/types/](references/types/) (`types/.md`); reuse loaded references across views. Do not read `graph-schema.md`, `visual-contract.md`, `examples/`, `scripts/`, `assets/` or tests to learn rules. Use the type skeleton and validator messages for fields. 3. Write the evidenced graph at the chosen granularity, without coordinates. Record level/coverage in `meta.scope` and check every user requirement before layout. Apply the common rules for names, evidence, ownership, order and business centre. Across views reuse the same non-empty `module` value for the same business module. Preserve ER keys/cardinalities, class members/multiplicities, sequence pairing/fragments/executions, state guards and architecture/deployment boundaries required at this level. Write once; correct only reported fields. 4. Templates measure text and preserve order; routes use feasible outlines and independent labels. Never remove facts. @@ -46,10 +46,10 @@ node scripts/validate-graph.mjs "/graph.json" --repo- ``` - Execute the scripts; do not read them, the bundled HTML, the Viewer source or tests. `--help` lists every option. Failures report elements, rule, measurement and remediation; `--verbose` prints the receipt. -- On failure, run `node scripts/validate-graph.mjs "" --input-only --fix --repo-root ""` first: it repairs sequence order, operand ids, unambiguous replies/callee bars and unique source/site symbols, prints changes and writes only a valid graph. Then edit only reported fields/elements and rerun. Rewrite the whole file only for a wrong type or view split. Never delete supported facts, shrink text or use `--force` to pass a check. -- Composition warnings never fail the run; input validation prints them, later commands count them (`warnings: n`). Fix `module.missing`, `module.inconsistent`, `flowchart.process-branch` (a non-decision branches) and `edge.site-missing`. For `module.single-tone`, keep one module if the flow really belongs to it; never rename a module for colour. `view.oversized` means over 4 screens at readable zoom: apply the common contract's view-splitting rules while preserving requested detail and graph count. A failing collection names every failing view. -- If bounded layout still fails, distinguish a search budget from proven impossibility, report the blocking nodes and relationships and propose separate views with explicit coverage of the original model; never silently reduce the requested detail. Generation defaults to `--layout auto`; `--layout preserve` keeps existing geometry under the same gate. -- For repository-backed diagrams, pass the target repository root to both commands: they verify every node `source` and edge `site` against local UTF-8 files (existence, line range, symbol, no path escape) and report `sourceEvidence` with its `relations` coverage. This checks the working tree, not the commit in `sourceRef` or whether code proves a relationship. Omitting `--repo-root` reports `skipped`, never verified evidence; say so when source files are unavailable. Conceptual diagrams need no root. +- On failure, run `node scripts/validate-graph.mjs "" --input-only --fix --repo-root ""` first: it repairs sequence order, operand ids, unambiguous replies/callee bars and moved anchors, prints changes and writes only a valid graph. Then edit only reported fields/elements and rerun. Rewrite the whole file only for a wrong type or view split. Never delete supported facts, shrink text or use `--force` to pass a check. +- Composition warnings never fail the run; input validation prints them, later commands count them (`warnings: n`). Fix `module.missing`, `module.inconsistent`, `flowchart.process-branch` (a non-decision branches) and `edge.site-missing`. For `module.single-tone`, keep one module if the flow really belongs to it; never rename a module for colour. `view.oversized` means over 4 screens at readable zoom: split into same-type views or fold shared dependencies; keep requested detail and topics. A failing collection names every failing view. +- If bounded layout still fails, distinguish a search budget from proven impossibility, report the blocking nodes and relationships and propose separate views with explicit coverage of the original model; never silently reduce the requested detail. +- For repository-backed diagrams, pass the target repository root to both commands: they verify every node `source` and edge `site` against local files (existence, line range, symbol) and report `sourceEvidence` with `relations` coverage. Generation records `meta.sourceFiles`: moved lines pass, changed code fails as drift. Neither proves a claim. Omitting `--repo-root` reports `skipped`, never verified evidence; say so when source files are unavailable. Conceptual diagrams need no root. - Outputs are `index.html`, `graph.json` and one SVG per view (`diagram.svg`, or `diagram--.svg` in a collection), built from the prebuilt viewer; no rebuild or install. Use `--force` only with approval to replace the named outputs. All collection views must pass before replacing output. - Reply with artifact paths, types, granularity and coverage (`meta.scope`), semantic/geometry/source-relation results, `meta.notes`, unresolved evidence boundaries, and `Browser acceptance: not performed` unless the next section ran. Never paste full HTML or graph JSON. @@ -59,19 +59,19 @@ Ordinary graph delivery ends with the three commands above. Run the browser chec ## Refresh an existing diagram -Read the supplied graph and collection metadata. Inherit type, scope, granularity, view count and directory. An explicit update approves `--force` for that directory; audit findings alone do not. Resolve only the requested views; ask if their identity is ambiguous. +Read the supplied graph and collection metadata. An explicit update approves `--force` for that directory; audit findings alone do not. Resolve only the requested views; ask if their identity is ambiguous. -Simplification uses verified facts in Author. Expansion returns to Evidence before Author. Preserve stable IDs; report gaps, aggregations, additions and exclusions. These changes authorize `--layout auto --force` for the requested views only. In a collection add `--view ` for each changed view; omit it only when all views need layout. Unselected views must pass preserve; never relayout them to clear a failure. Ordinary refresh preserves geometry: +Simplification uses verified facts in Author. Expansion returns to Evidence before Author. Preserve stable IDs; report gaps, aggregations, additions and exclusions. These changes authorize `--layout auto --force` for the requested views only. In a collection add `--view ` per changed view (omit only when all need layout); never relayout unselected views to clear a failure. Ordinary refresh preserves geometry: ```bash node scripts/validate-graph.mjs "/graph.json" --input-only --fix --repo-root "" -node scripts/generate-viewer.mjs "/graph.json" "" --layout preserve --force --repo-root "" +node scripts/generate-viewer.mjs "/graph.json" "" --layout preserve --force --repo-root "" --compare HEAD ``` -Between the two, fix only anchors still reported: read just their files, edit just those `source` / `site` anchors or facts, and report a symbol you cannot place. Then validate the output as above. `preserve` keeps the user's moved positions and edited text; if it fails the gate, report the nodes and ask before `--layout auto`. Reply with the changed anchors and every artifact path. If a browser could only download `graph.json`, put it in `` and regenerate the page and SVGs. +Between the two, work only what `--fix` left: update just the elements each `meta.sourceDrift` item names (relate uncovered new code), then delete the item; fix anchors still reported; report symbols you cannot place. Validate the output as above. `--compare HEAD` marks what changed; an uncommitted graph compares with a pre-edit copy. `preserve` keeps node positions and reroutes new or crowded edges; if that fails, report the nodes and ask before `--layout auto`. Regenerate a sequence view that lost messages with `--layout auto --view `; columns stay. Reply with the changed elements and every artifact path. If a browser could only download `graph.json`, put it in `` and regenerate the page and SVGs. ## Viewer maintenance -For Viewer changes or interaction audits, read [viewer-development.md](references/viewer-development.md), including its maintained visual/interaction contract. Changes to Viewer source, routing, schema behavior, or validation require the full eleven-view browser matrix described there. Graph-only delivery uses the single-page check in [acceptance.md](references/acceptance.md). +For Viewer changes or interaction audits, read [viewer-development.md](references/viewer-development.md), including its maintained visual/interaction contract. Changes to Viewer source, routing, schema behavior, or validation require the full nine-view browser matrix described there. Graph-only delivery uses the single-page check in [acceptance.md](references/acceptance.md). Publishing the plugin or creating a remote repository requires separate user authorization. diff --git a/skills/q-flow/agents/openai.yaml b/skills/q-flow/agents/openai.yaml index 7ea9145..85a861f 100644 --- a/skills/q-flow/agents/openai.yaml +++ b/skills/q-flow/agents/openai.yaml @@ -1,5 +1,5 @@ interface: display_name: "Q flow" - short_description: "Eleven kinds of interactive software diagrams from source, configuration and documents" + short_description: "Nine kinds of interactive software diagrams from source, configuration and documents" brand_color: "#203f35" default_prompt: "Use $q-flow to generate the right kind of interactive software diagram from the current evidence." diff --git a/skills/q-flow/assets/viewer-dist/index.html b/skills/q-flow/assets/viewer-dist/index.html index ef919be..7a14472 100644 --- a/skills/q-flow/assets/viewer-dist/index.html +++ b/skills/q-flow/assets/viewer-dist/index.html @@ -220,21 +220,21 @@ QGraphFlow - - ${f.lines.map((e,t)=>Q(64,43+t*f.lineHeight,e,`heading`)).join(``)}${p.lines.map((e,t)=>Q(64,m+t*p.lineHeight,e,`meta`)).join(``)}${S}${a===`sequence`?E+w:w+E}${C}${_.svg}\n`}RegExp(`^diagram(-\\d+-(${Um.join(`|`)}))?\\.svg$`);function vv(e){let t=Array.isArray(e.diagrams),n=t?e.diagrams:[e],r=Ff(n,Of.light);return n.map((e,n)=>({name:t?`diagram-${n+1}-${Gm(e)}.svg`:`diagram.svg`,svg:_v(e,`light`,r)}))}function yv(e){return e.trim().replace(/[^\p{L}\p{N}._-]+/gu,`-`).replace(/^-+|-+$/g,``)||`diagram`}function bv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}async function xv(e,t,n,r=decodeURIComponent(window.location?.pathname?.split(`/`).pop()||`index.html`)){let i=(e,n)=>_f(t,e,n),a=`${JSON.stringify(e,null,2)}\n`,o;try{if(typeof window.showDirectoryPicker==`function`){let t=await window.showDirectoryPicker({id:`qgraphflow-page`,mode:`readwrite`}),s=await t.getFileHandle(r,{create:!1}).catch(()=>null);if(!s)throw Object.assign(Error(`wrong directory`),{name:`NotFoundError`});let c=$_(await(await s.getFile()).text(),e),l;try{l=vv(e).map(e=>[e.name,e.svg])}catch(e){if(!e.phases)throw e}for(let[e,n]of[[`graph.json`,a],[r,c],...l??[]])o=await(await t.getFileHandle(e,{create:!0})).createWritable(),await o.write(n),await o.close(),o=null;n(i(l?`Saved into this page, its sibling graph.json and SVGs`:`Saved into this page and its sibling graph.json; SVGs not updated: the layout needs adjustment`))}else typeof window.showSaveFilePicker==`function`?(o=await(await window.showSaveFilePicker({suggestedName:`graph.json`,types:[{description:`Graph JSON`,accept:{"application/json":[`.json`]}}]})).createWritable(),await o.write(a),await o.close(),o=null,n(i(`Graph JSON saved`))):(bv(new Blob([a],{type:`application/json;charset=utf-8`}),`graph.json`),n(i(`Graph JSON downloaded; keep the file to preserve edits`)))}catch(e){o&&await o.abort().catch(()=>{}),n(i(e.name===`AbortError`?`Save cancelled; edits remain in this page`:e.name===`NotFoundError`?`Choose the folder containing this page ({page}); edits remain in this page`:`Save failed; edits remain in this page`,{page:r}))}}async function Sv(e,t){t=xf(t);let n=[],r=[],i=document.createElement(`div`);i.style.cssText=`position:fixed;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none`;let a=new DOMParser().parseFromString(e,`image/svg+xml`);if(a.querySelector(`parsererror`))throw a_(t,`rendering`,`The exported SVG could not be parsed`);let o=document.importNode(a.documentElement,!0);i.append(o),document.body.append(i);try{await document.fonts.ready;let e=o.viewBox.baseVal,i=Number(o.dataset.graphOffsetX),a=Number(o.dataset.graphOffsetY);if(!Number.isFinite(i)||!Number.isFinite(a))throw Error(`The exported SVG has no geometry offset`);let s=new Map([...o.querySelectorAll(`.node-drawing`)].map(e=>[e.dataset.diagramNodeId,e])),c=e=>String(e??``).replace(/\s+/gu,``),l=(e,t)=>e.x>=t.x-.5&&e.y>=t.y-.5&&e.x+e.width<=t.x+t.width+.5&&e.y+e.height<=t.y+t.height+.5,u=e=>{let t=e.getBBox(),n=e.getCTM(),r=[new DOMPoint(t.x,t.y),new DOMPoint(t.x+t.width,t.y),new DOMPoint(t.x,t.y+t.height),new DOMPoint(t.x+t.width,t.y+t.height)].map(e=>e.matrixTransform(n)),i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y));return{x:i,y:a,width:Math.max(...r.map(e=>e.x))-i,height:Math.max(...r.map(e=>e.y))-a}};for(let t of o.querySelectorAll(`text`)){if(!t.textContent)continue;let o=u(t),s=parseFloat(getComputedStyle(t).fontSize)*Math.hypot(t.getCTM().a,t.getCTM().b),c=t.closest(`[data-diagram-node-id],[data-diagram-edge-id],[data-diagram-group-id],[data-fragment-group-id]`);n=c?[c.dataset.diagramNodeId??c.dataset.diagramEdgeId??c.dataset.diagramGroupId??c.dataset.fragmentGroupId]:[],r=[{...o,x:o.x-i,y:o.y-a}];let d=/(?:title|heading)/.test(t.getAttribute(`class`))?20:/^(body|operand-body|field-name|field-type|member|edge|cardinality)$/.test(t.getAttribute(`class`))?16:14;if(!l(o,e)||s+.01e.textContent).map(e=>({element:e,box:u(e)})),v=c(_.map(e=>e.element.textContent).join(``)),y=[[`initial`,`final`].includes(e.kind)&&!e.subtitle?``:e.label,e.subtitle,...(e.badges??[]).map(e=>e.label),...(e.fields??[]).flatMap(e=>[e.name,e.type]),...e.attributes??[],...e.methods??[],...h?[`entry`,`do`,`exit`].map(t=>e[t]):[]];for(let t of y)if(t&&!v.includes(c(t)))throw Error(`Node text is not fully shown: ${e.id} / ${e.label} / ${String(t).slice(0,80)}`);for(let t of _)if(!l(t.box,m)&&!(g&&l(t.box,g)))throw Error(`Node text leaves the safe area: ${e.id} / ${e.label} / ${t.element.textContent.slice(0,80)}`);for(let t=0;t<_.length;t++)for(let n of _.slice(t+1)){let r=_[t].box,i=n.box;if(r.x[e.dataset.diagramEdgeId,e])),m=e=>({...e,x:e.x+i,y:e.y+a}),h=(e,t)=>e.x[...e.label?[m(e.labelBox)]:[],...(e.endpointLabels??[]).map(e=>m(e.labelBox))]),_=(e,t,n,o,s=`Edges`)=>{if(r=[{...n,x:n.x-i,y:n.y-a}],c(e.map(e=>e.textContent).join(``))!==c(t))throw Error(`${s} text is not fully shown: ${o}`);if(e.some(e=>!l(u(e),n)))throw Error(`${s} text leaves the safe area: ${o}`)},v=new Map,y=new Map([...o.querySelectorAll(`[data-diagram-group-id]`)].map(e=>[e.dataset.diagramGroupId,e])),b=wh(t);for(let e of t.groups??[]){n=[e.id];let r=y.get(e.id),i=d===`sequence`?gh(e,f,t.meta.locale,t.groups,b):null,a=i?.heading??{x:e.position.x+16,y:e.position.y+6,width:e.size.width-32,height:bp(e).height};_([...r?.querySelectorAll(`:scope > text.group`)??[]],e.label,m(a),e.id,`group`),[`alt`,`opt`,`loop`,`par`].includes(e.kind)&&_([...r?.querySelectorAll(`:scope > text.group-kind`)??[]],e.kind,m({x:e.position.x+e.size.width-60,y:e.position.y+6,width:48,height:30}),e.id);for(let[t,n]of[[`guard`,i?.guards],[`body`,i?.bodies]])for(let r of n??[])_([...o.querySelectorAll(`.operand-${t}[data-fragment-group-id="${CSS.escape(e.id)}"][data-operand-id="${CSS.escape(r.operandId)}"] text`)],r.lines.join(``),m(r),`${e.id}/${r.operandId}/${t}`,`fragment`)}for(let r of t.edges){n=[r.id,r.source,r.target];let i=p.get(r.id),a=f.get(r.id),s=i?.querySelector(`:scope > path`);if(!s)throw Error(`Export is missing edge ${r.id}`);_([...i.querySelectorAll(`:scope > text.edge`)],a.label,m(a.labelBox),r.id);for(let e of a.endpointLabels??[])_([...[...i.querySelectorAll(`.edge-multiplicity`)].find(t=>t.dataset.endpoint===e.role)?.querySelectorAll(`text`)??[]],e.label,m(e.labelBox),`${r.id}/${e.role}`);if($(d).cardinalities)for(let[t,n,o]of[[`source`,a.points[0],a.points[1]],[`target`,a.points.at(-1),a.points.at(-2)]]){let a=Oh(r[`${t}Cardinality`],n,o),s=i.querySelector(`[data-cardinality-endpoint="${t}"]`),c=s?.querySelector(`path`),d=s?.querySelector(`circle`);if(!c||c.getAttribute(`d`)!==a.path||!!d!=!!a.circle||a.circle&&Object.entries(a.circle).some(([e,t])=>Number(d.getAttribute(e))!==t))throw Error(`Cardinality mark missing or mismatched: ${r.id}/${t}`);let f=u(s),p=m(a.bounds);if(!l(f,p)||!l(p,f)||!l(f,e))throw Error(`Cardinality mark is out of bounds: ${r.id}/${t}`)}for(let[n,i]of Object.entries(Zm(r,d))){let a=s.getAttribute(`marker-${n}`),c=/^url\(#([^)]*)\)$/.exec(a??``)?.[1];if(!i&&!a)continue;if(!i||!c||!(c===i||i===`arrow`&&/^arrow-(module|warn|ok|data)$/.test(c)))throw Error(`Edge marker mismatch: ${r.id}/${n}`);let u=o.querySelector(`marker[id="${CSS.escape(c)}"]`);if(!u)throw Error(`Edge marker missing: ${r.id}/${n}/${c}`);if(!v.has(c)){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);for(let t of u.childNodes)e.append(t.cloneNode(!0));o.append(e);try{let t=e.getBBox(),n=Math.max(0,...[...e.querySelectorAll(`*`)].map(e=>getComputedStyle(e).stroke===`none`?0:parseFloat(getComputedStyle(e).strokeWidth)/2));if(!t.width||!t.height)throw Error(`Edge marker is empty: ${r.id}/${c}`);v.set(c,{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2})}finally{e.remove()}}let f=v.get(c),p=u.viewBox.baseVal,_=u.markerWidth.baseVal.value,y=u.markerHeight.baseVal.value;if(!(_>0&&y>0&&p.width>0&&p.height>0)||!l(f,p))throw Error(`Edge marker is clipped: ${r.id}/${c}`);let b=Math.min(_/p.width,y/p.height)*(u.getAttribute(`markerUnits`)===`userSpaceOnUse`?1:parseFloat(getComputedStyle(s).strokeWidth)),x=s.getTotalLength(),S=s.getPointAtLength(n===`start`?0:x),C=s.getPointAtLength(n===`start`?Math.min(1,x):Math.max(0,x-1)),w=Math.atan2(n===`start`?C.y-S.y:S.y-C.y,n===`start`?C.x-S.x:S.x-C.x)*180/Math.PI,T=s.getCTM().translate(S.x,S.y).rotate(w).scale(b).translate(-u.refX.baseVal.value,-u.refY.baseVal.value),E=[[f.x,f.y],[f.x+f.width,f.y],[f.x,f.y+f.height],[f.x+f.width,f.y+f.height]].map(([e,t])=>new DOMPoint(e,t).matrixTransform(T)),D=Math.min(...E.map(e=>e.x)),O=Math.min(...E.map(e=>e.y)),k={x:D,y:O,width:Math.max(...E.map(e=>e.x))-D,height:Math.max(...E.map(e=>e.y))-O};if(!l(k,e)||g.some(e=>h(k,e))||t.nodes.some(e=>e.id!==r.source&&e.id!==r.target&&h(k,m(Kh(e,d)))))throw Error(`Edge marker out of bounds or covered: ${r.id}/${n}/${c}`)}}}catch(e){throw a_(t,`rendering`,e.message,[{ruleId:`rendering.svg`,severity:`error`,diagramType:Gm(t),elementIds:n,bounds:r,measured:e.message,required:`Complete visible text and notation within the measured safety regions and viewBox`,remediation:`Inspect the identified element and regenerate after correcting its text or geometry.`}])}finally{i.remove()}}function Cv(e,t){return new Promise((n,r)=>{let i=new Blob([e],{type:`image/svg+xml;charset=utf-8`}),a=URL.createObjectURL(i),o=new Image;o.onload=()=>{try{let e=o.naturalWidth,i=o.naturalHeight;if(!e||!i||e>32767||i>32767||e*i>64e6)throw Error(`Image exceeds the PNG export limit; export SVG instead`);let a=document.createElement(`canvas`);a.width=e,a.height=i;let s=a.getContext(`2d`);if(!s)throw Error(`The browser could not create the PNG canvas`);s.drawImage(o,0,0);let c=document.createElement(`canvas`);c.width=Math.min(128,e),c.height=Math.min(128,i);let l=c.getContext(`2d`);if(!l)throw Error(`The browser could not inspect the PNG canvas`);l.drawImage(a,0,0,c.width,c.height);let u=l.getImageData(0,0,c.width,c.height).data;if(!u.some((e,t)=>e!==u[t%4]))throw Error(`The browser produced a blank PNG canvas`);a.toBlob(e=>{if(!e||!e.size||e.type!==`image/png`)return r(Error(`The browser could not generate the PNG`));bv(e,t),n()},`image/png`)}catch(e){r(e)}finally{URL.revokeObjectURL(a)}},o.onerror=()=>{URL.revokeObjectURL(a),r(Error(`The browser could not read the exported SVG`))},o.src=a})}async function wv(e,t,n,r,i){e=structuredClone(e),i&&=If(i);let a=(t,n)=>_f(e.meta.locale,t,n);try{r(a(`Generating {format}…`,{format:n.toUpperCase()}));let o=_v(e,t,i),s=`${yv(e.meta.title)}.${n}`;await Sv(o,e),n===`svg`?bv(new Blob([o],{type:`image/svg+xml;charset=utf-8`}),s):await Cv(o,s),r(a(`{format} downloaded`,{format:n.toUpperCase()}))}catch(e){return r(e.message),e}}function Tv(e,t,n,r,i,a,o){let[s,c]=(0,y.useState)(()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches);(0,y.useEffect)(()=>{let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[l,u]=(0,y.useState)(null),d=(0,y.useCallback)(e=>u({message:e}),[]),f=Of[t],p=av(e,s,d,i),[m,h]=o,g=m&&!s,_=uv(d,()=>p.readGraph(p.currentGraph,0)),v=cv(p.currentGraph,{focusNode:p.focusNode,panels:n,isFullscreen:_.isFullscreen,toggleFullscreen:_.toggleFullscreen}),b=lv(e,p,v,g,f,r),x=async e=>{p.setRenderProblem(null);let n=await wv(p.currentGraph,t,e,d,r);n?.diagnostics&&p.setRenderProblem({graph:p.currentGraph,message:n.message,diagnostics:n.diagnostics})},S=()=>xv(a(p.currentGraph),e.meta.locale,d),C=()=>{p.resetLayout(),v.resetSelection(),h(!0),d(`Reset: original positions and reading view restored`)};return{...p,...v,...b,...n,..._,diagramType:Gm(e),palette:f,moduleColors:r,reduceMotion:s,exportStatus:l,exportDiagram:x,saveGraph:S,reset:C,inspectedNode:v.selected,inspectedEdge:v.selectedEdge,hasFlow:bf(e).some(t=>Jm(t,Gm(e))),flowRunning:g,setFlowEnabled:h,nudgeLayout:()=>p.nudgeLayout(v.selectedId)}}function Ev(){let[e,t]=(0,y.useState)(null),n=(0,y.useCallback)(e=>t(t=>t===e?null:e),[]),r=(0,y.useCallback)(()=>{let n=document.querySelector(`[data-popover-root="${e}"]`);n?.contains(document.activeElement)&&n.querySelector(`[aria-haspopup]`)?.focus(),t(null)},[e]);return(0,y.useEffect)(()=>{if(!e)return;let n=n=>{n.target.closest?.(`[data-popover-root]`)?.dataset.popoverRoot!==e&&t(null)},i=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),r();return}let n=t.target.closest?.(`[data-popover-root]`);if(n?.dataset.popoverRoot!==e)return;let i=t.target.closest(`[role="radiogroup"]`);if(![`ArrowDown`,`ArrowUp`,`Home`,`End`,...i?[`ArrowLeft`,`ArrowRight`]:[]].includes(t.key))return;let a=[...(i??n).querySelectorAll(i?`[role="radio"]`:`[role="menu"] button`)].filter(e=>!e.disabled);if(!a.length)return;t.preventDefault(),t.stopPropagation();let o=a.indexOf(document.activeElement),s=[`ArrowDown`,`ArrowRight`].includes(t.key),c=t.key===`Home`?0:t.key===`End`?a.length-1:o<0?s?0:a.length-1:(o+(s?1:-1)+a.length)%a.length;a[c].focus(),i&&a[c].click()};return window.addEventListener(`pointerdown`,n,!0),window.addEventListener(`keydown`,i,!0),()=>{window.removeEventListener(`pointerdown`,n,!0),window.removeEventListener(`keydown`,i,!0)}},[e,r]),{open:e,toggle:n,close:r}}function Dv(e,t,n,r,i){let{getViewport:a,setViewport:o}=vl();return(0,y.useCallback)((s,c,l,u)=>{let d=e.current?.getBoundingClientRect();if(!d?.width)return;if(r===`sequence`){let t=Wh(n),d=n.nodes.find(e=>e.id===s),f=t.get(c),p=d?Kh(d,r):f?.labelBox;if(!p)return;let m=K_(p,W_(e.current,l,u),a());(m.x!==a().x||m.y!==a().y||m.zoom!==a().zoom)&&o(m,{duration:i?0:360,ease:U_});return}let f=t.find(e=>e.id===s&&e.type===`diagram`);if(!f)return;let p=a(),m=f.position.x*p.zoom+p.x,h=m+(f.measured?.width??f.style.width)*p.zoom,g=f.position.y*p.zoom+p.y,_=l?328:12,v=d.width-(u?328:12),y=0,b=0;h>v&&(y=v-h),m+y<_&&(y=_-m),g<64&&(b=64-g),(y||b)&&o({...p,x:p.x+y,y:p.y+b},{duration:i?0:360,ease:U_})},[e,r,n,t,i,a,o])}var Ov={"panel-left":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M9 3v18`})]}),"panel-right":(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}),(0,x.jsx)(`path`,{d:`M15 3v18`})]}),views:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`})]}),search:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`11`,cy:`11`,r:`8`}),(0,x.jsx)(`path`,{d:`m21 21-4.3-4.3`})]}),spacing:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m18 8 4 4-4 4`}),(0,x.jsx)(`path`,{d:`m6 8-4 4 4 4`}),(0,x.jsx)(`path`,{d:`M2 12h20`})]}),wash:(0,x.jsx)(`path`,{d:`M12 2.5c-.6 2.6-2.2 5-4.3 6.9C5.9 11 5 13 5 15a7 7 0 0 0 14 0c0-2-.9-4-2.7-5.6C14.2 7.5 12.6 5.1 12 2.5Z`}),more:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`5`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`}),(0,x.jsx)(`circle`,{cx:`19`,cy:`12`,r:`1.6`,fill:`currentColor`,stroke:`none`})]}),download:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,x.jsx)(`path`,{d:`m7 10 5 5 5-5`}),(0,x.jsx)(`path`,{d:`M12 15V3`})]}),lock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]}),unlock:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,x.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`})]}),reset:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`}),(0,x.jsx)(`path`,{d:`M3 3v5h5`})]}),moon:(0,x.jsx)(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`}),sun:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`4`}),(0,x.jsx)(`path`,{d:`M12 2v2`}),(0,x.jsx)(`path`,{d:`M12 20v2`}),(0,x.jsx)(`path`,{d:`m4.93 4.93 1.41 1.41`}),(0,x.jsx)(`path`,{d:`m17.66 17.66 1.41 1.41`}),(0,x.jsx)(`path`,{d:`M2 12h2`}),(0,x.jsx)(`path`,{d:`M20 12h2`}),(0,x.jsx)(`path`,{d:`m6.34 17.66-1.41 1.41`}),(0,x.jsx)(`path`,{d:`m19.07 4.93-1.41 1.41`})]}),close:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M18 6 6 18`}),(0,x.jsx)(`path`,{d:`m6 6 12 12`})]}),check:(0,x.jsx)(`path`,{d:`M20 6 9 17l-5-5`}),chevron:(0,x.jsx)(`path`,{d:`m6 9 6 6 6-6`}),notes:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M3 6h.01`}),(0,x.jsx)(`path`,{d:`M3 12h.01`}),(0,x.jsx)(`path`,{d:`M3 18h.01`}),(0,x.jsx)(`path`,{d:`M8 6h13`}),(0,x.jsx)(`path`,{d:`M8 12h13`}),(0,x.jsx)(`path`,{d:`M8 18h13`})]}),legend:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`rect`,{x:`3`,y:`14`,width:`7`,height:`7`,rx:`1`}),(0,x.jsx)(`path`,{d:`M14 5h7`}),(0,x.jsx)(`path`,{d:`M14 9h5`}),(0,x.jsx)(`path`,{d:`M14 16h7`}),(0,x.jsx)(`path`,{d:`M14 20h5`})]}),source:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 12.5 8 15l2 2.5`}),(0,x.jsx)(`path`,{d:`m14 12.5 2 2.5-2 2.5`}),(0,x.jsx)(`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`}),(0,x.jsx)(`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`})]}),arrowRight:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M5 12h14`}),(0,x.jsx)(`path`,{d:`m12 5 7 7-7 7`})]}),fit:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`}),(0,x.jsx)(`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`}),(0,x.jsx)(`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`}),(0,x.jsx)(`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`})]}),expand:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`m15 3 6 0 0 6`}),(0,x.jsx)(`path`,{d:`m9 21-6 0 0-6`}),(0,x.jsx)(`path`,{d:`M21 3 14 10`}),(0,x.jsx)(`path`,{d:`M3 21l7-7`})]}),collapse:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 14H4v6`}),(0,x.jsx)(`path`,{d:`M20 4h-6v6`}),(0,x.jsx)(`path`,{d:`m4 20 6-6`}),(0,x.jsx)(`path`,{d:`m20 4-6 6`})]})};function kv({name:e}){return(0,x.jsx)(`svg`,{className:`ic`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:Ov[e]})}function Av(e,t,n,r,i,a=()=>{}){let o=t??e,s=o?`${t?`edge`:`node`}:${o.id}`:null,c=(0,y.useRef)(0),[l,u]=(0,y.useState)({editing:!1,pending:!1,label:``,subtitle:``,error:``}),d=(t=!1)=>u({editing:!1,pending:!1,label:o?.label??``,subtitle:e?.subtitle??``,error:``,returnFocus:t});(0,y.useEffect)(()=>{c.current++,a(),d()},[s]);let f=e=>u(t=>({...t,...e}));return{...l,set:f,cancel:()=>{c.current++,a(),d(!0)},begin:()=>f({editing:!0,returnFocus:!1,label:o?.label??``,subtitle:e?.subtitle??``,error:``}),save:async a=>{if(a.preventDefault(),l.pending)return;let o=l.label.trim();if(!o){f({error:_f(i,`Name is required`)});return}let s=++c.current;f({pending:!0});let u=await(t?r(t.id,o):n(e.id,o,l.subtitle.trim()));if(c.current===s){if(f({pending:!1}),u){f({error:u});return}f({editing:!1,error:``})}}}}function jv({editor:e,relation:t,locked:n,locale:r}){let i=e=>_f(r,e),a=(0,y.useRef)(null),o=(0,y.useRef)(null);return(0,y.useEffect)(()=>{!e.editing&&e.returnFocus&&a.current?.focus(),e.error&&o.current?.focus()},[e.editing,e.error,e.returnFocus]),e.editing?(0,x.jsxs)(`form`,{"aria-busy":e.pending,className:`card-form`,onSubmit:e.save,onKeyDown:t=>{if(t.nativeEvent.isComposing||t.keyCode===229){t.key===`Enter`&&t.preventDefault();return}t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.cancel())},children:[(0,x.jsxs)(`label`,{children:[i(`Name`),(0,x.jsx)(`input`,{ref:o,autoFocus:!0,required:!0,disabled:e.pending,value:e.label,onChange:t=>e.set({label:t.target.value,error:``}),"aria-invalid":!!e.error})]}),!t&&(0,x.jsxs)(`label`,{children:[i(`Description`),(0,x.jsx)(`textarea`,{disabled:e.pending,value:e.subtitle,onChange:t=>e.set({subtitle:t.target.value,error:``})})]}),e.error&&(0,x.jsx)(`p`,{className:`card-error`,role:`alert`,children:e.error}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(`button`,{type:`button`,onClick:e.cancel,children:i(`Cancel`)}),(0,x.jsx)(`button`,{type:`submit`,disabled:e.pending,children:i(`Save`)})]})]}):(0,x.jsx)(`button`,{ref:a,disabled:n,title:n?i(`Unlock the layout first`):``,onClick:e.begin,children:i(`Edit text`)})}var Mv=292,Nv=232,Pv=14;function Fv({node:e,edge:t,source:n,target:r,others:i=[],canvasRef:a,palette:o,moduleColors:s,locale:c,locked:l,editor:u,graph:d,isFullscreen:f,onDetails:p,onClose:m}){let h=Td(),g=(e,t)=>_f(c,e,t),_=!!t,v=_?(Wh(d).get(t.id)?.label??Dh(t,t.diagramType,c))||t.kind:e.label,b=(0,y.useRef)(null),S=(0,y.useRef)(!1),[C,w]=(0,y.useState)(Nv),[,T]=(0,y.useState)(``),[E,D]=(0,y.useState)(!1),O=(0,y.useRef)(!1);(0,y.useEffect)(()=>{S.current=!1},[e?.id,t?.id,f]),(0,y.useEffect)(()=>{if(!E){S.current=!1;return}!O.current||b.current?.offsetHeight!==C||S.current||(S.current=!0,p())},[E,p,f,C]),(0,y.useLayoutEffect)(()=>{D(O.current);let e=b.current?.offsetHeight;e&&e!==C&&w(e)}),(0,y.useLayoutEffect)(()=>{if(!b.current)return;let e=new ResizeObserver(()=>{w(b.current?.offsetHeight??Nv),T(`${a.current?.clientWidth}:${a.current?.clientHeight}`)});return e.observe(b.current),a.current&&e.observe(a.current),()=>e.disconnect()},[]);let k=a.current?.getBoundingClientRect();if(!e||!k?.width)return null;let A=t?.diagramType??e.diagramType??`architecture`,j=(e,t)=>({left:e.x*h.zoom+h.x,top:e.y*h.zoom+h.y,width:t.width*h.zoom,height:t.height*h.zoom}),M=_?e:Kh(e,A),N=j({x:M.x??M.position.x,y:M.y??M.position.y},{width:M.width??M.size.width,height:M.height??M.size.height}),P=W_(a.current,a.current.dataset.navOpen===`true`,a.current.dataset.drawerOpen===`true`),ee=[{side:`right`,x:N.left+N.width+Pv,y:N.top},{side:`left`,x:N.left-Pv-Mv,y:N.top},{side:`below`,x:N.left,y:N.top+N.height+Pv},{side:`above`,x:N.left,y:N.top-Pv-C}],F=e=>e.x>=P.left&&e.x+Mv<=P.right&&e.y>=P.top&&e.y+C<=P.bottom,I=i.filter(t=>t.type===`diagram`&&(!e.id||t.id!==e.id)).map(e=>{let t=Kh({...e.data,position:e.position,size:{width:e.measured?.width??e.style.width,height:e.measured?.height??e.style.height}},A);return j({x:t.x,y:t.y},{width:t.width,height:t.height})});if(A===`sequence`){let e=Wh(d),t=[...e.values()].flatMap(e=>[e.labelBox,...oh(e)]),n=wh(d);for(let r of d.groups??[]){let i=gh(r,e,c,d.groups??[],n);t.push(...i.guards,...i.bodies??[],...i.heading?[i.heading]:[])}I.push(...t.map(e=>j(e,e)))}let te=e=>I.reduce((t,n)=>t+Math.max(0,Math.min(e.x+Mv,n.left+n.width)-Math.max(e.x,n.left))*Math.max(0,Math.min(e.y+C,n.top+n.height)-Math.max(e.y,n.top)),0),ne=ee.filter(F),L=ne.find(e=>te(e)===0),R=A===`sequence`&&!L;O.current=R;let z=L??ne.sort((e,t)=>te(e)-te(t))[0]??ee[2],B=Math.min(Math.max(z.x,P.left),Math.max(P.left,P.right-Mv)),re=Math.min(Math.max(z.y,P.top),Math.max(P.top,P.bottom-C)),ie=!_&&e.source?Gf(e.source):_&&t.site?Gf(t.site):null,ae=_?Hf(t,r,o,s,n,vh(d).get(t.id)):Bf(e,o,s).stroke;return(0,x.jsxs)(`aside`,{ref:b,className:`node-card ${_?`relation-card`:``} ${z.side===`left`?`is-flipped`:z.side===`below`?`is-below`:z.side===`above`?`is-above`:``}`,style:{left:B,top:re,width:Mv,visibility:R?`hidden`:void 0},role:`dialog`,"aria-label":v,"data-node-id":_?void 0:e.id,"data-edge-id":_?t.id:void 0,children:[(0,x.jsx)(`button`,{className:`card-close`,onClick:m,"aria-label":g(`Close`),children:(0,x.jsx)(kv,{name:`close`})}),u.editing?(0,x.jsx)(jv,{editor:u,relation:_,locked:l,locale:c}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`p`,{className:`card-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:ae}}),_?`${g(`Edges`)} · ${t.kind}`:`${g(Kf[e.kind]??e.kind)}${e.module?` · ${e.module}`:``}`]}),(0,x.jsx)(`h4`,{children:v}),_?(0,x.jsxs)(`p`,{className:`card-subtitle`,children:[n?.label,` → `,r?.label]}):e.subtitle&&(0,x.jsx)(`p`,{className:`card-subtitle`,children:e.subtitle}),_&&t.evidence&&(0,x.jsxs)(`p`,{className:`card-source`,children:[g(`Evidence`),` · `,g(Wf[t.evidence]??t.evidence)]}),ie&&(0,x.jsxs)(`p`,{className:`card-source`,title:ie,children:[(0,x.jsx)(kv,{name:`source`}),(0,x.jsx)(`code`,{children:ie})]}),!_&&e.tags?.length>0&&(0,x.jsx)(`div`,{className:`card-tags`,children:e.tags.slice(0,4).map(e=>(0,x.jsx)(`span`,{children:e},e))}),(0,x.jsxs)(`div`,{className:`card-actions`,children:[(0,x.jsx)(jv,{editor:u,relation:_,locked:l,locale:c}),(0,x.jsxs)(`button`,{className:`card-action`,onClick:p,children:[g(`View details`),(0,x.jsx)(kv,{name:`arrowRight`})]})]})]})]})}var Iv=[`system`,`light`,`dark`],Lv={system:`Follow system`,light:`Light`,dark:`Dark`};function Rv(e,t,n){let[r,i]=(0,y.useState)(e?`still`:``);return e&&!r?i(`in`):!e&&r&&t&&i(``),(0,y.useEffect)(()=>{if(e||!r)return;let t=!0;return Promise.allSettled((n.current?.getAnimations()??[]).map(e=>e.finished)).then(()=>{t&&i(``)}),()=>{t=!1}},[e,r,n]),[r,`${r===`still`?` is-still`:``}${e?``:` is-closing`}`]}function zv({graph:e,originalGraph:t,graphForSave:n,allDiagrams:r,moduleColors:i,wash:a,setWash:o,onDiagramChange:s,theme:c,appearance:l,setAppearance:u,panels:d,flowControl:f}){let p=G(e=>e.transform[2]),{setCenter:m}=vl(),h=(t,n)=>_f(e.meta.locale,t,n),{diagramType:g,palette:_,reduceMotion:v,hasFlow:b,flowRunning:S,setFlowEnabled:C,inspectedNode:w,inspectedEdge:T,selectedId:E,selectedEdgeId:D,selectionPulse:O,query:k,setQuery:A,normalizedQuery:j,results:M,selectNode:N,selectEdge:P,clearSelectedNode:ee,handleCanvasKeyDown:F,locked:I,setLocked:te,canvasRef:ne,currentGraph:L,acceptedGraph:R,nodes:z,onNodesChange:B,onNodeDragStop:re,layoutPending:ie,cancelLayout:ae,updateNodeText:oe,updateEdgeText:se,readGraph:ce,focusDiagram:le,nudgeLayout:ue,visibleNodes:de,visibleEdges:fe,reset:pe,exportDiagram:me,saveGraph:he,exportStatus:ge,layoutProblem:_e,layoutWarnings:ve,focusProblem:ye,boardRef:be,fullscreenButtonRef:xe,isFullscreen:Se,fullscreenPending:Ce,fullscreenSupported:we,toggleFullscreen:Te,toolbarOpen:Ee,drawerOpen:De,toolbarButtonRef:Oe,drawerButtonRef:ke,searchInputRef:Ae,inspectorRef:je,panelRef:Me,toggleToolbar:Ne,toggleDrawer:Pe,openDetails:Fe}=Tv(e,c,d,i,t,n,f),[Ie,Le]=Rv(Ee,v,Me),[Re,ze]=Rv(De,v,je),Be=(0,y.useRef)(null),Ve=Av(w,T,oe,se,e.meta.locale,ae),{open:He,toggle:Ue,close:We}=Ev(),Ge=e.meta.notes??[],Ke=rg(e),qe=cg(e),Je=lg(qe),Ye=Ge.length?{title:h(`Key points`),count:Ge.length,hide:h(`Hide key points`),show:h(`Show key points`)}:Ke.length?{title:h(`Source changes`),count:Ke.length,hide:h(`Hide source changes`),show:h(`Show source changes`)}:{title:h(`This update`),count:Je,hide:h(`Hide this update`),show:h(`Show this update`)},Xe=e=>{let t=L.nodes.find(t=>t.id===e),n=t?null:L.edges.find(t=>t.id===e);return t||n?(0,x.jsx)(`button`,{type:`button`,className:`folded-edge`,onClick:()=>t?N(t):P(n,!0),children:ag(L,e)},e):(0,x.jsx)(`span`,{className:`update-group`,children:L.groups?.find(t=>t.id===e)?.label??e},e)},[Ze,Qe]=(0,y.useState)(!0),$e=Ye.count>0&&Ze&&!Re,et=De||$e&&!Se,tt=(0,y.useRef)(!1),nt=(0,y.useRef)(null);(0,y.useEffect)(()=>{tt.current&&nt.current?.focus({preventScroll:!0})},[Ze]);let rt=Dv(ne,z,L,g,v),[it,at]=(0,y.useState)(!1),[ot,st]=(0,y.useState)(``),[ct,lt]=(0,y.useState)(0);(0,y.useEffect)(()=>{(De||O===0)&<(O)},[De,O]);let ut=(0,y.useMemo)(()=>{let e=new Map(de.map(e=>[e.id,e]));return function({id:t,x:n,y:r,width:i,height:a,color:o,strokeColor:s,strokeWidth:c,className:l,selected:u,shapeRendering:d,onClick:f}){let p=e.get(t),m=`react-flow__minimap-node${l?` ${l}`:``}${u?` selected`:``}`;if(p?.type===`boundary`)return(0,x.jsx)(`g`,{className:m,"data-group-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:Sp({...p.data,size:{width:i,height:a}},p.data.appearance,n,r)}});if(!p)return(0,x.jsx)(`rect`,{className:m,x:n,y:r,width:i,height:a,rx:`14`,fill:o,stroke:s,strokeWidth:c,shapeRendering:d,onClick:f?e=>f(e,t):void 0});let h=eh(p.data,g,n,r,i,a,o,s,c);return(0,x.jsx)(`g`,{className:m,"data-node-id":t,shapeRendering:d,onClick:f?e=>f(e,t):void 0,dangerouslySetInnerHTML:{__html:h}})}},[g,de]);(0,y.useEffect)(()=>{if(!ge)return;st(h(ge.message));let e=window.setTimeout(()=>st(``),4500);return()=>window.clearTimeout(e)},[ge]);let dt=O>0&&!De&&(g!==`sequence`||O!==ct)&&!z.some(e=>e.dragging),ft=dt?z.find(e=>e.id===E&&e.type===`diagram`):null,pt=dt?fe.find(e=>e.id===D):null,mt=pt?L.edges.find(e=>e.id===pt.id):null,ht=pt?{position:pt.data.route.labelPoint,size:{width:0,height:0}}:null,gt=mt?L.nodes.find(e=>e.id===mt.source):null,_t=mt?L.nodes.find(e=>e.id===mt.target):null,vt=T?L.nodes.find(e=>e.id===T.source):null,yt=T?L.nodes.find(e=>e.id===T.target):null,bt=(e,t)=>(0,x.jsxs)(`button`,{onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(Kf[e.kind]??e.kind)})]},e.id),xt=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Details`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:()=>ee(!0),"aria-label":h(`Close details`),title:h(`Close details`),children:(0,x.jsx)(kv,{name:`close`})})]}),(0,x.jsx)(`section`,{className:`inspector-card drawer-body`,"data-node-id":w?.id,"data-edge-id":T?.id,children:w?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:Bf(w,_,i).stroke}}),h(Kf[w.kind]??w.kind),w.module?` · ${w.module}`:``]}),(0,x.jsx)(`h2`,{children:w.label}),(0,x.jsx)(`p`,{className:`drawer-subtitle`,children:w.subtitle}),w.badges?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Badges`)}),(0,x.jsx)(`ul`,{children:w.badges.map((e,t)=>(0,x.jsxs)(`li`,{children:[e.label,` · `,h(Wf[e.evidence]),e.source&&(0,x.jsx)(`code`,{className:`source-path`,children:Gf(e.source)})]},t))})]}),(e=>e.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Shared dependencies`)}),(0,x.jsx)(`ul`,{children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsxs)(`button`,{type:`button`,className:`folded-edge`,onClick:()=>P(e),children:[e.label??e.kind,` → `,L.nodes.find(t=>t.id===e.target)?.label]}),e.site&&(0,x.jsx)(`code`,{className:`source-path`,children:Gf(e.site)})]},e.id))})]}))(yf(L).filter(e=>e.source===w.id)),w.fields?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Fields`)}),(0,x.jsx)(`ul`,{children:w.fields.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`code`,{children:[e.key,` `,e.name,`: `,e.type,e.nullable===!1?` · NOT NULL`:e.nullable===!0?` · NULL`:``]})},e.name))})]}),w.attributes?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Attributes`)}),(0,x.jsx)(`ul`,{children:w.attributes.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.methods?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Methods`)}),(0,x.jsx)(`ul`,{children:w.methods.map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`code`,{children:e})},e))})]}),w.source&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`h3`,{children:[h(`Source`),` · `,h(Wf[w.source.kind??`source`]??w.source.kind)]}),(0,x.jsx)(`code`,{className:`source-path`,children:Gf(w.source)}),w.source.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:w.source.symbol})]}),w.tags?.length>0&&(0,x.jsx)(`div`,{className:`tags`,children:w.tags.map(e=>(0,x.jsx)(`span`,{children:e},e))})]}):T?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`node-kicker`,children:[(0,x.jsx)(`span`,{className:`node-dot`,style:{backgroundColor:fe.find(e=>e.id===T.id)?.style.stroke??_.edge}}),h(`Edges`),` · `,T.kind]}),(0,x.jsx)(`h2`,{children:(Wh(L).get(T.id)?.label??Dh(T,g,e.meta.locale))||T.kind}),(0,x.jsxs)(`p`,{className:`drawer-subtitle`,children:[vt?.label,` → `,yt?.label]}),(0,x.jsxs)(`h3`,{children:[h(`Evidence`),` · `,h(Wf[T.evidence]??T.evidence)]}),T.site&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`code`,{className:`source-path`,children:Gf(T.site)}),T.site.symbol&&(0,x.jsx)(`p`,{className:`symbol`,children:T.site.symbol})]}),T.facts?.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{children:h(`Evidence facts`)}),(0,x.jsx)(`ul`,{children:T.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]}):(0,x.jsxs)(`div`,{className:`drawer-empty`,children:[(0,x.jsx)(`span`,{className:`empty-icon`,children:(0,x.jsx)(kv,{name:`fit`})}),(0,x.jsx)(`span`,{children:h(`Start with a node`)}),(0,x.jsx)(`p`,{children:h(`Select a component or a list entry to explore its role, fields, methods and source.`)})]})}),(w||T)&&(0,x.jsx)(`section`,{className:`inspector-card`,children:(0,x.jsx)(`div`,{className:Ve.editing?``:`card-actions`,children:(0,x.jsx)(jv,{editor:Ve,relation:!!T,locked:I,locale:e.meta.locale})})}),w?.facts?.length>0&&(0,x.jsxs)(`section`,{className:`inspector-card inspector-facts`,"data-node-id":w.id,children:[(0,x.jsx)(`h3`,{children:w.source?h(`Evidence facts`):h(`Node notes`)}),(0,x.jsx)(`ul`,{children:w.facts.map(e=>(0,x.jsx)(`li`,{children:e},e))})]})]});return De&&(Be.current=xt),(0,x.jsxs)(`main`,{className:`app-shell`,"data-view-id":uf(e),children:[(0,x.jsxs)(`header`,{className:`toolbar`,children:[(0,x.jsxs)(`div`,{className:`tb-group tb-left`,children:[(0,x.jsx)(`button`,{className:`tb`,ref:Oe,onClick:()=>{Ne(),Ee||rt(E,D,!0,et)},"aria-controls":`graph-tools`,"aria-expanded":Ee,"aria-pressed":Ee,"aria-label":h(Ee?`Hide graph navigation`:`Show graph navigation`),title:h(Ee?`Hide graph navigation`:`Show graph navigation`),children:(0,x.jsx)(kv,{name:`panel-left`})}),(0,x.jsxs)(`div`,{className:`tb-title`,children:[(0,x.jsx)(`b`,{children:e.meta.title}),(0,x.jsxs)(`span`,{children:[h(pf(e)),` · `,e.meta.sourceRef]})]})]}),(0,x.jsx)(`div`,{className:`tb-group tb-center`,children:(0,x.jsxs)(`div`,{className:`tb-search`,"data-popover-root":`search`,onFocus:()=>at(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||at(!1)},onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),e.currentTarget.contains(document.activeElement)&&document.activeElement.blur())},children:[(0,x.jsx)(kv,{name:`search`}),(0,x.jsx)(`input`,{ref:Ae,id:`search`,value:k,onChange:e=>A(e.target.value),placeholder:h(`Search nodes`),"aria-label":h(`Search nodes`),autoComplete:`off`}),it&&j&&(0,x.jsxs)(`div`,{className:`popover results`,role:`listbox`,"aria-label":h(`Matches · {count}`,{count:M.length}),onMouseDown:e=>e.preventDefault(),children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Matches · {count}`,{count:M.length})}),M.length>0?M.map((e,t)=>(0,x.jsxs)(`button`,{role:`option`,"aria-selected":`false`,onClick:()=>N(e),children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`i`,{children:String(t+1).padStart(2,`0`)}),e.label]}),(0,x.jsx)(`small`,{children:e.subtitle??h(Kf[e.kind]??e.kind)})]},e.id)):(0,x.jsx)(`p`,{className:`pop-empty`,children:h(`No matches. Try a name or responsibility.`)})]})]})}),(0,x.jsxs)(`div`,{className:`tb-group tb-right`,children:[r.length>1&&(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`views`,children:[(0,x.jsxs)(`button`,{id:`view-menu-button`,className:`tb tb-wide`,onClick:()=>Ue(`views`),"aria-haspopup":`menu`,"aria-expanded":He===`views`,title:h(`Diagram types`),children:[(0,x.jsx)(kv,{name:`views`}),(0,x.jsx)(`span`,{children:h(pf(e))}),(0,x.jsx)(kv,{name:`chevron`})]}),He===`views`&&(0,x.jsx)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`view-menu-button`,children:r.map(t=>{Gm(t);let n=uf(t),i=n===uf(e);return(0,x.jsxs)(`button`,{"data-view-id":n,role:`menuitemradio`,"aria-checked":i,className:i?`is-current`:``,onClick:()=>{s(n,R),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:i?(0,x.jsx)(kv,{name:`check`}):null}),`${h(pf(t))}${r.filter(e=>ff(e)===ff(t)).length>1?` · ${t.meta.title}`:``}`,(0,x.jsx)(`small`,{children:h(`{count} relations`,{count:t.edges.length})})]},n)})})]}),(0,x.jsx)(`button`,{className:`tb tb-wash`,role:`switch`,"aria-checked":a,onClick:()=>o(e=>!e),title:h(`Card wash`),"aria-label":h(`Card wash`),children:(0,x.jsx)(kv,{name:`wash`})}),(0,x.jsxs)(`div`,{className:`menu-anchor`,"data-popover-root":`more`,children:[(0,x.jsx)(`button`,{id:`more-menu-button`,className:`tb`,onClick:()=>Ue(`more`),"aria-haspopup":`menu`,"aria-expanded":He===`more`,title:h(`More`),"aria-label":h(`More`),children:(0,x.jsx)(kv,{name:`more`})}),He===`more`&&(0,x.jsxs)(`div`,{className:`popover menu is-right`,role:`menu`,"aria-labelledby":`more-menu-button`,children:[(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ie,onClick:()=>{me(`svg`),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`download`})}),h(`Export SVG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ie,onClick:()=>{me(`png`),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`download`})}),h(`Export PNG`)]}),(0,x.jsxs)(`button`,{role:`menuitem`,disabled:ie,onClick:()=>{he(),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`download`})}),h(`Save changes`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`button`,{role:`menuitem`,onClick:()=>{pe(),We()},title:h(`Restore the original layout and view, and clear search and selection.`),children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`reset`})}),h(`Reset`)]}),(0,x.jsxs)(`div`,{className:`menu-row`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:I?`lock`:`unlock`})}),h(`Locked`)]}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":I,"aria-label":h(I?`Locked`:`Draggable`),onClick:()=>te(e=>!e),children:(0,x.jsx)(`i`,{})})]}),(0,x.jsxs)(`button`,{role:`menuitem`,"aria-disabled":I,title:h(I?`Unlock the layout first`:E?`Space the selected node and its direct neighbors`:`Space all nodes`),onClick:()=>{ue(),We()},children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:`spacing`})}),h(`Arrange`)]}),(0,x.jsx)(`div`,{className:`menu-sep`}),(0,x.jsxs)(`div`,{className:`menu-row menu-row-stack`,children:[(0,x.jsxs)(`span`,{className:`menu-lead`,children:[(0,x.jsx)(`span`,{className:`menu-mark`,children:(0,x.jsx)(kv,{name:c===`light`?`sun`:`moon`})}),h(`Appearance`)]}),(0,x.jsxs)(`div`,{className:`seg`,role:`radiogroup`,"aria-label":h(`Appearance`),style:{"--seg-n":Iv.length},children:[(0,x.jsx)(`span`,{className:`seg-knob`,"aria-hidden":`true`,style:{transform:`translateX(${Iv.indexOf(l)*100}%)`}}),Iv.map(e=>(0,x.jsx)(`button`,{role:`radio`,"aria-checked":l===e,onClick:()=>u(e),children:h(Lv[e])},e))]})]})]})]}),(0,x.jsx)(`button`,{className:`tb`,ref:ke,onClick:()=>{Pe(),De||rt(E,D,Ee,!0)},"aria-controls":`node-inspector`,"aria-expanded":De,"aria-pressed":De,title:h(De?`Hide details`:`Show details`),"aria-label":h(De?`Hide details`:`Show details`),children:(0,x.jsx)(kv,{name:`panel-right`})})]})]}),(0,x.jsxs)(`section`,{className:`workspace ${Ee?`nav-open`:``} ${De?`drawer-open`:``}`,children:[Ie&&(0,x.jsxs)(`aside`,{id:`graph-tools`,ref:Me,tabIndex:-1,className:`sidebar nav${Le}`,"aria-label":h(`Graph navigation`),children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Graph navigation`)}),(0,x.jsx)(`button`,{className:`side-close`,onClick:Ne,"aria-label":h(`Close`),title:h(`Close`),children:(0,x.jsx)(kv,{name:`close`})})]}),(0,x.jsxs)(`div`,{className:`project-summary`,children:[(0,x.jsx)(`p`,{className:`panel-title`,children:h(`Overview`)}),e.meta.scope&&(0,x.jsx)(`p`,{children:e.meta.scope}),(0,x.jsxs)(`div`,{className:`stat-grid`,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.nodes.length}),h(`Nodes`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.edges.length}),h(`Edges`)]}),(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:e.groups?.length??0}),h(`Groups`)]})]})]}),(0,x.jsx)(`p`,{className:`result-heading`,children:h(`Nodes · {count}`,{count:e.nodes.length})}),(0,x.jsx)(`div`,{className:`search-results`,children:L.nodes.map(bt)})]}),(0,x.jsxs)(`figure`,{ref:be,className:`board diagram-board`,children:[(0,x.jsxs)(`svg`,{className:`relation-defs`,width:`0`,height:`0`,"aria-hidden":`true`,children:[(0,x.jsx)(`style`,{children:zp(_,`:is(.node-visual,.fragment-visual,.fragment-text) `)}),(0,x.jsxs)(`defs`,{children:[(0,x.jsx)(`filter`,{id:`node-shadow`,x:`-20%`,y:`-20%`,width:`140%`,height:`150%`,children:(0,x.jsx)(`feDropShadow`,{dx:`0`,dy:`5`,stdDeviation:`7`,floodColor:_.ink,floodOpacity:`.045`})}),(0,x.jsx)(`marker`,{id:`codegraph-arrow-open`,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`7`,markerHeight:`7`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L9 5L1 9`,fill:`none`,stroke:`context-stroke`,strokeWidth:`1.5`})}),(0,x.jsx)(`marker`,{id:`codegraph-triangle`,viewBox:`0 0 12 12`,refX:`11`,refY:`6`,markerWidth:`9`,markerHeight:`9`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 1L11 6L1 11Z`,fill:`var(--canvas)`,stroke:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-filled`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`context-stroke`})}),(0,x.jsx)(`marker`,{id:`codegraph-diamond-open`,viewBox:`0 0 14 10`,refX:`1`,refY:`5`,markerWidth:`12`,markerHeight:`10`,orient:`auto`,children:(0,x.jsx)(`path`,{d:`M1 5L7 1L13 5L7 9Z`,fill:`var(--canvas)`,stroke:`context-stroke`})})]})]}),(0,x.jsxs)(`div`,{ref:ne,"aria-busy":ie,className:`canvas`,style:{"--sequence-flow-unit":`${Math.max(1,.6/p)}px`},"data-nav-open":Ee,"data-drawer-open":et,onKeyDownCapture:F,"aria-label":h(`Interactive {type}`,{type:h(pf(e))}),children:[(0,x.jsxs)(Sd,{nodeExtent:[[0,0],[1/0,1/0]],nodes:de,edges:fe,nodeTypes:gg,edgeTypes:_g,onNodesChange:B,onNodeDragStop:re,onPaneClick:()=>{ee(),We()},onNodeClick:(e,t)=>{t.type===`diagram`&&N(t,!1)},onEdgeClick:(e,t)=>P(t.data),onNodeDragStart:(e,t)=>{t.type===`diagram`&&N(t,!1)},onInit:()=>requestAnimationFrame(()=>ce(L,0)),nodesDraggable:!I&&!ie,nodesConnectable:!1,deleteKeyCode:null,elementsSelectable:!0,minZoom:.08,maxZoom:2,colorMode:c,ariaLabelConfig:{"controls.zoomIn.ariaLabel":h(`Zoom in`),"controls.zoomOut.ariaLabel":h(`Zoom out`),"minimap.ariaLabel":h(`Minimap`)},proOptions:{hideAttribution:!0},children:[(0,x.jsxs)(Hd,{position:`bottom-left`,showInteractive:!1,showFitView:!1,children:[(0,x.jsx)(zd,{className:`react-flow__controls-fitview`,onClick:le,title:h(`Fit canvas`),"aria-label":h(`Fit canvas`),children:(0,x.jsx)(kv,{name:`fit`})}),(0,x.jsx)(zd,{className:`react-flow__controls-fullscreen`,ref:xe,onClick:Te,"aria-pressed":Se,"aria-busy":Ce,"aria-disabled":Ce||!we&&!Se,"aria-label":h(Se?`Exit fullscreen`:`Enter fullscreen`),title:h(!we&&!Se?`Fullscreen is not available in this browser or page`:Se?`Exit fullscreen (Esc)`:`Enter fullscreen`),children:(0,x.jsx)(kv,{name:Se?`collapse`:`expand`})})]}),(0,x.jsx)(of,{pannable:!0,zoomable:!0,onClick:(e,t)=>m(t.x,t.y,{zoom:p}),nodeComponent:ut,nodeStrokeColor:e=>e.type===`boundary`?`none`:Bf(e.data,_,i).stroke,nodeStrokeWidth:2,nodeColor:e=>e.type===`boundary`?e.data.appearance.fill:Bf(e.data,_,i).fill,maskColor:_.mask})]}),(0,x.jsxs)(`div`,{className:`float legend-anchor`,"data-popover-root":`legend`,children:[(0,x.jsxs)(`button`,{className:`float-btn`,onClick:()=>Ue(`legend`),"aria-expanded":He===`legend`,"aria-haspopup":`true`,title:h(`Legend`),children:[(0,x.jsx)(kv,{name:`legend`}),(0,x.jsx)(`span`,{children:h(`Legend`)})]}),He===`legend`&&(0,x.jsxs)(`div`,{className:`popover legend-pop`,children:[(0,x.jsx)(`p`,{className:`pop-title`,children:h(`Legend`)}),(0,x.jsx)(`div`,{className:`legend`,role:`group`,"aria-label":h(`Legend`),children:Sg(L,_,i).map(e=>(0,x.jsxs)(`span`,{"data-legend-role":e.role,"data-legend-shape":e.shape,children:[e.shape===`ramp`?(0,x.jsx)(`i`,{className:`legend-ramp`,style:{backgroundColor:e.fill,borderColor:e.stroke,backgroundImage:xg(e.ramp)}}):e.shape===`self`?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M5 3C22 0 22 13 6 11`,fill:`none`,stroke:`currentColor`}),(0,x.jsx)(`path`,{d:`M10 8L5.5 11L10.5 13.4`,fill:`none`,stroke:`currentColor`})]}):[`sync`,`async`,`return`].includes(e.shape)?(0,x.jsxs)(`svg`,{style:{color:e.stroke},width:`28`,height:`14`,viewBox:`0 0 28 14`,"aria-hidden":`true`,children:[(0,x.jsx)(`path`,{d:`M1 7H25`,stroke:`currentColor`,strokeDasharray:e.shape===`return`?`4 3`:void 0}),(0,x.jsx)(`path`,{d:e.shape===`sync`?`M19 2L26 7L19 12Z`:`M19 2L26 7L19 12`,fill:e.shape===`sync`?`currentColor`:`none`,stroke:`currentColor`})]}):(0,x.jsx)(`i`,{className:`legend-${e.shape}`,style:{backgroundColor:e.fill??`transparent`,borderColor:e.stroke,color:e.stroke,"--legend-body":_.surface2}}),e.label]},e.id))}),b&&(0,x.jsxs)(`div`,{className:`pop-opt`,children:[(0,x.jsx)(`span`,{children:h(`Edge animation`)}),(0,x.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":S,disabled:!!v,onClick:()=>C(e=>!e),"aria-label":h(`Edge animation`),children:(0,x.jsx)(`i`,{})})]}),v&&(0,x.jsx)(`p`,{className:`pop-note`,children:h(`System reduced-motion preference is respected`)})]})]}),Ye.count>0&&!Re&&($e?(0,x.jsxs)(`section`,{className:`float notes-anchor notes-card`,"aria-label":Ye.title,children:[(0,x.jsxs)(`div`,{className:`side-head`,children:[(0,x.jsxs)(`p`,{className:`panel-title`,children:[Ye.title,` · `,Ye.count]}),(0,x.jsx)(`button`,{className:`side-close`,ref:nt,onClick:()=>{tt.current=!0,Qe(!1)},"aria-label":Ye.hide,title:Ye.hide,children:(0,x.jsx)(kv,{name:`close`})})]}),Ge.length>0&&(0,x.jsx)(`ul`,{children:Ge.map((e,t)=>(0,x.jsx)(`li`,{children:e},t))}),Ke.length>0&&(0,x.jsxs)(x.Fragment,{children:[Ge.length>0&&(0,x.jsxs)(`p`,{className:`panel-title source-changes-title`,children:[h(`Source changes`),` · `,Ke.length]}),(0,x.jsx)(`ul`,{className:`source-changes`,children:Ke.map((e,t)=>(0,x.jsxs)(`li`,{children:[(0,x.jsxs)(`code`,{children:[String(e?.file??``).split(`/`).pop(),`:`,e?.line]}),` `,e?.change,(e?.elements??[]).map(Xe),(e?.removed?.length>0||e?.added?.length>0)&&(0,x.jsx)(`pre`,{children:[...(e.removed??[]).slice(0,3).map(e=>`- ${e}`),...(e.added??[]).slice(0,3).map(e=>`+ ${e}`)].join(` +`)})]},t))})]}),Je>0&&(0,x.jsxs)(x.Fragment,{children:[(Ge.length>0||Ke.length>0)&&(0,x.jsxs)(`p`,{className:`panel-title source-changes-title`,children:[h(`This update`),` · `,Je]}),(0,x.jsxs)(`ul`,{className:`graph-update`,children:[qe.added.length>0&&(0,x.jsxs)(`li`,{className:`update-added`,children:[h(`Added`),` · `,qe.added.length,qe.added.map(Xe)]}),qe.changed.length>0&&(0,x.jsxs)(`li`,{className:`update-changed`,children:[h(`Changed`),` · `,qe.changed.length,qe.changed.map(Xe)]}),qe.removed.length>0&&(0,x.jsxs)(`li`,{className:`update-removed`,children:[h(`Removed`),` · `,qe.removed.length,qe.removed.map(e=>(0,x.jsx)(`s`,{children:e.label},e.id))]}),qe.meta&&(0,x.jsx)(`li`,{children:h(`View notes updated`)})]})]})]}):(0,x.jsxs)(`button`,{className:`float notes-anchor float-btn`,ref:nt,"aria-expanded":`false`,onClick:()=>{tt.current=!0,Qe(!0),Se||rt(E,D,Ee,!0)},"aria-label":Ye.show,title:Ye.show,children:[(0,x.jsx)(kv,{name:`notes`}),(0,x.jsxs)(`span`,{children:[Ye.title,` · `,Ye.count]})]})),ft&&(0,x.jsx)(Fv,{node:{...ft.data,position:ft.position},others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:Ve,graph:L,isFullscreen:Se,onDetails:async()=>{Se&&!await Te()||(Fe(),rt(E,D,Ee,!0))},onClose:()=>ee()}),mt&&(0,x.jsx)(Fv,{node:ht,edge:{...mt,diagramType:g},source:gt,target:_t,others:z,canvasRef:ne,palette:_,moduleColors:i,locale:e.meta.locale,locked:I,editor:Ve,graph:L,isFullscreen:Se,onDetails:async()=>{Se&&!await Te()||(Fe(),rt(E,D,Ee,!0))},onClose:()=>ee()}),!_e&&ve.length>0&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout suggestions`)}),(0,x.jsx)(`p`,{children:h(`Arrange this view to improve connector clearance and spacing. Existing positions are preserved until then.`)}),(0,x.jsx)(`ul`,{children:[...new Set(ve.flatMap(e=>e.elementIds).filter(e=>L.edges.some(t=>t.id===e)))].map(e=>(0,x.jsx)(`li`,{children:(0,x.jsx)(`button`,{onClick:()=>ye(ve.find(t=>t.elementIds.includes(e))),children:L.edges.find(t=>t.id===e)?.label||h(`Relationship`)})},e))})]}),_e&&(0,x.jsxs)(`details`,{className:`layout-problems`,children:[(0,x.jsx)(`summary`,{children:h(`Layout needs adjustment; JSON drafts can still be saved`)}),(0,x.jsx)(`ul`,{children:_e.diagnostics.filter(e=>e.severity===`error`).map((e,t)=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{onClick:()=>ye(e),children:[e.elementIds.join(`, `),` · `,e.ruleId]})},t))}),(0,x.jsx)(`pre`,{children:_e.message})]}),(0,x.jsx)(`div`,{className:`toast ${ot?`is-on`:``}`,role:`status`,"aria-live":`polite`,children:ot})]})]}),Re&&(0,x.jsx)(`aside`,{id:`node-inspector`,ref:je,tabIndex:-1,className:`sidebar drawer inspector${w||T?` is-open`:``}${ze}`,"aria-label":h(`Details`),children:Be.current})]})]})}function Bv(){let[e,t]=(0,y.useState)(!1),[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(null),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(null),c=(0,y.useRef)(null),l=(0,y.useRef)(null),u=(0,y.useCallback)(()=>cancelAnimationFrame(l.current),[]),d=(0,y.useCallback)(e=>{u();let t=document.activeElement;l.current=requestAnimationFrame(()=>{(document.activeElement===t||!t?.isConnected)&&e.current?.focus({preventScroll:!0})})},[u]);return(0,y.useEffect)(()=>u,[u]),{toolbarOpen:e,drawerOpen:n,toolbarButtonRef:i,drawerButtonRef:a,searchInputRef:o,inspectorRef:s,panelRef:c,openDetails:(0,y.useCallback)(()=>{r(!0),d(s)},[d]),closeDetails:(0,y.useCallback)((e=!1)=>{u(),r(!1),e&&d(a)},[u,d]),closeNav:(0,y.useCallback)((e=!1)=>{u(),t(!1),e&&d(i)},[u,d]),toggleToolbar:()=>{u(),t(!e),e||d(c)},toggleDrawer:()=>{u(),r(!n),n||d(s)}}}var Vv=JSON.parse(document.querySelector(`#graph-data`).textContent);sg(JSON.parse(document.querySelector(`#graph-compare`)?.textContent??`null`));var Hv=[...Array.isArray(Vv.diagrams)?Vv.diagrams:[Vv]].sort(mf),Uv=window.matchMedia(`(prefers-color-scheme: dark)`);function Wv(){let[e,t]=(0,y.useState)(`system`),[n,r]=(0,y.useState)(Uv.matches);return(0,y.useEffect)(()=>{let e=e=>r(e.matches);return Uv.addEventListener(`change`,e),()=>Uv.removeEventListener(`change`,e)},[]),{preference:e,setPreference:t,theme:e===`system`?n?`dark`:`light`:e}}function Gv(){let[e,t]=(0,y.useState)(uf(Hv[0])),n=(0,y.useRef)(new Map),r=(0,y.useState)(!0),{preference:i,setPreference:a,theme:o}=Wv(),s=Bv(),c=Hv.find(t=>uf(t)===e)??Hv[0],l=n.current.get(e)??c,u=(r,i)=>{n.current.set(e,i),t(r)},d=e=>ev(Vv,n.current,e),[f,p]=(0,y.useState)(!0),m=(0,y.useMemo)(()=>{let e=Ff(Hv,Of[o]);return f?e:Lf(e,Of[o])},[o,f]);return(0,y.useEffect)(()=>{document.documentElement.lang=l.meta.locale??`zh-CN`},[l.meta.locale]),(0,y.useEffect)(()=>{document.title=`${l.meta.title} · QGraphFlow`},[l.meta.title]),(0,y.useEffect)(()=>{document.documentElement.dataset.theme=o,document.documentElement.dataset.appearance=i;for(let[e,t]of Object.entries(Uf(Of[o])))document.documentElement.style.setProperty(e,t)},[o,i]),(0,x.jsx)(vd,{children:(0,x.jsx)(zv,{flowControl:r,graph:l,originalGraph:c,graphForSave:d,allDiagrams:Hv,moduleColors:m,wash:f,setWash:p,onDiagramChange:u,theme:o,appearance:i,setAppearance:a,panels:s},e)})}(0,b.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(Gv,{})); + diff --git a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx index 00211e3..0797c30 100644 --- a/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx +++ b/skills/q-flow/assets/viewer/src/DiagramCanvas.jsx @@ -1,7 +1,6 @@ -import { visibleEdges } from './presentation-graph.js'; -import { overviewSections, sectionSvg } from './architecture-overview.js'; +import { presentationGraph, visibleEdges } from './presentation-graph.js'; import React, { useId } from 'react'; -import { BaseEdge, EdgeLabelRenderer, Handle, MarkerType, Position } from '@xyflow/react'; +import { BaseEdge, EdgeLabelRenderer, Handle, MarkerType, Position, useStore } from '@xyflow/react'; import SelectionOutline from './SelectionOutline.jsx'; import { renderNode } from './node-svg.js'; import { compactCards, getDiagram, hasArrow, edgeMarkers } from './diagrams/registry.js'; @@ -9,6 +8,8 @@ import { cardinalityMarks } from './edge-routing.js'; import { renderFragment, fragmentDepth } from './sequence-fragments.js'; import { isCore, TYPOGRAPHY } from './visual-style.js'; import { groupHeadingSvg, groupFrameSvg } from './diagrams/drawing.js'; +import { driftedElements } from './source-changes.js'; +import { comparisonOf } from './graph-diff.js'; function NodeHandles({ sequence = false }) { if (sequence) return <> @@ -27,10 +28,14 @@ function NodeHandles({ sequence = false }) { ; } +// Cards whose body text would read under 10px on screen draw only their name, enlarged (diagrams/card.js summaryCard). +// The boolean subscription redraws a card only when zoom crosses that point, not on every zoom step. +const SUMMARY_TYPES = new Set(['architecture', 'deployment']); function DiagramNode({ data, selected }) { const moduleColor = data.moduleColors?.get(data.module); - const markup = renderNode({ ...data, position: { x: 0, y: 0 } }, data.diagramType, 0, 0, data.palette, data.locale, data.moduleColors); - return
+ const summary = useStore(state => SUMMARY_TYPES.has(data.diagramType) && state.transform[2] * TYPOGRAPHY.body < 10); + const markup = renderNode({ ...data, summary, position: { x: 0, y: 0 } }, data.diagramType, 0, 0, data.palette, data.locale, data.moduleColors); + return
{selected && } @@ -79,16 +84,19 @@ function RoutedEdge({ id, markerEnd, style, data }) { {label.label} )} - {route.label && } + {route.label && } ; } -function OverviewSection({ data }) { - return
; -} -export const nodeTypes = { diagram: DiagramNode, boundary: BoundaryNode, overview: OverviewSection }; +export const nodeTypes = { diagram: DiagramNode, boundary: BoundaryNode }; export const edgeTypes = { routed: RoutedEdge }; +// generate-viewer --compare: 'added' or 'changed' for an element of this view, else undefined. +function diffOf(graph) { + const compared = comparisonOf(graph); + return id => compared?.added.includes(id) ? 'added' : compared?.changed.includes(id) ? 'changed' : undefined; +} + export function initialNodes(graph, diagramType) { const boundaries = [...(graph.groups ?? [])].sort((a, b) => fragmentDepth(a, graph.groups ?? []) - fragmentDepth(b, graph.groups ?? [])).map(group => ({ id: group.id, @@ -101,19 +109,20 @@ export function initialNodes(graph, diagramType) { connectable: false, zIndex: -(graph.groups?.length ?? 0) + fragmentDepth(group, graph.groups ?? []) })); - const classicCard = !compactCards(graph); - return [...overviewSections(graph).map((section, index) => ({ id: section.id, type: 'overview', position: section.position, data: { ...section }, style: { width: section.size.width, height: section.size.height, pointerEvents: 'none' }, draggable: false, selectable: false, zIndex: -100 + index })), ...boundaries, ...graph.nodes.map(node => ({ + const classicCard = !compactCards(graph), drawn = new Map(presentationGraph(graph).nodes.map(node => [node.id, node])), drifted = driftedElements(graph), diff = diffOf(graph); + return [...boundaries, ...graph.nodes.map(node => ({ id: node.id, type: 'diagram', className: diagramType === 'sequence' ? 'sequence-column' : undefined, position: node.position, - data: { ...node, diagramType, locale: graph.meta.locale, classicCard }, + data: { ...drawn.get(node.id), diagramType, locale: graph.meta.locale, classicCard, drifted: drifted.has(node.id), diff: diff(node.id) }, style: { width: node.size.width, height: node.size.height, ...(diagramType === 'sequence' ? { pointerEvents: 'none' } : {}) }, zIndex: 2 }))]; } export function initialEdges(graph, diagramType) { + const drifted = driftedElements(graph), diff = diffOf(graph); return visibleEdges(graph).map(edge => ({ id: edge.id, source: edge.source, @@ -121,6 +130,6 @@ export function initialEdges(graph, diagramType) { type: 'routed', zIndex: diagramType === 'sequence' ? 3 : 0, markerEnd: hasArrow(edge, diagramType) ? { type: MarkerType.ArrowClosed } : undefined, - data: { ...edge, diagramType } + data: { ...edge, diagramType, drifted: drifted.has(edge.id), diff: diff(edge.id) } })); } diff --git a/skills/q-flow/assets/viewer/src/TextEditor.jsx b/skills/q-flow/assets/viewer/src/TextEditor.jsx index 1650235..1d2c704 100644 --- a/skills/q-flow/assets/viewer/src/TextEditor.jsx +++ b/skills/q-flow/assets/viewer/src/TextEditor.jsx @@ -2,22 +2,20 @@ import React, { useEffect, useRef, useState } from 'react'; import { evidenceLabels } from './visual-style.js'; import { translate } from './i18n.js'; -export function useTextEditor(node, edge, onSaveNode, onSaveEdge, locale, overviewView = false, onCancel = () => {}) { +export function useTextEditor(node, edge, onSaveNode, onSaveEdge, locale, onCancel = () => {}) { const object = edge ?? node, key = object ? `${edge ? 'edge' : 'node'}:${object.id}` : null; - const overview = Boolean(node && (overviewView || node.section || node.overviewText !== undefined || node.badges !== undefined)); const saveToken = useRef(0); - const [draft, setDraft] = useState({ editing: false, pending: false, label: '', subtitle: '', overviewText: '', badges: [], error: '' }); - const reset = (returnFocus = false) => setDraft({ editing: false, pending: false, label: object?.label ?? '', subtitle: node?.subtitle ?? '', overviewText: (node?.overviewText ?? []).join('\n'), badges: structuredClone(node?.badges ?? []), error: '', returnFocus }); + const [draft, setDraft] = useState({ editing: false, pending: false, label: '', subtitle: '', error: '' }); + const reset = (returnFocus = false) => setDraft({ editing: false, pending: false, label: object?.label ?? '', subtitle: node?.subtitle ?? '', error: '', returnFocus }); useEffect(() => { saveToken.current++; onCancel(); reset(); }, [key]); const set = patch => setDraft(current => ({ ...current, ...patch })); - return { ...draft, section: Boolean(node?.section), overview, set, cancel: () => { saveToken.current++; onCancel(); reset(true); }, begin: () => set({ editing: true, returnFocus: false, label: object?.label ?? '', subtitle: node?.subtitle ?? '', overviewText: (node?.overviewText ?? []).join('\n'), badges: structuredClone(node?.badges ?? []), error: '' }), save: async event => { + return { ...draft, set, cancel: () => { saveToken.current++; onCancel(); reset(true); }, begin: () => set({ editing: true, returnFocus: false, label: object?.label ?? '', subtitle: node?.subtitle ?? '', error: '' }), save: async event => { event.preventDefault(); if (draft.pending) return; const label = draft.label.trim(); if (!label) { set({ error: translate(locale, 'Name is required') }); return; } - if (draft.badges.some(badge => !badge.label.trim())) { set({ error: translate(locale, 'Name is required') }); return; } const token = ++saveToken.current; set({ pending: true }); - const error = await (edge ? onSaveEdge(edge.id, label) : onSaveNode(node.id, label, draft.subtitle.trim(), overview ? { overviewText: draft.overviewText.split(/\r?\n/).map(line => line.trim()).filter(Boolean), ...(node.section ? {} : { badges: draft.badges }) } : {})); + const error = await (edge ? onSaveEdge(edge.id, label) : onSaveNode(node.id, label, draft.subtitle.trim())); if (saveToken.current !== token) return; set({ pending: false }); if (error) { set({ error }); return; } @@ -36,9 +34,7 @@ export default function TextEditor({ editor, relation, locked, locale }) { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); editor.cancel(); } }}> - {!relation && !editor.section &&