Adaptive Diagram Layouts for Dynamic Canvas Orientation
When generating diagrams dynamically, ensuring they render correctly across different screen orientations can be tricky. A horizontal layout might be perfect for landscape, but cramped and unreadable in portrait mode.
The Problem: Fixed Layouts
Traditional diagram generation tools often bake in a specific layout (e.g., left-to-right) at design time. This works fine for fixed-size canvases, but falls apart when the available space changes.
Imagine a flowchart designed for a wide screen being forced into a narrow mobile view. The nodes get squeezed, labels overlap, and the whole thing becomes illegible.
The Solution: Dynamic Layout Switching
The key is to detect the canvas orientation (or aspect ratio) and switch the diagram layout accordingly. For portrait orientations, a top-down (TD) layout generally works better than a left-to-right (LR) or right-to-left (RL) layout.
Here's a simplified example of how you might implement this:
<?php
function generateDiagram(array $data, string $orientation): string {
if ($orientation === 'portrait') {
$layout = 'TD'; // Top-down
} else {
$layout = 'LR'; // Left-to-right
}
$nodes = [];
foreach ($data as $item) {
$nodes[] = sprintf('%s[