| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003 |
- {% extends "layout.html" %}
- {% block title %}家谱世系树状图 - 家谱管理系统{% endblock %}
- {% block extra_css %}
- <style>
- #tree-container {
- width: 100%;
- height: 700px;
- background: white;
- border: 1px solid #e9ecef;
- border-radius: 8px;
- margin-top: 10px;
- box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
- position: relative;
- overflow: hidden;
- }
-
- .zoom-controls {
- position: absolute;
- top: 10px;
- right: 10px;
- z-index: 100;
- background: white;
- border-radius: 4px;
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
- padding: 5px;
- }
-
- .zoom-btn {
- display: block;
- width: 30px;
- height: 30px;
- margin: 5px 0;
- border: 1px solid #ddd;
- border-radius: 4px;
- background: white;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- }
-
- .zoom-btn:hover {
- background: #f8f9fa;
- }
-
- #tree-container::-webkit-scrollbar {
- width: 8px;
- height: 8px;
- }
-
- #tree-container::-webkit-scrollbar-track {
- background: #f1f1f1;
- border-radius: 4px;
- }
-
- #tree-container::-webkit-scrollbar-thumb {
- background: #c1c1c1;
- border-radius: 4px;
- }
-
- #tree-container::-webkit-scrollbar-thumb:hover {
- background: #a1a1a1;
- }
- .node rect, .node circle {
- stroke-width: 2px;
- filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
- }
- .node text { font: 13px 'Microsoft YaHei', sans-serif; }
- .node .node-name {
- font-size: 13px;
- font-weight: 500;
- fill: #334155;
- stroke: #fff;
- stroke-width: 4px;
- paint-order: stroke;
- stroke-linejoin: round;
- }
-
- /* 样图一致:较粗的细实线、浅灰蓝色,显得专业 */
- .link { fill: none; stroke: #94A3B8; stroke-width: 2px; stroke-linejoin: round; }
-
- /* 关系标签文字,取消白色粗描边,因为已有胶囊形背景 */
- .link-label { font-size: 11px; fill: #64748B; font-weight: 500; }
- .link-label-sibling { fill: #64748B; }
- /* 男女形状与颜色区分:男性方形(蓝),女性圆形(粉红),添加轻微圆角与投影 */
- .node-male rect { stroke: #3B82F6; fill: #EFF6FF; rx: 8px; ry: 8px; }
-
- /* 出继节点样式:同色虚线框,仅边框样式区别,颜色与普通节点保持一致 */
- .node-adopted-out rect, .node-adopted-out circle {
- stroke-dasharray: 6, 4 !important;
- }
- .node-female circle { stroke: #EC4899; fill: #FDF2F8; }
-
- /* 未知性别默认 */
- .node-leaf circle, .node-internal circle { stroke: #94A3B8; fill: #F8FAFC; }
- .node-male circle { stroke: none; fill: none; } /* 清除可能的干扰 */
- /* 样图一致:全部细实线 */
- .link-parent-child { stroke: #333; stroke-dasharray: none; }
- .link-spouse { stroke: #333; stroke-dasharray: none; stroke-width: 1.2px; }
- .link-sibling { stroke: #333; stroke-dasharray: none; stroke-width: 1.2px; }
- /* 右键菜单样式 */
- .context-menu {
- position: absolute;
- display: none;
- background: white;
- border: 1px solid #ccc;
- box-shadow: 2px 2px 10px rgba(0,0,0,0.2);
- z-index: 1000;
- border-radius: 4px;
- padding: 5px 0;
- min-width: 120px;
- }
- .context-menu-item {
- padding: 8px 15px;
- cursor: pointer;
- font-size: 14px;
- color: #333;
- }
- .context-menu-item:hover {
- background-color: #f8f9fa;
- color: #0d6efd;
- }
- .context-menu-item i {
- margin-right: 8px;
- }
- /* 折叠/展开 +/- 小圆钮 */
- .collapse-toggle {
- cursor: pointer;
- }
- .collapse-toggle circle {
- transition: fill 0.2s, transform 0.2s;
- }
- .collapse-toggle:hover circle {
- opacity: 0.85;
- }
- .collapse-toggle text {
- pointer-events: none;
- user-select: none;
- }
- /* 节点被折叠时降低透明度以区分 */
- .node-collapsed > rect,
- .node-collapsed > circle {
- opacity: 0.75;
- stroke-dasharray: 5, 3;
- }
- </style>
- {% endblock %}
- {% block content %}
- <div class="d-flex justify-content-between align-items-center mb-3">
- <h2><i class="bi bi-diagram-3"></i> 家谱关系树状图</h2>
- <div class="d-flex gap-2">
- <div class="input-group" style="width: 300px;">
- <input type="text" id="memberSearch" class="form-control form-control-sm" placeholder="输入成员名字搜索">
- <button class="btn btn-sm btn-primary" onclick="searchMember()">
- <i class="bi bi-search"></i> 搜索
- </button>
- </div>
- <button class="btn btn-outline-secondary btn-sm" onclick="expandAll()" title="展开所有已折叠节点">
- <i class="bi bi-arrows-expand"></i> 全部展开
- </button>
- <a href="{{ url_for('tree_classic') }}" class="btn btn-outline-primary btn-sm">
- <i class="bi bi-printer"></i> 导出传统吊线图
- </a>
- </div>
- </div>
- <div class="alert alert-light border small py-2">
- <i class="bi bi-info-circle me-1"></i> 提示:图中按家谱世系树状图格式展示。支持拖拽建立关系,右键点击成员可查看、编辑或新增。
- </div>
- <div id="tree-container">
- <!-- 缩放控制 -->
- <div class="zoom-controls">
- <button class="zoom-btn" onclick="zoomIn()"><i class="bi bi-plus"></i></button>
- <button class="zoom-btn" onclick="zoomOut()"><i class="bi bi-dash"></i></button>
- <button class="zoom-btn" onclick="zoomReset()"><i class="bi bi-arrow-counterclockwise"></i></button>
- </div>
- <!-- 右键菜单 -->
- <div id="contextMenu" class="context-menu">
- <div class="context-menu-item" onclick="menuAction('detail')"><i class="bi bi-eye"></i>查看成员</div>
- <div class="context-menu-item" onclick="menuAction('edit')"><i class="bi bi-pencil"></i>编辑成员</div>
- <div class="context-menu-item" onclick="menuAction('add')"><i class="bi bi-plus-lg"></i>新增成员</div>
- <div class="context-menu-item" id="collapseMenuItem" onclick="menuAction('collapse')"><i class="bi bi-arrows-collapse"></i>收起子节点</div>
- </div>
- </div>
- <!-- 关系选择弹窗 -->
- <div class="modal fade" id="relationModal" tabindex="-1">
- <div class="modal-dialog modal-sm">
- <div class="modal-content">
- <div class="modal-header">
- <h5 class="modal-title">建立关系</h5>
- <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
- </div>
- <div class="modal-body">
- <p id="relationInfo" class="small mb-3"></p>
- <input type="hidden" id="sourceMid">
- <input type="hidden" id="targetMid">
- <div class="mb-3">
- <label class="form-label small">关系类型</label>
- <select id="relType" class="form-select form-select-sm">
- <option value="1">是其 儿子/女儿</option>
- <option value="10">是其 妻子/丈夫</option>
- <option value="11">是其 兄弟</option>
- <option value="12">是其 姐妹</option>
- </select>
- </div>
- <div class="mb-3">
- <label class="form-label small">子类型</label>
- <select id="subRelType" class="form-select form-select-sm">
- <option value="0">亲生/正妻</option>
- <option value="1">养子/女</option>
- <option value="2">过继</option>
- </select>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">取消</button>
- <button type="button" class="btn btn-sm btn-primary" onclick="saveRelation()">保存关系</button>
- </div>
- </div>
- </div>
- </div>
- {% endblock %}
- {% block extra_js %}
- <!-- 优先使用本地 D3.js -->
- <script src="{{ url_for('static', filename='js/d3.min.js') }}"></script>
- <!-- fallback to CDN if local fails -->
- <script>
- if (typeof d3 === 'undefined') {
- var script = document.createElement('script');
- script.src = 'https://cdn.jsdelivr.net/npm/d3@7.8.5/dist/d3.min.js';
- script.onload = function() {
- if (typeof d3 !== 'undefined') {
- loadTree();
- } else {
- var container = document.getElementById('tree-container');
- if (container) container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">D3.js 未加载,请检查网络或稍后重试。</div>';
- }
- };
- script.onerror = function() {
- var container = document.getElementById('tree-container');
- if (container) container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">D3.js 未加载,请检查网络或稍后重试。</div>';
- };
- document.head.appendChild(script);
- }
- </script>
- <script>
- (function() {
- if (typeof d3 === 'undefined') {
- // CDN will handle loading and initialization
- }
- })();
- let currentData = null;
- let dragSource = null;
- let dragTarget = null;
- let selectedMid = null; // 当前选中的成员 ID
- let collapsedNodes = new Set(); // 已折叠的节点 ID 集合
- let zoomScale = 1;
- let zoomTransform = d3.zoomIdentity;
- let zoomBehavior = d3.zoom().scaleExtent([0.1, 4]).on("zoom", zoomed);
- const relationModal = new bootstrap.Modal(document.getElementById('relationModal'));
- const contextMenu = document.getElementById('contextMenu');
- // 隐藏右键菜单
- window.addEventListener('click', () => {
- contextMenu.style.display = 'none';
- });
- // 全部展开
- function expandAll() {
- collapsedNodes.clear();
- renderTree(currentData);
- }
- // 处理菜单点击
- function menuAction(type) {
- if (!selectedMid && type !== 'add') return;
-
- switch(type) {
- case 'detail':
- window.location.href = `/manager/member_detail/${selectedMid}`;
- break;
- case 'edit':
- window.location.href = `/manager/edit_member/${selectedMid}`;
- break;
- case 'add':
- window.location.href = '/manager/add_member';
- break;
- case 'collapse': {
- const savedTr = zoomTransform;
- if (collapsedNodes.has(selectedMid)) {
- collapsedNodes.delete(selectedMid);
- } else {
- collapsedNodes.add(selectedMid);
- }
- renderTree(currentData);
- d3.select("#tree-container svg").call(zoomBehavior.transform, savedTr);
- break;
- }
- }
- }
- // 获取数据并渲染
- function loadTree() {
- if (typeof d3 === 'undefined') return;
- fetch('/manager/api/tree_data')
- .then(response => response.json())
- .then(data => {
- currentData = data;
- renderTree(data);
- });
- }
- if (typeof d3 !== 'undefined') loadTree();
- function renderTree(data) {
- const container = document.getElementById('tree-container');
- container.innerHTML = '';
- container.appendChild(contextMenu);
- try {
- const { members, relations } = data;
- if (!members || members.length === 0) {
- container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-muted">暂无成员数据,无法生成关系图。</div>';
- return;
- }
- // 构建节点,保留所有关系信息
- const nodes = members.map(m => ({ id: m.id, name: m.name, simplified_name: m.simplified_name, sex: m.sex, adoptedOut: false, adoptedOutTarget: null }));
-
- // 获取所有父子关系(包括出继/入继)
- const allHierarchicalRelations = relations.filter(r => r.relation_type === 1 || r.relation_type === 2);
-
- // 对于出继的子女,只要有 sub_relation_type===2 的关系即标记;同时尝试找到入继目标名称
- const adoptedOutMap = new Map();
- allHierarchicalRelations.forEach(r => {
- if (r.sub_relation_type === 2) { // 出继
- // 即便未找到入继关系也先标记(target 置 null)
- if (!adoptedOutMap.has(r.child_mid)) {
- adoptedOutMap.set(r.child_mid, null);
- }
- // 尝试找到对应的入继关系,获取养父名
- const targetRelation = allHierarchicalRelations.find(r2 => r2.child_mid === r.child_mid && r2.sub_relation_type === 3);
- if (targetRelation) {
- const targetMember = members.find(m => m.id === targetRelation.parent_mid);
- if (targetMember) {
- adoptedOutMap.set(r.child_mid, targetMember.name);
- }
- }
- }
- });
-
- // 更新节点的出继标记
- nodes.forEach(node => {
- if (adoptedOutMap.has(node.id)) {
- node.adoptedOut = true;
- node.adoptedOutTarget = adoptedOutMap.get(node.id);
- }
- });
-
- // 保留所有父子关系(包括出继),用于构建树
- const hierarchicalLinks = allHierarchicalRelations.map(r => ({
- source: r.parent_mid,
- target: r.child_mid,
- sub_relation_type: r.sub_relation_type
- }));
- // ── 推断缺失的入继关系 ──────────────────────────────────────────────
- // 若同一亲生父的多个出继子女共享同一已知养父,则为缺失入继记录的子女补全推断链接
- {
- // 按亲生父分组:parentId → [childId, ...](仅 sub=2 的出继子女)
- const outByParent = new Map();
- allHierarchicalRelations.forEach(r => {
- if (r.sub_relation_type === 2) {
- if (!outByParent.has(r.parent_mid)) outByParent.set(r.parent_mid, []);
- outByParent.get(r.parent_mid).push(r.child_mid);
- }
- });
- outByParent.forEach((childMids, _parentId) => {
- // 收集已知养父 ID 集合
- const knownTargetIds = new Set();
- childMids.forEach(childId => {
- const link = hierarchicalLinks.find(l => l.target === childId && l.sub_relation_type === 3);
- if (link) knownTargetIds.add(link.source);
- });
- // 只有唯一确定的养父时才推断(避免歧义)
- if (knownTargetIds.size === 1) {
- const adoptiveParentId = [...knownTargetIds][0];
- childMids.forEach(childId => {
- const exists = hierarchicalLinks.some(l => l.source === adoptiveParentId && l.target === childId && l.sub_relation_type === 3);
- if (!exists) {
- hierarchicalLinks.push({ source: adoptiveParentId, target: childId, sub_relation_type: 3 });
- // 同步更新 adoptedOutTarget
- const targetMember = members.find(m => m.id === adoptiveParentId);
- if (targetMember && adoptedOutMap.has(childId) && !adoptedOutMap.get(childId)) {
- adoptedOutMap.set(childId, targetMember.name);
- }
- }
- });
- }
- });
- // adoptedOutTarget 同步回 nodes
- nodes.forEach(node => {
- if (adoptedOutMap.has(node.id)) {
- node.adoptedOut = true;
- node.adoptedOutTarget = adoptedOutMap.get(node.id);
- }
- });
- }
- // ────────────────────────────────────────────────────────────────────
- const spouseLinks = relations.filter(r => r.relation_type === 10);
- const otherLinks = relations.filter(r => r.relation_type >= 11);
- const childIds = new Set(hierarchicalLinks.map(l => l.target));
- const allSpouseIds = new Set(spouseLinks.map(l => l.child_mid));
- const roots = nodes.filter(n => !childIds.has(n.id) && !allSpouseIds.has(n.id));
- function buildHierarchy(nodeId, processedNodes = new Set()) {
- const node = nodes.find(n => n.id === nodeId);
- if (!node || processedNodes.has(nodeId)) return null;
- processedNodes.add(nodeId);
- const childLinks = hierarchicalLinks.filter(l => l.source === nodeId);
- const hasHierarchicalChildren = childLinks.length > 0;
- const isCollapsed = collapsedNodes.has(nodeId);
- // 折叠时不递归子代(但仍保留配偶以维持同层显示)
- const children = isCollapsed
- ? []
- : childLinks.map(l => {
- if (processedNodes.has(l.target)) {
- // 入继(sub_relation_type===3)子女已在亲生父处渲染过,
- // 在养父下创建浅引用节点(不再递归,避免重复/死循环)
- if (l.sub_relation_type === 3) {
- const cn = nodes.find(n => n.id === l.target);
- if (cn) {
- return {
- id: cn.id,
- name: cn.name,
- simplified_name: cn.simplified_name,
- sex: cn.sex,
- adoptedIn: true,
- hasHierarchicalChildren: false,
- isCollapsed: false,
- children: []
- };
- }
- }
- return null;
- }
- return buildHierarchy(l.target, processedNodes);
- }).filter(c => c !== null);
- const spouses = spouseLinks.filter(l => l.parent_mid === nodeId)
- .map(l => {
- const spouseId = l.child_mid;
- if (!childIds.has(spouseId)) {
- const sNode = nodes.find(n => n.id === spouseId);
- if (sNode && !processedNodes.has(spouseId)) {
- processedNodes.add(spouseId);
- return { id: sNode.id, name: sNode.name, simplified_name: sNode.simplified_name, sex: sNode.sex, isSpouseNode: true, children: [] };
- }
- }
- return null;
- })
- .filter(s => s !== null);
- return {
- id: node.id,
- name: node.name,
- simplified_name: node.simplified_name,
- sex: node.sex,
- adoptedOut: node.adoptedOut,
- adoptedOutTarget: node.adoptedOutTarget,
- hasHierarchicalChildren,
- isCollapsed,
- children: spouses.concat(children)
- };
- }
- let treeData;
- if (roots.length > 1) {
- treeData = { name: "家谱根源", children: roots.map(root => buildHierarchy(root.id)).filter(r => r !== null) };
- } else if (roots.length === 1) {
- treeData = buildHierarchy(roots[0].id);
- } else {
- treeData = buildHierarchy(nodes[0].id);
- }
- const margin = {top: 80, right: 60, bottom: 80, left: 60};
- const containerWidth = document.getElementById('tree-container').offsetWidth;
- let rootNode = d3.hierarchy(treeData, d => (d && d.children) || []);
-
- // 动态调整间距,保证节点绝对不重叠,长辈/同辈/配偶使用固定基础间距
- const nodeWidth = 120; // 增加基础宽度以避免重叠
- const nodeHeight = 260; // 基础高度,调大以避免上下层重叠
- const treemap = d3.tree().nodeSize([nodeWidth, nodeHeight]).separation((a, b) => {
- return a.parent === b.parent ? 2.0 : 2.0; // 增加同级节点间距
- });
-
- let nodesHier = treemap(rootNode);
- // 配偶固定在同一水平线上:与本人并列显示
- const spouseSpreadX = 140; // 增加间距以确保不重叠
- nodesHier.descendants().forEach(parent => {
- const spouses = (parent.children || []).filter(c => c.data && c.data.isSpouseNode);
- if (spouses.length === 0) return;
- spouses.forEach((spouse, idx) => {
- // 计算配偶位置,从右侧开始排列
- spouse.x = parent.x + (idx + 1) * spouseSpreadX;
- spouse.y = parent.y; // 同一水平线
- });
- });
- // 计算边界以动态设置 SVG 宽高,实现自动滚动不挤压
- let x0 = Infinity;
- let x1 = -Infinity;
- let y1 = -Infinity;
- nodesHier.descendants().forEach(d => {
- if (d.x < x0) x0 = d.x;
- if (d.x > x1) x1 = d.x;
- if (d.y > y1) y1 = d.y;
- });
- // 增加更宽的边距以确保左侧不被切断
- const minWidth = containerWidth;
- const calculatedWidth = x1 - x0 + margin.left + margin.right + 400; // 增加额外的宽度缓冲
- const svgWidth = Math.max(minWidth, calculatedWidth);
- const svgHeight = Math.max(600, y1 + margin.top + margin.bottom);
-
- // 修正偏移量计算:确保最小的 x0 节点完全在可视区域内(加上足够的左边距)
- // 这样即便是负的很大,也会被完整平移到正数区域
- const extraLeftMargin = 200; // 增加更多左侧空间
- let offsetX = margin.left - x0 + extraLeftMargin; // 强制将最左侧节点右移确保文字不被截断
-
- // 确保offsetX至少为margin.left,防止内容被左侧菜单遮挡
- offsetX = Math.max(offsetX, margin.left + 50);
- const svg = d3.select("#tree-container").append("svg")
- .attr("width", svgWidth)
- .attr("height", svgHeight)
- .call(zoomBehavior)
- .append("g")
- .attr("transform", `translate(${offsetX},${margin.top})`);
-
- // 存储SVG元素引用,用于缩放操作
- window.svgGroup = svg;
- // 节点圆圈半径(连线与节点共用),调大让图谱更清晰大气
- const circleR = 20;
- // 辅助函数:绘制精致的徽章式关系标签
- function addBadge(g, x, y, text) {
- const group = g.append("g").attr("transform", `translate(${x},${y})`);
- group.append("rect")
- .attr("x", -20).attr("y", -10)
- .attr("width", 40).attr("height", 20)
- .attr("rx", 10).attr("ry", 10) // 胶囊形状
- .attr("fill", "#fff")
- .attr("stroke", "#CBD5E1").attr("stroke-width", 1.2);
- group.append("text")
- .attr("class", "link-label")
- .attr("x", 0).attr("y", 0).attr("dy", "0.32em")
- .attr("text-anchor", "middle")
- .text(text);
- }
- // 连线:第二层连线设计(U型配偶线 + 亲子水平线)
- nodesHier.descendants().forEach(node => {
- if (!node.children || node.children.length === 0) return;
- const realChildren = (node.children || []).filter(c => c.data && !c.data.isSpouseNode);
- const spouses = (node.children || []).filter(c => c.data && c.data.isSpouseNode);
- // 配偶连线拐点:位于本人与配偶节点之间,匹配“下层半级”显示
- // const hY = node.y + Math.round(spouseHalfLevelOffsetY * 0.55);
- const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
- // 夫妻关系:水平连线(主节点右侧连接到配偶左侧)
- if (spouses.length > 0) {
- const g = svg.append("g").attr("class", "link-group");
- spouses.forEach((spouse, idx) => {
- // 水平连线,稍微向下偏移一点以避开节点
- const linkY = node.y + 10;
- const pathD = `M${num(node.x + circleR)},${num(linkY)}
- L${num(spouse.x - circleR)},${num(linkY)}`;
- g.append("path").attr("class", "link link-spouse").attr("d", pathD);
-
- if (idx === 0) addBadge(g, (node.x + spouse.x) / 2, linkY, "配偶");
- });
- }
- if (realChildren.length === 0) return;
-
- const childrenY = realChildren[0].y;
- const minChildX = d3.min(realChildren, c => c.x);
- const maxChildX = d3.max(realChildren, c => c.x);
-
- // 如果有配偶,子代主线从本人和最右侧配偶的中间引出,否则从自己直接引出
- const startX = spouses.length > 0 ? (node.x + spouses[spouses.length - 1].x) / 2 : node.x;
- // 若节点有折叠按钮(底部),连线从按钮下方起始
- const startY = node.y + circleR + (node.data.hasHierarchicalChildren ? 28 : 0);
-
- // 将子女横线也相应地下移一些,避免和配偶长名字重叠
- const sibsY = childrenY - 60;
- const g = svg.append("g").attr("class", "link-group");
-
- const hLineLeft = Math.min(minChildX, startX);
- const hLineRight = Math.max(maxChildX, startX);
- // 主线:从配偶U型线中点连到子女水平线
- let pathD = `M${num(startX)},${num(startY)} L${num(startX)},${num(sibsY)} M${num(hLineLeft)},${num(sibsY)} L${num(hLineRight)},${num(sibsY)}`;
-
- // 短竖线:连到每个子女顶部
- realChildren.forEach(child => {
- pathD += ` M${num(child.x)},${num(sibsY)} L${num(child.x)},${num(child.y) - circleR}`;
- });
- g.append("path").attr("class", "link link-parent-child").attr("d", pathD);
- // 去除家谱根源到第一层的关系展示;下层亲子关系标记使用徽章式标签放在短竖线上,一目了然
- const isRootToFirst = !node.parent || !(node.data && node.data.id);
- if (!isRootToFirst && node.data) {
- realChildren.forEach(child => {
- const pSex = node.data.sex;
- const cSex = child.data && child.data.sex;
- let label = "亲子";
- if (child.data && child.data.adoptedIn) {
- label = cSex === 1 ? "养子" : "养女";
- } else if (pSex === 1) {
- label = cSex === 1 ? "父子" : "父女";
- } else if (pSex === 2) {
- label = cSex === 1 ? "母子" : "母女";
- }
-
- const childLinkMidY = (sibsY + child.y - circleR) / 2;
- addBadge(g, child.x, childLinkMidY, label);
- });
- }
- });
- // 兄弟/姐妹:上方 U 型连线避免穿透节点
- const idToPos = {};
- nodesHier.descendants().forEach(d => { if (d.data.id) idToPos[d.data.id] = { x: d.x, y: d.y }; });
- otherLinks.forEach(rel => {
- const s = idToPos[rel.parent_mid], t = idToPos[rel.child_mid];
- if (s && t) {
- const x1 = Math.min(s.x, t.x), x2 = Math.max(s.x, t.x);
- const y = s.y - circleR - 25; // 兄弟线在节点上方
- const g = svg.append("g");
- const pathD = `M${x1},${s.y - circleR} L${x1},${y} L${x2},${y} L${x2},${t.y - circleR}`;
- g.append("path").attr("class", "link link-sibling").attr("d", pathD);
- addBadge(g, (x1 + x2) / 2, y, rel.relation_type === 11 ? "兄弟" : "姐妹");
- }
- });
- const node = svg.selectAll(".node")
- .data(nodesHier.descendants())
- .enter().append("g")
- .attr("class", d => {
- let cls = "node" + (d.children ? " node--internal" : " node--leaf");
- if (d.data.sex === 1) cls += " node-male";
- else if (d.data.sex === 2) cls += " node-female";
- if (d.data.adoptedOut) cls += " node-adopted-out";
- return cls;
- })
- .attr("transform", d => `translate(${d.x},${d.y})`)
- .on("contextmenu", function(event, d) {
- if (!d.data.id) return;
- event.preventDefault();
- selectedMid = d.data.id;
- // 动态更新折叠菜单项文字与可见性
- const collapseItem = document.getElementById('collapseMenuItem');
- if (d.data.hasHierarchicalChildren) {
- collapseItem.style.display = '';
- const icon = collapseItem.querySelector('i');
- if (collapsedNodes.has(d.data.id)) {
- icon.className = 'bi bi-arrows-expand';
- collapseItem.childNodes[1].textContent = '展开子节点';
- } else {
- icon.className = 'bi bi-arrows-collapse';
- collapseItem.childNodes[1].textContent = '收起子节点';
- }
- } else {
- collapseItem.style.display = 'none';
- }
- const containerRect = document.getElementById('tree-container').getBoundingClientRect();
- contextMenu.style.display = 'block';
- contextMenu.style.left = (event.clientX - containerRect.left) + 'px';
- contextMenu.style.top = (event.clientY - containerRect.top) + 'px';
- })
- .call(d3.drag()
- .on("start", dragstarted)
- .on("drag", dragged)
- .on("end", dragended));
- // 图形:男性方形,女性圆形,更符合生物遗传图谱
- node.each(function(d) {
- const el = d3.select(this);
- // 出继节点 hover 提示
- if (d.data.adoptedOut) {
- const tip = d.data.adoptedOutTarget ? `出继给 ${d.data.adoptedOutTarget}` : '出继';
- el.append('title').text(tip);
- }
- if (d.data.sex === 1) {
- el.append("rect")
- .attr("x", -circleR).attr("y", -circleR)
- .attr("width", circleR * 2).attr("height", circleR * 2)
- .style("cursor", "grab");
- } else {
- el.append("circle")
- .attr("r", circleR)
- .style("cursor", "grab");
- }
- });
-
- // 人名:往下移动更多,避免和长方形/圆形图形或者连线重叠
- // 有折叠按钮的节点多留出按钮空间(按钮中心在 y=circleR,高度约 20px,再留 8px 间距)
- // circleR(20) + 按钮中心(12) + 按钮半径(11) + 间距(6) = 49
- const nameOffsetY = circleR + 49;
- const maxNameLen = 12; // 允许稍微长一点的文字
- function fullName(d) {
- if (!d.data) return '';
- return d.data.simplified_name ? `${d.data.name || ''} (${d.data.simplified_name})` : (d.data.name || '');
- }
-
- const nameGroup = node.append("g").attr("class", "node-name-wrap").attr("transform", "translate(0, " + nameOffsetY + ")");
- nameGroup.each(function(d) {
- const g = d3.select(this);
- const full = fullName(d);
- const disp = full.length <= maxNameLen ? full : full.slice(0, maxNameLen) + '…';
-
- // 姓名可能较长,我们这里做个简单的多行拆分显示或者让它有一个白色背景遮挡线
- // 这里为了简单不破坏原有结构,仅使用 text,但可以给一个白色的 stroke 做底或者调整 y 坐标
- const textNode = g.append("text")
- .attr("class", "node-name")
- .attr("x", 0).attr("y", 0)
- .attr("dy", "0.8em") // 使得文字基线往下靠,进一步远离图形
- .attr("text-anchor", "middle")
- .style("pointer-events", "all")
- .style("cursor", "default")
- .text(disp);
-
- if (full.length > maxNameLen) {
- textNode.append("title").text(full);
- }
- });
- // 标记折叠节点样式
- node.each(function(d) {
- if (d.data.isCollapsed) d3.select(this).classed("node-collapsed", true);
- });
- // ── 折叠/展开按钮 ──────────────────────────────────────────────────
- // 直接追加到 SVG 坐标层(非节点 g 内部),彻底脱离 drag 事件树,确保可见可点
- nodesHier.descendants().forEach(function(nd) {
- if (!nd.data.id || !nd.data.hasHierarchicalChildren) return;
- const collapsed = nd.data.isCollapsed;
- const bx = nd.x;
- const by = nd.y + circleR + 14; // 形状底边再往下 14px
- const tg = svg.append("g")
- .attr("class", "collapse-toggle")
- .attr("transform", `translate(${bx},${by})`)
- .style("cursor", "pointer");
- tg.on("mousedown", function(e) { e.stopPropagation(); });
- tg.on("click", function(e) {
- e.stopPropagation();
- const savedTransform = zoomTransform; // 保存当前视图位置
- if (collapsedNodes.has(nd.data.id)) {
- collapsedNodes.delete(nd.data.id);
- } else {
- collapsedNodes.add(nd.data.id);
- }
- renderTree(currentData);
- // 重建后立即还原 zoom 位置,不触发动画
- d3.select("#tree-container svg").call(zoomBehavior.transform, savedTransform);
- });
- tg.append("title").text(collapsed ? "展开子节点" : "收起子节点");
- // 白色底圆(防止线条透底)
- tg.append("circle").attr("r", 11).attr("fill", "white");
- // 彩色实心圆:展开=蓝,折叠=绿
- tg.append("circle")
- .attr("r", 10)
- .attr("fill", collapsed ? "#10B981" : "#3B82F6")
- .attr("stroke", "white").attr("stroke-width", 1.5);
- // 符号文字
- tg.append("text")
- .attr("text-anchor", "middle").attr("dy", "0.38em")
- .attr("fill", "white").attr("font-size", "16px").attr("font-weight", "bold")
- .attr("pointer-events", "none")
- .text(collapsed ? "+" : "−");
- });
- function dragstarted(event, d) {
- if (!d.data.id) return;
- d3.select(this).raise().classed("active", true);
- d._currentX = d.x; d._currentY = d.y;
- dragSource = d.data;
- }
- function dragged(event, d) {
- d._currentX += event.dx; d._currentY += event.dy;
- d3.select(this).attr("transform", `translate(${d._currentX},${d._currentY})`);
- }
- function dragended(event, d) {
- d3.select(this).classed("active", false);
- const mouseX = event.sourceEvent.clientX, mouseY = event.sourceEvent.clientY;
- let foundNode = null;
- svg.selectAll(".node").each(function(nodeData) {
- if (!nodeData.data || nodeData.data.id === d.data.id || !nodeData.data.id) return;
- const rect = this.getBoundingClientRect();
- if (mouseX >= rect.left && mouseX <= rect.right && mouseY >= rect.top && mouseY <= rect.bottom) foundNode = nodeData.data;
- });
- if (foundNode && foundNode.id) {
- dragTarget = foundNode;
- document.getElementById('sourceMid').value = dragSource.id;
- document.getElementById('targetMid').value = dragTarget.id;
- document.getElementById('relationInfo').innerHTML = `确认将 <strong>${dragSource.name}</strong> 设定为 <strong>${dragTarget.name}</strong> 的关系人?`;
- relationModal.show();
- }
- setTimeout(() => { renderTree(currentData); }, 100);
- }
- } catch (err) {
- console.error('renderTree error:', err);
- container.innerHTML = '<div class="h-100 d-flex align-items-center justify-content-center text-danger small">关系图渲染出错,请刷新重试。<br>' + (err.message || '') + '</div>';
- }
- }
- function saveRelation() {
- const payload = {
- source_mid: document.getElementById('sourceMid').value,
- target_mid: document.getElementById('targetMid').value,
- relation_type: document.getElementById('relType').value,
- sub_relation_type: document.getElementById('subRelType').value
- };
- fetch('/manager/api/save_relation', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- }).then(res => res.json()).then(data => {
- if (data.success) { relationModal.hide(); loadTree(); }
- else { alert('保存失败: ' + data.message); }
- });
- }
-
- // 缩放函数
- function zoomed(event) {
- zoomTransform = event.transform;
- zoomScale = event.transform.k;
- if (window.svgGroup) {
- window.svgGroup.attr("transform", event.transform);
- }
- }
-
- function zoomIn() {
- if (zoomScale < 4) {
- const newScale = zoomScale * 1.2;
- const container = document.getElementById('tree-container');
- const centerX = container.clientWidth / 2;
- const centerY = container.clientHeight / 2;
-
- const svg = d3.select("#tree-container svg");
- svg.transition().duration(300).call(
- zoomBehavior.transform,
- d3.zoomIdentity.translate(centerX, centerY).scale(newScale).translate(-centerX, -centerY)
- );
- }
- }
-
- function zoomOut() {
- if (zoomScale > 0.1) {
- const newScale = zoomScale / 1.2;
- const container = document.getElementById('tree-container');
- const centerX = container.clientWidth / 2;
- const centerY = container.clientHeight / 2;
-
- const svg = d3.select("#tree-container svg");
- svg.transition().duration(300).call(
- zoomBehavior.transform,
- d3.zoomIdentity.translate(centerX, centerY).scale(newScale).translate(-centerX, -centerY)
- );
- }
- }
-
- function zoomReset() {
- const svg = d3.select("#tree-container svg");
- svg.transition().duration(300).call(
- zoomBehavior.transform,
- d3.zoomIdentity
- );
- zoomScale = 1;
- }
- // 搜索成员并定位
- function searchMember() {
- const searchTerm = document.getElementById('memberSearch').value.trim();
- if (!searchTerm) {
- alert('请输入成员名字');
- return;
- }
- if (!currentData || !currentData.members) {
- alert('数据未加载完成,请稍后再试');
- return;
- }
- // 搜索匹配的成员
- const matchedMembers = currentData.members.filter(member => {
- if (!member) return false;
- const name = (member.name || '').toLowerCase();
- const simplifiedName = (member.simplified_name || '').toLowerCase();
- const searchLower = searchTerm.toLowerCase();
- return name.includes(searchLower) || simplifiedName.includes(searchLower);
- });
- if (matchedMembers.length === 0) {
- alert('未找到匹配的成员');
- return;
- }
- // 如果找到多个匹配项,让用户选择
- let targetMember;
- if (matchedMembers.length === 1) {
- targetMember = matchedMembers[0];
- } else {
- const memberNames = matchedMembers.map(m => `${m.name} (${m.simplified_name || '无简化名'})`).join('\n');
- const selectedIndex = prompt(`找到多个匹配成员,请输入编号选择:\n${matchedMembers.map((m, i) => `${i + 1}. ${m.name} (${m.simplified_name || '无简化名'})`).join('\n')}`);
- const index = parseInt(selectedIndex) - 1;
- if (isNaN(index) || index < 0 || index >= matchedMembers.length) {
- return;
- }
- targetMember = matchedMembers[index];
- }
- // 定位到成员
- locateMember(targetMember.id);
- }
- // 定位到指定成员
- function locateMember(memberId) {
- const svg = d3.select("#tree-container svg");
- if (!svg.empty()) {
- // 查找对应的节点
- const node = d3.selectAll(".node").filter(function(d) {
- return d.data && d.data.id === memberId;
- });
- if (node.size() > 0) {
- // 获取节点位置
- const nodeData = node.datum();
- const container = document.getElementById('tree-container');
- const containerWidth = container.clientWidth;
- const containerHeight = container.clientHeight;
- // 计算缩放和平移,使节点位于中心
- const scale = 1.5; // 放大一点以突出显示
- const translateX = containerWidth / 2 - nodeData.x * scale;
- const translateY = containerHeight / 2 - nodeData.y * scale;
- // 应用变换
- svg.transition().duration(1000).call(
- zoomBehavior.transform,
- d3.zoomIdentity.translate(translateX, translateY).scale(scale)
- );
- // 高亮显示节点
- node.select("rect, circle").transition().duration(500)
- .attr("stroke", "#ff0000")
- .attr("stroke-width", 3)
- .transition().duration(1000).attr("stroke", function(d) {
- return d.data.sex === 1 ? "#3B82F6" : "#EC4899";
- }).attr("stroke-width", 2);
- } else {
- alert('未在树中找到该成员');
- }
- } else {
- alert('树图未加载完成,请稍后再试');
- }
- }
- // 支持回车键搜索
- document.getElementById('memberSearch').addEventListener('keypress', function(e) {
- if (e.key === 'Enter') {
- searchMember();
- }
- });
- </script>
- {% endblock %}
|