Public/DrawPage.ps1

#Requires -Version 7.0
# ============================================================
# DrawManagement — Page / Sheet Management Public Functions
#
# REVIEW CHANGES vs original:
# [PAGE-01] Add-DrawPage: added [ValidateRange] on PageWidth/Height
# and GridSize so callers get a clear error for out-of-range
# values rather than silently writing bad XML.
# [PAGE-02] Get-DrawPage: the original returned $null silently for a
# missing name; now emits Write-Warning so callers notice.
# [PAGE-03] Remove-DrawPage: added -ErrorAction Stop on the internal
# .Remove() call and a Confirm prompt so accidental removal
# of pages with many shapes requires confirmation.
# [PAGE-04] Copy-DrawPage: the original cloned Metadata with
# $c.Metadata.Clone() which is a shallow copy — fine for
# string values but documented; also fixed the ID remapping
# bug where a container child's ParentId was resolved against
# idMap before containers were fully populated.
# [PAGE-05] Add-DrawLegendPage: delegates to the private
# Build-LegendPage helper (no change) but now returns the
# created page for pipeline use without needing -PassThru.
# [PAGE-06] All functions: replaced Out-Null with $null = on New-Item
# calls for consistency with the rest of the module.
# [PAGE-07] Rename-DrawPage: added -Confirm / SupportsShouldProcess
# since renaming is a destructive mutation.
# ============================================================

function Add-DrawPage {
    <#
    .SYNOPSIS
        Adds a new diagram page (tab/sheet) to a DrawFile.

    .PARAMETER DrawFile
        The [DrawFile] to add the page to.

    .PARAMETER Name
        Tab name shown in draw.io. Supports emoji.

    .PARAMETER PageWidth
        Canvas width in pixels. Default: 1100. Minimum: 100.

    .PARAMETER PageHeight
        Canvas height in pixels. Default: 850. Minimum: 100.

    .PARAMETER GridSize
        Snap-grid size in pixels. Default: 10. Range: 1–100.

    .PARAMETER NoGrid
        Disable the snap grid.

    .PARAMETER NoTooltips
        Disable hover tooltips on shapes.

    .PARAMETER Background
        [FIX-04] Canvas background colour as #RGB or #RRGGBB, or 'none'.
        Default: 'none', which omits the attribute and lets draw.io use its
        own default canvas.

    .PARAMETER PassThru
        Return the new [DrawPage] object.

    .EXAMPLE
        $page = Add-DrawPage -DrawFile $doc -Name '🗺 Architecture' -PassThru

    .INPUTS
        [DrawFile] via pipeline.

    .OUTPUTS
        [DrawPage] when -PassThru is specified, otherwise nothing.
    #>

    [CmdletBinding()]
    [OutputType([DrawPage])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)][DrawFile]$DrawFile,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Name,
        # [PAGE-01] range validation
        [Parameter()][ValidateRange(100, 99999)][int]$PageWidth  = 1100,
        [Parameter()][ValidateRange(100, 99999)][int]$PageHeight = 850,
        [Parameter()][ValidateRange(1, 100)][int]    $GridSize   = 10,
        [Parameter()][switch]$NoGrid,
        [Parameter()][switch]$NoTooltips,
        # [FIX-04] canvas background — 'none' omits the attribute
        [Parameter()]
        [ValidatePattern('^(none|#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}))$')]
        [string]$Background = 'none',
        [Parameter()][switch]$PassThru
    )
    process {
        $page             = [DrawPage]::new($Name)
        $page.PageWidth   = $PageWidth
        $page.PageHeight  = $PageHeight
        $page.GridSize    = $GridSize
        $page.Grid        = (-not $NoGrid.IsPresent)
        $page.Tooltips    = (-not $NoTooltips.IsPresent)
        # [FIX-04] store '' for 'none' so ToXml omits the attribute
        $page.Background  = if ($Background -eq 'none') { '' } else { $Background }

        $DrawFile.AddPage($page)
        Write-Verbose "Add-DrawPage: added page '$Name' to DrawFile"

        if ($PassThru) { return $page }
    }
}

