Public/DrawLayout.ps1

#Requires -Version 7.0
# ============================================================
# DrawManagement — Layout Engine
#
# Assigns coordinates to cells that already exist on a page, so callers
# describe WHAT to draw and let these functions decide WHERE.
#
# Ported from the auto-layout engine in New-AzureArchitectureDiagram.ps1
# and generalised: the originals were entangled with Azure resource
# objects, these take [DrawCell] and know nothing about any cloud.
#
# Every Set-Draw*Layout function mutates the X/Y (and optionally
# Width/Height) of the cells it is given and returns a bounds object:
# X, Y, Width, Height, Right, Bottom
# so callers can stack layouts or size a parent around the result.
# ============================================================

# Bounds objects come from New-DrawBounds and column arithmetic from
# Measure-DrawColumnHeight — both in Private/Helpers.ps1, so this file
# contains only exported functions.

function Measure-DrawGrid {
    <#
    .SYNOPSIS
        Computes the geometry of N equal cells wrapped at MaxColumns.

    .DESCRIPTION
        Pure arithmetic — no cells are touched. Use it to size a container
        BEFORE creating it, which is the usual reason a diagram builder
        needs the numbers ahead of the shapes.

    .PARAMETER Count
        Number of cells to place. 0 yields an empty 0x0 grid.

    .PARAMETER CellWidth
        Width of a single cell in pixels.

    .PARAMETER CellHeight
        Height of a single cell in pixels.

    .PARAMETER GapX
        Horizontal spacing between columns. Default: 20.

    .PARAMETER GapY
        Vertical spacing between rows. Default: 20.

    .PARAMETER MaxColumns
        Wrap after this many columns. Default: 8.

    .EXAMPLE
        $g = Measure-DrawGrid -Count 17 -CellWidth 60 -CellHeight 60 -MaxColumns 6
        $lane = Add-DrawContainer -Page $p -Label 'App' -Height ($g.Height + 42) -PassThru

    .OUTPUTS
        [PSCustomObject] with Columns, Rows, Width, Height.
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Mandatory)][ValidateRange(0, 100000)][int] $Count,
        [Parameter(Mandatory)][ValidateRange(1, 99999)][double] $CellWidth,
        [Parameter(Mandatory)][ValidateRange(1, 99999)][double] $CellHeight,
        [Parameter()][ValidateRange(0, 9999)][double] $GapX = 20,
        [Parameter()][ValidateRange(0, 9999)][double] $GapY = 20,
        [Parameter()][ValidateRange(1, 1000)][int]    $MaxColumns = 8
    )

    if ($Count -le 0) {
        return [PSCustomObject]@{
            PSTypeName = 'DrawManagement.Grid'
            Columns = 0; Rows = 0; Width = 0.0; Height = 0.0
        }
    }

    [int]$cols = [Math]::Min($Count, [Math]::Max(1, $MaxColumns))
    [int]$rows = [Math]::Ceiling($Count / [double]$cols)

    [PSCustomObject]@{
        PSTypeName = 'DrawManagement.Grid'
        Columns    = $cols
        Rows       = $rows
        Width      = $cols * $CellWidth  + ($cols - 1) * $GapX
        Height     = $rows * $CellHeight + ($rows - 1) * $GapY
    }
}

