feat(cli,playground,docs,generators): Export LikeC4 views to Draw.io#12
feat(cli,playground,docs,generators): Export LikeC4 views to Draw.io#12
Conversation
…e exitCode, basename, arcSize, parse DRY, useDot flags, json empty guard - Changesets: export-only scope; remove import wording from release notes - DrawioContextMenuProvider: memoize api with useMemo(..., [actions.openMenu]) - LanguageClientSync: use LayoutView.req for type-safe sendRequest (no cast) - e2e likec4-cli-export-drawio: assert exitCode === 1 on empty workspace - config/filenames: basename strip trailing slashes, empty fallback - generate-drawio: arcSize=12 (percent integer) for rounded corners - parse-drawio: buildCommonDiagramStateFromCells shared by buildSingleDiagramState/buildDiagramState - drawio handler: useDot from args for graphviz (binary vs wasm) - json handler: useDot from args; guard when projectsModels.length === 0 Co-authored-by: Cursor <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Implementado: - generate-drawio.spec: flag g no replace de modified para multi-diagrama - png handler: remover eslint-disable; output/projects const; seq/flat sem boolean redundante - worker.ts (browser): remover ramo morto typeof err === 'object' - e2e likec4-cli: limpar outDir com rmSync antes do export (evitar falsos positivos) - drawio-playground.spec: readFile (fs/promises) em vez de readFileSync - monaco index: re-exportar MonacoEditorProps de MonacoEditor; remover comentário - MonacoEditor: setLayoutedModelApi como prop direta - LanguageClientSync: layoutViews em paralelo com Promise.all - useDrawioContextMenuActions: usar DrawioViewModelLike; Object.values sem ?? []; anchor append/remove no download - generate-drawio.ts: remover variáveis não usadas; titleInner só no ramo navTo !== '' - parse-drawio: linkLine em vez de line (shadowing); i+=1 antes de continue nos blocos STROKE_COLOR/WIDTH/WAYPOINTS - cli index: exitWithFailure(err, prefix) reutilizado em unhandledRejection - playwright.playground.config: reporter CI (github, list, html) - README playground: título da secção troubleshooting mais claro - parse-drawio.spec: describe(parseDrawioToLikeC4), parseDrawioToLikeC4Multi, parseDrawioRoundtripComments, decompressDrawioDiagram) Não implementado (e porquê): - Pin ubuntu-24.04 nos workflows: decisão de repo/CI; pode divergir do main; baixa prioridade. - ExtendedNode type alias em generate-drawio.ts: refactor maior em vários acessores; deixa-se para PR dedicado. - Cache do RegExp em getAttr (parse-drawio): impacto negligível; reviewer disse "consider caching if profiling identifies"; otimização prematura. - Union discriminada canExportAllViews/onExportAllViews: alteração de tipos mais invasiva; consumidor atual já emparelha corretamente. - Comentários "outside diff range": não aplicáveis inline neste commit. Co-authored-by: Cursor <[email protected]>
…erate-drawio - workflows: runs-on ubuntu-latest -> ubuntu-24.04 for reproducible CI - generate-drawio: ExtendedNode type alias for optional node fields; accessors use single cast Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
…equest, exactOptionalPropertyTypes) Co-authored-by: Cursor <[email protected]>
📝 WalkthroughWalkthroughRescopes Draw.io work to export-only; removes an implementation-plan changeset; migrates CI runners to Ubuntu 24.04; introduces DrawioViewModelLike and related refactors across generators and playground; adds CLI Changes
Sequence Diagram(s)(No sequence diagrams generated.) Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
⚔️ Resolve merge conflicts (beta)
No actionable comments were generated in the recent review. 🎉 Comment |
…ypecheck Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/generators/src/drawio/parse-drawio.ts (1)
1274-1352:⚠️ Potential issue | 🟡 MinorGuard empty diagram names to avoid
view elementIDs.Line 1315 uses
toId(diagramName). If a diagram hasname="",toIdreturnselement, so the view id becomeselementinstead of a sensible default likeindex/diagram_n. Suggest treating blank names as missing.Suggested fix
- const viewId = toId(diagramName) || 'index' + const safeName = diagramName?.trim() ? diagramName : 'index' + const viewId = toId(safeName) || 'index'
🧹 Nitpick comments (5)
apps/playground/README.md (1)
25-25: Documentation improvement looks good!The updated heading with a specific error message example helps users identify LSP connection issues more quickly.
For slightly better readability, consider using single quotes for the inner error message example to avoid nested double quotes:
-### LSP connection errors (e.g. "Client likec4: connection to server is erroring") +### LSP connection errors (e.g. 'Client likec4: connection to server is erroring')e2e/tests/drawio-playground.spec.ts (1)
68-69: Consider moving the import to the top of the file.The dynamic import of
node:fs/promisesinside the test function adds unnecessary overhead on each test run. Since this is a Node.js test environment, a static import at the top of the file would be cleaner and more performant.♻️ Proposed refactor
Add at the top of the file:
import { readFile } from 'node:fs/promises'Then simplify the test:
- const { readFile } = await import('node:fs/promises') - const content = await readFile(path!, 'utf8') + const content = await readFile(path!, 'utf8').changeset/drawio-import-postpack.md (1)
10-10: Improve capitalization and clarity.The phrase "export drawio" has inconsistent capitalization and could be clearer. Consider revising to "export to Draw.io" or "export Draw.io format" to match the capitalization used in line 8 and improve readability.
📝 Suggested improvement
-- **Draw.io export:** Generators and CLI export drawio (this PR is export-only; import will be proposed in a separate PR). +- **Draw.io export:** Generators and CLI export to Draw.io (this PR is export-only; import will be proposed in a separate PR)..changeset/drawio-implementation-plan.md (1)
8-8: Clarify "re-export from Playground/CLI" phrasing.The phrase "re-export from Playground/CLI" at the end of the Export description is somewhat ambiguous. Does this mean the round-trip comment parsing functionality is exported by the generators and then used/re-exported by Playground/CLI, or that these components implement the parsing themselves? Consider rephrasing for clarity, e.g., "used by Playground/CLI for round-trip export" or "with round-trip support in Playground/CLI".
packages/generators/src/drawio/generate-drawio.spec.ts (1)
83-92: Handle<diagram>tags without attributes in snapshot normalization.Line 92 requires a space + attributes, so
<diagram>with no attributes won’t be normalized. If the generator ever emits attribute-less tags, snapshots could reintroduce layout-dependent diffs. Consider making the attributes optional.Proposed tweak
- .replace(/<diagram ([^>]*)>[\s\S]*?<\/diagram>/g, '<diagram $1>LAYOUT</diagram>') + .replace(/<diagram\b([^>]*)>[\s\S]*?<\/diagram>/g, '<diagram$1>LAYOUT</diagram>')
… e2e import, changesets, snapshot regex) Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
feat(cli,playground,docs,generators): Export LikeC4 views to Draw.io
Summary
This PR adds export of LikeC4 views to Draw.io (
.drawio) format from the CLI (likec4 export drawio) and the Playground (right-click on diagram → DrawIO → Export view / Export all). It does not include import; import will be proposed in a separate PR.Context for maintainers: This work was first submitted in PR #2614, which received substantial review feedback focused on clean code, structure, and maintainability. We took that feedback seriously and ran a deliberate refactor pass (Uncle Bob / Clean Code) over the DrawIO-related code. This PR re-submits the same feature set with a cleaner, refactored codebase that we believe is easier to review and maintain. We’re grateful for the earlier review and have aimed to address those concerns in this iteration.
What’s in this PR
1. Generators (
@likec4/generators)computeDiagramLayoutsplit into smaller helpers;getViewDescriptionStringextracted;buildNodeCellXml/buildEdgeCellXmland constants (SOLID/DRY/KISS); exported typeDrawioViewModelLike.parseDrawioToLikeC4Multisplit intomergeDiagramStatesIntoMaps,buildRootsFromFqnToCell,emitMultiDiagramModel(orchestrator ~50–60 lines);buildViewBlockLines/escapeLikec4Quotes; O(n²) deduplication replaced withparsedIdsSet; UserObjectfullTagusesinnerXmlso sibling<data>is preserved.generate-drawio.spec.ts,parse-drawio.spec.ts; snapshots in__snapshots__/. Decompress error assertion accepts (base64 decode|inflate|URI decode) for Node/env behavior; snapshots updated for CI.2. CLI (
@likec4/likec4)likec4 export drawiowith--outdir/-o,--all-in-one,--roundtrip,--uncompressed,--project,--use-dot. UsesDEFAULT_DRAWIO_ALL_FILENAMEfrom@likec4/generators(DRY). Phase comments and thin handler pattern aligned with other export commands.PngExportArgs,runExportPng(args, logger); PNG export supports--outdir/-o(docs updated).likec4 import drawioin this PR (nopackages/likec4/src/cli/import/).3. Playground
generateDrawio/generateDrawioMultiandparseDrawioRoundtripComments. No Import menu item or file input.4. Documentation
--outdir; no Import section.5. E2E & tests
playwright.playground.config.ts.drawio-demo-export-import.spec.ts,drawio-tutorial-export-import.spec.ts— export tests; import/round-trip tests skipped in this PR.What’s not in this PR
likec4 import drawiocommand.Refactor summary (response to PR likec4#2614 feedback)
After the initial submission (PR likec4#2614), we applied a structured clean-code pass:
DrawioViewModelLike); constants; phase comments; DRY (e.g.DEFAULT_DRAWIO_ALL_FILENAME, shared helpers).runExport*(args, logger)pattern for drawio/PNG/JSON; consistent error handling and JSDoc.e2e/helpers/.We believe this version is in better shape for review and long-term maintenance.
Correções após review (PR #11)
Incorporadas as sugestões do review anterior:
apimemoizado comuseMemo(..., [actions.openMenu])para evitar re-renders desnecessários.LayoutView.reqemsendRequest(type-safe; removido cast manual).exitCode === 1no erro rejeitado.basenameremove barras finais (/e\) e trata resultado vazio com fallback.arcSize=12(inteiro percentagem) em vez de0.12para cantos ligeiramente arredondados no Draw.io.buildCommonDiagramStateFromCells;buildSingleDiagramStateebuildDiagramStatereutilizam (DRY).useDotlido dos args e passado arunExportDrawio; graphvizbinaryvswasmconforme flag--use-dot.useDotnos args e emrunExportJson; guard quandoprojectsModels.length === 0(warn + throw).Checklist
main(merge/rebase as appropriate).feat:,refactor:,test:).pnpm ci:test(Vitest) passes.Verification
pnpm build(filter!./apps/*),pnpm typecheck,pnpm test(orpnpm ci:test) — pass.Notes for reviewers
DrawioViewModelLikeis the public type for view models passed togenerateDrawio/generateDrawioMulti.runExport*+ thin handler).Reference
Summary by CodeRabbit
New Features
Bug Fixes
Performance
Chores
Documentation
Tests