function Get-DrawPage {
    <#
    .SYNOPSIS
        Retrieves one or more pages from a DrawFile.

    .PARAMETER DrawFile
        The source [DrawFile].

    .PARAMETER Name
        Page name to find (exact, case-sensitive match). Returns all pages
        when omitted.

    .PARAMETER Index
        Zero-based page index. Out-of-range values produce a warning and
        return nothing.

    .EXAMPLE
        Get-DrawPage -DrawFile $doc -Name '🗺 Architecture'

    .INPUTS
        [DrawFile] via pipeline.

    .OUTPUTS
        [DrawPage]
    #>

    [CmdletBinding(DefaultParameterSetName = 'All')]
    [OutputType([DrawPage])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)][DrawFile]$DrawFile,
        [Parameter(ParameterSetName = 'ByName')][string]$Name,
        [Parameter(ParameterSetName = 'ByIndex')][int]  $Index
    )
    process {
        switch ($PSCmdlet.ParameterSetName) {
            'ByName' {
                $found = $DrawFile.Pages | Where-Object { $_.Name -ceq $Name }
                # [PAGE-02] warn on miss rather than silently returning nothing
                if (-not $found) {
                    Write-Warning "Get-DrawPage: no page named '$Name' found."
                }
                return $found
            }
            'ByIndex' {
                if ($Index -lt 0 -or $Index -ge $DrawFile.Pages.Count) {
                    Write-Warning "Get-DrawPage: index $Index is out of range (0..$($DrawFile.Pages.Count - 1))."
                    return
                }
                return $DrawFile.Pages[$Index]
            }
            default {
                return $DrawFile.Pages
            }
        }
    }
}

function Remove-DrawPage {
    <#
    .SYNOPSIS
        Removes a page from a DrawFile.

    .PARAMETER DrawFile
        The [DrawFile] to modify.

    .PARAMETER Name
        Name of the page to remove (exact match).

    .EXAMPLE
        Remove-DrawPage -DrawFile $doc -Name 'Draft'

    .INPUTS
        [DrawFile] via pipeline.

    .OUTPUTS
        None
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [Parameter(Mandatory, ValueFromPipeline)][DrawFile]$DrawFile,
        [Parameter(Mandatory)][string]$Name
    )
    process {
        # [FIX-27] -First 1: page names are not unique. Handing an array to
        # List.Remove() matches nothing, so it returned $false and reported
        # "it may have already been removed" about a page that was right
        # there.
        $page = $DrawFile.Pages | Where-Object { $_.Name -ceq $Name } | Select-Object -First 1
        if (-not $page) {
            Write-Warning "Remove-DrawPage: page '$Name' not found."
            return
        }

        # Report what will be lost so -WhatIf / -Confirm is informative
        $cellCount = $page.Cells.Count + $page.Edges.Count + $page.Containers.Count
        $target    = "page '$Name' ($cellCount elements)"

        if ($PSCmdlet.ShouldProcess($target, 'Remove page')) {
            # [PAGE-03] .Remove returns bool; check it
            $removed = $DrawFile.Pages.Remove($page)
            if (-not $removed) {
                Write-Warning "Remove-DrawPage: could not remove page '$Name' — it may have already been removed."
            }
            else {
                Write-Verbose "Remove-DrawPage: removed '$Name'"
            }
        }
    }
}

function Rename-DrawPage {
    <#
    .SYNOPSIS
        Renames an existing page.

    .PARAMETER DrawFile
        The [DrawFile] containing the page.

    .PARAMETER OldName
        Current page name (exact, case-sensitive match).

    .PARAMETER NewName
        New page name.

    .EXAMPLE
        Rename-DrawPage -DrawFile $doc -OldName 'Page-1' -NewName '🏗 Infrastructure'

    .OUTPUTS
        None
    #>

    # [PAGE-07] ShouldProcess — renaming is a mutation
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param(
        [Parameter(Mandatory)][DrawFile]$DrawFile,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$OldName,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$NewName
    )

    # [FIX-27] -First 1, and this is the damaging one of the three. Page
    # names are not unique, and PowerShell propagates a property ASSIGNMENT
    # across every element of an array: with two tabs both named 'Draft',
    # `$page.Name = $NewName` renamed BOTH of them. No error, no warning,
    # and the report said it had renamed one page. Renaming the first match
    # is the documented contract ("exact, case-sensitive match"), so pinning
    # it is also what the help already promises.
    $page = $DrawFile.Pages | Where-Object { $_.Name -ceq $OldName } | Select-Object -First 1
    if (-not $page) {
        throw "Rename-DrawPage: page '$OldName' not found."
    }

    if ($PSCmdlet.ShouldProcess("'$OldName' → '$NewName'", 'Rename page')) {
        $page.Name = $NewName
        Write-Verbose "Rename-DrawPage: '$OldName' → '$NewName'"
    }
}

