Как убедиться, что узлы подключены на этой диаграмме дереваJavascript

Форум по Javascript
Ответить
Anonymous
 Как убедиться, что узлы подключены на этой диаграмме дерева

Сообщение Anonymous »

У меня есть следующая структура данных: < /p>

Код: Выделить всё

const data = {
label: "root",
children: [
{
label: "child_1_A",
},
{
label: "child_1_B",
},
{
label: "child_1_C",
},
{
label: "child_1_D",
},
{
label: "child_1_E",
},
{
label: "child_1_F",
children: [
{
label: "child_2_A",
children: [
{ label: "child_3_A" },
{ label: "child_3_B" },
{ label: "child_3_C"  },
{
label: "child_3_D",
children: [
{
label: "child_4_A",
children: [
{
label: "child_5_A",
children: [
{
label: "child_6_A",
},
],
},
{
label: "child_5_B",
children: [
{
label: "child_6_B",
},
],
},
{
label: "child_5_C",
},
{
label: "child_5_D",
children: [
{
label: "child_6_C",
children: [
{
label: "child_7_A",
children: [
{
label: "child_8_A",
},
{
label: "child_8_B",
children: [
{
label: "child_9_A",
children: [
{
label: "child_10_A",
children: [
{
label: "child_11_A",
},
{
label: "child_11_B",
children: [
{
label: "child_12_A",
},
],
},
],
},
],
},
],
},
],
},
],
},
{
label: "child_6_D",
},
],
},
{
label: "child_5_E",
children: [
{
label: "child_6_E",
children: [
{
label: "child_7_B",
},
{
label: "child_7_C",
children: [
{
label: "child_8_C",
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
};
< /code>
Мне нужно отображать вложенную диаграмму деревьев с линиями, которые соединяют все уровни: < /p>
 
Это прекрасно работает для большинства уровней, но когда я добираюсь до узла, в котором внутренние вложенные дети - внешняя линия, которая соединяет узлы не соединяются:  
  p>
Итак, в захвате вы можете видеть, что у child_4_a есть несколько детей, и линия, которая должна соединить всех этих детей, не распространяется достаточно далеко до Child_5_e. Я пробовал много разных вещей.  Код, который я должен рассчитать, какой рост, чтобы нарисовать эту линию: < /p>
  const calculateTotalHeight = (nodes, depth = 0) => {
if (!nodes || nodes.length === 0) return 0;

const nodeHeight = 38;
let totalHeight = 0;

// Process all siblings
for (let i = 0; i < nodes.length - 1; i++) {
// Add height for this sibling
totalHeight += nodeHeight;

// Process children for all nodes, not just non-last siblings
if (nodes[i].children && nodes[i].children.length > 0) {
totalHeight += calculateTotalHeight(nodes[i].children, depth + 1);
}
}

return totalHeight;
};
< /code>
Весь код здесь: < /p>
const TreeNode = ({ label, children, index, siblingCount }) => {
// Add helper function to calculate total height
const calculateTotalHeight = (nodes, depth = 0) => {
if (!nodes || nodes.length === 0) return 0;

const nodeHeight = 38;
let totalHeight = 0;

// Process all siblings
for (let i = 0; i < nodes.length - 1; i++) {
// Add height for this sibling
totalHeight += nodeHeight;

// Process children for all nodes, not just non-last siblings
if (nodes[i].children && nodes[i].children.length > 0) {
totalHeight += calculateTotalHeight(nodes[i].children, depth + 1);
}
}

return totalHeight;
};

// Helper to generate curved connecting path
const getConnectorPath = () => {
return `
M 0 16
L 10 16
`;
};

const getCurvedConnectorPath = () => {
return `
M 0 -2 L 0 14.08 C 0 18.4541 4.38531 22 8.7594 22V22
`;
};

const isSibling = index !== undefined && siblingCount > 1;
const isLastSibling = index === siblingCount - 1;

return (

{/* Main node */}

{label}

{isSibling && !isLastSibling && (


d={getConnectorPath()}
fill="none"
stroke="#ccc"
strokeWidth="1"
/>


)}

{isSibling && isLastSibling && (



)}

{/* Single child connector */}
{children?.length === 1 && (



)}

{children?.length > 1 &&  (



)}

{children?.length > 0 && (



{children.map((child, idx) => (

))}



)}

{`
.tree-node {
position: relative;
}

.node-content {
display: flex;
z-index: 2;
position: relative;
align-items: center;
gap: 6px;
border: 1px solid #ccc;
border-radius: 6px;
padding: 6px 12px;
width: 95%;
}

.label {
font-size: 12px;
}

.children-container {
position: relative;
margin-left: 16px;
padding-top: 6px;
}

.children {
display: flex;
flex-direction: column;
gap: 6px;
}
`}

);
};

const Diagram = () => {
const data = {
label: "root",
children: [
{
label: "child_1_A",
},
{
label: "child_1_B",
},
{
label: "child_1_C",
},
{
label: "child_1_D",
},
{
label: "child_1_E",
},
{
label: "child_1_F",
children: [
{
label: "child_2_A",
children: [
{ label: "child_3_A" },
{ label: "child_3_B" },
{ label: "child_3_C"  },
{
label: "child_3_D",
children: [
{
label: "child_4_A",
children: [
{
label: "child_5_A",
children: [
{
label: "child_6_A",
},
],
},
{
label: "child_5_B",
children: [
{
label: "child_6_B",
},
],
},
{
label: "child_5_C",
},
{
label: "child_5_D",
children: [
{
label: "child_6_C",
children: [
{
label: "child_7_A",
children: [
{
label: "child_8_A",
},
{
label: "child_8_B",
children: [
{
label: "child_9_A",
children: [
{
label: "child_10_A",
children: [
{
label: "child_11_A",
},
{
label: "child_11_B",
children: [
{
label: "child_12_A",
},
],
},
],
},
],
},
],
},
],
},
],
},
{
label: "child_6_D",
},
],
},
{
label: "child_5_E",
children: [
{
label: "child_6_E",
children: [
{
label: "child_7_B",
},
{
label: "child_7_C",
children: [
{
label: "child_8_C",
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
};

return (



);
};

export default Diagram;
Если я удалю -1 из цикла For, то каждый узел с ребенком заканчивает линией, которую вытягивают в нижнюю часть диаграммы. Код каким -то образом должен взять всех вложенных детей на учетную запись, но перестать рисовать вертикальную линию у последнего ребенка/брата.


Подробнее здесь: https://stackoverflow.com/questions/794 ... ee-diagram
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»