tree.html 25 KB

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