---
name: drawio-position-adjuster
description: Adjusts element positions in Drawio XML files to ensure beautiful layout, avoid interference, and meet expectations. Only modifies positions; does not change element content.
---

# draw.io Position Adjuster

This document explains how to adjust element positions in draw.io XML files to ensure reasonable element layout during visualization and avoid interference.

> **Important Note:** This skill only adjusts element positions (`mxGeometry`); it does not modify element content, styles, or connection relationships.

---

# 1. Layout Principles

## 1.1 Basic Layout Rules

When adjusting element positions, the following principles must be followed:

- **Items cannot cross or overlap with each other**
- **Minimize line crossings**
- **Lines cannot pass through items**
- **Orphan items (without connections) can only appear as comments or descriptions**
- **Maintain container nesting structure unchanged**

## 1.2 Layout Styles

Choose appropriate layout style based on chart type:

| Chart Type | Layout Style | Recommended Direction |
|---------|---------|----------|
| Flowchart | Hierarchical Layout | Top-down |
| Organization Chart | Tree Layout | Top-down |
| Class Diagram | Grid Layout | Top-down or left-to-right |
| State Diagram | Circular Layout | Circular direction |
| Sequence Diagram | Horizontal Layout | Left-to-right |
| Architecture Diagram | Layered Layout | Top-down |

---

# 2. Element Size Adjustment

## 2.1 Core Objective
To eliminate the "Text Overflow" issue in `mxCell` nodes by dynamically calculating the optimal `width` and `height` based on string length, ensuring a professional and balanced visual layout.

## 2.2 Calculation Logic (The Geometry Formula)

The Agent must pre-process the `value` string to determine the `mxGeometry` attributes:

### A. Width Prediction
$$Width = \max(BaseWidth, \min(MaxWidth, \text{CharCount} \times \text{FontSize} \times \text{Ratio}))$$

*   **BaseWidth**: Recommended **120**.
*   **MaxWidth**: Recommended **280** (Force a line break if this limit is exceeded).
*   **Ratio (Scaling Factor)**: 
    *   **CJK Characters**: Use **1.0** (Full-width).
    *   **Latin/Alphanumeric**: Use **0.6** (Average half-width).
    *   **Mixed Text**: Use **0.8** as a safety buffer.

### B. Height Prediction
$$LineCount = \lceil (\text{CharCount} \times \text{FontSize} \times \text{Ratio}) / \text{Width} \rceil$$
$$Height = \max(BaseHeight, (LineCount \times \text{LineHeight}) + \text{VerticalPadding})$$

*   **BaseHeight**: Recommended **40** to **60**.
*   **LineHeight**: Use `FontSize * 1.25`.
*   **VerticalPadding**: Add **10~20** pixels for visual breathing room.

---

## 2.3 XML Style Injection Standards

Every generated `mxCell` style MUST include these four key-value pairs to ensure rendering consistency:

| Attribute | Value | Purpose |
| :--- | :--- | :--- |
| `html` | `1` | Enables HTML rendering for smart text wrapping. |
| `whiteSpace` | `wrap` | **CRITICAL**: Forces text to wrap within the defined width. |
| `overflow` | `hidden` | Prevents minor rendering artifacts from showing outside the box. |
| `spacing` | `5` | Adds internal padding to prevent text from touching borders. |

---

## 2.4 Advanced Optimization Tips

*   **Monospace for Precision**: For technical diagrams, use `fontFamily=JetBrains Mono, monospace;`. This makes character width prediction nearly 100% accurate.
*   **Aspect Ratio Balancing**: If `LineCount > 4`, the Agent should prioritize increasing the `Width` rather than the `Height` to maintain an aesthetic rectangular proportion.
*   **Character Escaping**: Always escape XML-sensitive characters:
    *   `&` &rarr; `&amp;`
    *   `<` &rarr; `&lt;`
    *   `>` &rarr; `&gt;`
*   **Alignment**: Always set `verticalAlign=middle;align=center;` to keep text perfectly centered as the box expands.

---

## 2.5 Execution Example

**Input Content**: `"Vision-Language-Action (VLA) Model Optimization and Data Governance Strategies"`

**❌ Unoptimized (Using Default Fixed Size)**:
*   `width="100" height="40"`
*   `style="rounded=1;"`
*   **Result**: Text bleeds out horizontally; unreadable.

**✅ Optimized (Applying Dynamic Size Calculation from Section 2.2)**:
*   **Analysis**: ~75 characters, FontSize 12.
*   **Prediction**: Calculate dimensions using the formulas in Section 2.2, not fixed values.
*   **Note**: Result will be approximately `width="220" height="80"` based on text length, but always calculate dynamically for accurate results.
*   **XML Snippet**:
```xml
<mxCell value="Vision-Language-Action (VLA) Model Optimization and Data Governance Strategies"
        style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;spacingLeft=5;spacingRight=5;verticalAlign=middle;align=center;"
        vertex="1" parent="1">
    <mxGeometry x="100" y="100" width="[calculated_from_text]" height="[calculated_from_text]" as="geometry" />
</mxCell>
```

**Note**: Replace `[calculated_from_text]` with actual values calculated using the formulas in Section 2.2

---

# 3. Position Adjustment Strategies

## 3.1 Grid Layout

Use standard grid system for layout to ensure even element spacing:

```
Horizontal spacing = 180px
Vertical spacing = 120px
```

**Note:** Element dimensions (width and height) should be calculated dynamically based on text content as described in Section 2.

### 3.1.1 Calculation Formula

- **Horizontal position:** `x = col_index * 180 + margin_left`
- **Vertical position:** `y = row_index * 120 + margin_top`

### 3.1.2 Example

```xml
<!-- Row 1, Column 1 - dimensions calculated based on text content -->
<mxCell id="n1" vertex="1" parent="1">
  <mxGeometry x="40" y="40" width="[calculated]" height="[calculated]" as="geometry"/>
</mxCell>

<!-- Row 1, Column 2 - dimensions calculated based on text content -->
<mxCell id="n2" vertex="1" parent="1">
  <mxGeometry x="220" y="40" width="[calculated]" height="[calculated]" as="geometry"/>
</mxCell>

<!-- Row 2, Column 1 - dimensions calculated based on text content -->
<mxCell id="n3" vertex="1" parent="1">
  <mxGeometry x="40" y="160" width="[calculated]" height="[calculated]" as="geometry"/>
</mxCell>
```

## 3.2 Hierarchical Layout

Suitable for flowcharts, decision trees, and other charts with hierarchical structure:

```
Level 0: Root node (top center)
Level 1: Direct child nodes
Level 2: Grandchild nodes
...
```

### 3.2.1 Hierarchical Layout Principles

1. **Parent nodes located above and centered relative to child nodes**
2. **Same-level nodes arranged horizontally**
3. **Level spacing greater than row spacing** for easier connection

### 3.2.2 Rhombus Node Special Handling

Rhombus (decision) nodes need extra width and height based on text content:

**Size Multipliers for Rhombus:**
- Width multiplier: 1.5x (calculate from text width, then multiply by 1.5)
- Height multiplier: 1.3x (calculate from text height, then multiply by 1.3)
- Vertical space reserved: Ensure at least 100px between rhombus and next row

**Example:**
If text requires width=120px and height=50px:
- Rhombus width = 120 × 1.5 = 180px
- Rhombus height = 50 × 1.3 = 65px

## 3.3 Tree Layout

Suitable for organization charts, inheritance relationship diagrams, etc.:

```
Root node: Top center
Child nodes: Uniformly distributed below parent node
Branch angle: Keep within 45° to avoid excessive dispersion
```

### 3.3.1 Alignment Strategy

- **Odd number of child nodes:** One centered, others symmetrically distributed
- **Even number of child nodes:** Symmetrically distributed on both sides of central axis

## 3.4 Circular Layout

Suitable for state diagrams, circular processes, etc.:

```
Center point: (canvas_width/2, canvas_height/2)
Radius: Adjust based on element count
Angle interval: 360° / element count
```

### 3.4.1 Calculation Formula

```
x = center_x + radius * cos(angle)
y = center_y + radius * sin(angle)
```

---

# 4. Container Internal Layout

## 4.1 Relative Coordinates

Elements within containers use coordinates relative to the container:

```xml
<!-- Container -->
<mxCell id="group1" vertex="1" parent="1">
  <mxGeometry x="100" y="100" width="400" height="300" as="geometry"/>
</mxCell>

<!-- Elements within container: coordinates relative to group1 -->
<mxCell id="child1" vertex="1" parent="group1">
  <mxGeometry x="20" y="40" width="[calculated]" height="[calculated]" as="geometry"/>
</mxCell>
```

## 4.2 Swimlane Layout

Swimlane containers typically include title bars; child elements need to avoid title bars:

```
startSize = 30px (default title bar height)
Child element y coordinate >= startSize + padding
```

### 4.2.1 Swimlane Internal Layout Example

```xml
<!-- Swimlane container -->
<mxCell id="swimlane1" value="Swimlane 1" style="swimlane;startSize=30;" vertex="1" parent="1">
  <mxGeometry x="100" y="100" width="400" height="300" as="geometry"/>
</mxCell>

<!-- Elements within swimlane -->
<mxCell id="lane1-n1" vertex="1" parent="swimlane1">
  <mxGeometry x="20" y="40" width="[calculated]" height="[calculated]" as="geometry"/>
</mxCell>
```

## 4.3 Nested Containers

For multi-layer nested containers, coordinates at each level are relative to its parent container:

```
Absolute position = Parent container position + Relative position
```

---

# 5. Strategies to Avoid Interference

## 5.1 Detecting Overlap

### 5.1.1 Rectangle Collision Detection

Condition for two rectangles to overlap:

```
(x1 < x2 + width2) AND (x1 + width1 > x2) AND
(y1 < y2 + height2) AND (y1 + height1 > y2)
```

### 5.1.2 Safe Spacing

Reserve safe spacing between elements:

```
Minimum horizontal spacing = 40px
Minimum vertical spacing = 40px
```

## 5.2 Handling Overlap

### 5.2.1 Horizontal Separation

When horizontal overlap is detected, move element away:

```
new_x = existing_x + existing_width + min_spacing
```

### 5.2.2 Vertical Separation

When vertical overlap is detected, move element down:

```
new_y = existing_y + existing_height + min_spacing
```

## 5.3 Reducing Line Crossings

### 5.3.1 Using Orthogonal Edges

Set edge style to orthogonal routing:

```xml
<mxCell edge="1" source="n1" target="n2"
  style="edgeStyle=orthogonalEdgeStyle;rounded=1;">
  <mxGeometry relative="1" as="geometry"/>
</mxCell>
```

### 5.3.2 Adjusting Node Positions

Place tightly connected nodes in adjacent positions to reduce long lines:

```
Original layout: A(0,0) → B(400,0) → C(400,400)
Optimized: A(0,0) → B(180,0) → C(180,120)
```

### 5.3.3 Grouping Related Nodes

Place related nodes together and use containers for grouping:

```xml
<!-- Container -->
<mxCell id="related-group" style="group;" vertex="1" parent="1">
  <mxGeometry x="100" y="100" width="400" height="200" as="geometry"/>
</mxCell>

<!-- Related nodes -->
<mxCell id="n1" vertex="1" parent="related-group">...</mxCell>
<mxCell id="n2" vertex="1" parent="related-group">...</mxCell>
<mxCell id="n3" vertex="1" parent="related-group">...</mxCell>
```

## 5.4 Avoiding Lines Passing Through Items

### 5.4.1 Adjusting Connection Points

Use `entryX`/`entryY` and `exitX`/`exitY` to control connection positions:

```xml
<mxCell edge="1" source="n1" target="n2"
  style="exitX=1;exitY=0.5;entryX=0;entryY=0.5;">
  <mxGeometry relative="1" as="geometry"/>
</mxCell>
```

### 5.4.2 Routing Optimization

Let lines bypass obstacles using additional path points:

```xml
<mxGeometry relative="1" as="geometry">
  <Array as="points">
    <mxPoint x="200" y="100"/>
    <mxPoint x="200" y="300"/>
  </Array>
</mxGeometry>
```

---

# 6. Common Chart Layout Patterns

## 6.1 Flowchart Layout

```
      Start
       ↓
    [Step 1] ←───┐
       ↓        │
    [Step 2]     │ Loop
       ↓        │
    [Decision]──┘
      ↙    ↘
   [Yes]    [No]
    ↓        ↓
  [Continue]  [End]
```

