Public/DrawShapeIndex.ps1

#Requires -Version 7.0
# ============================================================
# DrawManagement — Built-in Shape Index
#
# draw.io ships thousands of shapes it can render without any external
# asset: ~9,000 XML stencils, ~800 shapes registered from JavaScript, and
# ~1,750 SVG icons. Referencing one costs about 40 bytes of style string
# and the diagram stays small, vector and recolourable.
#
# The obstacle has never been capability — it is DISCOVERY. Nothing tells
# you that 'mxgraph.azure.virtual_network' exists while
# 'mxgraph.azure.virtualnetwork' does not.
#
# This file is that missing catalogue. It reads Data/DrawShapeIndex.json,
# generated by Build/Update-DrawShapeIndex.ps1 from a local draw.io
# Desktop install.
#
# THREE KINDS, three style forms:
# Stencil shape=mxgraph.<library>.<name> vector, recolourable
# Shape shape=mxgraph.<name> ditto; registered in JS
# Icon image=img/lib/<path>.svg fixed-colour SVG glyph
#
# NOTE ON LIBRARIES: a draw.io "library" (.xml with an <mxlibrary> root)
# is a PALETTE — a set of shapes a human drags from. It has no effect on
# how a cell renders. What makes a cell draw as a firewall is the style
# string on that cell, nothing else. When generating diagrams
# programmatically the palette is irrelevant; this index is what matters.
# ============================================================

# The index is loaded lazily and cached by Initialize-DrawShapeIndex
# (Private/Helpers.ps1), which populates $script:DrawShapeIndex and
# $script:DrawShapeFlat. Only exported functions live in this file.

