Skip to content

refactor(core): dedupe compile-diff pipelines, CJK width heuristic, and layout decomposition opportunities #2014

Closed

Description

@kompiro

Analysis of packages/core (parser, style resolution, SVG renderer, translate — pure TS) for refactoring opportunities. All refactorings must be zero-behavior-change (output SVGs byte-identical); existing tests must keep passing. Constraints: barrel imports of **/index.js are forbidden inside packages/core/src; pnpm check:cycles forbids circular deps including type-only imports.

Context worth noting: pnpm knip currently reports zero unused exports in core, so there is no dead-code cleanup to be had — the wins are in duplication and decomposition. Package exports only expose "." and "./icons/*", so all internal file moves below are invisible to consumers.

Refactoring opportunities in packages/core

1. Deduplicate the three compile*Diff pipelines in index.ts

  • Files: src/index.ts (compileSystemDiff L1266–1375, compileDeployDiff L1408–1487, compileOrgDiff L1520–1573, buildAllViewsSvgDiffProject L1608+)
  • Problem: All three diff compilers repeat the same boilerplate verbatim: create ImportResolver, Promise.all-resolve before/after entries, concat diagnostics, assemble [builtin, ...before.styleSheets, ...after.styleSheets], append icon-theme sheet (displayMode === "icon" ? [...sheets, getIconThemeStyleSheet()] : sheets appears 4x in this file plus once in renderer/all-layers-svg.ts:101), convert diffed.nodes/diffed.edges into Map<string,string> state maps, and injectDiffStyle the SVG. Any change to sheet ordering or diagnostics merging must be applied in 3–4 places.
  • Suggested approach: Extract three tiny helpers: resolveBeforeAfter(fs, beforePath, afterPath), assembleDiffSheets(before, after, theme, badgeLabels, displayMode), and toDiffStateMaps(diffed). Pure mechanical inlining in reverse; output SVGs byte-identical.
  • Risk: low
  • Effort: S

2. Move the compile facade out of the index.ts barrel

  • Files: src/index.ts (1716 lines; implementation spans ~L258–1716: _compileFromPreparedInput L506–710, _compileCore L712+, compile/compileProject overloads L776–851, buildNodeMetadata L885, buildDeployNodeMetadata L952, all compile*Diff, buildAllViewsSvgDiffProject, diagnosticToWarning)
  • Problem: The barrel mixes ~1,100 lines of real compile-pipeline logic with re-exports, making it both the highest-traffic API file and a large implementation file. Because barrel imports are forbidden inside packages/core/src, no other core module can reuse anything defined here (e.g. diagnosticToWarning).
  • Suggested approach: Move the implementation (interfaces + functions, unmodified) into e.g. src/compile/compile.ts and src/compile/compile-diff.ts using deep imports, and replace with export { ... } from "./compile/compile.js" lines in index.ts. This is not a wholesale barrel restructure — the export surface stays identical, only ~1,100 implementation lines relocate. Verified safe: nothing in core imports index.js internally, package.json exports only exposes "." and "./icons/*", and knip currently reports zero unused exports. Gate with pnpm typecheck, core tests, pnpm check:cycles, pnpm knip.
  • Risk: medium (large mechanical move; mitigated by full-repo typecheck + tests)
  • Effort: M

3. Consolidate CJK text-width estimation and font-ratio constants

  • Files: src/renderer/layout.ts:2455, src/renderer/deploy-layout.ts:23, src/render/matrix-svg.ts:41, src/renderer/svg-builder.ts:57–100, src/renderer/rendering-constants.ts
  • Problem: The "CJK char = 1.5x width, threshold charCodeAt(0) > 0x2e80" heuristic exists as three separate estimateTextWidth functions (layout.ts and deploy-layout.ts are line-for-line identical apart from the charWidth parameter) plus three inline copies inside truncateToWidth/wrapToWidth in svg-builder.ts. matrix-svg.ts has a deliberately different, wider-coverage heuristic (isWideChar with full CJK ranges) — the divergence is invisible today. There is also a live drift bug-in-waiting: layout.ts:41 defines DESCRIPTION_FONT_RATIO = 0.85 for width estimation, but svg-renderer.ts:1077 uses CHAR_WIDTH * 0.8; // DESCRIPTION_FONT_RATIO — the comment claims a constant it doesn't use, so layout width and rendered font size are computed with different ratios.
  • Suggested approach: Add charDisplayWidth(ch, charWidth) (or estimateTextWidth(text, charWidth)) to rendering-constants.ts or svg-builder.ts and use it from layout.ts, deploy-layout.ts, and the three svg-builder loops — values unchanged, zero behavior change. Keep matrix-svg's heuristic separate but add a comment cross-referencing the intentional difference. Name the 0.8 in svg-renderer.ts as its own constant (do not unify it to 0.85 — that would change output) and fix the misleading comment.
  • Risk: low
  • Effort: S

4. layoutMultipleSystems: 10 positional optional parameters, mirrored machinery with layout()

  • Files: src/renderer/layout.ts (layout L946–1520, 574 lines; layoutMultipleSystems L1587–1986, 399 lines; call site L982)
  • Problem: layoutMultipleSystems(viewSlice, ownerIndex?, boundaryIndex?, displayMode?, layoutHints?, edgeDirections?, collapsedCategories?, groupBy?, collapsedGroups?, edgeDiffState?) takes 10 mostly-optional positional params that just re-splat the LayoutOptions object layout() already received — adding an option means threading an 11th positional arg. Beyond that, both functions duplicate the group-collapse/grouped-layer sequence; comments in the multi-system path literally say "mirrors layout()" but it's copy-adapted, not shared.
  • Suggested approach: Step 1 (trivially safe): change the signature to layoutMultipleSystems(viewSlice, options: LayoutOptions). Step 2 (optional, separate commit): extract the shared per-node-set group-collapse block into a helper. layout.test.ts (1786 lines) + group-*-render.test.ts fence this well.
  • Risk: low (step 1) / medium (step 2)
  • Effort: M

