tree.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. {% extends "layout.html" %}
  2. {% block title %}生物遗传图谱 - 家谱管理系统{% endblock %}
  3. {% block extra_css %}
  4. <style>
  5. #tree-container {
  6. width: 100%;
  7. height: 700px;
  8. background: white;
  9. border: 1px solid #e9ecef;
  10. border-radius: 8px;
  11. margin-top: 10px;
  12. box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  13. position: relative;
  14. overflow: hidden;
  15. }
  16. .zoom-controls {
  17. position: absolute;
  18. top: 10px;
  19. right: 10px;
  20. z-index: 100;
  21. background: white;
  22. border-radius: 4px;
  23. box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  24. padding: 5px;
  25. }
  26. .zoom-btn {
  27. display: block;
  28. width: 30px;
  29. height: 30px;
  30. margin: 5px 0;
  31. border: 1px solid #ddd;
  32. border-radius: 4px;
  33. background: white;
  34. cursor: pointer;
  35. display: flex;
  36. align-items: center;
  37. justify-content: center;
  38. }
  39. .zoom-btn:hover {
  40. background: #f8f9fa;
  41. }
  42. #tree-container::-webkit-scrollbar {
  43. width: 8px;
  44. height: 8px;
  45. }
  46. #tree-container::-webkit-scrollbar-track {
  47. background: #f1f1f1;
  48. border-radius: 4px;
  49. }
  50. #tree-container::-webkit-scrollbar-thumb {
  51. background: #c1c1c1;
  52. border-radius: 4px;
  53. }
  54. #tree-container::-webkit-scrollbar-thumb:hover {
  55. background: #a1a1a1;
  56. }
  57. .node rect, .node circle {
  58. stroke-width: 2px;
  59. filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
  60. }
  61. .node text { font: 13px 'Microsoft YaHei', sans-serif; }
  62. .node .node-name {
  63. font-size: 13px;
  64. font-weight: 500;
  65. fill: #334155;
  66. stroke: #fff;
  67. stroke-width: 4px;
  68. paint-order: stroke;
  69. stroke-linejoin: round;
  70. }
  71. /* 样图一致:较粗的细实线、浅灰蓝色,显得专业 */
  72. .link { fill: none; stroke: #94A3B8; stroke-width: 2px; stroke-linejoin: round; }
  73. /* 关系标签文字,取消白色粗描边,因为已有胶囊形背景 */
  74. .link-label { font-size: 11px; fill: #64748B; font-weight: 500; }
  75. .link-label-sibling { fill: #64748B; }
  76. /* 男女形状与颜色区分:男性方形(蓝),女性圆形(粉红),添加轻微圆角与投影 */
  77. .node-male rect { stroke: #3B82F6; fill: #EFF6FF; rx: 8px; ry: 8px; }
  78. .node-female circle { stroke: #EC4899; fill: #FDF2F8; }
  79. /* 未知性别默认 */
  80. .node-leaf circle, .node-internal circle { stroke: #94A3B8; fill: #F8FAFC; }
  81. .node-male circle { stroke: none; fill: none; } /* 清除可能的干扰 */
  82. /* 样图一致:全部细实线 */
  83. .link-parent-child { stroke: #333; stroke-dasharray: none; }
  84. .link-spouse { stroke: #333; stroke-dasharray: none; stroke-width: 1.2px; }
  85. .link-sibling { stroke: #333; stroke-dasharray: none; stroke-width: 1.2px; }
  86. /* 右键菜单样式 */
  87. .context-menu {
  88. position: absolute;
  89. display: none;
  90. background: white;
  91. border: 1px solid #ccc;
  92. box-shadow: 2px 2px 10px rgba(0,0,0,0.2);
  93. z-index: 1000;
  94. border-radius: 4px;
  95. padding: 5px 0;
  96. min-width: 120px;
  97. }
  98. .context-menu-item {
  99. padding: 8px 15px;
  100. cursor: pointer;
  101. font-size: 14px;
  102. color: #333;
  103. }
  104. .context-menu-item:hover {
  105. background-color: #f8f9fa;
  106. color: #0d6efd;
  107. }
  108. .context-menu-item i {
  109. margin-right: 8px;
  110. }
  111. </style>
  112. {% endblock %}
  113. {% block content %}
  114. <div class="d-flex justify-content-between align-items-center mb-3">
  115. <h2><i class="bi bi-diagram-3"></i> 家谱关系树状图</h2>
  116. <div>
  117. <a href="{{ url_for('tree_classic') }}" class="btn btn-outline-primary" target="_blank">
  118. <i class="bi bi-printer"></i> 导出传统吊线图
  119. </a>
  120. </div>
  121. </div>
  122. <div class="alert alert-light border small py-2">
  123. <i class="bi bi-info-circle me-1"></i> 提示:图中按生物遗传图谱格式展示。支持拖拽建立关系,右键点击成员可查看、编辑或新增。
  124. </div>
  125. <div id="tree-container">
  126. <!-- 缩放控制 -->
  127. <div class="zoom-controls">
  128. <button class="zoom-btn" onclick="zoomIn()"><i class="bi bi-plus"></i></button>
  129. <button class="zoom-btn" onclick="zoomOut()"><i class="bi bi-dash"></i></button>
  130. <button class="zoom-btn" onclick="zoomReset()"><i class="bi bi-arrow-counterclockwise"></i></button>
  131. </div>
  132. <!-- 右键菜单 -->
  133. <div id="contextMenu" class="context-menu">
  134. <div class="context-menu-item" onclick="menuAction('detail')"><i class="bi bi-eye"></i>查看成员</div>
  135. <div class="context-menu-item" onclick="menuAction('edit')"><i class="bi bi-pencil"></i>编辑成员</div>
  136. <div class="context-menu-item" onclick="menuAction('add')"><i class="bi bi-plus-lg"></i>新增成员</div>
  137. </div>
  138. </div>
  139. <!-- 关系选择弹窗 -->
  140. <div class="modal fade" id="relationModal" tabindex="-1">
  141. <div class="modal-dialog modal-sm">
  142. <div class="modal-content">
  143. <div class="modal-header">
  144. <h5 class="modal-title">建立关系</h5>
  145. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  146. </div>
  147. <div class="modal-body">
  148. <p id="relationInfo" class="small mb-3"></p>
  149. <input type="hidden" id="sourceMid">
  150. <input type="hidden" id="targetMid">
  151. <div class="mb-3">
  152. <label class="form-label small">关系类型</label>
  153. <select id="relType" class="form-select form-select-sm">
  154. <option value="1">是其 儿子/女儿</option>
  155. <option value="10">是其 妻子/丈夫</option>
  156. <option value="11">是其 兄弟</option>
  157. <option value="12">是其 姐妹</option>
  158. </select>
  159. </div>
  160. <div class="mb-3">
  161. <label class="form-label small">子类型</label>
  162. <select id="subRelType" class="form-select form-select-sm">
  163. <option value="0">亲生/正妻</option>
  164. <option value="1">养子/女</option>
  165. <option value="2">过继</option>
  166. </select>
  167. </div>
  168. </div>
  169. <div class="modal-footer">
  170. <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">取消</button>
  171. <button type="button" class="btn btn-sm btn-primary" onclick="saveRelation()">保存关系</button>
  172. </div>
  173. </div>
  174. </div>
  175. </div>
  176. {% endblock %}
  177. {% block extra_js %}
  178. <!-- 优先使用本地 D3.js -->
  179. <script src="{{ url_for('static', filename='js/d3.min.js') }}"></script>
  180. <!-- fallback to CDN if local fails -->
  181. <script>
  182. if (typeof d3 === 'undefined') {
  183. var script = document.createElement('script');
  184. script.src = 'https://cdn.jsdelivr.net/npm/d3@7.8.5/dist/d3.min.js';
  185. script.onload = function() {
  186. if (typeof d3 !== 'undefined') {
  187. loadTree();
  188. } else {
  189. var container = document.getElementById('tree-container');
  190. if (container) container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">D3.js 未加载,请检查网络或稍后重试。</div>';
  191. }
  192. };
  193. script.onerror = function() {
  194. var container = document.getElementById('tree-container');
  195. if (container) container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">D3.js 未加载,请检查网络或稍后重试。</div>';
  196. };
  197. document.head.appendChild(script);
  198. }
  199. </script>
  200. <script>
  201. (function() {
  202. if (typeof d3 === 'undefined') {
  203. // CDN will handle loading and initialization
  204. }
  205. })();
  206. let currentData = null;
  207. let dragSource = null;
  208. let dragTarget = null;
  209. let selectedMid = null; // 当前选中的成员 ID
  210. let zoomScale = 1;
  211. let zoomTransform = d3.zoomIdentity;
  212. let zoomBehavior = d3.zoom().scaleExtent([0.1, 4]).on("zoom", zoomed);
  213. const relationModal = new bootstrap.Modal(document.getElementById('relationModal'));
  214. const contextMenu = document.getElementById('contextMenu');
  215. // 隐藏右键菜单
  216. window.addEventListener('click', () => {
  217. contextMenu.style.display = 'none';
  218. });
  219. // 处理菜单点击
  220. function menuAction(type) {
  221. if (!selectedMid && type !== 'add') return;
  222. switch(type) {
  223. case 'detail':
  224. window.location.href = `/manager/member_detail/${selectedMid}`;
  225. break;
  226. case 'edit':
  227. window.location.href = `/manager/edit_member/${selectedMid}`;
  228. break;
  229. case 'add':
  230. window.location.href = '/manager/add_member';
  231. break;
  232. }
  233. }
  234. // 获取数据并渲染
  235. function loadTree() {
  236. if (typeof d3 === 'undefined') return;
  237. fetch('/manager/api/tree_data')
  238. .then(response => response.json())
  239. .then(data => {
  240. currentData = data;
  241. renderTree(data);
  242. });
  243. }
  244. if (typeof d3 !== 'undefined') loadTree();
  245. function renderTree(data) {
  246. const container = document.getElementById('tree-container');
  247. container.innerHTML = '';
  248. container.appendChild(contextMenu);
  249. try {
  250. const { members, relations } = data;
  251. if (!members || members.length === 0) {
  252. container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-muted">暂无成员数据,无法生成关系图。</div>';
  253. return;
  254. }
  255. const nodes = members.map(m => ({ id: m.id, name: m.name, simplified_name: m.simplified_name, sex: m.sex }));
  256. const hierarchicalLinks = relations.filter(r => r.relation_type === 1 || r.relation_type === 2)
  257. .map(r => ({ source: r.parent_mid, target: r.child_mid }));
  258. const spouseLinks = relations.filter(r => r.relation_type === 10);
  259. const otherLinks = relations.filter(r => r.relation_type >= 11);
  260. const childIds = new Set(hierarchicalLinks.map(l => l.target));
  261. const allSpouseIds = new Set(spouseLinks.map(l => l.child_mid));
  262. const roots = nodes.filter(n => !childIds.has(n.id) && !allSpouseIds.has(n.id));
  263. function buildHierarchy(nodeId, processedNodes = new Set()) {
  264. const node = nodes.find(n => n.id === nodeId);
  265. if (!node || processedNodes.has(nodeId)) return null;
  266. processedNodes.add(nodeId);
  267. const children = hierarchicalLinks.filter(l => l.source === nodeId)
  268. .map(l => buildHierarchy(l.target, processedNodes))
  269. .filter(c => c !== null);
  270. const spouses = spouseLinks.filter(l => l.parent_mid === nodeId)
  271. .map(l => {
  272. const spouseId = l.child_mid;
  273. if (!childIds.has(spouseId)) {
  274. const sNode = nodes.find(n => n.id === spouseId);
  275. if (sNode && !processedNodes.has(spouseId)) {
  276. processedNodes.add(spouseId);
  277. return { id: sNode.id, name: sNode.name, simplified_name: sNode.simplified_name, sex: sNode.sex, isSpouseNode: true, children: [] };
  278. }
  279. }
  280. return null;
  281. })
  282. .filter(s => s !== null);
  283. return { id: node.id, name: node.name, simplified_name: node.simplified_name, sex: node.sex, children: spouses.concat(children) };
  284. }
  285. let treeData;
  286. if (roots.length > 1) {
  287. treeData = { name: "家谱根源", children: roots.map(root => buildHierarchy(root.id)).filter(r => r !== null) };
  288. } else if (roots.length === 1) {
  289. treeData = buildHierarchy(roots[0].id);
  290. } else {
  291. treeData = buildHierarchy(nodes[0].id);
  292. }
  293. const margin = {top: 80, right: 60, bottom: 80, left: 60};
  294. const containerWidth = document.getElementById('tree-container').offsetWidth;
  295. let rootNode = d3.hierarchy(treeData, d => (d && d.children) || []);
  296. // 动态调整间距,保证节点绝对不重叠,长辈/同辈/配偶使用固定基础间距
  297. const nodeWidth = 120; // 增加基础宽度以避免重叠
  298. const nodeHeight = 260; // 基础高度,调大以避免上下层重叠
  299. const treemap = d3.tree().nodeSize([nodeWidth, nodeHeight]).separation((a, b) => {
  300. return a.parent === b.parent ? 2.0 : 2.0; // 增加同级节点间距
  301. });
  302. let nodesHier = treemap(rootNode);
  303. // 配偶固定在同一水平线上:与本人并列显示
  304. const spouseSpreadX = 140; // 增加间距以确保不重叠
  305. nodesHier.descendants().forEach(parent => {
  306. const spouses = (parent.children || []).filter(c => c.data && c.data.isSpouseNode);
  307. if (spouses.length === 0) return;
  308. spouses.forEach((spouse, idx) => {
  309. // 计算配偶位置,从右侧开始排列
  310. spouse.x = parent.x + (idx + 1) * spouseSpreadX;
  311. spouse.y = parent.y; // 同一水平线
  312. });
  313. });
  314. // 计算边界以动态设置 SVG 宽高,实现自动滚动不挤压
  315. let x0 = Infinity;
  316. let x1 = -Infinity;
  317. let y1 = -Infinity;
  318. nodesHier.descendants().forEach(d => {
  319. if (d.x < x0) x0 = d.x;
  320. if (d.x > x1) x1 = d.x;
  321. if (d.y > y1) y1 = d.y;
  322. });
  323. // 增加更宽的边距以确保左侧不被切断
  324. const minWidth = containerWidth;
  325. const calculatedWidth = x1 - x0 + margin.left + margin.right + 400; // 增加额外的宽度缓冲
  326. const svgWidth = Math.max(minWidth, calculatedWidth);
  327. const svgHeight = Math.max(600, y1 + margin.top + margin.bottom);
  328. // 修正偏移量计算:确保最小的 x0 节点完全在可视区域内(加上足够的左边距)
  329. // 这样即便是负的很大,也会被完整平移到正数区域
  330. const extraLeftMargin = 200; // 增加更多左侧空间
  331. let offsetX = margin.left - x0 + extraLeftMargin; // 强制将最左侧节点右移确保文字不被截断
  332. // 确保offsetX至少为margin.left,防止内容被左侧菜单遮挡
  333. offsetX = Math.max(offsetX, margin.left + 50);
  334. const svg = d3.select("#tree-container").append("svg")
  335. .attr("width", svgWidth)
  336. .attr("height", svgHeight)
  337. .call(zoomBehavior)
  338. .append("g")
  339. .attr("transform", `translate(${offsetX},${margin.top})`);
  340. // 存储SVG元素引用,用于缩放操作
  341. window.svgGroup = svg;
  342. // 节点圆圈半径(连线与节点共用),调大让图谱更清晰大气
  343. const circleR = 20;
  344. // 辅助函数:绘制精致的徽章式关系标签
  345. function addBadge(g, x, y, text) {
  346. const group = g.append("g").attr("transform", `translate(${x},${y})`);
  347. group.append("rect")
  348. .attr("x", -20).attr("y", -10)
  349. .attr("width", 40).attr("height", 20)
  350. .attr("rx", 10).attr("ry", 10) // 胶囊形状
  351. .attr("fill", "#fff")
  352. .attr("stroke", "#CBD5E1").attr("stroke-width", 1.2);
  353. group.append("text")
  354. .attr("class", "link-label")
  355. .attr("x", 0).attr("y", 0).attr("dy", "0.32em")
  356. .attr("text-anchor", "middle")
  357. .text(text);
  358. }
  359. // 连线:第二层连线设计(U型配偶线 + 亲子水平线)
  360. nodesHier.descendants().forEach(node => {
  361. if (!node.children || node.children.length === 0) return;
  362. const realChildren = (node.children || []).filter(c => c.data && !c.data.isSpouseNode);
  363. const spouses = (node.children || []).filter(c => c.data && c.data.isSpouseNode);
  364. // 配偶连线拐点:位于本人与配偶节点之间,匹配“下层半级”显示
  365. // const hY = node.y + Math.round(spouseHalfLevelOffsetY * 0.55);
  366. const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
  367. // 夫妻关系:水平连线(主节点右侧连接到配偶左侧)
  368. if (spouses.length > 0) {
  369. const g = svg.append("g").attr("class", "link-group");
  370. spouses.forEach((spouse, idx) => {
  371. // 水平连线,稍微向下偏移一点以避开节点
  372. const linkY = node.y + 10;
  373. const pathD = `M${num(node.x + circleR)},${num(linkY)}
  374. L${num(spouse.x - circleR)},${num(linkY)}`;
  375. g.append("path").attr("class", "link link-spouse").attr("d", pathD);
  376. if (idx === 0) addBadge(g, (node.x + spouse.x) / 2, linkY, "配偶");
  377. });
  378. }
  379. if (realChildren.length === 0) return;
  380. const childrenY = realChildren[0].y;
  381. const minChildX = d3.min(realChildren, c => c.x);
  382. const maxChildX = d3.max(realChildren, c => c.x);
  383. // 如果有配偶,子代主线从本人和最右侧配偶的中间引出,否则从自己直接引出
  384. const startX = spouses.length > 0 ? (node.x + spouses[spouses.length - 1].x) / 2 : node.x;
  385. const startY = node.y + circleR;
  386. // 将子女横线也相应地下移一些,避免和配偶长名字重叠
  387. const sibsY = childrenY - 60;
  388. const g = svg.append("g").attr("class", "link-group");
  389. const hLineLeft = Math.min(minChildX, startX);
  390. const hLineRight = Math.max(maxChildX, startX);
  391. // 主线:从配偶U型线中点连到子女水平线
  392. let pathD = `M${num(startX)},${num(startY)} L${num(startX)},${num(sibsY)} M${num(hLineLeft)},${num(sibsY)} L${num(hLineRight)},${num(sibsY)}`;
  393. // 短竖线:连到每个子女顶部
  394. realChildren.forEach(child => {
  395. pathD += ` M${num(child.x)},${num(sibsY)} L${num(child.x)},${num(child.y) - circleR}`;
  396. });
  397. g.append("path").attr("class", "link link-parent-child").attr("d", pathD);
  398. // 去除家谱根源到第一层的关系展示;下层亲子关系标记使用徽章式标签放在短竖线上,一目了然
  399. const isRootToFirst = !node.parent || !(node.data && node.data.id);
  400. if (!isRootToFirst && node.data) {
  401. realChildren.forEach(child => {
  402. const pSex = node.data.sex;
  403. const cSex = child.data && child.data.sex;
  404. let label = "亲子";
  405. if (pSex === 1) label = cSex === 1 ? "父子" : "父女";
  406. else if (pSex === 2) label = cSex === 1 ? "母子" : "母女";
  407. const childLinkMidY = (sibsY + child.y - circleR) / 2;
  408. addBadge(g, child.x, childLinkMidY, label);
  409. });
  410. }
  411. });
  412. // 兄弟/姐妹:上方 U 型连线避免穿透节点
  413. const idToPos = {};
  414. nodesHier.descendants().forEach(d => { if (d.data.id) idToPos[d.data.id] = { x: d.x, y: d.y }; });
  415. otherLinks.forEach(rel => {
  416. const s = idToPos[rel.parent_mid], t = idToPos[rel.child_mid];
  417. if (s && t) {
  418. const x1 = Math.min(s.x, t.x), x2 = Math.max(s.x, t.x);
  419. const y = s.y - circleR - 25; // 兄弟线在节点上方
  420. const g = svg.append("g");
  421. const pathD = `M${x1},${s.y - circleR} L${x1},${y} L${x2},${y} L${x2},${t.y - circleR}`;
  422. g.append("path").attr("class", "link link-sibling").attr("d", pathD);
  423. addBadge(g, (x1 + x2) / 2, y, rel.relation_type === 11 ? "兄弟" : "姐妹");
  424. }
  425. });
  426. const node = svg.selectAll(".node")
  427. .data(nodesHier.descendants())
  428. .enter().append("g")
  429. .attr("class", d => {
  430. let cls = "node" + (d.children ? " node--internal" : " node--leaf");
  431. if (d.data.sex === 1) cls += " node-male";
  432. else if (d.data.sex === 2) cls += " node-female";
  433. return cls;
  434. })
  435. .attr("transform", d => `translate(${d.x},${d.y})`)
  436. .on("contextmenu", function(event, d) {
  437. if (!d.data.id) return;
  438. event.preventDefault();
  439. selectedMid = d.data.id;
  440. const containerRect = document.getElementById('tree-container').getBoundingClientRect();
  441. contextMenu.style.display = 'block';
  442. contextMenu.style.left = (event.clientX - containerRect.left) + 'px';
  443. contextMenu.style.top = (event.clientY - containerRect.top) + 'px';
  444. })
  445. .call(d3.drag()
  446. .on("start", dragstarted)
  447. .on("drag", dragged)
  448. .on("end", dragended));
  449. // 图形:男性方形,女性圆形,更符合生物遗传图谱
  450. node.each(function(d) {
  451. const el = d3.select(this);
  452. if (d.data.sex === 1) {
  453. el.append("rect")
  454. .attr("x", -circleR).attr("y", -circleR)
  455. .attr("width", circleR * 2).attr("height", circleR * 2)
  456. .style("cursor", "grab");
  457. } else {
  458. el.append("circle")
  459. .attr("r", circleR)
  460. .style("cursor", "grab");
  461. }
  462. });
  463. // 人名:往下移动更多,避免和长方形/圆形图形或者连线重叠
  464. const nameOffsetY = circleR + 25; // 增加间距
  465. const maxNameLen = 12; // 允许稍微长一点的文字
  466. function fullName(d) {
  467. if (!d.data) return '';
  468. return d.data.simplified_name ? `${d.data.name || ''} (${d.data.simplified_name})` : (d.data.name || '');
  469. }
  470. const nameGroup = node.append("g").attr("class", "node-name-wrap").attr("transform", "translate(0, " + nameOffsetY + ")");
  471. nameGroup.each(function(d) {
  472. const g = d3.select(this);
  473. const full = fullName(d);
  474. const disp = full.length <= maxNameLen ? full : full.slice(0, maxNameLen) + '…';
  475. // 姓名可能较长,我们这里做个简单的多行拆分显示或者让它有一个白色背景遮挡线
  476. // 这里为了简单不破坏原有结构,仅使用 text,但可以给一个白色的 stroke 做底或者调整 y 坐标
  477. const textNode = g.append("text")
  478. .attr("class", "node-name")
  479. .attr("x", 0).attr("y", 0)
  480. .attr("dy", "0.8em") // 使得文字基线往下靠,进一步远离图形
  481. .attr("text-anchor", "middle")
  482. .style("pointer-events", "all")
  483. .style("cursor", "default")
  484. .text(disp);
  485. if (full.length > maxNameLen) {
  486. textNode.append("title").text(full);
  487. }
  488. });
  489. function dragstarted(event, d) {
  490. if (!d.data.id) return;
  491. d3.select(this).raise().classed("active", true);
  492. d._currentX = d.x; d._currentY = d.y;
  493. dragSource = d.data;
  494. }
  495. function dragged(event, d) {
  496. d._currentX += event.dx; d._currentY += event.dy;
  497. d3.select(this).attr("transform", `translate(${d._currentX},${d._currentY})`);
  498. }
  499. function dragended(event, d) {
  500. d3.select(this).classed("active", false);
  501. const mouseX = event.sourceEvent.clientX, mouseY = event.sourceEvent.clientY;
  502. let foundNode = null;
  503. svg.selectAll(".node").each(function(nodeData) {
  504. if (!nodeData.data || nodeData.data.id === d.data.id || !nodeData.data.id) return;
  505. const rect = this.getBoundingClientRect();
  506. if (mouseX >= rect.left && mouseX <= rect.right && mouseY >= rect.top && mouseY <= rect.bottom) foundNode = nodeData.data;
  507. });
  508. if (foundNode && foundNode.id) {
  509. dragTarget = foundNode;
  510. document.getElementById('sourceMid').value = dragSource.id;
  511. document.getElementById('targetMid').value = dragTarget.id;
  512. document.getElementById('relationInfo').innerHTML = `确认将 <strong>${dragSource.name}</strong> 设定为 <strong>${dragTarget.name}</strong> 的关系人?`;
  513. relationModal.show();
  514. }
  515. setTimeout(() => { renderTree(currentData); }, 100);
  516. }
  517. } catch (err) {
  518. console.error('renderTree error:', err);
  519. container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">关系图渲染出错,请刷新重试。<br>' + (err.message || '') + '</div>';
  520. }
  521. }
  522. function saveRelation() {
  523. const payload = {
  524. source_mid: document.getElementById('sourceMid').value,
  525. target_mid: document.getElementById('targetMid').value,
  526. relation_type: document.getElementById('relType').value,
  527. sub_relation_type: document.getElementById('subRelType').value
  528. };
  529. fetch('/manager/api/save_relation', {
  530. method: 'POST',
  531. headers: { 'Content-Type': 'application/json' },
  532. body: JSON.stringify(payload)
  533. }).then(res => res.json()).then(data => {
  534. if (data.success) { relationModal.hide(); loadTree(); }
  535. else { alert('保存失败: ' + data.message); }
  536. });
  537. }
  538. // 缩放函数
  539. function zoomed(event) {
  540. zoomTransform = event.transform;
  541. zoomScale = event.transform.k;
  542. if (window.svgGroup) {
  543. window.svgGroup.attr("transform", event.transform);
  544. }
  545. }
  546. function zoomIn() {
  547. if (zoomScale < 4) {
  548. const newScale = zoomScale * 1.2;
  549. const container = document.getElementById('tree-container');
  550. const centerX = container.clientWidth / 2;
  551. const centerY = container.clientHeight / 2;
  552. const svg = d3.select("#tree-container svg");
  553. svg.transition().duration(300).call(
  554. zoomBehavior.transform,
  555. d3.zoomIdentity.translate(centerX, centerY).scale(newScale).translate(-centerX, -centerY)
  556. );
  557. }
  558. }
  559. function zoomOut() {
  560. if (zoomScale > 0.1) {
  561. const newScale = zoomScale / 1.2;
  562. const container = document.getElementById('tree-container');
  563. const centerX = container.clientWidth / 2;
  564. const centerY = container.clientHeight / 2;
  565. const svg = d3.select("#tree-container svg");
  566. svg.transition().duration(300).call(
  567. zoomBehavior.transform,
  568. d3.zoomIdentity.translate(centerX, centerY).scale(newScale).translate(-centerX, -centerY)
  569. );
  570. }
  571. }
  572. function zoomReset() {
  573. const svg = d3.select("#tree-container svg");
  574. svg.transition().duration(300).call(
  575. zoomBehavior.transform,
  576. d3.zoomIdentity
  577. );
  578. zoomScale = 1;
  579. }
  580. </script>
  581. {% endblock %}