function Find-DrawShape {
    <#
    .SYNOPSIS
        Searches draw.io's built-in shapes, stencils and SVG icons by name.

    .DESCRIPTION
        The discovery command for built-in shapes. Every result carries a
        ready-to-use Style string, so the usual workflow is: search, pick,
        pass the Style straight to Add-DrawShape.

        Covers three kinds:
          Stencil vector shape from an XML stencil library
          Shape vector shape registered in draw.io's JavaScript
          Icon SVG glyph under img/lib/

        All of these render from draw.io's own bundled assets — the saved
        file stays small and needs no embedded image data.

        The Style property is the bare index style, without colours. Prefer
        Get-DrawShapeStyle or Add-DrawShapeByName, which add the colours
        draw.io's sidebar uses — fill-only libraries (mxgraph.vvd, veeam2,
        azure, office) otherwise render as an outline or white-on-white.

    .PARAMETER Name
        Wildcard pattern matched against the shape name. Bare text is
        wrapped in wildcards automatically, so 'firewall' behaves like
        '*firewall*'. Matching is case-insensitive.

    .PARAMETER Library
        Wildcard pattern on the library, e.g. 'mxgraph.azure*' or 'azure2'.

    .PARAMETER Kind
        Restrict to Stencil, Shape or Icon.

    .PARAMETER First
        Return at most this many results.

    .EXAMPLE
        Find-DrawShape -Name 'firewall'

    .EXAMPLE
        Find-DrawShape -Name 'kubernetes' -Kind Icon -First 10

    .EXAMPLE
        # search, then place with draw.io's colours
        $fw = Find-DrawShape -Name 'firewall' -Kind Stencil | Select-Object -First 1
        Add-DrawShape -Page $p -Label 'edge-fw' -Style (Get-DrawShapeStyle $fw.Name) `
            -Width $fw.Width -Height $fw.Height

    .OUTPUTS
        [PSCustomObject] with Name, Kind, Library, Width, Height, Style.
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Position = 0, ValueFromPipeline)][string] $Name,
        [Parameter()][string] $Library,
        [Parameter()][ValidateSet('Stencil', 'Shape', 'Icon')][string] $Kind,
        [Parameter()][ValidateRange(1, 100000)][int] $First
    )

    process {
        Initialize-DrawShapeIndex

        $pattern = if ([string]::IsNullOrWhiteSpace($Name)) {
            '*'
        }
        elseif ($Name -match '[\*\?]') {
            $Name
        }
        else {
            # bare text is a convenience for "contains"
            "*$Name*"
        }

        $results = $script:DrawShapeFlat | Where-Object { $_.Name -like $pattern }

        if (-not [string]::IsNullOrWhiteSpace($Kind)) {
            $results = $results | Where-Object { $_.Kind -eq $Kind }
        }
        if (-not [string]::IsNullOrWhiteSpace($Library)) {
            $libPattern = if ($Library -match '[\*\?]') { $Library } else { "*$Library*" }
            $results = $results | Where-Object { $_.Library -like $libPattern }
        }

        $results = $results | Sort-Object Kind, Name
        if ($First) { $results = $results | Select-Object -First $First }

        return $results
    }
}

function Get-DrawShapeLibrary {
    <#
    .SYNOPSIS
        Lists the built-in shape libraries and how many shapes each holds.

    .DESCRIPTION
        Use it to orient yourself before searching — it answers "is there
        an Azure set? a Cisco set? how big?" in one look.

    .PARAMETER Name
        Wildcard filter on the library name.

    .PARAMETER Kind
        Restrict to Stencil, Shape or Icon libraries.

    .EXAMPLE
        Get-DrawShapeLibrary -Name 'azure'

    .EXAMPLE
        Get-DrawShapeLibrary | Sort-Object Count -Descending | Select-Object -First 15

    .OUTPUTS
        [PSCustomObject] with Library, Kind, Count.
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Position = 0)][string] $Name,
        [Parameter()][ValidateSet('Stencil', 'Shape', 'Icon')][string] $Kind
    )

    Initialize-DrawShapeIndex

    $set = $script:DrawShapeFlat
    if (-not [string]::IsNullOrWhiteSpace($Kind)) {
        $set = $set | Where-Object { $_.Kind -eq $Kind }
    }
    if (-not [string]::IsNullOrWhiteSpace($Name)) {
        $pattern = if ($Name -match '[\*\?]') { $Name } else { "*$Name*" }
        $set = $set | Where-Object { $_.Library -like $pattern }
    }

    $set | Group-Object Library, Kind | ForEach-Object {
        [PSCustomObject]@{
            PSTypeName = 'DrawManagement.ShapeLibrary'
            Library    = $_.Group[0].Library
            Kind       = $_.Group[0].Kind
            Count      = $_.Count
        }
    } | Sort-Object Kind, Library
}

function Get-DrawShapeStyle {
    <#
    .SYNOPSIS
        Returns the draw.io style string for a built-in shape or icon.

    .DESCRIPTION
        Resolves an exact name against the index and returns a style ready
        for Add-DrawShape -Style. Accepts either form:

            mxgraph.azure.virtual_network (stencil or JS shape)
            azure2/compute/Virtual_Machine.svg (SVG icon)

        Unknown names throw rather than returning a style that would
        render as a blank rectangle — a silent blank box in the middle of
        a diagram is far harder to notice than an error at build time.

    .PARAMETER Name
        Exact shape name or icon path. Case-insensitive.

    .PARAMETER LabelBelow
        Place the label under the glyph instead of over it. Recommended
        whenever shapes sit in a grid.

    .PARAMETER Fill
        Fill colour (#RGB or #RRGGBB). Applies to vector stencils and JS
        shapes; SVG icons carry their own colours and ignore it. Replaces
        the palette fill (and gradient).

    .PARAMETER Stroke
        Outline colour (#RGB or #RRGGBB), or 'none'. Vector shapes only.
        Replaces the palette stroke.

    .PARAMETER NoPaletteColor
        Return the bare index style. By default a stencil gets the colours
        draw.io's own sidebar gives it (Data/DrawPaletteColors.json) — without
        them fill-only libraries such as mxgraph.vvd, veeam2, azure and office
        render as a black outline or white-on-white.

    .EXAMPLE
        Add-DrawShape -Page $p -Label 'vnet' `
            -Style (Get-DrawShapeStyle 'mxgraph.azure.virtual_network')

    .EXAMPLE
        Get-DrawShapeStyle 'azure2/compute/Virtual_Machine.svg' -LabelBelow

    .EXAMPLE
        # VMware glyph in VMware blue instead of draw.io's grey
        Get-DrawShapeStyle 'mxgraph.vvd.vcenter_server' -Fill '#0091DA' -LabelBelow

    .OUTPUTS
        [string]
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory, Position = 0, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()][string] $Name,
        [Parameter()][switch] $LabelBelow,
        [Parameter()][string] $Fill,
        [Parameter()][string] $Stroke,
        [Parameter()][switch] $NoPaletteColor
    )

    process {
        Initialize-DrawShapeIndex

        $entry = $script:DrawShapeFlat | Where-Object { $_.Name -eq $Name } | Select-Object -First 1

        if ($null -eq $entry) {
            $hint = ''
            $near = @(Find-DrawShape -Name $Name -First 3)
            if ($near.Count -gt 0) {
                $hint = " Did you mean: $($near.Name -join ', ')?"
            }
            throw ("Get-DrawShapeStyle: '$Name' is not a known built-in shape." +
                   "$hint Search with Find-DrawShape.")
        }

        $style = $entry.Style

        if ($LabelBelow -and $style -notmatch 'verticalLabelPosition') {
            $style = Join-DrawStyle $style 'verticalLabelPosition=bottom;verticalAlign=top;align=center;'
        }

        $hasFill   = -not [string]::IsNullOrWhiteSpace($Fill)
        $hasStroke = -not [string]::IsNullOrWhiteSpace($Stroke)

        if (-not $NoPaletteColor -and $entry.Kind -ne 'Icon') {
            $pal = Get-DrawPaletteColor -ShapeName $entry.Name
            if ($null -ne $pal) {
                foreach ($k in $pal.Keys) {
                    if ($hasFill   -and $k -in 'fillColor', 'gradientColor', 'gradientDirection') { continue }
                    if ($hasStroke -and $k -eq 'strokeColor') { continue }
                    $style = Join-DrawStyle $style "$k=$($pal[$k]);"
                }
            }
        }

        if ($hasFill) {
            Assert-HexColor -Color $Fill -ParamName 'Fill'
            $style = Join-DrawStyle $style "fillColor=$Fill;"
        }
        if ($hasStroke) {
            if ($Stroke -ne 'none') { Assert-HexColor -Color $Stroke -ParamName 'Stroke' }
            $style = Join-DrawStyle $style "strokeColor=$Stroke;"
        }

        return $style
    }
}