5. Decompose renderNode (534 lines) in svg-renderer

  • Files: src/renderer/svg-renderer.ts (renderNode L904–1438; also renderFromLayout L218–492)
  • Problem: renderNode is a single 534-line function interleaving independent concerns: icon-mode card frame, shape, labelSlot-positioned text vs. default text stack, multi-line description wrapping, badges, link/team meta row, and the info button. Each new node feature has grown it further; reviewing a change means paging through all concerns.
  • Suggested approach: Extract per-concern private helpers (renderIconFrame, renderSlottedText, renderDefaultText, renderMetaRow, renderInfoButton) that append to the children array, keeping attribute order and string output byte-identical. The SVG string equality tests (svg-renderer.test.ts 1019 lines, svg-builder-family-parity.test.ts) make this mechanically verifiable.
  • Risk: medium
  • Effort: M

6. Decompose extractView (344 lines)

  • Files: src/view/view-extract.ts (extractView L685–1029)
  • Problem: The central view-slicing function handles root vs. drill-down paths, ghost-edge synthesis, unassigned-node merging, and expansion frames in one body. It is the function most feature PRs touch (expand Comprehension: single-container in-frame expansion — mixed-LOD Phase 1 (案3) #1921, boundary Declare semantic clusters within a system; render with boundary frames #1822 both grew it), so merge conflicts and review cost concentrate here.
  • Suggested approach: Split into phase helpers (path resolution, child collection, ghost-edge synthesis, expanded-frame construction) with explicit input/output types. view-extract.test.ts (1755 lines) + view-extract.expand.test.ts + derivation-contracts.test.ts give strong fencing.
  • Risk: medium
  • Effort: M

7. Type-safety: illegal LayoutNode["kind"] cast in drawio org-layout (untested file)

  • Files: src/exporter/drawio/org-layout.ts:92 (kind: "member" as unknown as LayoutNode["kind"]), src/renderer/layout-types.ts:20 (kind: LogicalNodeKind | DeployNodeKind)
  • Problem: This is one of only two as unknown as / as any casts in all of core's production code. It smuggles the string "member" into a union that doesn't contain it, so downstream switches on kind silently miss org nodes and the compiler can't warn. org-layout.ts also has no co-located test file.
  • Suggested approach: Widen LayoutNode["kind"] to include the org kinds ("member" / "team") or introduce an OrgLayoutNodeKind union member in layout-types.ts, then delete the cast. Type-only change; runtime output identical. Optionally add a small snapshot test for org-layout.ts in the same PR.
  • Risk: low
  • Effort: S

8. Micro-duplication and placement inconsistencies

  • Files: src/render/matrix-svg.ts (sole file in render/; every other renderer lives in renderer/), src/translate/db.ts:5 vs src/translate/openapi.ts:39 (byte-identical toPascalCase), src/renderer/svg-builder.ts:18 vs src/exporter/drawio/mxgraph-builder.ts:17 (two escapeXml variants — the drawio one additionally escapes ')
  • Problem: render/ vs renderer/ forces contributors to remember one exception and makes greps miss files. The duplicated toPascalCase means an ID-derivation fix in one translator can silently miss the other. The two escapeXmls are near-duplicates whose semantic difference (apostrophe escaping) is undocumented.
  • Suggested approach: Move matrix-svg.ts into renderer/ (only importer is index.ts:85 plus its own test). Hoist toPascalCase into a shared translate/identifier.ts (deep import, no barrel). For escapeXml, don't merge (the &apos; difference is load-bearing for mxgraph attributes) — just add a one-line comment in each explaining why two exist.
  • Risk: low
  • Effort: S

Suggested first batch

A single low-risk PR combining the mechanical items, verified by pnpm --filter @karasu-tools/core test, pnpm typecheck, pnpm check:cycles, pnpm knip:

  1. Point 1 — dedupe the compile*Diff pipelines (pure helper extraction inside index.ts)
  2. Point 3 — consolidate the CJK width heuristic + name the 0.8 ratio constant (values untouched)
  3. Point 7 — fix the LayoutNode["kind"] cast (type-only)
  4. Point 8 — render/ → renderer/ move + shared toPascalCase

Point 2 (compile facade extraction) is the natural follow-up PR: it builds directly on point 1's helpers but is a big enough diff to deserve its own review. Points 4–6 are independent decomposition PRs, each fenced by an existing large test suite.


Analysis performed by Claude Code agents on 2026-07-16.

Activity

  1. added
    refactor
    status: implementing
    status: in-review
    and removed
    status: implementing
    on Jul 16, 2026
  2. added
    status: implementing
    and removed
    status: implementing
    on Jul 17, 2026
  3. added
    status: implementing
    and removed
    status: implementing
    on Jul 17, 2026
  4. added
    status: implementing
    and removed
    status: implementing
    on Jul 18, 2026
  5. kompiro commented on Jul 18, 2026

    @kompiro
    OwnerAuthor

    All refactoring points implemented and merged across batches: compile*Diff dedup, compile facade extraction (#2038), CJK width heuristic, layoutMultipleSystems options (#2057), renderNode decomposition (#2061), extractView decomposition (#2064), LayoutNode kind cast fix, render/→renderer/ + toPascalCase consolidation. All PRs verified byte-identical via the render harness. Closing as done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    refactorstatus: in-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions