tree.html 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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 class="d-flex gap-2">
  117. <div class="input-group" style="width: 300px;">
  118. <input type="text" id="memberSearch" class="form-control form-control-sm" placeholder="输入成员名字搜索">
  119. <button class="btn btn-sm btn-primary" onclick="searchMember()">
  120. <i class="bi bi-search"></i> 搜索
  121. </button>
  122. </div>
  123. <a href="{{ url_for('tree_classic') }}" class="btn btn-outline-primary btn-sm">
  124. <i class="bi bi-printer"></i> 导出传统吊线图
  125. </a>
  126. </div>
  127. </div>
  128. <div class="alert alert-light border small py-2">
  129. <i class="bi bi-info-circle me-1"></i> 提示:图中按生物遗传图谱格式展示。支持拖拽建立关系,右键点击成员可查看、编辑或新增。
  130. </div>
  131. <div id="tree-container">
  132. <!-- 缩放控制 -->
  133. <div class="zoom-controls">
  134. <button class="zoom-btn" onclick="zoomIn()"><i class="bi bi-plus"></i></button>
  135. <button class="zoom-btn" onclick="zoomOut()"><i class="bi bi-dash"></i></button>
  136. <button class="zoom-btn" onclick="zoomReset()"><i class="bi bi-arrow-counterclockwise"></i></button>
  137. </div>
  138. <!-- 右键菜单 -->
  139. <div id="contextMenu" class="context-menu">
  140. <div class="context-menu-item" onclick="menuAction('detail')"><i class="bi bi-eye"></i>查看成员</div>
  141. <div class="context-menu-item" onclick="menuAction('edit')"><i class="bi bi-pencil"></i>编辑成员</div>
  142. <div class="context-menu-item" onclick="menuAction('add')"><i class="bi bi-plus-lg"></i>新增成员</div>
  143. </div>
  144. </div>
  145. <!-- 关系选择弹窗 -->
  146. <div class="modal fade" id="relationModal" tabindex="-1">
  147. <div class="modal-dialog modal-sm">
  148. <div class="modal-content">
  149. <div class="modal-header">
  150. <h5 class="modal-title">建立关系</h5>
  151. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  152. </div>
  153. <div class="modal-body">
  154. <p id="relationInfo" class="small mb-3"></p>
  155. <input type="hidden" id="sourceMid">
  156. <input type="hidden" id="targetMid">
  157. <div class="mb-3">
  158. <label class="form-label small">关系类型</label>
  159. <select id="relType" class="form-select form-select-sm">
  160. <option value="1">是其 儿子/女儿</option>
  161. <option value="10">是其 妻子/丈夫</option>
  162. <option value="11">是其 兄弟</option>
  163. <option value="12">是其 姐妹</option>
  164. </select>
  165. </div>
  166. <div class="mb-3">
  167. <label class="form-label small">子类型</label>
  168. <select id="subRelType" class="form-select form-select-sm">
  169. <option value="0">亲生/正妻</option>
  170. <option value="1">养子/女</option>
  171. <option value="2">过继</option>
  172. </select>
  173. </div>
  174. </div>
  175. <div class="modal-footer">
  176. <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">取消</button>
  177. <button type="button" class="btn btn-sm btn-primary" onclick="saveRelation()">保存关系</button>
  178. </div>
  179. </div>
  180. </div>
  181. </div>
  182. {% endblock %}
  183. {% block extra_js %}
  184. <!-- 优先使用本地 D3.js -->
  185. <script src="{{ url_for('static', filename='js/d3.min.js') }}"></script>
  186. <!-- fallback to CDN if local fails -->
  187. <script>
  188. if (typeof d3 === 'undefined') {
  189. var script = document.createElement('script');
  190. script.src = 'https://cdn.jsdelivr.net/npm/d3@7.8.5/dist/d3.min.js';
  191. script.onload = function() {
  192. if (typeof d3 !== 'undefined') {
  193. loadTree();
  194. } else {
  195. var container = document.getElementById('tree-container');
  196. if (container) container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">D3.js 未加载,请检查网络或稍后重试。</div>';
  197. }
  198. };
  199. script.onerror = function() {
  200. var container = document.getElementById('tree-container');
  201. if (container) container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">D3.js 未加载,请检查网络或稍后重试。</div>';
  202. };
  203. document.head.appendChild(script);
  204. }
  205. </script>
  206. <script>
  207. (function() {
  208. if (typeof d3 === 'undefined') {
  209. // CDN will handle loading and initialization
  210. }
  211. })();
  212. let currentData = null;
  213. let dragSource = null;
  214. let dragTarget = null;
  215. let selectedMid = null; // 当前选中的成员 ID
  216. let zoomScale = 1;
  217. let zoomTransform = d3.zoomIdentity;
  218. let zoomBehavior = d3.zoom().scaleExtent([0.1, 4]).on("zoom", zoomed);
  219. const relationModal = new bootstrap.Modal(document.getElementById('relationModal'));
  220. const contextMenu = document.getElementById('contextMenu');
  221. // 隐藏右键菜单
  222. window.addEventListener('click', () => {
  223. contextMenu.style.display = 'none';
  224. });
  225. // 处理菜单点击
  226. function menuAction(type) {
  227. if (!selectedMid && type !== 'add') return;
  228. switch(type) {
  229. case 'detail':
  230. window.location.href = `/manager/member_detail/${selectedMid}`;
  231. break;
  232. case 'edit':
  233. window.location.href = `/manager/edit_member/${selectedMid}`;
  234. break;
  235. case 'add':
  236. window.location.href = '/manager/add_member';
  237. break;
  238. }
  239. }
  240. // 获取数据并渲染
  241. function loadTree() {
  242. if (typeof d3 === 'undefined') return;
  243. fetch('/manager/api/tree_data')
  244. .then(response => response.json())
  245. .then(data => {
  246. currentData = data;
  247. renderTree(data);
  248. });
  249. }
  250. if (typeof d3 !== 'undefined') loadTree();
  251. function renderTree(data) {
  252. const container = document.getElementById('tree-container');
  253. container.innerHTML = '';
  254. container.appendChild(contextMenu);
  255. try {
  256. const { members, relations } = data;
  257. if (!members || members.length === 0) {
  258. container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-muted">暂无成员数据,无法生成关系图。</div>';
  259. return;
  260. }
  261. const nodes = members.map(m => ({ id: m.id, name: m.name, simplified_name: m.simplified_name, sex: m.sex }));
  262. const hierarchicalLinks = relations.filter(r => r.relation_type === 1 || r.relation_type === 2)
  263. .map(r => ({ source: r.parent_mid, target: r.child_mid }));
  264. const spouseLinks = relations.filter(r => r.relation_type === 10);
  265. const otherLinks = relations.filter(r => r.relation_type >= 11);
  266. const childIds = new Set(hierarchicalLinks.map(l => l.target));
  267. const allSpouseIds = new Set(spouseLinks.map(l => l.child_mid));
  268. const roots = nodes.filter(n => !childIds.has(n.id) && !allSpouseIds.has(n.id));
  269. function buildHierarchy(nodeId, processedNodes = new Set()) {
  270. const node = nodes.find(n => n.id === nodeId);
  271. if (!node || processedNodes.has(nodeId)) return null;
  272. processedNodes.add(nodeId);
  273. const children = hierarchicalLinks.filter(l => l.source === nodeId)
  274. .map(l => buildHierarchy(l.target, processedNodes))
  275. .filter(c => c !== null);
  276. const spouses = spouseLinks.filter(l => l.parent_mid === nodeId)
  277. .map(l => {
  278. const spouseId = l.child_mid;
  279. if (!childIds.has(spouseId)) {
  280. const sNode = nodes.find(n => n.id === spouseId);
  281. if (sNode && !processedNodes.has(spouseId)) {
  282. processedNodes.add(spouseId);
  283. return { id: sNode.id, name: sNode.name, simplified_name: sNode.simplified_name, sex: sNode.sex, isSpouseNode: true, children: [] };
  284. }
  285. }
  286. return null;
  287. })
  288. .filter(s => s !== null);
  289. return { id: node.id, name: node.name, simplified_name: node.simplified_name, sex: node.sex, children: spouses.concat(children) };
  290. }
  291. let treeData;
  292. if (roots.length > 1) {
  293. treeData = { name: "家谱根源", children: roots.map(root => buildHierarchy(root.id)).filter(r => r !== null) };
  294. } else if (roots.length === 1) {
  295. treeData = buildHierarchy(roots[0].id);
  296. } else {
  297. treeData = buildHierarchy(nodes[0].id);
  298. }
  299. const margin = {top: 80, right: 60, bottom: 80, left: 60};
  300. const containerWidth = document.getElementById('tree-container').offsetWidth;
  301. let rootNode = d3.hierarchy(treeData, d => (d && d.children) || []);
  302. // 动态调整间距,保证节点绝对不重叠,长辈/同辈/配偶使用固定基础间距
  303. const nodeWidth = 120; // 增加基础宽度以避免重叠
  304. const nodeHeight = 260; // 基础高度,调大以避免上下层重叠
  305. const treemap = d3.tree().nodeSize([nodeWidth, nodeHeight]).separation((a, b) => {
  306. return a.parent === b.parent ? 2.0 : 2.0; // 增加同级节点间距
  307. });
  308. let nodesHier = treemap(rootNode);
  309. // 配偶固定在同一水平线上:与本人并列显示
  310. const spouseSpreadX = 140; // 增加间距以确保不重叠
  311. nodesHier.descendants().forEach(parent => {
  312. const spouses = (parent.children || []).filter(c => c.data && c.data.isSpouseNode);
  313. if (spouses.length === 0) return;
  314. spouses.forEach((spouse, idx) => {
  315. // 计算配偶位置,从右侧开始排列
  316. spouse.x = parent.x + (idx + 1) * spouseSpreadX;
  317. spouse.y = parent.y; // 同一水平线
  318. });
  319. });
  320. // 计算边界以动态设置 SVG 宽高,实现自动滚动不挤压
  321. let x0 = Infinity;
  322. let x1 = -Infinity;
  323. let y1 = -Infinity;
  324. nodesHier.descendants().forEach(d => {
  325. if (d.x < x0) x0 = d.x;
  326. if (d.x > x1) x1 = d.x;
  327. if (d.y > y1) y1 = d.y;
  328. });
  329. // 增加更宽的边距以确保左侧不被切断
  330. const minWidth = containerWidth;
  331. const calculatedWidth = x1 - x0 + margin.left + margin.right + 400; // 增加额外的宽度缓冲
  332. const svgWidth = Math.max(minWidth, calculatedWidth);
  333. const svgHeight = Math.max(600, y1 + margin.top + margin.bottom);
  334. // 修正偏移量计算:确保最小的 x0 节点完全在可视区域内(加上足够的左边距)
  335. // 这样即便是负的很大,也会被完整平移到正数区域
  336. const extraLeftMargin = 200; // 增加更多左侧空间
  337. let offsetX = margin.left - x0 + extraLeftMargin; // 强制将最左侧节点右移确保文字不被截断
  338. // 确保offsetX至少为margin.left,防止内容被左侧菜单遮挡
  339. offsetX = Math.max(offsetX, margin.left + 50);
  340. const svg = d3.select("#tree-container").append("svg")
  341. .attr("width", svgWidth)
  342. .attr("height", svgHeight)
  343. .call(zoomBehavior)
  344. .append("g")
  345. .attr("transform", `translate(${offsetX},${margin.top})`);
  346. // 存储SVG元素引用,用于缩放操作
  347. window.svgGroup = svg;
  348. // 节点圆圈半径(连线与节点共用),调大让图谱更清晰大气
  349. const circleR = 20;
  350. // 辅助函数:绘制精致的徽章式关系标签
  351. function addBadge(g, x, y, text) {
  352. const group = g.append("g").attr("transform", `translate(${x},${y})`);
  353. group.append("rect")
  354. .attr("x", -20).attr("y", -10)
  355. .attr("width", 40).attr("height", 20)
  356. .attr("rx", 10).attr("ry", 10) // 胶囊形状
  357. .attr("fill", "#fff")
  358. .attr("stroke", "#CBD5E1").attr("stroke-width", 1.2);
  359. group.append("text")
  360. .attr("class", "link-label")
  361. .attr("x", 0).attr("y", 0).attr("dy", "0.32em")
  362. .attr("text-anchor", "middle")
  363. .text(text);
  364. }
  365. // 连线:第二层连线设计(U型配偶线 + 亲子水平线)
  366. nodesHier.descendants().forEach(node => {
  367. if (!node.children || node.children.length === 0) return;
  368. const realChildren = (node.children || []).filter(c => c.data && !c.data.isSpouseNode);
  369. const spouses = (node.children || []).filter(c => c.data && c.data.isSpouseNode);
  370. // 配偶连线拐点:位于本人与配偶节点之间,匹配“下层半级”显示
  371. // const hY = node.y + Math.round(spouseHalfLevelOffsetY * 0.55);
  372. const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
  373. // 夫妻关系:水平连线(主节点右侧连接到配偶左侧)
  374. if (spouses.length > 0) {
  375. const g = svg.append("g").attr("class", "link-group");
  376. spouses.forEach((spouse, idx) => {
  377. // 水平连线,稍微向下偏移一点以避开节点
  378. const linkY = node.y + 10;
  379. const pathD = `M${num(node.x + circleR)},${num(linkY)}
  380. L${num(spouse.x - circleR)},${num(linkY)}`;
  381. g.append("path").attr("class", "link link-spouse").attr("d", pathD);
  382. if (idx === 0) addBadge(g, (node.x + spouse.x) / 2, linkY, "配偶");
  383. });
  384. }
  385. if (realChildren.length === 0) return;
  386. const childrenY = realChildren[0].y;
  387. const minChildX = d3.min(realChildren, c => c.x);
  388. const maxChildX = d3.max(realChildren, c => c.x);
  389. // 如果有配偶,子代主线从本人和最右侧配偶的中间引出,否则从自己直接引出
  390. const startX = spouses.length > 0 ? (node.x + spouses[spouses.length - 1].x) / 2 : node.x;
  391. const startY = node.y + circleR;
  392. // 将子女横线也相应地下移一些,避免和配偶长名字重叠
  393. const sibsY = childrenY - 60;
  394. const g = svg.append("g").attr("class", "link-group");
  395. const hLineLeft = Math.min(minChildX, startX);
  396. const hLineRight = Math.max(maxChildX, startX);
  397. // 主线:从配偶U型线中点连到子女水平线
  398. let pathD = `M${num(startX)},${num(startY)} L${num(startX)},${num(sibsY)} M${num(hLineLeft)},${num(sibsY)} L${num(hLineRight)},${num(sibsY)}`;
  399. // 短竖线:连到每个子女顶部
  400. realChildren.forEach(child => {
  401. pathD += ` M${num(child.x)},${num(sibsY)} L${num(child.x)},${num(child.y) - circleR}`;
  402. });
  403. g.append("path").attr("class", "link link-parent-child").attr("d", pathD);
  404. // 去除家谱根源到第一层的关系展示;下层亲子关系标记使用徽章式标签放在短竖线上,一目了然
  405. const isRootToFirst = !node.parent || !(node.data && node.data.id);
  406. if (!isRootToFirst && node.data) {
  407. realChildren.forEach(child => {
  408. const pSex = node.data.sex;
  409. const cSex = child.data && child.data.sex;
  410. let label = "亲子";
  411. if (pSex === 1) label = cSex === 1 ? "父子" : "父女";
  412. else if (pSex === 2) label = cSex === 1 ? "母子" : "母女";
  413. const childLinkMidY = (sibsY + child.y - circleR) / 2;
  414. addBadge(g, child.x, childLinkMidY, label);
  415. });
  416. }
  417. });
  418. // 兄弟/姐妹:上方 U 型连线避免穿透节点
  419. const idToPos = {};
  420. nodesHier.descendants().forEach(d => { if (d.data.id) idToPos[d.data.id] = { x: d.x, y: d.y }; });
  421. otherLinks.forEach(rel => {
  422. const s = idToPos[rel.parent_mid], t = idToPos[rel.child_mid];
  423. if (s && t) {
  424. const x1 = Math.min(s.x, t.x), x2 = Math.max(s.x, t.x);
  425. const y = s.y - circleR - 25; // 兄弟线在节点上方
  426. const g = svg.append("g");
  427. const pathD = `M${x1},${s.y - circleR} L${x1},${y} L${x2},${y} L${x2},${t.y - circleR}`;
  428. g.append("path").attr("class", "link link-sibling").attr("d", pathD);
  429. addBadge(g, (x1 + x2) / 2, y, rel.relation_type === 11 ? "兄弟" : "姐妹");
  430. }
  431. });
  432. const node = svg.selectAll(".node")
  433. .data(nodesHier.descendants())
  434. .enter().append("g")
  435. .attr("class", d => {
  436. let cls = "node" + (d.children ? " node--internal" : " node--leaf");
  437. if (d.data.sex === 1) cls += " node-male";
  438. else if (d.data.sex === 2) cls += " node-female";
  439. return cls;
  440. })
  441. .attr("transform", d => `translate(${d.x},${d.y})`)
  442. .on("contextmenu", function(event, d) {
  443. if (!d.data.id) return;
  444. event.preventDefault();
  445. selectedMid = d.data.id;
  446. const containerRect = document.getElementById('tree-container').getBoundingClientRect();
  447. contextMenu.style.display = 'block';
  448. contextMenu.style.left = (event.clientX - containerRect.left) + 'px';
  449. contextMenu.style.top = (event.clientY - containerRect.top) + 'px';
  450. })
  451. .call(d3.drag()
  452. .on("start", dragstarted)
  453. .on("drag", dragged)
  454. .on("end", dragended));
  455. // 图形:男性方形,女性圆形,更符合生物遗传图谱
  456. node.each(function(d) {
  457. const el = d3.select(this);
  458. if (d.data.sex === 1) {
  459. el.append("rect")
  460. .attr("x", -circleR).attr("y", -circleR)
  461. .attr("width", circleR * 2).attr("height", circleR * 2)
  462. .style("cursor", "grab");
  463. } else {
  464. el.append("circle")
  465. .attr("r", circleR)
  466. .style("cursor", "grab");
  467. }
  468. });
  469. // 人名:往下移动更多,避免和长方形/圆形图形或者连线重叠
  470. const nameOffsetY = circleR + 25; // 增加间距
  471. const maxNameLen = 12; // 允许稍微长一点的文字
  472. function fullName(d) {
  473. if (!d.data) return '';
  474. return d.data.simplified_name ? `${d.data.name || ''} (${d.data.simplified_name})` : (d.data.name || '');
  475. }
  476. const nameGroup = node.append("g").attr("class", "node-name-wrap").attr("transform", "translate(0, " + nameOffsetY + ")");
  477. nameGroup.each(function(d) {
  478. const g = d3.select(this);
  479. const full = fullName(d);
  480. const disp = full.length <= maxNameLen ? full : full.slice(0, maxNameLen) + '…';
  481. // 姓名可能较长,我们这里做个简单的多行拆分显示或者让它有一个白色背景遮挡线
  482. // 这里为了简单不破坏原有结构,仅使用 text,但可以给一个白色的 stroke 做底或者调整 y 坐标
  483. const textNode = g.append("text")
  484. .attr("class", "node-name")
  485. .attr("x", 0).attr("y", 0)
  486. .attr("dy", "0.8em") // 使得文字基线往下靠,进一步远离图形
  487. .attr("text-anchor", "middle")
  488. .style("pointer-events", "all")
  489. .style("cursor", "default")
  490. .text(disp);
  491. if (full.length > maxNameLen) {
  492. textNode.append("title").text(full);
  493. }
  494. });
  495. function dragstarted(event, d) {
  496. if (!d.data.id) return;
  497. d3.select(this).raise().classed("active", true);
  498. d._currentX = d.x; d._currentY = d.y;
  499. dragSource = d.data;
  500. }
  501. function dragged(event, d) {
  502. d._currentX += event.dx; d._currentY += event.dy;
  503. d3.select(this).attr("transform", `translate(${d._currentX},${d._currentY})`);
  504. }
  505. function dragended(event, d) {
  506. d3.select(this).classed("active", false);
  507. const mouseX = event.sourceEvent.clientX, mouseY = event.sourceEvent.clientY;
  508. let foundNode = null;
  509. svg.selectAll(".node").each(function(nodeData) {
  510. if (!nodeData.data || nodeData.data.id === d.data.id || !nodeData.data.id) return;
  511. const rect = this.getBoundingClientRect();
  512. if (mouseX >= rect.left && mouseX <= rect.right && mouseY >= rect.top && mouseY <= rect.bottom) foundNode = nodeData.data;
  513. });
  514. if (foundNode && foundNode.id) {
  515. dragTarget = foundNode;
  516. document.getElementById('sourceMid').value = dragSource.id;
  517. document.getElementById('targetMid').value = dragTarget.id;
  518. document.getElementById('relationInfo').innerHTML = `确认将 <strong>${dragSource.name}</strong> 设定为 <strong>${dragTarget.name}</strong> 的关系人?`;
  519. relationModal.show();
  520. }
  521. setTimeout(() => { renderTree(currentData); }, 100);
  522. }
  523. } catch (err) {
  524. console.error('renderTree error:', err);
  525. container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">关系图渲染出错,请刷新重试。<br>' + (err.message || '') + '</div>';
  526. }
  527. }
  528. function saveRelation() {
  529. const payload = {
  530. source_mid: document.getElementById('sourceMid').value,
  531. target_mid: document.getElementById('targetMid').value,
  532. relation_type: document.getElementById('relType').value,
  533. sub_relation_type: document.getElementById('subRelType').value
  534. };
  535. fetch('/manager/api/save_relation', {
  536. method: 'POST',
  537. headers: { 'Content-Type': 'application/json' },
  538. body: JSON.stringify(payload)
  539. }).then(res => res.json()).then(data => {
  540. if (data.success) { relationModal.hide(); loadTree(); }
  541. else { alert('保存失败: ' + data.message); }
  542. });
  543. }
  544. // 缩放函数
  545. function zoomed(event) {
  546. zoomTransform = event.transform;
  547. zoomScale = event.transform.k;
  548. if (window.svgGroup) {
  549. window.svgGroup.attr("transform", event.transform);
  550. }
  551. }
  552. function zoomIn() {
  553. if (zoomScale < 4) {
  554. const newScale = zoomScale * 1.2;
  555. const container = document.getElementById('tree-container');
  556. const centerX = container.clientWidth / 2;
  557. const centerY = container.clientHeight / 2;
  558. const svg = d3.select("#tree-container svg");
  559. svg.transition().duration(300).call(
  560. zoomBehavior.transform,
  561. d3.zoomIdentity.translate(centerX, centerY).scale(newScale).translate(-centerX, -centerY)
  562. );
  563. }
  564. }
  565. function zoomOut() {
  566. if (zoomScale > 0.1) {
  567. const newScale = zoomScale / 1.2;
  568. const container = document.getElementById('tree-container');
  569. const centerX = container.clientWidth / 2;
  570. const centerY = container.clientHeight / 2;
  571. const svg = d3.select("#tree-container svg");
  572. svg.transition().duration(300).call(
  573. zoomBehavior.transform,
  574. d3.zoomIdentity.translate(centerX, centerY).scale(newScale).translate(-centerX, -centerY)
  575. );
  576. }
  577. }
  578. function zoomReset() {
  579. const svg = d3.select("#tree-container svg");
  580. svg.transition().duration(300).call(
  581. zoomBehavior.transform,
  582. d3.zoomIdentity
  583. );
  584. zoomScale = 1;
  585. }
  586. // 搜索成员并定位
  587. function searchMember() {
  588. const searchTerm = document.getElementById('memberSearch').value.trim();
  589. if (!searchTerm) {
  590. alert('请输入成员名字');
  591. return;
  592. }
  593. if (!currentData || !currentData.members) {
  594. alert('数据未加载完成,请稍后再试');
  595. return;
  596. }
  597. // 搜索匹配的成员
  598. const matchedMembers = currentData.members.filter(member => {
  599. if (!member) return false;
  600. const name = (member.name || '').toLowerCase();
  601. const simplifiedName = (member.simplified_name || '').toLowerCase();
  602. const searchLower = searchTerm.toLowerCase();
  603. return name.includes(searchLower) || simplifiedName.includes(searchLower);
  604. });
  605. if (matchedMembers.length === 0) {
  606. alert('未找到匹配的成员');
  607. return;
  608. }
  609. // 如果找到多个匹配项,让用户选择
  610. let targetMember;
  611. if (matchedMembers.length === 1) {
  612. targetMember = matchedMembers[0];
  613. } else {
  614. const memberNames = matchedMembers.map(m => `${m.name} (${m.simplified_name || '无简化名'})`).join('\n');
  615. const selectedIndex = prompt(`找到多个匹配成员,请输入编号选择:\n${matchedMembers.map((m, i) => `${i + 1}. ${m.name} (${m.simplified_name || '无简化名'})`).join('\n')}`);
  616. const index = parseInt(selectedIndex) - 1;
  617. if (isNaN(index) || index < 0 || index >= matchedMembers.length) {
  618. return;
  619. }
  620. targetMember = matchedMembers[index];
  621. }
  622. // 定位到成员
  623. locateMember(targetMember.id);
  624. }
  625. // 定位到指定成员
  626. function locateMember(memberId) {
  627. const svg = d3.select("#tree-container svg");
  628. if (!svg.empty()) {
  629. // 查找对应的节点
  630. const node = d3.selectAll(".node").filter(function(d) {
  631. return d.data && d.data.id === memberId;
  632. });
  633. if (node.size() > 0) {
  634. // 获取节点位置
  635. const nodeData = node.datum();
  636. const container = document.getElementById('tree-container');
  637. const containerWidth = container.clientWidth;
  638. const containerHeight = container.clientHeight;
  639. // 计算缩放和平移,使节点位于中心
  640. const scale = 1.5; // 放大一点以突出显示
  641. const translateX = containerWidth / 2 - nodeData.x * scale;
  642. const translateY = containerHeight / 2 - nodeData.y * scale;
  643. // 应用变换
  644. svg.transition().duration(1000).call(
  645. zoomBehavior.transform,
  646. d3.zoomIdentity.translate(translateX, translateY).scale(scale)
  647. );
  648. // 高亮显示节点
  649. node.select("rect, circle").transition().duration(500)
  650. .attr("stroke", "#ff0000")
  651. .attr("stroke-width", 3)
  652. .transition().duration(1000).attr("stroke", function(d) {
  653. return d.data.sex === 1 ? "#3B82F6" : "#EC4899";
  654. }).attr("stroke-width", 2);
  655. } else {
  656. alert('未在树中找到该成员');
  657. }
  658. } else {
  659. alert('树图未加载完成,请稍后再试');
  660. }
  661. }
  662. // 支持回车键搜索
  663. document.getElementById('memberSearch').addEventListener('keypress', function(e) {
  664. if (e.key === 'Enter') {
  665. searchMember();
  666. }
  667. });
  668. </script>
  669. {% endblock %}