function Set-DrawGridLayout {
    <#
    .SYNOPSIS
        Packs cells into a wrapped grid, left-to-right then top-to-bottom.

    .DESCRIPTION
        Assigns X/Y to every supplied cell. With -Resize it also normalises
        Width/Height so a mixed set of shapes lines up cleanly.

        Coordinates are written in the space the cells live in: pass the
        container-relative origin when the cells are parented to a
        container, page coordinates when they sit on the root layer.

    .PARAMETER Cell
        The [DrawCell] objects to position, in the order they should appear.
        Accepts pipeline input.

    .PARAMETER OriginX
        X of the grid's top-left corner. Default: 0.

    .PARAMETER OriginY
        Y of the grid's top-left corner. Default: 0.

    .PARAMETER CellWidth
        Column width. Default: 60.

    .PARAMETER CellHeight
        Row height. Default: 60.

    .PARAMETER GapX
        Horizontal spacing between columns. Default: 20.

    .PARAMETER GapY
        Vertical spacing between rows. Default: 20.

    .PARAMETER MaxColumns
        Wrap after this many columns. Default: 8.

    .PARAMETER Resize
        Also set each cell's Width/Height to CellWidth/CellHeight.

    .EXAMPLE
        $cells = 1..12 | ForEach-Object {
            Add-DrawShape -Page $p -Label "svc-$_" -PassThru
        }
        Set-DrawGridLayout -Cell $cells -OriginX 40 -OriginY 60 -MaxColumns 4 -Resize

    .INPUTS
        [DrawCell] via pipeline.

    .OUTPUTS
        [PSCustomObject] bounds — X, Y, Width, Height, Right, Bottom.
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param(
        # [FIX-28] AllowEmptyCollection: an empty set is a legal layout, and
        # every other part of this file already says so — Measure-DrawGrid
        # documents "0 yields an empty 0x0 grid", the end block below has an
        # explicit $all.Count -eq 0 guard, and Measure-DrawColumnHeight in
        # Private/Helpers.ps1 carries this very attribute. Without it the two
        # input paths disagreed: `@() | Set-DrawGridLayout` returned empty
        # bounds, while `-Cell @()` was rejected by the parameter binder with
        # Cannot bind argument to parameter 'Cell' because it is an empty array.
        # That is the data-dependent form, since the usual way to build the
        # argument is a Where-Object that may legitimately match nothing —
        # so the layout crashed only on the inputs where it had no work to do.
        [Parameter(Mandatory, ValueFromPipeline)]
        [AllowEmptyCollection()]
        [DrawCell[]] $Cell,
        [Parameter()][double] $OriginX    = 0,
        [Parameter()][double] $OriginY    = 0,
        [Parameter()][ValidateRange(1, 99999)][double] $CellWidth  = 60,
        [Parameter()][ValidateRange(1, 99999)][double] $CellHeight = 60,
        [Parameter()][ValidateRange(0, 9999)][double]  $GapX       = 20,
        [Parameter()][ValidateRange(0, 9999)][double]  $GapY       = 20,
        [Parameter()][ValidateRange(1, 1000)][int]     $MaxColumns = 8,
        [Parameter()][switch] $Resize
    )

    begin { $all = New-Object 'System.Collections.Generic.List[DrawCell]' }

    process { foreach ($c in $Cell) { if ($null -ne $c) { $all.Add($c) } } }

    end {
        $grid = Measure-DrawGrid -Count $all.Count -CellWidth $CellWidth `
                    -CellHeight $CellHeight -GapX $GapX -GapY $GapY -MaxColumns $MaxColumns

        if ($all.Count -eq 0) { return New-DrawBounds $OriginX $OriginY 0 0 }

        for ($i = 0; $i -lt $all.Count; $i++) {
            [int]$col = $i % $grid.Columns
            [int]$row = [Math]::Floor($i / $grid.Columns)

            $all[$i].X = $OriginX + $col * ($CellWidth  + $GapX)
            $all[$i].Y = $OriginY + $row * ($CellHeight + $GapY)

            if ($Resize) {
                $all[$i].Width  = $CellWidth
                $all[$i].Height = $CellHeight
            }
        }

        Write-Verbose ("Set-DrawGridLayout: placed $($all.Count) cells in " +
                       "$($grid.Columns)x$($grid.Rows)")
        New-DrawBounds $OriginX $OriginY $grid.Width $grid.Height
    }
}

function Set-DrawLayeredLayout {
    <#
    .SYNOPSIS
        Arranges cells into labelled lanes — one lane per logical layer.

    .DESCRIPTION
        Creates a swimlane container per layer, grid-packs that layer's
        cells inside it, and stacks the lanes vertically (or side by side
        with -Orientation Horizontal). This is the classic tier diagram:
        Edge / App / Data lanes with flow arrows between them.

        Cells are re-parented to their lane by default, so dragging a lane
        in draw.io moves its contents. Use -NoParent to leave them on the
        root layer positioned in absolute page coordinates instead — that
        renders identically but keeps the cells independent of the lane.

    .PARAMETER Page
        The [DrawPage] the lanes are created on.

    .PARAMETER Layer
        Ordered array of hashtables, one per lane. Recognised keys:
            Name (required) lane title
            Cells [DrawCell[]] members, may be empty
            FillColor lane header/background colour
            StrokeColor lane border colour
            Style complete swimlane style, overrides the colours
        Layers with no cells are skipped.

    .PARAMETER OriginX
        X of the first lane. Default: 40.

    .PARAMETER OriginY
        Y of the first lane. Default: 40.

    .PARAMETER LaneLength
        Lane width when stacking vertically, lane height when horizontal.
        Default: 1080.

    .PARAMETER Orientation
        Vertical stacks lanes top to bottom (default).
        Horizontal places them left to right, for a service-flow diagram.

    .PARAMETER HeaderSize
        Lane title-bar thickness in pixels. Default: 26.

    .PARAMETER CellWidth
        Member cell width. Default: 60.

    .PARAMETER CellHeight
        Member cell height. Default: 60.

    .PARAMETER GapX
        Horizontal spacing between member cells. Default: 34.

    .PARAMETER GapY
        Vertical spacing between member cells. Default: 46.

    .PARAMETER LaneGap
        Space between adjacent lanes. Default: 40.

    .PARAMETER Padding
        Inner padding between the lane edge and its cells. Default: 16.

    .PARAMETER Resize
        Normalise member cells to CellWidth/CellHeight.

    .PARAMETER NoParent
        Leave cells on the root layer at absolute page coordinates rather
        than re-parenting them into their lane.

    .EXAMPLE
        $lanes = Set-DrawLayeredLayout -Page $p -Layer @(
            @{ Name = 'Edge'; Cells = $edge; FillColor = '#FFE6CC' }
            @{ Name = 'App'; Cells = $app; FillColor = '#DAE8FC' }
            @{ Name = 'Data'; Cells = $data; FillColor = '#D5E8D4' }
        )
        # Connect the lanes top to bottom
        for ($i = 0; $i -lt $lanes.Count - 1; $i++) {
            Add-DrawEdge -Page $p -Source $lanes[$i] -Target $lanes[$i+1]
        }

    .OUTPUTS
        [DrawCell[]] — the lane containers, in the order they were drawn.
    #>

    [CmdletBinding()]
    [OutputType([DrawCell[]])]
    param(
        [Parameter(Mandatory)][DrawPage]    $Page,
        # [FIX-28] as above — no lanes is an empty diagram, not an error.
        [Parameter(Mandatory)][AllowEmptyCollection()][hashtable[]] $Layer,
        [Parameter()][double] $OriginX    = 40,
        [Parameter()][double] $OriginY    = 40,
        [Parameter()][ValidateRange(1, 99999)][double] $LaneLength = 1080,
        [Parameter()][ValidateSet('Vertical', 'Horizontal')][string] $Orientation = 'Vertical',
        [Parameter()][ValidateRange(10, 100)][int]     $HeaderSize = 26,
        [Parameter()][ValidateRange(1, 99999)][double] $CellWidth  = 60,
        [Parameter()][ValidateRange(1, 99999)][double] $CellHeight = 60,
        [Parameter()][ValidateRange(0, 9999)][double]  $GapX       = 34,
        [Parameter()][ValidateRange(0, 9999)][double]  $GapY       = 46,
        [Parameter()][ValidateRange(0, 9999)][double]  $LaneGap    = 40,
        [Parameter()][ValidateRange(0, 9999)][double]  $Padding    = 16,
        [Parameter()][switch] $Resize,
        [Parameter()][switch] $NoParent
    )

    $lanes = New-Object 'System.Collections.Generic.List[DrawCell]'
    [double]$cursor = if ($Orientation -eq 'Vertical') { $OriginY } else { $OriginX }

    foreach ($spec in $Layer) {
        if (-not $spec.ContainsKey('Name') -or [string]::IsNullOrWhiteSpace([string]$spec['Name'])) {
            throw "Set-DrawLayeredLayout: every -Layer entry needs a non-empty 'Name' key."
        }

        $members = @()
        if ($spec.ContainsKey('Cells') -and $null -ne $spec['Cells']) {
            $members = @($spec['Cells'] | Where-Object { $_ -is [DrawCell] })
        }
        if ($members.Count -eq 0) { continue }

        # Usable run length inside the lane, then how many fit across it.
        [double]$run = $LaneLength - 2 * $Padding
        [int]$maxCols = [Math]::Max(1, [Math]::Floor(($run + $GapX) / ($CellWidth + $GapX)))

        if ($Orientation -eq 'Vertical') {
            $grid    = Measure-DrawGrid -Count $members.Count -CellWidth $CellWidth `
                           -CellHeight $CellHeight -GapX $GapX -GapY $GapY -MaxColumns $maxCols
            $laneW   = $LaneLength
            $laneH   = $HeaderSize + $Padding + $grid.Height + $Padding
            $laneX   = $OriginX
            $laneY   = $cursor
        }
        else {
            # Horizontal: cells stack downward inside a narrow column lane.
            [int]$maxRows = [Math]::Max(1, [Math]::Floor(($LaneLength - $HeaderSize - 2 * $Padding + $GapY) / ($CellHeight + $GapY)))
            [int]$cols    = [Math]::Ceiling($members.Count / [double]$maxRows)
            [int]$rows    = [Math]::Min($members.Count, $maxRows)
            $grid    = [PSCustomObject]@{
                Columns = $cols
                Rows    = $rows
                Width   = $cols * $CellWidth  + ($cols - 1) * $GapX
                Height  = $rows * $CellHeight + ($rows - 1) * $GapY
            }
            $maxCols = $cols
            $laneW   = $Padding + $grid.Width + $Padding
            $laneH   = $LaneLength
            $laneX   = $cursor
            $laneY   = $OriginY
        }

        # Lane container
        $laneArgs = @{
            Page   = $Page
            Label  = [string]$spec['Name']
            X      = $laneX
            Y      = $laneY
            Width  = $laneW
            Height = $laneH
        }
        if ($spec.ContainsKey('Style') -and -not [string]::IsNullOrWhiteSpace([string]$spec['Style'])) {
            $laneArgs['Style'] = [string]$spec['Style']
        }
        else {
            $laneArgs['HeaderSize'] = $HeaderSize
            if ($spec.ContainsKey('FillColor')   -and $spec['FillColor'])   { $laneArgs['FillColor']   = [string]$spec['FillColor'] }
            if ($spec.ContainsKey('StrokeColor') -and $spec['StrokeColor']) { $laneArgs['StrokeColor'] = [string]$spec['StrokeColor'] }
        }
        if ($spec.ContainsKey('Tooltip') -and $spec['Tooltip']) { $laneArgs['Tooltip'] = [string]$spec['Tooltip'] }

        $lane = Add-DrawContainer @laneArgs -PassThru
        $lanes.Add($lane)

        # Member cells: relative to the lane when parented, absolute when not.
        if ($NoParent) {
            $ox = $laneX + $Padding
            $oy = $laneY + $HeaderSize + $Padding
        }
        else {
            foreach ($m in $members) { $m.ParentId = $lane.Id }
            $ox = $Padding
            $oy = $HeaderSize + $Padding
        }

        $null = Set-DrawGridLayout -Cell $members -OriginX $ox -OriginY $oy `
                    -CellWidth $CellWidth -CellHeight $CellHeight `
                    -GapX $GapX -GapY $GapY -MaxColumns $maxCols -Resize:$Resize

        # NB: a parenthesised if-statement is not an expression in PowerShell,
        # so the advance is computed into a variable first.
        $advance = if ($Orientation -eq 'Vertical') { $laneH } else { $laneW }
        $cursor += $advance + $LaneGap
    }

    Write-Verbose "Set-DrawLayeredLayout: created $($lanes.Count) lanes ($Orientation)"

    # [FIX-16] The leading comma stops PowerShell unrolling a single-lane
    # result into a bare [DrawCell]. Callers index and count this
    # ($lanes.Count, $lanes[0]), and under Set-StrictMode -Version Latest
    # .Count on an unrolled scalar is a terminating error rather than 1.
    return , $lanes.ToArray()
}