function Add-DrawLegendPage {
    <#
    .SYNOPSIS
        Generates and inserts a standardised legend as the first page.

    .DESCRIPTION
        Creates a formatted reference table listing shapes, connectors and
        colour coding. Always inserted as page index 0 so it opens first.

    .PARAMETER DrawFile
        The target [DrawFile].

    .PARAMETER Shapes
        Array of hashtables describing shapes.
        Required keys: Name, Style.
        Optional keys: UsedFor, FillColor.

    .PARAMETER PageName
        Legend tab name. Default: '📋 Legend'.

    .EXAMPLE
        $shapes = @(
            @{ Name='Process'; Style='rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;'
               UsedFor='System task'; FillColor='#dae8fc' }
            @{ Name='Decision'; Style='rhombus;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;'
               UsedFor='Branch'; FillColor='#fff2cc' }
        )
        $legend = Add-DrawLegendPage -DrawFile $doc -Shapes $shapes

    .OUTPUTS
        [DrawPage]
    #>

    [CmdletBinding()]
    [OutputType([DrawPage])]
    param(
        [Parameter(Mandatory)][DrawFile]$DrawFile,
        [Parameter(Mandatory)][hashtable[]]$Shapes,
        [Parameter()][ValidateNotNullOrEmpty()][string]$PageName = '📋 Legend'
    )

    $legendPage = Build-LegendPage -Shapes $Shapes -PageName $PageName

    # Insert at index 0 so it is always the first tab
    $DrawFile.Pages.Insert(0, $legendPage)
    Write-Verbose "Add-DrawLegendPage: legend inserted as first page"

    # [PAGE-05] always return the page — no -PassThru needed
    return $legendPage
}

