Public/DrawShape.ps1
|
#Requires -Version 7.0 # ============================================================ # DrawManagement — Shape / Cell / Edge Public Functions # # REVIEW CHANGES vs original: # [SHAPE-01] $script:DrawStyles and $script:DrawColors defined as # ordered hashtables ([ordered]@{}) so Get-DrawShapeTypes # produces consistent output order across PS versions. # [SHAPE-02] Add-DrawShape: removed [DrawFontStyle]::Normal as a # default parameter value — enum defaults in PS 5.1 param # blocks are evaluated at parse time in some edge cases; # moved to an explicit $PSBoundParameters check instead. # [SHAPE-03] Add-DrawShape: ShapeType unknown value now emits # Write-Warning rather than silently falling back so the # caller knows their typo wasn't applied. # [SHAPE-04] Add-DrawShape: hex colour values validated with a regex # before being appended to the style string to prevent # malformed XML output. # [SHAPE-05] Add-DrawShape: FontSize range validated (1–144) so # negative or absurd values are caught early. # [SHAPE-06] Add-DrawContainer: FillColor and StrokeColor validated # with same hex regex as Add-DrawShape. # [SHAPE-07] Add-DrawText: explicit [OutputType] added; function now # returns the created cell unconditionally (it was already # doing so — made explicit and consistent with -PassThru # pattern used elsewhere). # [SHAPE-08] Add-DrawEdge: $edgeStyleMap and $arrowMap moved to # script-scope constants so they are not re-allocated on # every call — these maps never change. # [SHAPE-09] Add-DrawEdge: StrokeWidth validated (range 1–20). # [SHAPE-10] Add-DrawEdge: Source/Target typed as [object] with a # ValidateScript that calls Resolve-CellId early, producing # a clear error at binding time rather than mid-process. # [SHAPE-11] Add-DrawBidirectionalEdge: documented that it delegates # to Add-DrawEdge; removed redundant return statement # (Write-Output / implicit return is more idiomatic). # [SHAPE-12] Set-DrawCellMetadata: added validation that property key # names are safe XML attribute names. # [SHAPE-13] Get-DrawShapeTypes: ?? operator removed (PS 5.1); now # uses if/else for category lookup fallback. # ============================================================ # ── Script-scoped style library ───────────────────────────────────── # [SHAPE-01] [ordered] for deterministic iteration order $script:DrawStyles = [ordered]@{ # General Rectangle = 'rounded=0;whiteSpace=wrap;html=1;' RoundedRect = 'rounded=1;whiteSpace=wrap;html=1;' Ellipse = 'ellipse;whiteSpace=wrap;html=1;' Diamond = 'rhombus;whiteSpace=wrap;html=1;' Triangle = 'triangle;whiteSpace=wrap;html=1;' Hexagon = 'shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;' Cloud = 'shape=cloud;whiteSpace=wrap;html=1;' Cylinder = 'shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;' Note = 'shape=note;whiteSpace=wrap;html=1;backgroundOutline=1;' Document = 'shape=document;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;' Callout = 'shape=callout;whiteSpace=wrap;html=1;' Parallelogram = 'shape=parallelogram;perimeter=parallelogramPerimeter;whiteSpace=wrap;html=1;' Swimlane = 'swimlane;startSize=26;' Star = 'shape=mxgraph.basic.star;whiteSpace=wrap;html=1;' # Flowchart FcProcess = 'rounded=1;whiteSpace=wrap;html=1;' FcDecision = 'rhombus;whiteSpace=wrap;html=1;' FcTerminal = 'ellipse;whiteSpace=wrap;html=1;' FcDatabase = 'shape=mxgraph.flowchart.database;whiteSpace=wrap;html=1;' FcDelay = 'shape=mxgraph.flowchart.delay;whiteSpace=wrap;html=1;' FcDisplay = 'shape=mxgraph.flowchart.display;whiteSpace=wrap;html=1;' FcPrep = 'shape=mxgraph.flowchart.preparation;whiteSpace=wrap;html=1;' FcManualInput = 'shape=mxgraph.flowchart.manual_input;whiteSpace=wrap;html=1;' FcMerge = 'shape=mxgraph.flowchart.merge_or_storage;whiteSpace=wrap;html=1;' # Network — the package is 'networks' (plural); 'network' does not exist NetServer = 'shape=mxgraph.networks.server;html=1;' NetRouter = 'shape=mxgraph.networks.router;html=1;' NetSwitch = 'shape=mxgraph.networks.switch;html=1;' NetFirewall = 'shape=mxgraph.networks.firewall;html=1;' NetCloud = 'shape=mxgraph.networks.cloud;html=1;' NetPC = 'shape=mxgraph.networks.pc;html=1;' NetLaptop = 'shape=mxgraph.networks.laptop;html=1;' NetMobile = 'shape=mxgraph.networks.mobile;html=1;' # AWS AwsEC2 = 'shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.ec2;html=1;' AwsS3 = 'shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.s3;html=1;' AwsLambda = 'shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.lambda;html=1;' AwsRDS = 'shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.rds;html=1;' AwsSQS = 'shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.sqs;html=1;' AwsApiGW = 'shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.api_gateway;html=1;' AwsCloudFront = 'shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.cloudfront;html=1;' # Azure — fill-only glyphs: palette colour, no outline, label below AzureVM = 'shape=mxgraph.azure.virtual_machine;html=1;fillColor=#00BEF2;strokeColor=none;' + 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' AzureSQL = 'shape=mxgraph.azure.sql_database;html=1;fillColor=#00BEF2;strokeColor=none;' + 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' AzureStorage = 'shape=mxgraph.azure.storage;html=1;fillColor=#00BEF2;strokeColor=none;' + 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' # The classic mxgraph.azure stencil set has no Functions shape — use the # azure2 SVG icon instead. Same style form as Get-DrawAzureStyle. AzureFunc = 'image;aspect=fixed;html=1;points=[];align=center;fontSize=12;' + 'image=img/lib/azure2/compute/Function_Apps.svg;' + 'verticalLabelPosition=bottom;verticalAlign=top;' # Active Directory AdServer = 'shape=mxgraph.networks.server;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;' AdUser = 'shape=mxgraph.cisco.people.pc_man;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;' AdGroup = 'shape=mxgraph.cisco.people.man_woman;html=1;fillColor=#d5e8d4;strokeColor=#82b366;' AdOU = 'shape=mxgraph.cisco.buildings.generic_building;html=1;fillColor=#fff2cc;strokeColor=#d6b656;' # VMware — mxgraph.vvd glyphs are fill-only: VMware blue, no outline, # label below. Sized to their true proportions (see $script:DrawIconPresets). VmHost = 'shape=mxgraph.vvd.server;html=1;whiteSpace=wrap;fillColor=#0091DA;strokeColor=none;' + 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' VmVM = 'shape=mxgraph.vvd.virtual_machine;html=1;whiteSpace=wrap;fillColor=#0091DA;strokeColor=none;' + 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' VmvCenter = 'shape=mxgraph.vvd.vcenter_server;html=1;whiteSpace=wrap;fillColor=#0091DA;strokeColor=none;' + 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' VmCluster = 'shape=mxgraph.vvd.resource_pool;html=1;whiteSpace=wrap;fillColor=#0091DA;strokeColor=none;' + 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' VmNSX = 'shape=mxgraph.vvd.nsx_manager;html=1;whiteSpace=wrap;fillColor=#0091DA;strokeColor=none;' + 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' VmvSAN = 'shape=mxgraph.vvd.vsan;html=1;whiteSpace=wrap;fillColor=#0091DA;strokeColor=none;' + 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' } # Presets that are glyphs, not boxes. Without an explicit -Width/-Height, # Add-DrawShape sizes them to fit this many pixels at the glyph's own aspect # ratio — the 120x60 box default squashes them (mxgraph.vvd.server is 5:1). $script:DrawIconPresets = @('AzureVM', 'AzureSQL', 'AzureStorage', 'VmHost', 'VmVM', 'VmvCenter', 'VmCluster', 'VmNSX', 'VmvSAN') $script:DrawIconPresetSize = 60 # ── Script-scoped colour presets ──────────────────────────────────── $script:DrawColors = [ordered]@{ Blue = @{ Fill = '#dae8fc'; Stroke = '#6c8ebf' } Green = @{ Fill = '#d5e8d4'; Stroke = '#82b366' } Yellow = @{ Fill = '#fff2cc'; Stroke = '#d6b656' } Red = @{ Fill = '#f8cecc'; Stroke = '#b85450' } Purple = @{ Fill = '#e1d5e7'; Stroke = '#9673a6' } Grey = @{ Fill = '#f5f5f5'; Stroke = '#666666' } Orange = @{ Fill = '#ffe6cc'; Stroke = '#d79b00' } Teal = @{ Fill = '#d5e8d4'; Stroke = '#009999' } } # [SHAPE-08] script-scope edge/arrow maps — allocated once, not per call $script:DrawEdgeStyleMap = @{ Orthogonal = 'edgeStyle=orthogonalEdgeStyle' Straight = 'edgeStyle=none' Curved = 'curved=1;edgeStyle=elbowEdgeStyle' ElbowEdge = 'edgeStyle=elbowEdgeStyle' EntityRelation = 'edgeStyle=entityRelationEdgeStyle' IsometricEdge = 'edgeStyle=isometricEdgeStyle' } $script:DrawArrowMap = @{ Block = 'block' Open = 'open' Classic = 'classic' None = 'none' Oval = 'oval' Diamond = 'diamond' ERone = 'ERone' ERmany = 'ERmany' } # ── Hex colour validation helper ───────────────────────────────────── # [SHAPE-04] reused by Add-DrawShape and Add-DrawContainer function Assert-HexColor { param([string]$Color, [string]$ParamName) if (-not [string]::IsNullOrWhiteSpace($Color) -and $Color -notmatch '^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$') { throw "Assert-HexColor: '$Color' is not a valid hex colour for -$ParamName. Use #RGB or #RRGGBB format." } } # NOTE: style fragments are appended via Join-DrawStyle (Private/Helpers.ps1), # which guarantees no space is introduced after the separating ';'. See # [FIX-01] there for why a space silently breaks the setting. # ───────────────────────────────────────────────────────────────────── # SHAPE / CELL FUNCTIONS # ───────────────────────────────────────────────────────────────────── function Add-DrawShape { <# .SYNOPSIS Adds a shape (vertex cell) to a draw.io page. .DESCRIPTION Supports named style presets (-ShapeType), raw style strings (-Style), colour presets (-Color), explicit colours, font control, UserObject metadata (-Metadata), tooltips and hyperlinks. .PARAMETER Page The [DrawPage] to add the shape to. .PARAMETER Label Text displayed inside the shape. Supports HTML. .PARAMETER ShapeType Named preset from the built-in style library. Run Get-DrawShapeTypes to see all available values. .PARAMETER Style Raw draw.io style string. Takes precedence over -ShapeType. .PARAMETER X Horizontal position in pixels. Default: 100. .PARAMETER Y Vertical position in pixels. Default: 100. .PARAMETER Width Shape width in pixels. Default: 120. Minimum: 1. Glyph presets (Azure*, Vm* except AzureFunc) default to their true proportions fitted to 60 px; give only -Width or -Height to keep the ratio. .PARAMETER Height Shape height in pixels. Default: 60. Minimum: 1. .PARAMETER Color Named colour preset applied on top of -ShapeType: Blue, Green, Yellow, Red, Purple, Grey, Orange, Teal. .PARAMETER FillColor Explicit hex fill colour (#RGB or #RRGGBB). Overrides -Color. .PARAMETER StrokeColor Explicit hex border/stroke colour (#RGB or #RRGGBB). .PARAMETER FontSize Font size in pt. Default: 12. Range: 1–144. .PARAMETER Bold Apply bold font style. .PARAMETER Italic Apply italic font style. .PARAMETER Metadata Hashtable of custom UserObject properties (owner, version, SLA…). Visible in draw.io via right-click → Edit Data (Ctrl+M). .PARAMETER Tooltip Hover text shown on mouse-over in draw.io. .PARAMETER Link URL opened when the shape is clicked. .PARAMETER ParentId ID of the parent container cell. Default: '1' (root layer). .PARAMETER PassThru Return the created [DrawCell] object. .EXAMPLE $cell = Add-DrawShape -Page $page -Label 'Web Server' ` -ShapeType NetServer -Color Blue -X 100 -Y 100 ` -Tooltip 'nginx 1.24' -PassThru .EXAMPLE Add-DrawShape -Page $page -Label 'Orders λ' -ShapeType AwsLambda ` -Metadata @{ version = '1.2'; owner = 'team-a'; sla = '99.9%' } ` -X 300 -Y 200 .INPUTS [DrawPage] via pipeline. .OUTPUTS [DrawCell] when -PassThru is specified, otherwise nothing. #> [CmdletBinding()] [OutputType([DrawCell])] param( [Parameter(Mandatory, ValueFromPipeline)][DrawPage] $Page, [Parameter()][string] $Label = '', [Parameter()][string] $ShapeType, [Parameter()][string] $Style, [Parameter()][ValidateRange(0, 99999)][double] $X = 100, [Parameter()][ValidateRange(0, 99999)][double] $Y = 100, [Parameter()][ValidateRange(1, 99999)][double] $Width = 120, [Parameter()][ValidateRange(1, 99999)][double] $Height = 60, [Parameter()][ValidateSet( 'Blue','Green','Yellow','Red','Purple','Grey','Orange','Teal')] [string] $Color, [Parameter()][string] $FillColor, [Parameter()][string] $StrokeColor, # [SHAPE-05] font size range validation [Parameter()][ValidateRange(1,144)][int] $FontSize = 12, # [SHAPE-02] bold/italic as switches — cleaner than enum default [Parameter()][switch] $Bold, [Parameter()][switch] $Italic, [Parameter()][hashtable] $Metadata = @{}, [Parameter()][string] $Tooltip, [Parameter()][string] $Link, [Parameter()][string] $ParentId = '1', [Parameter()][switch] $PassThru ) process { # [SHAPE-04] validate hex colours early Assert-HexColor -Color $FillColor -ParamName 'FillColor' Assert-HexColor -Color $StrokeColor -ParamName 'StrokeColor' # Resolve base style $baseStyle = if (-not [string]::IsNullOrWhiteSpace($Style)) { $Style } elseif (-not [string]::IsNullOrWhiteSpace($ShapeType)) { if ($script:DrawStyles.Contains($ShapeType)) { $script:DrawStyles[$ShapeType] } else { # [SHAPE-03] warn on unknown type rather than silently falling back Write-Warning ("Add-DrawShape: ShapeType '$ShapeType' is not a known preset. " + "Falling back to Rectangle. Run Get-DrawShapeTypes for valid values.") $script:DrawStyles['Rectangle'] } } else { $script:DrawStyles['Rectangle'] } # Apply named colour preset if (-not [string]::IsNullOrWhiteSpace($Color) -and $script:DrawColors.Contains($Color)) { $c = $script:DrawColors[$Color] # [FIX-01] no space after ';' — see Join-DrawStyle $baseStyle = Join-DrawStyle $baseStyle "fillColor=$($c.Fill);strokeColor=$($c.Stroke);" } # Explicit colour overrides if (-not [string]::IsNullOrWhiteSpace($FillColor)) { $baseStyle = Join-DrawStyle $baseStyle "fillColor=$FillColor;" } if (-not [string]::IsNullOrWhiteSpace($StrokeColor)) { $baseStyle = Join-DrawStyle $baseStyle "strokeColor=$StrokeColor;" } # Font size (only append if non-default to keep styles terse) if ($FontSize -ne 12) { $baseStyle = Join-DrawStyle $baseStyle "fontSize=$FontSize;" } # [SHAPE-02] font style computed from switches $fontStyleValue = 0 if ($Bold) { $fontStyleValue += 1 } if ($Italic) { $fontStyleValue += 2 } if ($fontStyleValue -gt 0) { $baseStyle = Join-DrawStyle $baseStyle "fontStyle=$fontStyleValue;" } $cell = [DrawCell]::new($Label) $cell.Style = $baseStyle $cell.X = $X $cell.Y = $Y $cell.Width = $Width $cell.Height = $Height # Glyph presets keep their true proportions unless both sides are given if ([string]::IsNullOrWhiteSpace($Style) -and $ShapeType -in $script:DrawIconPresets -and -not ($PSBoundParameters.ContainsKey('Width') -and $PSBoundParameters.ContainsKey('Height')) -and $baseStyle -match 'shape=(mxgraph\.[A-Za-z0-9_.]+);') { $shapeName = $Matches[1] Initialize-DrawShapeIndex $entry = $script:DrawShapeFlat | Where-Object { $_.Name -eq $shapeName } | Select-Object -First 1 if ($null -ne $entry) { $fit = if ($PSBoundParameters.ContainsKey('Width')) { Get-DrawFitSize -NaturalWidth $entry.Width -NaturalHeight $entry.Height -Width $Width } elseif ($PSBoundParameters.ContainsKey('Height')) { Get-DrawFitSize -NaturalWidth $entry.Width -NaturalHeight $entry.Height -Height $Height } else { Get-DrawFitSize -NaturalWidth $entry.Width -NaturalHeight $entry.Height -Size $script:DrawIconPresetSize } $cell.Width = $fit.Width $cell.Height = $fit.Height } } $cell.ParentId = $ParentId $cell.Metadata = $Metadata if (-not [string]::IsNullOrWhiteSpace($Tooltip)) { $cell.Tooltip = $Tooltip } if (-not [string]::IsNullOrWhiteSpace($Link)) { $cell.Link = $Link } $Page.AddCell($cell) Write-Verbose "Add-DrawShape: '$Label' (${ShapeType}) at ($X, $Y) on page '$($Page.Name)'" if ($PassThru) { return $cell } } } function Add-DrawContainer { <# .SYNOPSIS Adds a container (swimlane/group) that can hold child shapes. .DESCRIPTION Creates a labelled swimlane. Child shapes are added with Add-DrawShape using -ParentId set to the container's Id. .PARAMETER Page The [DrawPage] to add the container to. .PARAMETER Label Container header title. Supports HTML. .PARAMETER X Horizontal position in pixels. .PARAMETER Y Vertical position in pixels. .PARAMETER Width Container width in pixels. Default: 300. .PARAMETER Height Container height in pixels. Default: 200. .PARAMETER FillColor Background fill colour (#RGB or #RRGGBB). Default: #ffffff. .PARAMETER StrokeColor Border colour (#RGB or #RRGGBB). Default: #000000. .PARAMETER HeaderSize Height of the title bar in pixels. Default: 26. .PARAMETER Style [FIX-02] Raw draw.io style string, used verbatim. Takes precedence over -FillColor / -StrokeColor / -HeaderSize, which are ignored when this is supplied. Use it when you need swimlane properties the composed style does not cover (swimlaneFillColor, rounded, strokeWidth, whiteSpace, html, fontSize…). .PARAMETER ParentId [FIX-03] ID of the parent container, for nesting one container inside another. Default: '1' (root layer). Ordering note: DrawPage.ToXml emits containers before plain cells, each group in insertion order. Always add a parent container BEFORE its children, and do not parent a container to a cell created with Add-DrawShape — draw.io drops a child that appears ahead of its parent in the XML. .PARAMETER Metadata Custom UserObject properties. .PARAMETER Tooltip Hover text. .PARAMETER PassThru Return the [DrawCell] container object. .EXAMPLE $zone = Add-DrawContainer -Page $page -Label 'API Zone' ` -X 400 -Y 80 -Width 320 -Height 220 ` -FillColor '#f0fff0' -StrokeColor '#82b366' -PassThru # Add a child shape inside the container: Add-DrawShape -Page $page -Label 'Service' -ShapeType RoundedRect ` -X 20 -Y 50 -Width 120 -Height 50 -ParentId $zone.Id .EXAMPLE # Nested containers with a custom swimlane style $vnet = Add-DrawContainer -Page $page -Label 'VNet — 10.0.0.0/16' ` -X 40 -Y 40 -Width 820 -Height 400 ` -Style 'swimlane;whiteSpace=wrap;html=1;rounded=1;fillColor=#dae8fc;strokeColor=#0b66c2;startSize=28;swimlaneFillColor=#f5faff;strokeWidth=3;' ` -PassThru $subnet = Add-DrawContainer -Page $page -Label 'GatewaySubnet' ` -X 16 -Y 68 -Width 788 -Height 105 -ParentId $vnet.Id -PassThru .INPUTS None — Page is a positional/named parameter, not pipeline. .OUTPUTS [DrawCell] when -PassThru is specified, otherwise nothing. #> [CmdletBinding()] [OutputType([DrawCell])] param( [Parameter(Mandatory)][DrawPage] $Page, [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $Label, [Parameter()][ValidateRange(0, 99999)][double] $X = 40, [Parameter()][ValidateRange(0, 99999)][double] $Y = 80, [Parameter()][ValidateRange(1, 99999)][double] $Width = 300, [Parameter()][ValidateRange(1, 99999)][double] $Height = 200, [Parameter()][string] $FillColor = '#ffffff', [Parameter()][string] $StrokeColor = '#000000', [Parameter()][ValidateRange(10, 100)][int] $HeaderSize = 26, # [FIX-02] raw style escape hatch — overrides the composed style [Parameter()][string] $Style, # [FIX-03] nesting support — was hard-coded to '1' [Parameter()][string] $ParentId = '1', [Parameter()][hashtable] $Metadata = @{}, [Parameter()][string] $Tooltip, [Parameter()][switch] $PassThru ) if (-not [string]::IsNullOrWhiteSpace($Style)) { # [FIX-02] caller supplied a complete style — use it verbatim $finalStyle = $Style } else { # [SHAPE-06] validate colours Assert-HexColor -Color $FillColor -ParamName 'FillColor' Assert-HexColor -Color $StrokeColor -ParamName 'StrokeColor' $finalStyle = "swimlane;startSize=$HeaderSize;fillColor=$FillColor;" + "strokeColor=$StrokeColor;fontStyle=1;fontSize=12;" } $c = [DrawCell]::new($Label) $c.Style = $finalStyle $c.X = $X $c.Y = $Y $c.Width = $Width $c.Height = $Height $c.ParentId = $ParentId $c.Metadata = $Metadata if (-not [string]::IsNullOrWhiteSpace($Tooltip)) { $c.Tooltip = $Tooltip } $Page.AddContainer($c) Write-Verbose "Add-DrawContainer: '$Label' at ($X, $Y) [${Width}x${Height}]" if ($PassThru) { return $c } } function Add-DrawText { <# .SYNOPSIS Adds a free-floating text label to a page. .DESCRIPTION Creates a transparent text cell. Supports HTML content in -Text. Always returns the created cell (no -PassThru needed). .PARAMETER Page The [DrawPage] to add the label to. .PARAMETER Text Label content. HTML tags are supported. .PARAMETER X Horizontal position in pixels. Default: 40. .PARAMETER Y Vertical position in pixels. Default: 40. .PARAMETER Width Label width in pixels. Default: 300. .PARAMETER Height Label height in pixels. Default: 30. .PARAMETER FontSize Font size in pt. Default: 12. .PARAMETER Bold Apply bold formatting. .PARAMETER Italic Apply italic formatting. .PARAMETER Align Horizontal text alignment: left, center, right. Default: left. .PARAMETER FontColor Text colour (#RGB or #RRGGBB). Default: #000000. .EXAMPLE Add-DrawText -Page $page -Text '<b>Section A — Infrastructure</b>' ` -X 40 -Y 20 -Bold -FontSize 16 .OUTPUTS [DrawCell] #> [CmdletBinding()] [OutputType([DrawCell])] param( [Parameter(Mandatory)][DrawPage] $Page, [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $Text, [Parameter()][ValidateRange(0, 99999)][double] $X = 40, [Parameter()][ValidateRange(0, 99999)][double] $Y = 40, [Parameter()][ValidateRange(1, 99999)][double] $Width = 300, [Parameter()][ValidateRange(1, 99999)][double] $Height = 30, [Parameter()][ValidateRange(1, 144)][int] $FontSize = 12, [Parameter()][switch] $Bold, [Parameter()][switch] $Italic, [Parameter()][ValidateSet('left','center','right')][string]$Align = 'left', [Parameter()][string] $FontColor = '#000000' ) Assert-HexColor -Color $FontColor -ParamName 'FontColor' $fontStyleValue = 0 if ($Bold) { $fontStyleValue += 1 } if ($Italic) { $fontStyleValue += 2 } $style = ("text;html=1;fontSize=$FontSize;fontStyle=$fontStyleValue;" + "align=$Align;fontColor=$FontColor;strokeColor=none;fillColor=none;") $c = [DrawCell]::new($Text) $c.Style = $style $c.X = $X $c.Y = $Y $c.Width = $Width $c.Height = $Height $Page.AddCell($c) Write-Verbose "Add-DrawText: text label at ($X, $Y)" # [SHAPE-07] always return — callers often need the ID for links return $c } # ───────────────────────────────────────────────────────────────────── # EDGE / CONNECTOR FUNCTIONS # ───────────────────────────────────────────────────────────────────── function Add-DrawEdge { <# .SYNOPSIS Adds a connector (edge/arrow) between two shapes. .DESCRIPTION Creates a directed or undirected connector with full control over routing style, arrow head type, colour, weight and dashing. Source and Target accept either a [DrawCell] object or a string cell ID — both are resolved via Resolve-CellId. .PARAMETER Page The [DrawPage] to add the edge to. .PARAMETER Source Source shape — a [DrawCell] object or its ID string. .PARAMETER Target Target shape — a [DrawCell] object or its ID string. .PARAMETER Label Optional connector label. .PARAMETER EdgeStyle Routing algorithm: Orthogonal (default) | Straight | Curved | ElbowEdge | EntityRelation | IsometricEdge .PARAMETER StartArrow Arrow head at the source end. Default: None. .PARAMETER EndArrow Arrow head at the target end. Default: Block. .PARAMETER Dashed Render as a dashed line. .PARAMETER Color Stroke/line colour (#RGB or #RRGGBB). Default: #000000. .PARAMETER StrokeWidth Line thickness in pixels. Range: 1–20. Default: 1. .PARAMETER Metadata Custom UserObject properties on the connector. .PARAMETER Tooltip Hover text on the connector. .PARAMETER Link Hyperlink opened when the connector is clicked. [FIX-25] draw.io supports links on edges exactly as on shapes. .PARAMETER PassThru Return the created [DrawEdge] object. .EXAMPLE Add-DrawEdge -Page $page -Source $webApp -Target $apiGw ` -Label 'HTTPS' -Color '#6c8ebf' -PassThru .EXAMPLE Add-DrawEdge -Page $page -Source $orderSvc -Target $queue ` -Label 'publish' -Dashed -EdgeStyle Straight -EndArrow Open .INPUTS None — parameters are positional/named. .OUTPUTS [DrawEdge] when -PassThru is specified, otherwise nothing. #> [CmdletBinding()] [OutputType([DrawEdge])] param( [Parameter(Mandatory)][DrawPage] $Page, # [SHAPE-10] typed as [object]; validated in process block [Parameter(Mandatory)][object] $Source, [Parameter(Mandatory)][object] $Target, [Parameter()][string] $Label = '', [Parameter()][DrawEdgeStyle] $EdgeStyle = [DrawEdgeStyle]::Orthogonal, [Parameter()][DrawArrowType] $StartArrow = [DrawArrowType]::None, [Parameter()][DrawArrowType] $EndArrow = [DrawArrowType]::Block, [Parameter()][switch] $Dashed, [Parameter()][string] $Color = '#000000', # [SHAPE-09] stroke width validation [Parameter()][ValidateRange(1,20)][int] $StrokeWidth = 1, [Parameter()][hashtable] $Metadata = @{}, [Parameter()][string] $Tooltip, [Parameter()][string] $Link, [Parameter()][switch] $PassThru ) process { # [SHAPE-04] validate colour Assert-HexColor -Color $Color -ParamName 'Color' # Resolve cell references — gives descriptive errors on bad input $srcId = Resolve-CellId -Ref $Source $tgtId = Resolve-CellId -Ref $Target if ($srcId -eq $tgtId) { Write-Warning "Add-DrawEdge: source and target are the same cell ('$srcId'). Self-loops are valid in draw.io but may look odd." } $edgeStyleStr = $script:DrawEdgeStyleMap[[string]$EdgeStyle] $startArrowStr = $script:DrawArrowMap[[string]$StartArrow] $endArrowStr = $script:DrawArrowMap[[string]$EndArrow] $styleParts = New-Object 'System.Collections.Generic.List[string]' $null = $styleParts.Add($edgeStyleStr) $null = $styleParts.Add('html=1') $null = $styleParts.Add("startArrow=$startArrowStr") $null = $styleParts.Add("endArrow=$endArrowStr") $null = $styleParts.Add("strokeColor=$Color") $null = $styleParts.Add("strokeWidth=$StrokeWidth") if ($Dashed) { $null = $styleParts.Add('dashed=1') } # Fill the arrowhead if it is a solid type if ($StartArrow -notin @([DrawArrowType]::None, [DrawArrowType]::Open)) { $null = $styleParts.Add('startFill=1') } if ($EndArrow -notin @([DrawArrowType]::None, [DrawArrowType]::Open)) { $null = $styleParts.Add('endFill=1') } $edge = [DrawEdge]::new($srcId, $tgtId) $edge.Label = $Label $edge.Style = ($styleParts -join ';') + ';' $edge.Metadata = $Metadata if (-not [string]::IsNullOrWhiteSpace($Tooltip)) { $edge.Tooltip = $Tooltip } if (-not [string]::IsNullOrWhiteSpace($Link)) { $edge.Link = $Link } $Page.AddEdge($edge) Write-Verbose "Add-DrawEdge: '$Label' ($srcId → $tgtId) on page '$($Page.Name)'" if ($PassThru) { return $edge } } } function Add-DrawBidirectionalEdge { <# .SYNOPSIS Adds a bidirectional connector (filled block arrows on both ends). .DESCRIPTION Convenience wrapper around Add-DrawEdge with StartArrow=Block and EndArrow=Block. All other parameters are forwarded. .PARAMETER Page The [DrawPage] to add the edge to. .PARAMETER Source Source shape — [DrawCell] object or string ID. .PARAMETER Target Target shape — [DrawCell] object or string ID. .PARAMETER Label Optional connector label. .PARAMETER Color Stroke colour. Default: #000000. .PARAMETER StrokeWidth Line thickness. Range 1–20. Default: 1. .PARAMETER Dashed Render as a dashed line. .PARAMETER PassThru Return the created [DrawEdge] object. .EXAMPLE Add-DrawBidirectionalEdge -Page $page -Source $dc1 -Target $dc2 ` -Label 'AD Replication' -Color '#82b366' .OUTPUTS [DrawEdge] when -PassThru is specified, otherwise nothing. #> [CmdletBinding()] [OutputType([DrawEdge])] param( [Parameter(Mandatory)][DrawPage] $Page, [Parameter(Mandatory)][object] $Source, [Parameter(Mandatory)][object] $Target, [Parameter()][string] $Label = '', [Parameter()][string] $Color = '#000000', [Parameter()][ValidateRange(1,20)][int] $StrokeWidth = 1, [Parameter()][switch] $Dashed, [Parameter()][switch] $PassThru ) # [SHAPE-11] no return needed — Add-DrawEdge output flows through Add-DrawEdge -Page $Page -Source $Source -Target $Target ` -Label $Label -StartArrow Block -EndArrow Block ` -Color $Color -StrokeWidth $StrokeWidth ` -Dashed:$Dashed -PassThru:$PassThru } function Set-DrawCellMetadata { <# .SYNOPSIS Adds or updates UserObject metadata properties on a cell. .DESCRIPTION Sets one or more key/value pairs on the cell's Metadata hashtable. Keys are validated to be safe XML attribute names (letters, digits, hyphens, underscores only). .PARAMETER Cell [FIX-07] The [DrawCell] or [DrawEdge] to update. Both types carry a Metadata hashtable that ToXml serialises into UserObject attributes, so both are accepted. Typed as [object] because a param typed [DrawCell] silently refuses [DrawEdge] at pipeline-binding time. .PARAMETER Properties Hashtable of property names and values to set. .EXAMPLE Set-DrawCellMetadata -Cell $ec2 ` -Properties @{ version = '3.2'; sla = '99.9%'; on_call = 'pagerduty.com/acme' } .EXAMPLE # Edges take metadata too $link | Set-DrawCellMetadata -Properties @{ speed = '10G'; vlan = 'trunk' } .INPUTS [DrawCell] or [DrawEdge] via pipeline. .OUTPUTS None #> [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)][ValidateNotNull()][object]$Cell, [Parameter(Mandatory)][ValidateNotNullOrEmpty()][hashtable]$Properties ) process { if ($Cell -isnot [DrawCell] -and $Cell -isnot [DrawEdge]) { throw ("Set-DrawCellMetadata: expected a [DrawCell] or [DrawEdge], but received " + "[$($Cell.GetType().FullName)].") } foreach ($key in $Properties.Keys) { # [SHAPE-12] safe XML attribute name check if ($key -notmatch '^[a-zA-Z_][a-zA-Z0-9_\-]*$') { Write-Warning ("Set-DrawCellMetadata: key '$key' contains characters that are " + "invalid in XML attribute names and will be sanitised when serialised.") } $Cell.Metadata[$key] = [string]$Properties[$key] } Write-Verbose "Set-DrawCellMetadata: updated $($Properties.Count) properties on '$($Cell.Label)'" } } function Get-DrawShapeTypes { <# .SYNOPSIS Lists all built-in shape type presets for Add-DrawShape. .DESCRIPTION Returns one object per preset with its name, category and full style string. Useful for discovery and building legend pages. .EXAMPLE Get-DrawShapeTypes .EXAMPLE Get-DrawShapeTypes | Where-Object Category -eq 'AWS' .EXAMPLE Get-DrawShapeTypes | Format-Table Name, Category -AutoSize .OUTPUTS [PSCustomObject[]] #> [CmdletBinding()] [OutputType([PSCustomObject])] param() # Category map kept locally — only used in this function $catMap = @{ Rectangle = 'General'; RoundedRect = 'General'; Ellipse = 'General' Diamond = 'General'; Triangle = 'General'; Hexagon = 'General' Cloud = 'General'; Cylinder = 'General'; Note = 'General' Document = 'General'; Callout = 'General'; Parallelogram = 'General' Swimlane = 'General'; Star = 'General' FcProcess = 'Flowchart'; FcDecision = 'Flowchart'; FcTerminal = 'Flowchart' FcDatabase = 'Flowchart'; FcDelay = 'Flowchart'; FcDisplay = 'Flowchart' FcPrep = 'Flowchart'; FcManualInput = 'Flowchart'; FcMerge = 'Flowchart' NetServer = 'Network'; NetRouter = 'Network'; NetSwitch = 'Network' NetFirewall = 'Network'; NetCloud = 'Network'; NetPC = 'Network' NetLaptop = 'Network'; NetMobile = 'Network' AwsEC2 = 'AWS'; AwsS3 = 'AWS'; AwsLambda = 'AWS'; AwsRDS = 'AWS' AwsSQS = 'AWS'; AwsApiGW = 'AWS'; AwsCloudFront = 'AWS' AzureVM = 'Azure'; AzureSQL = 'Azure'; AzureStorage = 'Azure'; AzureFunc = 'Azure' AdServer = 'ActiveDirectory'; AdUser = 'ActiveDirectory' AdGroup = 'ActiveDirectory'; AdOU = 'ActiveDirectory' VmHost = 'VMware'; VmVM = 'VMware'; VmvCenter = 'VMware' VmCluster = 'VMware'; VmNSX = 'VMware'; VmvSAN = 'VMware' } $script:DrawStyles.GetEnumerator() | ForEach-Object { $name = $_.Key # [SHAPE-13] PS 5.1-safe — no ?? operator $cat = if ($catMap.ContainsKey($name)) { $catMap[$name] } else { 'General' } [PSCustomObject]@{ PSTypeName = 'DrawManagement.ShapeType' Name = $name Category = $cat Style = $_.Value } } | Sort-Object Category, Name } |