function Set-DrawHubSpokeLayout {
    <#
    .SYNOPSIS
        Places a hub cell centrally with spokes balanced left and right.

    .DESCRIPTION
        The classic hub-and-spoke network picture. Spokes alternate into a
        left and a right column; each column and the hub are centred
        vertically against the tallest of the three, so the result stays
        balanced however many spokes there are.

        Only coordinates are assigned — draw the peering edges yourself
        with Add-DrawEdge, which keeps labels and styling under your control.

    .PARAMETER Hub
        The [DrawCell] to centre.

    .PARAMETER Spoke
        The [DrawCell] objects to distribute either side of the hub.

    .PARAMETER OriginX
        Left edge of the layout. Default: 40.

    .PARAMETER OriginY
        Top edge of the layout. Default: 40.

    .PARAMETER ColumnGap
        Horizontal space between a spoke column and the hub. Default: 90.

    .PARAMETER RowGap
        Vertical space between spokes in the same column. Default: 34.

    .EXAMPLE
        $hub = Add-DrawContainer -Page $p -Label 'hub-vnet' -Width 240 -Height 160 -PassThru
        $spokes = 'app','data','mgmt' | ForEach-Object {
            Add-DrawContainer -Page $p -Label "$_-vnet" -Width 240 -Height 120 -PassThru
        }
        Set-DrawHubSpokeLayout -Hub $hub -Spoke $spokes
        $spokes | ForEach-Object { Add-DrawEdge -Page $p -Source $hub -Target $_ -Label 'peering' }

    .OUTPUTS
        [PSCustomObject] bounds — X, Y, Width, Height, Right, Bottom.
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Mandatory)][DrawCell]   $Hub,
        [Parameter()][DrawCell[]]          $Spoke = @(),
        [Parameter()][double] $OriginX   = 40,
        [Parameter()][double] $OriginY   = 40,
        [Parameter()][ValidateRange(0, 9999)][double] $ColumnGap = 90,
        [Parameter()][ValidateRange(0, 9999)][double] $RowGap    = 34
    )

    $spokes = @($Spoke | Where-Object { $null -ne $_ })

    # Alternate spokes into balanced columns.
    $left  = New-Object 'System.Collections.Generic.List[DrawCell]'
    $right = New-Object 'System.Collections.Generic.List[DrawCell]'
    for ($i = 0; $i -lt $spokes.Count; $i++) {
        if ($i % 2 -eq 0) { $left.Add($spokes[$i]) } else { $right.Add($spokes[$i]) }
    }

    [double]$leftH  = Measure-DrawColumnHeight -Cell $left.ToArray()  -Gap $RowGap
    [double]$rightH = Measure-DrawColumnHeight -Cell $right.ToArray() -Gap $RowGap
    [double]$totalH = [Math]::Max($Hub.Height, [Math]::Max($leftH, $rightH))

    # Widest cell in each column drives the column positions.
    [double]$leftW = 0;  foreach ($c in $left)  { if ($c.Width -gt $leftW)  { $leftW  = $c.Width } }
    [double]$rightW = 0; foreach ($c in $right) { if ($c.Width -gt $rightW) { $rightW = $c.Width } }

    [double]$leftX = $OriginX
    [double]$hubX  = if ($left.Count -gt 0) { $leftX + $leftW + $ColumnGap } else { $leftX }
    [double]$rightX = $hubX + $Hub.Width + $ColumnGap

    # Hub, vertically centred against the tallest column.
    $Hub.X = $hubX
    $Hub.Y = $OriginY + [Math]::Max(0, ($totalH - $Hub.Height) / 2)

    [double]$ly = $OriginY + [Math]::Max(0, ($totalH - $leftH) / 2)
    foreach ($c in $left)  { $c.X = $leftX;  $c.Y = $ly; $ly += $c.Height + $RowGap }

    [double]$ry = $OriginY + [Math]::Max(0, ($totalH - $rightH) / 2)
    foreach ($c in $right) { $c.X = $rightX; $c.Y = $ry; $ry += $c.Height + $RowGap }

    [double]$totalW = ($rightX + $rightW) - $OriginX
    if ($right.Count -eq 0) { $totalW = ($hubX + $Hub.Width) - $OriginX }

    Write-Verbose ("Set-DrawHubSpokeLayout: hub '$($Hub.Label)' with " +
                   "$($left.Count) left / $($right.Count) right spokes")
    New-DrawBounds $OriginX $OriginY $totalW $totalH
}