function Add-DrawShapeByName {
    <#
    .SYNOPSIS
        Adds a built-in draw.io shape to a page by its catalogue name.

    .DESCRIPTION
        The shortest path from "I know the shape exists" to "it is on the
        page": resolves the style from the index and defaults Width/Height
        to the shape's own declared dimensions.

        Everything else behaves like Add-DrawShape.

    .PARAMETER Page
        The [DrawPage] to add the shape to.

    .PARAMETER ShapeName
        Exact catalogue name, e.g. 'mxgraph.azure.virtual_network' or
        'azure2/compute/Virtual_Machine.svg'. Find one with Find-DrawShape.

    .PARAMETER Label
        Text shown on the shape.

    .PARAMETER X
        Horizontal position. Default: 100.

    .PARAMETER Y
        Vertical position. Default: 100.

    .PARAMETER Width
        Override the shape's declared width. Given alone, the height
        follows the shape's aspect ratio.

    .PARAMETER Height
        Override the shape's declared height. Given alone, the width
        follows the shape's aspect ratio.

    .PARAMETER Size
        Fit the longest side to this many pixels, keeping the aspect
        ratio. The usual choice for icons in a grid: many glyphs are not
        square (mxgraph.vvd.server is 5:1) and forcing both sides distorts
        them. Cannot be combined with -Width or -Height.

    .PARAMETER Fill
        Fill colour for vector shapes. Replaces the palette fill.

    .PARAMETER Stroke
        Outline colour for vector shapes, or 'none'.

    .PARAMETER NoPaletteColor
        Skip draw.io's sidebar colours and use the bare index style.

    .PARAMETER LabelBelow
        Place the label under the glyph.

    .PARAMETER ParentId
        Parent container id. Default: '1'.

    .PARAMETER Metadata
        UserObject properties.

    .PARAMETER Tooltip
        Hover text.

    .PARAMETER PassThru
        Return the created [DrawCell].

    .EXAMPLE
        Add-DrawShapeByName -Page $p -ShapeName 'mxgraph.azure.virtual_network' `
            -Label 'prod-vnet' -X 100 -Y 100

    .EXAMPLE
        $fw = Find-DrawShape -Name 'firewall' -Kind Stencil | Select-Object -First 1
        Add-DrawShapeByName -Page $p -ShapeName $fw.Name -Label 'edge-fw' -Fill '#f8cecc'

    .EXAMPLE
        # ESXi host, 60 px wide, true proportions, VMware blue
        Add-DrawShapeByName -Page $p -ShapeName 'mxgraph.vvd.server' -Label 'esxi-01' `
            -Size 60 -Fill '#0091DA' -LabelBelow

    .OUTPUTS
        [DrawCell] when -PassThru is specified.
    #>

    [CmdletBinding()]
    [OutputType([DrawCell])]
    param(
        [Parameter(Mandatory)][DrawPage] $Page,
        [Parameter(Mandatory, Position = 0)][ValidateNotNullOrEmpty()][string] $ShapeName,
        [Parameter()][string]    $Label = '',
        [Parameter()][double]    $X = 100,
        [Parameter()][double]    $Y = 100,
        [Parameter()][ValidateRange(1, 99999)][double] $Width,
        [Parameter()][ValidateRange(1, 99999)][double] $Height,
        [Parameter()][ValidateRange(1, 99999)][double] $Size,
        [Parameter()][string]    $Fill,
        [Parameter()][string]    $Stroke,
        [Parameter()][switch]    $NoPaletteColor,
        [Parameter()][switch]    $LabelBelow,
        [Parameter()][string]    $ParentId = '1',
        [Parameter()][hashtable] $Metadata = @{},
        [Parameter()][string]    $Tooltip,
        [Parameter()][switch]    $PassThru
    )

    Initialize-DrawShapeIndex

    $entry = $script:DrawShapeFlat | Where-Object { $_.Name -eq $ShapeName } | Select-Object -First 1
    if ($null -eq $entry) {
        throw ("Add-DrawShapeByName: '$ShapeName' is not a known built-in shape. " +
               "Search with Find-DrawShape.")
    }
    if ($PSBoundParameters.ContainsKey('Size') -and
        ($PSBoundParameters.ContainsKey('Width') -or $PSBoundParameters.ContainsKey('Height'))) {
        throw 'Add-DrawShapeByName: -Size cannot be combined with -Width or -Height.'
    }

    $style = Get-DrawShapeStyle -Name $ShapeName -LabelBelow:$LabelBelow -Fill $Fill -Stroke $Stroke `
                 -NoPaletteColor:$NoPaletteColor
    $dim   = Get-DrawFitSize -NaturalWidth $entry.Width -NaturalHeight $entry.Height `
                 -Size $Size -Width $Width -Height $Height

    $cell = Add-DrawShape -Page $Page -Label $Label -Style $style `
                -X $X -Y $Y -Width $dim.Width -Height $dim.Height -ParentId $ParentId `
                -Metadata $Metadata -Tooltip $Tooltip -PassThru

    if ($PassThru) { return $cell }
}

function Get-DrawShapeIndexInfo {
    <#
    .SYNOPSIS
        Reports which draw.io version the shape index was built from.

    .DESCRIPTION
        The index is a snapshot of one draw.io install. If your draw.io has
        been upgraded since, regenerate it with
        Build\Update-DrawShapeIndex.ps1 so names match what your app can
        actually render.

    .EXAMPLE
        Get-DrawShapeIndexInfo

    .OUTPUTS
        [PSCustomObject]
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param()

    Initialize-DrawShapeIndex

    [PSCustomObject]@{
        PSTypeName    = 'DrawManagement.ShapeIndexInfo'
        Path          = Get-DrawShapeIndexPath
        DrawioVersion = $script:DrawShapeIndex.drawioVersion
        Generated     = $script:DrawShapeIndex.generated
        Libraries     = $script:DrawShapeIndex.counts.libraries
        Stencils      = $script:DrawShapeIndex.counts.stencils
        JsShapes      = $script:DrawShapeIndex.counts.jsShapes
        Icons         = $script:DrawShapeIndex.counts.icons
        TotalEntries  = $script:DrawShapeFlat.Count
    }
}