Skip to content

fix(d3-force): respect explicit center and force positions - #295

Open
chilingling wants to merge 1 commit into
antvis:v5from
chilingling:fix/d3-force-center
Open

chilingling wants to merge 1 commit into
antvis:v5from
chilingling:fix/d3-force-center

Conversation

@chilingling

Copy link
Copy Markdown

close #294

问题

D3ForceLayout 在合并配置时,默认属性的合并优先级错误地高于用户传入的配置对象,导致以下自定义配置被默认值覆盖而无法生效:

  • center: { x, y }、centerX / centerY:无论如何配置,中心点坐标始终回退为视口中心 [width / 2, height / 2]
  • x: { x }、y: { y }、radial: { x, y }:中心力开启时,其自定义坐标会被中心点坐标覆盖
  • radial: { radius }:自定义半径被硬编码的默认值 100 覆盖

详细复现步骤与原因分析见关联 Issue。

改动

修改集中在 src/algorithm/d3-force/index.ts,调整了 getCenterOptions、getXForceOptions、getYForceOptions 与 getRadialOptions 的合并逻辑,将参数合并优先级统一为:
默认兜底值 → force 配置对象 → 扁平快捷属性。

  • 默认值兜底:默认属性仅在用户未显式配置时生效。
  • 规范统一:扁平快捷属性具有最高优先级并覆盖 force 对象中的对应字段,与 manyBody、link、collide 等其他力配置 getter 的现有规范保持一致。
  • 补全字段支持:getCenterOptions 补充对 centerX / centerY 快捷属性的解析(此前类型声明与文档均已提供,但代码实现中未实际读取)。

影响

  • 未配置上述参数的用户:完全向后兼容,布局结果保持不变(新增的“回退到视口中心”单测已覆盖该场景)。
  • 显式配置了上述参数的用户:属于预期的 Bug 修复,配置将按预期正常生效,相关节点的布局结果会随之更新。
  • 快照测试更新:更新了 __tests__/snapshots/d3-force/force-options.svg。该用例显式配置了 center: { x: 300, y: 300 }、x: { x: 300 }、y: { y: 300 } 与 radial: { x: 350, y: 350, radius: 120 }。此前由于参数被默认值覆盖,旧快照实际渲染使用的是 center/x/y 均为 350、径向半径为 100 的错误布局;本次修复后快照已更新为真实生效配置对应的正确图形。

验证

  • 单元测试:在 __tests__/unit/d3-force.test.ts 中新增 center position 测试套件(包含 5 个用例)。其中验证显式坐标的 4 个用例在 v5 旧代码上均失败,修复后全部通过;验证“回退到视口中心”的用例在修复前后均正常通过。
  • 自动化测试:运行 npm test,47 个测试套件全部通过,1 个跳过(47 passed, 1 skipped)。
  • 代码规范检查:运行 npm run lint(tsc --noEmit),src/ 核心代码无错误,本 PR 未引入任何新增类型问题。(注:__tests__/ 中现存的 228 个报错系 v5 分支基线历史遗留问题,全新安装下还会触发 @types/node@26 与 TS 4.9 的兼容问题,均与本 PR 无关)。

Defaults such as width / 2, the center point and radius 100 were merged
after the user-provided force objects, so explicit center, x, y and radial
options were overwritten. Apply defaults first, then force objects, then
shortcut fields.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

D3ForceLayout: 配置的 center / centerX / x / y / radial 坐标及 radius 参数被默认值覆盖失效

1 participant