function Copy-DrawPage {
    <#
    .SYNOPSIS
        Deep-copies a page within the same DrawFile or to another.

    .DESCRIPTION
        All cells, containers and edges are duplicated with new IDs.
        Cross-references (edges to their source/target, children to their
        containers) are re-mapped using the old-to-new ID table so the
        copy is fully self-consistent.

        [PAGE-04] Containers are processed before cells, and the idMap
        is fully populated before edges are remapped, fixing the original
        ordering bug where a container child's parent might not yet
        have a new ID.

    .PARAMETER SourceFile
        The [DrawFile] containing the source page.

    .PARAMETER PageName
        Name of the page to copy.

    .PARAMETER DestinationFile
        Target [DrawFile]. Defaults to SourceFile (copy within same doc).

    .PARAMETER NewName
        Name for the copied page. Defaults to '<PageName> (copy)'.

    .EXAMPLE
        Copy-DrawPage -SourceFile $doc -PageName 'Architecture' -NewName 'Architecture v2'

    .OUTPUTS
        [DrawPage]
    #>

    [CmdletBinding()]
    [OutputType([DrawPage])]
    param(
        [Parameter(Mandatory)][DrawFile]$SourceFile,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$PageName,
        [Parameter()][DrawFile]$DestinationFile,
        [Parameter()][string]$NewName
    )

    # [FIX-27] Select-Object -First 1. Page names are not unique — draw.io
    # lets you name two tabs the same thing, and Add-DrawPage never checks.
    # With two matches Where-Object hands back an ARRAY, and the first thing
    # this function does with it is $src.PageWidth, which then yields an
    # array too and fails the [int] assignment below with
    # Cannot convert the "System.Object[]" value ... to type "System.Int32"
    # — an error that names neither the page nor the duplicate. Same reason
    # the lookups in Remove-DrawPage and Rename-DrawPage are pinned.
    $src = $SourceFile.Pages | Where-Object { $_.Name -ceq $PageName } | Select-Object -First 1
    if (-not $src) {
        throw "Copy-DrawPage: page '$PageName' not found in SourceFile."
    }

    $dest       = if ($DestinationFile) { $DestinationFile } else { $SourceFile }
    $resolvedName = if (-not [string]::IsNullOrWhiteSpace($NewName)) {
        $NewName
    } else { "$PageName (copy)" }

    $newPage             = [DrawPage]::new($resolvedName)
    $newPage.PageWidth   = $src.PageWidth
    $newPage.PageHeight  = $src.PageHeight
    $newPage.GridSize    = $src.GridSize
    $newPage.Grid        = $src.Grid
    $newPage.Tooltips    = $src.Tooltips
    # [FIX-04] carry the canvas background across the copy
    $newPage.Background  = $src.Background

    # Build full ID map — containers first, then cells, so ParentId
    # lookups in the cells loop always find an already-remapped container ID
    $idMap = @{}

    # [PAGE-04] Pass 1: clone containers and register their ID mappings
    foreach ($srcCon in $src.Containers) {
        $nc         = [DrawCell]::new($srcCon.Label)
        $nc.Id      = [DrawCell]::NewId()
        $idMap[$srcCon.Id] = $nc.Id

        $nc.Style    = $srcCon.Style
        $nc.X        = $srcCon.X;  $nc.Y      = $srcCon.Y
        $nc.Width    = $srcCon.Width; $nc.Height = $srcCon.Height
        # [FIX-27] Carry the source ParentId through verbatim for now; the
        # remap sweep below rewrites it once every container ID is known.
        # This used to be a hard-coded '1', which silently FLATTENED nested
        # containers: [FIX-03] added -ParentId to Add-DrawContainer so a
        # swimlane can sit inside another swimlane, but the copy path was
        # never updated to match. Copying a page with a nested layout moved
        # every inner container out to the canvas root — the shapes were all
        # still there, so nothing errored and nothing looked missing until
        # someone compared the two tabs side by side.
        $nc.ParentId = $srcCon.ParentId
        # Shallow clone — string values are immutable so this is safe
        $nc.Metadata = $srcCon.Metadata.Clone()
        $nc.Tooltip  = $srcCon.Tooltip
        $nc.Link     = $srcCon.Link
        # [FIX-27] Placeholders governs whether draw.io expands %var% in the
        # label. Dropping it turned 'Env: %env%' in the copy into that
        # literal text while the original still resolved.
        $nc.Placeholders = $srcCon.Placeholders
        $newPage.AddContainer($nc)
    }

    # [FIX-27] Pass 1b: now that every container has a new ID, rewrite the
    # ParentIds. A container nested inside another one resolves through the
    # map; anything else (normally '1', the canvas root) is left alone.
    foreach ($nc in $newPage.Containers) {
        if ($idMap.ContainsKey($nc.ParentId)) { $nc.ParentId = $idMap[$nc.ParentId] }
    }

    # Pass 2: clone cells (after all container IDs are in the map)
    foreach ($srcCell in $src.Cells) {
        $nc      = [DrawCell]::new($srcCell.Label)
        $nc.Id   = [DrawCell]::NewId()
        $idMap[$srcCell.Id] = $nc.Id

        $nc.Style    = $srcCell.Style
        $nc.X        = $srcCell.X;  $nc.Y      = $srcCell.Y
        $nc.Width    = $srcCell.Width; $nc.Height = $srcCell.Height

        # Remap parent — use remapped ID if parent was a container in this page
        $nc.ParentId = if ($idMap.ContainsKey($srcCell.ParentId)) {
            $idMap[$srcCell.ParentId]
        } else { $srcCell.ParentId }

        $nc.Metadata = $srcCell.Metadata.Clone()
        $nc.Tooltip  = $srcCell.Tooltip
        $nc.Link     = $srcCell.Link
        # [FIX-27] see the container pass
        $nc.Placeholders = $srcCell.Placeholders
        $newPage.AddCell($nc)
    }

    # Pass 3: clone edges with remapped source/target
    foreach ($srcEdge in $src.Edges) {
        $ne          = New-Object DrawEdge
        $ne.Id       = [DrawCell]::NewId()
        $ne.Label    = $srcEdge.Label
        $ne.Style    = $srcEdge.Style
        $ne.Tooltip  = $srcEdge.Tooltip
        # [FIX-27] Link and Placeholders were never copied. Link is the
        # field FIX-25 had just added to DrawEdge, so every clickable edge
        # lost its target on copy; Placeholders is the same label defect as
        # above. Both are silent.
        $ne.Link     = $srcEdge.Link
        $ne.Placeholders = $srcEdge.Placeholders
        $ne.Metadata = $srcEdge.Metadata.Clone()

        $ne.SourceId = if ($idMap.ContainsKey($srcEdge.SourceId)) {
            $idMap[$srcEdge.SourceId]
        } else { $srcEdge.SourceId }

        $ne.TargetId = if ($idMap.ContainsKey($srcEdge.TargetId)) {
            $idMap[$srcEdge.TargetId]
        } else { $srcEdge.TargetId }

        $ne.ParentId = '1'
        $newPage.AddEdge($ne)
    }

    $dest.AddPage($newPage)
    Write-Verbose "Copy-DrawPage: '$PageName' → '$resolvedName' ($($src.Cells.Count) cells, $($src.Edges.Count) edges)"
    return $newPage
}