**Layout Points:**
- Vertical direction as main flow
- Decision nodes at branch points
- Loop return lines as short as possible
- Parallel paths arranged horizontally

## 6.2 Organization Chart Layout

```
                CEO
         ┌───────┼───────┐
      VP1      VP2      VP3
       ↓        ↓        ↓
    ┌────┐   ┌────┐   ┌────┐
    T1 T2   T3 T4   T5 T6
```

**Layout Points:**
- Root node at top center
- Child nodes symmetrically distributed
- Same-level nodes horizontally aligned
- Use same spacing

## 6.3 UML Class Diagram Layout

```
    ┌─────────┐
    │  Class A   │
    └─────────┘
         ↑
         │
    ┌─────────┐
    │  Class B   │
    └─────────┘
         ↑
         │
    ┌─────────┐
    │  Class C   │
    └─────────┘
```

**Layout Points:**
- Inheritance relationships bottom-to-top
- Association relationships mostly horizontal
- Interfaces usually placed next to associated classes
- Keep class diagrams clean

## 6.4 State Diagram Layout

```
      ┌──────┐
      │ Initial │
      └──┬───┘
         ↓
      ┌──────┐
      │ State A │◄────┐
      └──┬───┘     │
         │         │
      ┌──────┐     │
      │ State B │─────┘
      └──┬───┘
         ↓
      ┌──────┐
      │ End │
      └──────┘
```

**Layout Points:**
- Loop states placed together
- Initial state at top-left
- End state at bottom-right
- State transition direction consistent (usually downward or rightward)

---

# 7. Adjustment Process

## 7.1 Analyzing Existing Layout

1. **Identify chart type:** Flowchart, architecture diagram, class diagram, etc.
2. **Determine layout style:** Hierarchical, tree, grid, etc.
3. **Mark problem areas:** Overlaps, crossings, orphan nodes, etc.
4. **Identify key paths:** Main processes, core relationships

## 7.2 Planning New Layout

1. **Calculate canvas size:** Based on element count and layout type
2. **Determine grid system:** Choose appropriate spacing
3. **Plan hierarchy:** Determine node hierarchy relationships
4. **Assign coordinate positions:** Assign positions to each node

## 7.3 Executing Adjustments

1. **Adjust node positions:** Modify `x` and `y` in `mxGeometry`
2. **Adjust container elements:** Modify relative coordinates
3. **Optimize connection lines:** Adjust connection points if necessary
4. **Verify results:** Check for remaining interference

## 7.4 Iterative Optimization

1. **Check visibility:** Are all elements visible?
2. **Check readability:** Is text clear?
3. **Check aesthetics:** Is layout balanced?
4. **Fine-tune details:** Handle edge cases

---

# 8. Precautions

## 8.1 Content to Keep Unchanged

When adjusting positions, the following content **cannot be modified:**

- Element `value` (display text)
- Element `style` (style definition)
- Element `id` (unique identifier)
- Edge `source` and `target` (connection relationships)
- Container `parent` relationships

## 8.2 Special Element Handling

### 8.2.1 Text Labels

Positioning of text-only labels (without borders):
```
x = Related element center x - Label width/2
y = Related element top - Label height - Spacing
```

### 8.2.2 Annotation Elements

Annotation elements should be placed near related elements:
```
Offset = 20px
Position = Target element corner + Offset
```

## 8.3 Boundary Checking

Ensure all elements are within canvas range:

```
x >= 0 AND x + width <= canvas_width
y >= 0 AND y + height <= canvas_height
```

## 8.4 Saving Original Positions

It's recommended to backup original position information before modification:

```xml
<!-- Keep original position as comment -->
<!-- original: x=100,y=200 -->
<mxCell id="n1" vertex="1" parent="1">
  <mxGeometry x="150" y="180" width="140" height="60" as="geometry"/>
</mxCell>
```

---

# 9. Reference Resources

> For detailed draw.io XML format explanations, please refer to:
> - [drawio-format-adapter/SKILL.md](../drawio-format-adapter/SKILL.md)
> - [reference/xml-reference.md](reference/xml-reference.md)