From dca82c1f6e2feff1726d480047fd1470bb550db6 Mon Sep 17 00:00:00 2001 From: Shaun Lawrie Date: Mon, 12 Aug 2024 22:32:30 +1200 Subject: [PATCH] Fully qualify .net classes, the using statements make them shorter but you can't copy paste chunks for testing easily. Add format-spectrerows --- PwshSpectreConsole.Tests/TestHelpers.psm1 | 12 +- .../writing/Write-SpectreHost.tests.ps1 | 90 +++++------ PwshSpectreConsole/PwshSpectreConsole.psd1 | 4 +- PwshSpectreConsole/PwshSpectreConsole.psm1 | 9 +- .../private/Add-SpectreTreeNode.ps1 | 5 +- .../private/Add-TableColumns.ps1 | 11 +- .../private/Convert-ToSpectreColor.ps1 | 87 ++++++----- .../private/ConvertTo-SpectreDecoration.ps1 | 21 ++- .../private/Get-SpectreProfile.ps1 | 3 +- .../private/Invoke-SpectrePromptAsync.ps1 | 61 ++++---- PwshSpectreConsole/private/New-TableCell.ps1 | 15 +- PwshSpectreConsole/private/New-TableRow.ps1 | 2 +- .../private/Read-FigletFont.ps1 | 31 ++-- .../private/Start-AnsiConsoleProgress.ps1 | 61 ++++---- .../private/Start-AnsiConsoleStatus.ps1 | 49 +++--- .../private/Write-AnsiConsole.ps1 | 7 +- .../private/Write-SpectreHostInternal.ps1 | 33 ++-- .../private/completions/Completers.psm1 | 17 +- .../private/completions/Transformers.psm1 | 15 +- .../private/models/SpectreChartItem.psm1 | 22 ++- .../public/config/Set-SpectreColors.ps1 | 9 +- .../public/demo/Get-SpectreDemoColors.ps1 | 145 +++++++++--------- .../public/demo/Get-SpectreDemoEmoji.ps1 | 127 ++++++++------- .../public/demo/Start-SpectreDemo.ps1 | 23 ++- .../formatting/Format-SpectreBarChart.ps1 | 7 +- .../Format-SpectreBreakdownChart.ps1 | 7 +- .../formatting/Format-SpectreColumns.ps1 | 15 +- .../public/formatting/Format-SpectreJson.ps1 | 18 ++- .../public/formatting/Format-SpectrePanel.ps1 | 11 +- .../public/formatting/Format-SpectrePath.ps1 | 47 ++++++ .../public/formatting/Format-SpectreRows.ps1 | 51 ++++++ .../public/formatting/Format-SpectreTable.ps1 | 19 ++- .../public/formatting/Format-SpectreTree.ps1 | 9 +- .../formatting/New-SpectreChartItem.ps1 | 3 +- .../public/images/Get-SpectreImage.ps1 | 67 ++++---- .../Invoke-SpectreCommandWithStatus.ps1 | 7 +- .../public/prompts/Read-SpectreConfirm.ps1 | 15 +- .../prompts/Read-SpectreMultiSelection.ps1 | 11 +- .../Read-SpectreMultiSelectionGrouped.ps1 | 11 +- .../public/prompts/Read-SpectreSelection.ps1 | 13 +- .../public/prompts/Read-SpectreText.ps1 | 13 +- .../public/writing/Get-SpectreEscapedText.ps1 | 49 +++--- .../public/writing/Write-SpectreCalendar.ps1 | 17 +- .../writing/Write-SpectreFigletText.ps1 | 7 +- .../public/writing/Write-SpectreHost.ps1 | 3 +- .../public/writing/Write-SpectreRule.ps1 | 7 +- 46 files changed, 663 insertions(+), 603 deletions(-) create mode 100644 PwshSpectreConsole/public/formatting/Format-SpectrePath.ps1 create mode 100644 PwshSpectreConsole/public/formatting/Format-SpectreRows.ps1 diff --git a/PwshSpectreConsole.Tests/TestHelpers.psm1 b/PwshSpectreConsole.Tests/TestHelpers.psm1 index 6ac0caeb..d06a3e64 100644 --- a/PwshSpectreConsole.Tests/TestHelpers.psm1 +++ b/PwshSpectreConsole.Tests/TestHelpers.psm1 @@ -1,5 +1,3 @@ -using namespace Spectre.Console - function Get-RandomColor { $type = 1 # Get-Random -Minimum 0 -Maximum 2 switch ($type) { @@ -53,7 +51,7 @@ function Get-RandomBoxBorder { param ( [switch] $MustNotBeNone ) - $lookup = [BoxBorder] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name + $lookup = [Spectre.Console.BoxBorder] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name if ($MustNotBeNone) { $lookup = $lookup | Where-Object { $_ -ne 'None' } } @@ -61,22 +59,22 @@ function Get-RandomBoxBorder { } function Get-RandomJustify { - $lookup = [Justify].GetEnumNames() + $lookup = [Spectre.Console.Justify].GetEnumNames() return $lookup[$(Get-Random -Minimum 0 -Maximum $lookup.Count)] } function Get-RandomSpinner { - $lookup = [Spinner+Known] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name + $lookup = [Spectre.Console.Spinner+Known] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name return $lookup[$(Get-Random -Minimum 0 -Maximum $lookup.Count)] } function Get-RandomTreeGuide { - $lookup = [TreeGuide] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name + $lookup = [Spectre.Console.TreeGuide] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name return $lookup[$(Get-Random -Minimum 0 -Maximum $lookup.Count)] } function Get-RandomTableBorder { - $lookup = [TableBorder] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name + $lookup = [Spectre.Console.TableBorder] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name return $lookup[$(Get-Random -Minimum 0 -Maximum $lookup.Count)] } diff --git a/PwshSpectreConsole.Tests/writing/Write-SpectreHost.tests.ps1 b/PwshSpectreConsole.Tests/writing/Write-SpectreHost.tests.ps1 index 8c54bc35..d96b2c3a 100644 --- a/PwshSpectreConsole.Tests/writing/Write-SpectreHost.tests.ps1 +++ b/PwshSpectreConsole.Tests/writing/Write-SpectreHost.tests.ps1 @@ -1,46 +1,46 @@ -Remove-Module PwshSpectreConsole -Force -ErrorAction SilentlyContinue -Import-Module "$PSScriptRoot\..\..\PwshSpectreConsole\PwshSpectreConsole.psd1" -Force -Import-Module "$PSScriptRoot\..\TestHelpers.psm1" -Force - -Describe "Write-SpectreHost" { - InModuleScope "PwshSpectreConsole" { - BeforeEach { - $testConsole = [Spectre.Console.Testing.TestConsole]::new() - $testConsole.EmitAnsiSequences = $true - $testMessage = Get-RandomString - $testMessage | Out-Null - Mock Write-SpectreHostInternalMarkup { - $Message | Should -Be $testMessage - [AnsiConsoleExtensions]::Markup($testConsole, $Message) - } - Mock Write-SpectreHostInternalMarkupLine { - $Message | Should -Be $testMessage - [AnsiConsoleExtensions]::MarkupLine($testConsole, $Message) - } - } - - It "writes a message" { - Write-SpectreHost -Message $testMessage - Assert-MockCalled -CommandName "Write-SpectreHostInternalMarkupLine" -Times 1 -Exactly - $testConsole.Output.Split("`n").Count | Should -Be 2 - } - - It "accepts pipeline input" { - $testMessage | Write-SpectreHost - Assert-MockCalled -CommandName "Write-SpectreHostInternalMarkupLine" -Times 1 -Exactly - $testConsole.Output.Split("`n").Count | Should -Be 2 - } - - It "handles nonewline" { - Write-SpectreHost -Message $testMessage -NoNewline - Assert-MockCalled -CommandName "Write-SpectreHostInternalMarkup" -Times 1 -Exactly - $testConsole.Output.Split("`n").Count | Should -Be 1 - } - - It "Should match the snapshot" { - $testMessage = "[#00ff00]Hello[/], [DeepSkyBlue3_1]World![/] :smiling_face_with_sunglasses: Yay!" - Write-SpectreHost $testMessage - { Assert-OutputMatchesSnapshot -SnapshotName "Write-SpectreHost" -Output $testConsole.Output } | Should -Not -Throw - } - } +Remove-Module PwshSpectreConsole -Force -ErrorAction SilentlyContinue +Import-Module "$PSScriptRoot\..\..\PwshSpectreConsole\PwshSpectreConsole.psd1" -Force +Import-Module "$PSScriptRoot\..\TestHelpers.psm1" -Force + +Describe "Write-SpectreHost" { + InModuleScope "PwshSpectreConsole" { + BeforeEach { + $testConsole = [Spectre.Console.Testing.TestConsole]::new() + $testConsole.EmitAnsiSequences = $true + $testMessage = Get-RandomString + $testMessage | Out-Null + Mock Write-SpectreHostInternalMarkup { + $Message | Should -Be $testMessage + [Spectre.Console.AnsiConsoleExtensions]::Markup($testConsole, $Message) + } + Mock Write-SpectreHostInternalMarkupLine { + $Message | Should -Be $testMessage + [Spectre.Console.AnsiConsoleExtensions]::MarkupLine($testConsole, $Message) + } + } + + It "writes a message" { + Write-SpectreHost -Message $testMessage + Assert-MockCalled -CommandName "Write-SpectreHostInternalMarkupLine" -Times 1 -Exactly + $testConsole.Output.Split("`n").Count | Should -Be 2 + } + + It "accepts pipeline input" { + $testMessage | Write-SpectreHost + Assert-MockCalled -CommandName "Write-SpectreHostInternalMarkupLine" -Times 1 -Exactly + $testConsole.Output.Split("`n").Count | Should -Be 2 + } + + It "handles nonewline" { + Write-SpectreHost -Message $testMessage -NoNewline + Assert-MockCalled -CommandName "Write-SpectreHostInternalMarkup" -Times 1 -Exactly + $testConsole.Output.Split("`n").Count | Should -Be 1 + } + + It "Should match the snapshot" { + $testMessage = "[#00ff00]Hello[/], [DeepSkyBlue3_1]World![/] :smiling_face_with_sunglasses: Yay!" + Write-SpectreHost $testMessage + { Assert-OutputMatchesSnapshot -SnapshotName "Write-SpectreHost" -Output $testConsole.Output } | Should -Not -Throw + } + } } \ No newline at end of file diff --git a/PwshSpectreConsole/PwshSpectreConsole.psd1 b/PwshSpectreConsole/PwshSpectreConsole.psd1 index 0a9a4601..067eae4b 100644 --- a/PwshSpectreConsole/PwshSpectreConsole.psd1 +++ b/PwshSpectreConsole/PwshSpectreConsole.psd1 @@ -85,8 +85,8 @@ FunctionsToExport = 'Add-SpectreJob', 'Format-SpectreBarChart', 'Write-SpectreHost', 'Write-SpectreRule', 'Read-SpectreConfirm', 'New-SpectreChartItem', 'Invoke-SpectreScriptBlockQuietly', 'Get-SpectreDemoColors', 'Get-SpectreDemoEmoji', 'Format-SpectreJson', - 'Write-SpectreCalendar', 'Start-SpectreRecording', - 'Stop-SpectreRecording', 'Format-SpectreColumns', 'Write-AnsiConsole', + 'Write-SpectreCalendar', 'Start-SpectreRecording', 'Stop-SpectreRecording', + 'Format-SpectreColumns', 'Format-SpectreRows', 'Out-SpectreHost' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. diff --git a/PwshSpectreConsole/PwshSpectreConsole.psm1 b/PwshSpectreConsole/PwshSpectreConsole.psm1 index 905ab55d..3b12cbb6 100644 --- a/PwshSpectreConsole/PwshSpectreConsole.psm1 +++ b/PwshSpectreConsole/PwshSpectreConsole.psm1 @@ -1,10 +1,9 @@ using module ".\private\completions\Completers.psm1" -using namespace Spectre.Console -$script:AccentColor = [Color]::Blue -$script:DefaultValueColor = [Color]::Grey -$script:DefaultTableHeaderColor = [Color]::Default -$script:DefaultTableTextColor = [Color]::Default +$script:AccentColor = [Spectre.Console.Color]::Blue +$script:DefaultValueColor = [Spectre.Console.Color]::Grey +$script:DefaultTableHeaderColor = [Spectre.Console.Color]::Default +$script:DefaultTableTextColor = [Spectre.Console.Color]::Default foreach ($directory in @('private', 'public')) { Get-ChildItem -Path "$PSScriptRoot\$directory\*.ps1" -Recurse | ForEach-Object { diff --git a/PwshSpectreConsole/private/Add-SpectreTreeNode.ps1 b/PwshSpectreConsole/private/Add-SpectreTreeNode.ps1 index 4d042d81..8a48f16b 100644 --- a/PwshSpectreConsole/private/Add-SpectreTreeNode.ps1 +++ b/PwshSpectreConsole/private/Add-SpectreTreeNode.ps1 @@ -1,4 +1,3 @@ -using namespace Spectre.Console <# .SYNOPSIS @@ -19,7 +18,7 @@ See Format-SpectreTree for usage. function Add-SpectreTreeNode { param ( [Parameter(Mandatory)] - [IHasTreeNodes] $Node, + [Spectre.Console.IHasTreeNodes] $Node, [Parameter(Mandatory)] [array] $Children ) @@ -32,7 +31,7 @@ function Add-SpectreTreeNode { $child.Remove("Label") } - $newNode = [HasTreeNodeExtensions]::AddNode($Node, $child.Value) + $newNode = [Spectre.Console.HasTreeNodeExtensions]::AddNode($Node, $child.Value) if ($child.Children.Count -gt 0) { Add-SpectreTreeNode -Node $newNode -Children $child.Children } diff --git a/PwshSpectreConsole/private/Add-TableColumns.ps1 b/PwshSpectreConsole/private/Add-TableColumns.ps1 index 590a9bae..ba6f6050 100644 --- a/PwshSpectreConsole/private/Add-TableColumns.ps1 +++ b/PwshSpectreConsole/private/Add-TableColumns.ps1 @@ -1,13 +1,12 @@ -using namespace Spectre.Console - + function Add-TableColumns { [CmdletBinding()] param( [Parameter(Mandatory)] - [Table] $table, + [Spectre.Console.Table] $table, [Collections.Specialized.OrderedDictionary] $FormatData, [String] $Title, - [Color] $Color = [Color]::Default, + [Spectre.Console.Color] $Color = [Spectre.Console.Color]::Default, [Switch] $Scalar, [Switch] $Wrap ) @@ -28,13 +27,13 @@ function Add-TableColumns { $lookup = $FormatData[$key] Write-Debug "Adding column from formatdata: $($lookup.GetEnumerator())" $table.AddColumn("[$($Color.ToMarkup())]$($lookup.Label)[/]") | Out-Null - $table.Columns[-1].Padding = [Padding]::new(1, 0, 1, 0) + $table.Columns[-1].Padding = [Spectre.Console.Padding]::new(1, 0, 1, 0) if ($lookup.width -gt 0) { # width 0 is autosize, select the last entry in the column list $table.Columns[-1].Width = $lookup.Width } if ($lookup.Alignment -ne 'undefined') { - $table.Columns[-1].Alignment = [Justify]::$lookup.Alignment + $table.Columns[-1].Alignment = [Spectre.Console.Justify]::$lookup.Alignment } if (-Not $Wrap) { # https://github.com/spectreconsole/spectre.console/issues/1185 diff --git a/PwshSpectreConsole/private/Convert-ToSpectreColor.ps1 b/PwshSpectreConsole/private/Convert-ToSpectreColor.ps1 index 0f646f7c..cb09f72e 100644 --- a/PwshSpectreConsole/private/Convert-ToSpectreColor.ps1 +++ b/PwshSpectreConsole/private/Convert-ToSpectreColor.ps1 @@ -1,44 +1,43 @@ -using namespace Spectre.Console - -<# -.SYNOPSIS -Converts a string representation of a color to a Color object. - -.DESCRIPTION -This function takes a string representation of a color and converts it to a Color object. The input color can be in the form of a named color or a hexadecimal color code. - -.PARAMETER Color -The color to convert. This parameter is mandatory and accepts input from the pipeline. - -.EXAMPLE -'red' | Convert-ToSpectreColor - -.EXAMPLE -'#FF0000' | Convert-ToSpectreColor - -.EXAMPLE -[Color]::Salmon1 | Convert-ToSpectreColor -#> -function Convert-ToSpectreColor { - param ( - [Parameter(ValueFromPipeline, Mandatory)] - [object] $Color - ) - try { - # Just return the console color object - if ($Color -is [Color]) { - return $Color - } - # Already validated in validation attribute - if ($Color.StartsWith("#")) { - $hexString = $Color -replace '^#', '' - $hexBytes = [System.Convert]::FromHexString($hexString) - return [Color]::new($hexBytes[0], $hexBytes[1], $hexBytes[2]) - } - - # Validated in attribute as a real color already - return [Color]::$Color - } catch { - return $script:AccentColor - } -} + +<# +.SYNOPSIS +Converts a string representation of a color to a Color object. + +.DESCRIPTION +This function takes a string representation of a color and converts it to a Color object. The input color can be in the form of a named color or a hexadecimal color code. + +.PARAMETER Color +The color to convert. This parameter is mandatory and accepts input from the pipeline. + +.EXAMPLE +'red' | Convert-ToSpectreColor + +.EXAMPLE +'#FF0000' | Convert-ToSpectreColor + +.EXAMPLE +[Spectre.Console.Color]::Salmon1 | Convert-ToSpectreColor +#> +function Convert-ToSpectreColor { + param ( + [Parameter(ValueFromPipeline, Mandatory)] + [object] $Color + ) + try { + # Just return the console color object + if ($Color -is [Spectre.Console.Color]) { + return $Color + } + # Already validated in validation attribute + if ($Color.StartsWith("#")) { + $hexString = $Color -replace '^#', '' + $hexBytes = [System.Convert]::FromHexString($hexString) + return [Spectre.Console.Color]::new($hexBytes[0], $hexBytes[1], $hexBytes[2]) + } + + # Validated in attribute as a real color already + return [Spectre.Console.Color]::$Color + } catch { + return $script:AccentColor + } +} diff --git a/PwshSpectreConsole/private/ConvertTo-SpectreDecoration.ps1 b/PwshSpectreConsole/private/ConvertTo-SpectreDecoration.ps1 index 5d8a016a..3442eff8 100644 --- a/PwshSpectreConsole/private/ConvertTo-SpectreDecoration.ps1 +++ b/PwshSpectreConsole/private/ConvertTo-SpectreDecoration.ps1 @@ -1,4 +1,3 @@ -using namespace Spectre.Console function ConvertTo-SpectreDecoration { param( @@ -9,9 +8,9 @@ function ConvertTo-SpectreDecoration { Write-Debug "Module: $($ExecutionContext.SessionState.Module.Name) Command: $($MyInvocation.MyCommand.Name) Param: $($PSBoundParameters.GetEnumerator())" $lookup = [PwshSpectreConsole.VTCodes.Parser]::Parse($String) $ht = @{ - decoration = [Decoration]::None - fg = [Color]::Default - bg = [Color]::Default + decoration = [Spectre.Console.Decoration]::None + fg = [Spectre.Console.Color]::Default + bg = [Spectre.Console.Color]::Default } foreach ($item in $lookup) { # Write-Debug "Type: $($item.type) Value: $($item.value) Position: $($item.position) Color: $($item.color)" @@ -21,22 +20,22 @@ function ConvertTo-SpectreDecoration { $conversion = switch ($item.type) { '4bit' { if ($item.value -gt 0 -and $item.value -le 15) { - [Color]::FromConsoleColor($item.value) + [Spectre.Console.Color]::FromConsoleColor($item.value) } else { # spectre doesn't appear to have a way to convert from 4bit. # e.g all $PSStyle colors 30-37, 40-47 and 90-97, 100-107 # this will return the closest color in 8bit. - [Color]::FromConsoleColor((ConvertFrom-ConsoleColor $item.value)) + [Spectre.Console.Color]::FromConsoleColor((ConvertFrom-ConsoleColor $item.value)) } } '8bit' { - [Color]::FromInt32($item.value) + [Spectre.Console.Color]::FromInt32($item.value) } '24bit' { - [Color]::new($item.value.Red, $item.value.Green, $item.value.Blue) + [Spectre.Console.Color]::new($item.value.Red, $item.value.Green, $item.value.Blue) } 'decoration' { - [Decoration]::Parse([Decoration], $item.Value, $true) + [Spectre.Console.Decoration]::Parse([Spectre.Console.Decoration], $item.Value, $true) } } if ($item.type -eq 'decoration') { @@ -51,7 +50,7 @@ function ConvertTo-SpectreDecoration { $String = [System.Management.Automation.Host.PSHostUserInterface]::GetOutputString($String, $false) Write-Debug "Clean: '$String' deco: '$($ht.decoration)' fg: '$($ht.fg)' bg: '$($ht.bg)'" if ($AllowMarkup) { - return [Markup]::new($String, [Style]::new($ht.fg, $ht.bg, $ht.decoration)) + return [Spectre.Console.Markup]::new($String, [Spectre.Console.Style]::new($ht.fg, $ht.bg, $ht.decoration)) } - return [Text]::new($String, [Style]::new($ht.fg, $ht.bg, $ht.decoration)) + return [Spectre.Console.Text]::new($String, [Spectre.Console.Style]::new($ht.fg, $ht.bg, $ht.decoration)) } diff --git a/PwshSpectreConsole/private/Get-SpectreProfile.ps1 b/PwshSpectreConsole/private/Get-SpectreProfile.ps1 index 17ab4cdd..697e27ea 100644 --- a/PwshSpectreConsole/private/Get-SpectreProfile.ps1 +++ b/PwshSpectreConsole/private/Get-SpectreProfile.ps1 @@ -1,9 +1,8 @@ -using namespace Spectre.Console function Get-SpectreProfile { [CmdletBinding()] param () - $object = [AnsiConsole]::Profile + $object = [Spectre.Console.AnsiConsole]::Profile return [PSCustomObject]@{ Enrichers = $object.Enrichers -join ', ' ColorSystem = $object.Capabilities.ColorSystem diff --git a/PwshSpectreConsole/private/Invoke-SpectrePromptAsync.ps1 b/PwshSpectreConsole/private/Invoke-SpectrePromptAsync.ps1 index 36e224c8..cefbed9b 100644 --- a/PwshSpectreConsole/private/Invoke-SpectrePromptAsync.ps1 +++ b/PwshSpectreConsole/private/Invoke-SpectrePromptAsync.ps1 @@ -1,32 +1,31 @@ -using namespace Spectre.Console - -function Invoke-SpectrePromptAsync { - <# - .SYNOPSIS - Shows a Spectre.Console prompt. - - .DESCRIPTION - This function shows a Spectre.Console prompt "asynchronously" in PowerShell by faking the async call. By allowing the prompt to run asynchronously in the background and polling for its completion, it allows ctrl-c interrupts to continue to work within the single-threaded PowerShell world. - - .PARAMETER Prompt - The Spectre.Console prompt to show. - - .EXAMPLE - $result = Invoke-SpectrePromptAsync $prompt - #> - param ( - [Parameter(Mandatory)] - $Prompt - ) - $cts = [System.Threading.CancellationTokenSource]::new() - try { - $task = $Prompt.ShowAsync([AnsiConsole]::Console, $cts.Token) - while (-not $task.AsyncWaitHandle.WaitOne(200)) { - # Waiting for the async task this way allows ctrl-c interrupts to continue to work within the single-threaded PowerShell world - } - return $task.GetAwaiter().GetResult() - } finally { - $cts.Cancel() - $task.Dispose() - } + +function Invoke-SpectrePromptAsync { + <# + .SYNOPSIS + Shows a Spectre.Console prompt. + + .DESCRIPTION + This function shows a Spectre.Console prompt "asynchronously" in PowerShell by faking the async call. By allowing the prompt to run asynchronously in the background and polling for its completion, it allows ctrl-c interrupts to continue to work within the single-threaded PowerShell world. + + .PARAMETER Prompt + The Spectre.Console prompt to show. + + .EXAMPLE + $result = Invoke-SpectrePromptAsync $prompt + #> + param ( + [Parameter(Mandatory)] + $Prompt + ) + $cts = [System.Threading.CancellationTokenSource]::new() + try { + $task = $Prompt.ShowAsync([Spectre.Console.AnsiConsole]::Console, $cts.Token) + while (-not $task.AsyncWaitHandle.WaitOne(200)) { + # Waiting for the async task this way allows ctrl-c interrupts to continue to work within the single-threaded PowerShell world + } + return $task.GetAwaiter().GetResult() + } finally { + $cts.Cancel() + $task.Dispose() + } } \ No newline at end of file diff --git a/PwshSpectreConsole/private/New-TableCell.ps1 b/PwshSpectreConsole/private/New-TableCell.ps1 index a81c733d..c9e3f89d 100644 --- a/PwshSpectreConsole/private/New-TableCell.ps1 +++ b/PwshSpectreConsole/private/New-TableCell.ps1 @@ -1,10 +1,9 @@ -using namespace Spectre.Console function New-TableCell { [cmdletbinding()] param( [Object] $CellData, - [Color] $Color = [Color]::Default, + [Spectre.Console.Color] $Color = [Spectre.Console.Color]::Default, [Switch] $AllowMarkup ) Write-Debug "Module: $($ExecutionContext.SessionState.Module.Name) Command: $($MyInvocation.MyCommand.Name) Param: $($PSBoundParameters.GetEnumerator())" @@ -16,23 +15,23 @@ function New-TableCell { if ([String]::IsNullOrEmpty($CellData)) { if ($AllowMarkup) { - return [Markup]::new(' ', [Style]::new($Color)) + return [Spectre.Console.Markup]::new(' ', [Spectre.Console.Style]::new($Color)) } - return [Text]::new(' ', [Style]::new($Color)) + return [Spectre.Console.Text]::new(' ', [Spectre.Console.Style]::new($Color)) } if (-Not [String]::IsNullOrEmpty($CellData.ToString())) { if ($AllowMarkup) { Write-Debug "New-TableCell ToString(), Markup, $($CellData.ToString())" - return [Markup]::new($CellData.ToString(), [Style]::new($Color)) + return [Spectre.Console.Markup]::new($CellData.ToString(), [Spectre.Console.Style]::new($Color)) } Write-Debug "New-TableCell ToString(), Text, $($CellData.ToString())" - return [Text]::new($CellData.ToString(), [Style]::new($Color)) + return [Spectre.Console.Text]::new($CellData.ToString(), [Spectre.Console.Style]::new($Color)) } # just coerce to string. if ($AllowMarkup) { Write-Debug "New-TableCell [String], markup, $([String]$CellData)" - return [Markup]::new([String]$CellData, [Style]::new($Color)) + return [Spectre.Console.Markup]::new([String]$CellData, [Spectre.Console.Style]::new($Color)) } Write-Debug "New-TableCell [String], Text, $([String]$CellData)" - return [Text]::new([String]$CellData, [Style]::new($Color)) + return [Spectre.Console.Text]::new([String]$CellData, [Spectre.Console.Style]::new($Color)) } diff --git a/PwshSpectreConsole/private/New-TableRow.ps1 b/PwshSpectreConsole/private/New-TableRow.ps1 index 010d27a1..61795ba6 100644 --- a/PwshSpectreConsole/private/New-TableRow.ps1 +++ b/PwshSpectreConsole/private/New-TableRow.ps1 @@ -2,7 +2,7 @@ function New-TableRow { param( [Parameter(Mandatory)] [Object] $Entry, - [Color] $Color = [Color]::Default, + [Spectre.Console.Color] $Color = [Spectre.Console.Color]::Default, [Switch] $AllowMarkup, [Switch] $Scalar, [hashtable] $Renderables diff --git a/PwshSpectreConsole/private/Read-FigletFont.ps1 b/PwshSpectreConsole/private/Read-FigletFont.ps1 index b8ecf076..c48358cf 100644 --- a/PwshSpectreConsole/private/Read-FigletFont.ps1 +++ b/PwshSpectreConsole/private/Read-FigletFont.ps1 @@ -1,17 +1,16 @@ -using namespace Spectre.Console - -# Read in a figlet font or just return the default built-in one -function Read-FigletFont { - param ( - [string] $FigletFontPath - ) - $figletFont = [FigletFont]::Default - if ($FigletFontPath) { - if (!(Test-Path $FigletFontPath)) { - throw "The specified Figlet font file '$FigletFontPath' does not exist" - } - $fullPath = (Resolve-Path $FigletFontPath).Path - $figletFont = [FigletFont]::Load($fullPath) - } - return $figletFont + +# Read in a figlet font or just return the default built-in one +function Read-FigletFont { + param ( + [string] $FigletFontPath + ) + $figletFont = [Spectre.Console.FigletFont]::Default + if ($FigletFontPath) { + if (!(Test-Path $FigletFontPath)) { + throw "The specified Figlet font file '$FigletFontPath' does not exist" + } + $fullPath = (Resolve-Path $FigletFontPath).Path + $figletFont = [Spectre.Console.FigletFont]::Load($fullPath) + } + return $figletFont } \ No newline at end of file diff --git a/PwshSpectreConsole/private/Start-AnsiConsoleProgress.ps1 b/PwshSpectreConsole/private/Start-AnsiConsoleProgress.ps1 index bb7d3f79..f5823273 100644 --- a/PwshSpectreConsole/private/Start-AnsiConsoleProgress.ps1 +++ b/PwshSpectreConsole/private/Start-AnsiConsoleProgress.ps1 @@ -1,32 +1,31 @@ -using namespace Spectre.Console - -<# -.SYNOPSIS -Starts an ANSI console progress bar. - -.DESCRIPTION -This function is required for mocking ansiconsole in unit tests that write objects to the console. - -.PARAMETER ScriptBlock -The script block to execute while the progress bar is running. - -.EXAMPLE -Start-AnsiConsoleProgress { - # Some long-running operation -} -#> -function Start-AnsiConsoleProgress { - param ( - [Parameter(Mandatory)] - [scriptblock] $ScriptBlock - ) - $resultVariableName = "AnsiConsoleProgressResult-$([guid]::NewGuid())" - New-Variable -Name $resultVariableName -Scope "Script" - [AnsiConsole]::Progress().Start({ - param ( - $ctx - ) - Set-Variable -Name $resultVariableName -Value (& $ScriptBlock $ctx) -Scope "Script" - }) - return Get-Variable -Name $resultVariableName -ValueOnly + +<# +.SYNOPSIS +Starts an ANSI console progress bar. + +.DESCRIPTION +This function is required for mocking ansiconsole in unit tests that write objects to the console. + +.PARAMETER ScriptBlock +The script block to execute while the progress bar is running. + +.EXAMPLE +Start-AnsiConsoleProgress { + # Some long-running operation +} +#> +function Start-AnsiConsoleProgress { + param ( + [Parameter(Mandatory)] + [scriptblock] $ScriptBlock + ) + $resultVariableName = "AnsiConsoleProgressResult-$([guid]::NewGuid())" + New-Variable -Name $resultVariableName -Scope "Script" + [Spectre.Console.AnsiConsole]::Progress().Start({ + param ( + $ctx + ) + Set-Variable -Name $resultVariableName -Value (& $ScriptBlock $ctx) -Scope "Script" + }) + return Get-Variable -Name $resultVariableName -ValueOnly } \ No newline at end of file diff --git a/PwshSpectreConsole/private/Start-AnsiConsoleStatus.ps1 b/PwshSpectreConsole/private/Start-AnsiConsoleStatus.ps1 index c80e8a49..acdeb8ea 100644 --- a/PwshSpectreConsole/private/Start-AnsiConsoleStatus.ps1 +++ b/PwshSpectreConsole/private/Start-AnsiConsoleStatus.ps1 @@ -1,25 +1,24 @@ -using namespace Spectre.Console - -function Start-AnsiConsoleStatus { - param ( - [Parameter(Mandatory)] - [string] $Title, - [Parameter(Mandatory)] - [Spinner] $Spinner, - [Parameter(Mandatory)] - [Style] $SpinnerStyle, - [Parameter(Mandatory)] - [scriptblock] $ScriptBlock - ) - $resultVariableName = "AnsiConsoleStatusResult-$([guid]::NewGuid())" - New-Variable -Name $resultVariableName -Scope "Script" - [AnsiConsole]::Status().Start($Title, { - param ( - $ctx - ) - $ctx.Spinner = $Spinner - $ctx.SpinnerStyle = $SpinnerStyle - Set-Variable -Name $resultVariableName -Value (& $ScriptBlock $ctx) -Scope "Script" - }) - return Get-Variable -Name $resultVariableName -ValueOnly -} + +function Start-AnsiConsoleStatus { + param ( + [Parameter(Mandatory)] + [string] $Title, + [Parameter(Mandatory)] + [Spectre.Console.Spinner] $Spinner, + [Parameter(Mandatory)] + [Spectre.Console.Style] $SpinnerStyle, + [Parameter(Mandatory)] + [scriptblock] $ScriptBlock + ) + $resultVariableName = "AnsiConsoleStatusResult-$([guid]::NewGuid())" + New-Variable -Name $resultVariableName -Scope "Script" + [Spectre.Console.AnsiConsole]::Status().Start($Title, { + param ( + $ctx + ) + $ctx.Spinner = $Spinner + $ctx.SpinnerStyle = $SpinnerStyle + Set-Variable -Name $resultVariableName -Value (& $ScriptBlock $ctx) -Scope "Script" + }) + return Get-Variable -Name $resultVariableName -ValueOnly +} diff --git a/PwshSpectreConsole/private/Write-AnsiConsole.ps1 b/PwshSpectreConsole/private/Write-AnsiConsole.ps1 index 771fe913..ad4554e8 100644 --- a/PwshSpectreConsole/private/Write-AnsiConsole.ps1 +++ b/PwshSpectreConsole/private/Write-AnsiConsole.ps1 @@ -1,15 +1,14 @@ using module ".\completions\Transformers.psm1" -using namespace Spectre.Console <# .SYNOPSIS -Writes an object to the console using [AnsiConsole]::Write() +Writes an object to the console using [Spectre.Console.AnsiConsole]::Write() .DESCRIPTION This function is required for mocking ansiconsole in unit tests that write objects to the console. .PARAMETER RenderableObject -The renderable object to write to the console e.g. [BarChart] +The renderable object to write to the console e.g. [Spectre.Console.BarChart] .EXAMPLE Write-SpectreConsoleOutput -Object "Hello, World!" -ForegroundColor Green -BackgroundColor Black @@ -21,5 +20,5 @@ function Write-AnsiConsole { [RenderableTransformationAttribute()] [object] $RenderableObject ) - [AnsiConsole]::Render($RenderableObject) + [Spectre.Console.AnsiConsole]::Render($RenderableObject) } \ No newline at end of file diff --git a/PwshSpectreConsole/private/Write-SpectreHostInternal.ps1 b/PwshSpectreConsole/private/Write-SpectreHostInternal.ps1 index 442aa80a..730bd54a 100644 --- a/PwshSpectreConsole/private/Write-SpectreHostInternal.ps1 +++ b/PwshSpectreConsole/private/Write-SpectreHostInternal.ps1 @@ -1,18 +1,17 @@ -using namespace Spectre.Console - -# Functions required for unit testing write-spectrehost -function Write-SpectreHostInternalMarkup { - param ( - [Parameter(Mandatory)] - [string] $Message - ) - [AnsiConsoleExtensions]::Markup([AnsiConsole]::Console, $Message) -} - -function Write-SpectreHostInternalMarkupLine { - param ( - [Parameter(Mandatory)] - [string] $Message - ) - [AnsiConsoleExtensions]::MarkupLine([AnsiConsole]::Console, $Message) + +# Functions required for unit testing write-spectrehost +function Write-SpectreHostInternalMarkup { + param ( + [Parameter(Mandatory)] + [string] $Message + ) + [Spectre.Console.AnsiConsoleExtensions]::Markup([Spectre.Console.AnsiConsole]::Console, $Message) +} + +function Write-SpectreHostInternalMarkupLine { + param ( + [Parameter(Mandatory)] + [string] $Message + ) + [Spectre.Console.AnsiConsoleExtensions]::MarkupLine([Spectre.Console.AnsiConsole]::Console, $Message) } \ No newline at end of file diff --git a/PwshSpectreConsole/private/completions/Completers.psm1 b/PwshSpectreConsole/private/completions/Completers.psm1 index d32d3080..071334b1 100644 --- a/PwshSpectreConsole/private/completions/Completers.psm1 +++ b/PwshSpectreConsole/private/completions/Completers.psm1 @@ -1,4 +1,3 @@ -using namespace Spectre.Console using namespace System.Management.Automation class ValidateSpectreColor : ValidateArgumentsAttribute { @@ -9,10 +8,10 @@ class ValidateSpectreColor : ValidateArgumentsAttribute { return } # Handle an explicitly defined spectre color object - if ($ItemColor -is [Color]) { + if ($ItemColor -is [Spectre.Console.Color]) { return } - $spectreColors = [Color] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name + $spectreColors = [Spectre.Console.Color] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name $result = $spectreColors -contains $ItemColor if ($result -eq $false) { throw "'$ItemColor' is not in the list of valid Spectre colors ['$($spectreColors -join ''', ''')']" @@ -67,42 +66,42 @@ class ValidateSpectreTreeItem : ValidateArgumentsAttribute { class ArgumentCompletionsSpectreColors : ArgumentCompleterAttribute { ArgumentCompletionsSpectreColors() : base({ param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) - $options = [Color] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name + $options = [Spectre.Console.Color] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name return $options | Where-Object { $_ -like "$wordToComplete*" } }) { } } class SpectreConsoleTableBorder : IValidateSetValuesGenerator { [String[]] GetValidValues() { - $lookup = [TableBorder] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name + $lookup = [Spectre.Console.TableBorder] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name return $lookup } } class SpectreConsoleBoxBorder : IValidateSetValuesGenerator { [String[]] GetValidValues() { - $lookup = [BoxBorder] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name + $lookup = [Spectre.Console.BoxBorder] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name return $lookup } } class SpectreConsoleJustify : IValidateSetValuesGenerator { [String[]] GetValidValues() { - $lookup = [Justify].GetEnumNames() + $lookup = [Spectre.Console.Justify].GetEnumNames() return $lookup } } class SpectreConsoleSpinner : IValidateSetValuesGenerator { [String[]] GetValidValues() { - $lookup = [Spinner+Known] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name + $lookup = [Spectre.Console.Spinner+Known] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name return $lookup } } class SpectreConsoleTreeGuide : IValidateSetValuesGenerator { [String[]] GetValidValues() { - $lookup = [TreeGuide] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name + $lookup = [Spectre.Console.TreeGuide] | Get-Member -Static -MemberType Properties | Select-Object -ExpandProperty Name return $lookup } } diff --git a/PwshSpectreConsole/private/completions/Transformers.psm1 b/PwshSpectreConsole/private/completions/Transformers.psm1 index 78315556..8e707ea2 100644 --- a/PwshSpectreConsole/private/completions/Transformers.psm1 +++ b/PwshSpectreConsole/private/completions/Transformers.psm1 @@ -1,19 +1,18 @@ using module "..\models\SpectreChartItem.psm1" -using namespace Spectre.Console using namespace System.Management.Automation class ColorTransformationAttribute : ArgumentTransformationAttribute { static [object] TransformItem([object]$inputData) { - if ($InputData -is [Color]) { + if ($InputData -is [Spectre.Console.Color]) { return $InputData } if ($InputData.StartsWith('#')) { $hexBytes = [System.Convert]::FromHexString($InputData.Substring(1)) - return [Color]::new($hexBytes[0], $hexBytes[1], $hexBytes[2]) + return [Spectre.Console.Color]::new($hexBytes[0], $hexBytes[1], $hexBytes[2]) } if ($InputData -is [String]) { - return [Color]::$InputData + return [Spectre.Console.Color]::$InputData } throw [System.ArgumentException]::new("Cannot convert $($inputData.GetType().FullName) '$InputData' to [Spectre.Console.Color]") } @@ -34,7 +33,7 @@ class ColorThemeTransformationAttribute : ArgumentTransformationAttribute { if ($null -ne $colorValue) { $outputData[$color.Key] = $colorValue } else { - $spectreColors = [Color] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name + $spectreColors = [Spectre.Console.Color] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name throw "Invalid color value '$($color.Value)' for key '$($color.Key)' could not be mapped to one of the list of valid Spectre colors ['$($spectreColors -join ''', ''')']" } } @@ -50,15 +49,15 @@ class RenderableTransformationAttribute : ArgumentTransformationAttribute { } # These objects are already renderable - if ($InputData -is [Rendering.Renderable]) { + if ($InputData -is [Spectre.Console.Rendering.Renderable]) { return $InputData } # For others just dump them as either strings formatted with markup which are easy to identify by the closing tag [/] or as plain text if ($InputData -like "*[/]*") { - return [Markup]::new($InputData) + return [Spectre.Console.Markup]::new($InputData) } else { - return [Text]::new(($InputData | Out-String -NoNewline)) + return [Spectre.Console.Text]::new(($InputData | Out-String -NoNewline)) } } } diff --git a/PwshSpectreConsole/private/models/SpectreChartItem.psm1 b/PwshSpectreConsole/private/models/SpectreChartItem.psm1 index 0ba23194..ea56c837 100644 --- a/PwshSpectreConsole/private/models/SpectreChartItem.psm1 +++ b/PwshSpectreConsole/private/models/SpectreChartItem.psm1 @@ -1,13 +1,11 @@ -using namespace Spectre.Console - -class SpectreChartItem { - [string] $Label - [double] $Value - [Color] $Color - - SpectreChartItem([string] $Label, [double] $Value, [Color] $Color) { - $this.Label = $Label - $this.Value = $Value - $this.Color = $Color - } +class SpectreChartItem { + [string] $Label + [double] $Value + [Spectre.Console.Color] $Color + + SpectreChartItem([string] $Label, [double] $Value, [Spectre.Console.Color] $Color) { + $this.Label = $Label + $this.Value = $Value + $this.Color = $Color + } } \ No newline at end of file diff --git a/PwshSpectreConsole/public/config/Set-SpectreColors.ps1 b/PwshSpectreConsole/public/config/Set-SpectreColors.ps1 index 531a00c1..43bcb477 100644 --- a/PwshSpectreConsole/public/config/Set-SpectreColors.ps1 +++ b/PwshSpectreConsole/public/config/Set-SpectreColors.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Set-SpectreColors { <# @@ -33,16 +32,16 @@ function Set-SpectreColors { param ( [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $AccentColor = "Blue", + [Spectre.Console.Color] $AccentColor = "Blue", [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $DefaultValueColor = "Grey", + [Spectre.Console.Color] $DefaultValueColor = "Grey", [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $DefaultTableHeaderColor = [Color]::Default, + [Spectre.Console.Color] $DefaultTableHeaderColor = [Spectre.Console.Color]::Default, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $DefaultTableTextColor = [Color]::Default + [Spectre.Console.Color] $DefaultTableTextColor = [Spectre.Console.Color]::Default ) $script:AccentColor = $AccentColor $script:DefaultValueColor = $DefaultValueColor diff --git a/PwshSpectreConsole/public/demo/Get-SpectreDemoColors.ps1 b/PwshSpectreConsole/public/demo/Get-SpectreDemoColors.ps1 index 50f0620a..98e00850 100644 --- a/PwshSpectreConsole/public/demo/Get-SpectreDemoColors.ps1 +++ b/PwshSpectreConsole/public/demo/Get-SpectreDemoColors.ps1 @@ -1,74 +1,73 @@ -using namespace Spectre.Console - -<# -.SYNOPSIS - Retrieves a list of Spectre Console colors and displays them with their corresponding markup. - ![Spectre color demo](/colors.png) - -.DESCRIPTION - The Get-SpectreDemoColors function retrieves a list of Spectre Console colors and displays them with their corresponding markup. - It also provides information on how to use the colors as parameters for commands or in Spectre Console markup. - -.PARAMETER Count - Limit the number of colors returned. This is only really useful for generating the help docs. - -.EXAMPLE - Get-SpectreDemoColors -Count 4 -#> -function Get-SpectreDemoColors { - [Reflection.AssemblyMetadata("title", "Get-SpectreDemoColors")] - param ( - [int] $Count - ) - - Write-SpectreHost " " - Write-SpectreRule "Colors" - Write-SpectreHost " " - - $colors = [Color] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name - if($Count) { - $colors = $colors | Select-Object -First $Count - } - $colors = $colors | ForEach-Object { - $prefix = ($_ -replace '[_0-9]+', '') - $numeric = ($_ -replace '^[^0-9]+', '') - $value = 0 - if ([string]::IsNullOrEmpty($numeric)) { - $value = 0.0 - } else { - $numericParts = $numeric.Split('_') - if ($numericParts.Count -lt 2) { - $value = [double]"$($numericParts[0]).9" - } else { - $value = [double]"$($numericParts[0]).$($numericParts[1])" - } - } - return [pscustomobject]@{ - Name = $_ - Prefix = $prefix - Numeric = $value - } - } | Sort-Object -Property @{Expression = "Prefix" }, @{Expression = "Numeric" } | Select-Object -ExpandProperty Name - - $maxLength = $colors | Measure-Object -Maximum -Property Length | Select-Object -ExpandProperty Maximum - - foreach ($color in $colors) { - $total = [Color]::$color | Select-Object @{ Name = "Total"; Expression = { $_.R + $_.G + $_.B } } | Select-Object -ExpandProperty Total - $textColor = "white" - if ($total -gt 280) { - $textColor = "black" - } - - Write-SpectreHost -NoNewline "[$textColor on $color] $($color.PadRight($maxLength)) [/] " - Write-SpectreHost ("[$color]$color[/]") - } - - Write-SpectreHost " " - Write-SpectreRule "Help" - Write-SpectreHost " " - - Write-SpectreHost "The colors can be passed as the `"-Color`" parameter for most commands or used in Spectre Console markup like so:`n" - Write-SpectreHost " PS> [Yellow]Write-SpectreHost[/] [DeepSkyBlue1]`"$('I am [Red]colored text[/] using [Yellow1 on Turquoise4]Spectre markdown[/]!' | Get-SpectreEscapedText)`"[/]" - Write-SpectreHost " [white on grey19]I am [Red]colored text[/] using [Yellow1 on Turquoise4]Spectre markdown[/]! [/]" - Write-SpectreHost "`nFor more markdown hints see [link]https://spectreconsole.net/markup[/]`n" + +<# +.SYNOPSIS + Retrieves a list of Spectre Console colors and displays them with their corresponding markup. + ![Spectre color demo](/colors.png) + +.DESCRIPTION + The Get-SpectreDemoColors function retrieves a list of Spectre Console colors and displays them with their corresponding markup. + It also provides information on how to use the colors as parameters for commands or in Spectre Console markup. + +.PARAMETER Count + Limit the number of colors returned. This is only really useful for generating the help docs. + +.EXAMPLE + Get-SpectreDemoColors -Count 4 +#> +function Get-SpectreDemoColors { + [Reflection.AssemblyMetadata("title", "Get-SpectreDemoColors")] + param ( + [int] $Count + ) + + Write-SpectreHost " " + Write-SpectreRule "Colors" + Write-SpectreHost " " + + $colors = [Spectre.Console.Color] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name + if($Count) { + $colors = $colors | Select-Object -First $Count + } + $colors = $colors | ForEach-Object { + $prefix = ($_ -replace '[_0-9]+', '') + $numeric = ($_ -replace '^[^0-9]+', '') + $value = 0 + if ([string]::IsNullOrEmpty($numeric)) { + $value = 0.0 + } else { + $numericParts = $numeric.Split('_') + if ($numericParts.Count -lt 2) { + $value = [double]"$($numericParts[0]).9" + } else { + $value = [double]"$($numericParts[0]).$($numericParts[1])" + } + } + return [pscustomobject]@{ + Name = $_ + Prefix = $prefix + Numeric = $value + } + } | Sort-Object -Property @{Expression = "Prefix" }, @{Expression = "Numeric" } | Select-Object -ExpandProperty Name + + $maxLength = $colors | Measure-Object -Maximum -Property Length | Select-Object -ExpandProperty Maximum + + foreach ($color in $colors) { + $total = [Spectre.Console.Color]::$color | Select-Object @{ Name = "Total"; Expression = { $_.R + $_.G + $_.B } } | Select-Object -ExpandProperty Total + $textColor = "white" + if ($total -gt 280) { + $textColor = "black" + } + + Write-SpectreHost -NoNewline "[$textColor on $color] $($color.PadRight($maxLength)) [/] " + Write-SpectreHost ("[$color]$color[/]") + } + + Write-SpectreHost " " + Write-SpectreRule "Help" + Write-SpectreHost " " + + Write-SpectreHost "The colors can be passed as the `"-Color`" parameter for most commands or used in Spectre Console markup like so:`n" + Write-SpectreHost " PS> [Yellow]Write-SpectreHost[/] [DeepSkyBlue1]`"$('I am [Red]colored text[/] using [Yellow1 on Turquoise4]Spectre markdown[/]!' | Get-SpectreEscapedText)`"[/]" + Write-SpectreHost " [white on grey19]I am [Red]colored text[/] using [Yellow1 on Turquoise4]Spectre markdown[/]! [/]" + Write-SpectreHost "`nFor more markdown hints see [link]https://spectreconsole.net/markup[/]`n" } \ No newline at end of file diff --git a/PwshSpectreConsole/public/demo/Get-SpectreDemoEmoji.ps1 b/PwshSpectreConsole/public/demo/Get-SpectreDemoEmoji.ps1 index e4a1791f..6d2503bf 100644 --- a/PwshSpectreConsole/public/demo/Get-SpectreDemoEmoji.ps1 +++ b/PwshSpectreConsole/public/demo/Get-SpectreDemoEmoji.ps1 @@ -1,65 +1,64 @@ -using namespace Spectre.Console - -<# -.SYNOPSIS - Retrieves a collection of emojis available in Spectre Console. - ![Example emojis](/emoji.png) - -.DESCRIPTION - The Get-SpectreDemoEmoji function retrieves a collection of emojis available in Spectre Console. It displays the general emojis, faces, and provides information on how to use emojis in Spectre Console markup. - -.PARAMETER Count - Limit the number of emoji returned. This is only really useful for generating the help docs. - -.EXAMPLE - Get-SpectreDemoEmoji -Count 5 - -.NOTES - Emoji support is dependent on the operating system, terminal, and font support. For more information on Spectre Console markup and emojis, refer to the following links: - - Spectre Console Markup: https://spectreconsole.net/markup - - Spectre Console Emojis: https://spectreconsole.net/appendix/emojis -#> -function Get-SpectreDemoEmoji { - [Reflection.AssemblyMetadata("title", "Get-SpectreDemoEmoji")] - param ( - [int] $Count - ) - - Write-SpectreHost " " - Write-SpectreRule "`nGeneral" - Write-SpectreHost " " - - $emojiCollection = [Emoji+Known] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name - if($Count) { - $emojiCollection = $emojiCollection | Select-Object -First $Count - } - $faces = @() - foreach ($emoji in $emojiCollection) { - $id = ($emoji -creplace '([A-Z])', '_$1' -replace '^_', '').ToLower() - if ($id -like "*face*") { - $faces += $id - } else { - Write-SpectreHost ":${id}:`t$id" - } - } - - Write-SpectreHost " " - if($faces) { - Write-SpectreRule "Faces" - Write-SpectreHost " " - foreach ($face in $faces) { - Write-SpectreHost ":${face}:`t$face" - } - } - - Write-SpectreHost " " - Write-SpectreRule "Help" - Write-SpectreHost " " - Write-SpectreHost "The emoji can be used in Spectre Console markup like so:`n" - # Apparently there is no way to escape emoji codes https://github.com/spectreconsole/spectre.console/issues/408 - Write-SpectreHost -NoNewline " PS> [yellow]Write-SpectreHost[/] [DeepSkyBlue1]`"I am a :[/]" - Write-SpectreHost -NoNewline "[DeepSkyBlue1]grinning_face: Spectre markdown emoji string :[/]" - Write-SpectreHost "[DeepSkyBlue1]victory_hand: !`"[/]" - Write-SpectreHost " [white on grey19]I am a :grinning_face: Spectre markdown emoji string :victory_hand: ! [/]" - Write-SpectreHost "`nEmoji support is dependent on OS, terminal & font support. For more markdown hints see [link]https://spectreconsole.net/markup[/] and for more emoji help see [link]https://spectreconsole.net/appendix/emojis[/]`n" + +<# +.SYNOPSIS + Retrieves a collection of emojis available in Spectre Console. + ![Example emojis](/emoji.png) + +.DESCRIPTION + The Get-SpectreDemoEmoji function retrieves a collection of emojis available in Spectre Console. It displays the general emojis, faces, and provides information on how to use emojis in Spectre Console markup. + +.PARAMETER Count + Limit the number of emoji returned. This is only really useful for generating the help docs. + +.EXAMPLE + Get-SpectreDemoEmoji -Count 5 + +.NOTES + Emoji support is dependent on the operating system, terminal, and font support. For more information on Spectre Console markup and emojis, refer to the following links: + - Spectre Console Markup: https://spectreconsole.net/markup + - Spectre Console Emojis: https://spectreconsole.net/appendix/emojis +#> +function Get-SpectreDemoEmoji { + [Reflection.AssemblyMetadata("title", "Get-SpectreDemoEmoji")] + param ( + [int] $Count + ) + + Write-SpectreHost " " + Write-SpectreRule "`nGeneral" + Write-SpectreHost " " + + $emojiCollection = [Emoji+Known] | Get-Member -Static -Type Properties | Select-Object -ExpandProperty Name + if($Count) { + $emojiCollection = $emojiCollection | Select-Object -First $Count + } + $faces = @() + foreach ($emoji in $emojiCollection) { + $id = ($emoji -creplace '([A-Z])', '_$1' -replace '^_', '').ToLower() + if ($id -like "*face*") { + $faces += $id + } else { + Write-SpectreHost ":${id}:`t$id" + } + } + + Write-SpectreHost " " + if($faces) { + Write-SpectreRule "Faces" + Write-SpectreHost " " + foreach ($face in $faces) { + Write-SpectreHost ":${face}:`t$face" + } + } + + Write-SpectreHost " " + Write-SpectreRule "Help" + Write-SpectreHost " " + Write-SpectreHost "The emoji can be used in Spectre Console markup like so:`n" + # Apparently there is no way to escape emoji codes https://github.com/spectreconsole/spectre.console/issues/408 + Write-SpectreHost -NoNewline " PS> [yellow]Write-SpectreHost[/] [DeepSkyBlue1]`"I am a :[/]" + Write-SpectreHost -NoNewline "[DeepSkyBlue1]grinning_face: Spectre markdown emoji string :[/]" + Write-SpectreHost "[DeepSkyBlue1]victory_hand: !`"[/]" + Write-SpectreHost " [white on grey19]I am a :grinning_face: Spectre markdown emoji string :victory_hand: ! [/]" + Write-SpectreHost "`nEmoji support is dependent on OS, terminal & font support. For more markdown hints see [link]https://spectreconsole.net/markup[/] and for more emoji help see [link]https://spectreconsole.net/appendix/emojis[/]`n" } \ No newline at end of file diff --git a/PwshSpectreConsole/public/demo/Start-SpectreDemo.ps1 b/PwshSpectreConsole/public/demo/Start-SpectreDemo.ps1 index fca0880f..906360fa 100644 --- a/PwshSpectreConsole/public/demo/Start-SpectreDemo.ps1 +++ b/PwshSpectreConsole/public/demo/Start-SpectreDemo.ps1 @@ -1,4 +1,3 @@ -using namespace Spectre.Console function Write-SpectreExample { param ( @@ -16,7 +15,7 @@ function Write-SpectreExample { } Write-Host "" - Write-SpectreRule $Title -Color ([Color]::SteelBlue1) + Write-SpectreRule $Title -Color ([Spectre.Console.Color]::SteelBlue1) Write-SpectreHost "`n$Description" if (!$HideHeader) { Write-CodeblockHeader @@ -52,12 +51,12 @@ function Start-SpectreDemo { } Write-Host "" - Write-SpectreRule "PwshSpectreConsole Intro" -Color ([Color]::SteelBlue1) + Write-SpectreRule "PwshSpectreConsole Intro" -Color ([Spectre.Console.Color]::SteelBlue1) Write-SpectreHost "`nPwshSpectreConsole is an opinionated wrapper for the awesome Spectre.Console library. It's opinionated in that I have not just exposed the internals of Spectre Console to PowerShell but have wrapped them in a way that makes them work better in the PowerShell ecosystem (in my opinion 😜)." Write-SpectreHost "`nSpectre Console is mostly an async library and it leans heavily on types and extension methods in C# which are very verbose to work with in PowerShell so this module hides away some of the complexity." Write-SpectreHost "`nThe module doesn't expose the full feature set of Spectre.Console because the scope of the library is huge and I've focused on the features that I use to enhance my scripts." Write-Host "" - if (![AnsiConsole]::Console.Profile.Capabilities.Unicode) { + if (![Spectre.Console.AnsiConsole]::Console.Profile.Capabilities.Unicode) { Write-Warning "To enable all features of Spectre.Console you need to enable Unicode support in your PowerShell profile by adding the following to your profile at $PROFILE. See https://spectreconsole.net/best-practices for more info.`n`n`$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding`n" } @@ -163,22 +162,22 @@ $( @{ Label = "Apple" Value = 12 - Color = [Color]::Green + Color = [Spectre.Console.Color]::Green }, @{ Label = "Orange" Value = 54 - Color = [Color]::Orange1 + Color = [Spectre.Console.Color]::Orange1 }, @{ Label = "Strawberry" Value = 51 - Color = [Color]::Red + Color = [Spectre.Console.Color]::Red }, @{ Label = "Banana" Value = 33 - Color = [Color]::Yellow + Color = [Spectre.Console.Color]::Yellow } ) | Format-SpectreBarChart '@ @@ -193,22 +192,22 @@ $( @{ Label = "Apple" Value = 12 - Color = [Color]::Green + Color = [Spectre.Console.Color]::Green }, @{ Label = "Strawberry" Value = 15 - Color = [Color]::Red + Color = [Spectre.Console.Color]::Red }, @{ Label = "Orange" Value = 54 - Color = [Color]::Orange1 + Color = [Spectre.Console.Color]::Orange1 }, @{ Label = "Plum" Value = 75 - Color = [Color]::Fuchsia + Color = [Spectre.Console.Color]::Fuchsia } ) | Format-SpectreBreakdownChart '@ diff --git a/PwshSpectreConsole/public/formatting/Format-SpectreBarChart.ps1 b/PwshSpectreConsole/public/formatting/Format-SpectreBarChart.ps1 index 69a5460c..a57fb45c 100644 --- a/PwshSpectreConsole/public/formatting/Format-SpectreBarChart.ps1 +++ b/PwshSpectreConsole/public/formatting/Format-SpectreBarChart.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Format-SpectreBarChart { <# @@ -44,7 +43,7 @@ function Format-SpectreBarChart { [switch] $HideValues ) begin { - $barChart = [BarChart]::new() + $barChart = [Spectre.Console.BarChart]::new() if ($Label) { $barChart.Label = $Label } @@ -56,10 +55,10 @@ function Format-SpectreBarChart { process { if ($Data -is [array]) { foreach ($dataItem in $Data) { - $barChart = [BarChartExtensions]::AddItem($barChart, $dataItem.Label, $dataItem.Value, ($dataItem.Color | Convert-ToSpectreColor)) + $barChart = [Spectre.Console.BarChartExtensions]::AddItem($barChart, $dataItem.Label, $dataItem.Value, ($dataItem.Color | Convert-ToSpectreColor)) } } else { - $barChart = [BarChartExtensions]::AddItem($barChart, $Data.Label, $Data.Value, ($Data.Color | Convert-ToSpectreColor)) + $barChart = [Spectre.Console.BarChartExtensions]::AddItem($barChart, $Data.Label, $Data.Value, ($Data.Color | Convert-ToSpectreColor)) } } end { diff --git a/PwshSpectreConsole/public/formatting/Format-SpectreBreakdownChart.ps1 b/PwshSpectreConsole/public/formatting/Format-SpectreBreakdownChart.ps1 index 63575ae8..c6563d6e 100644 --- a/PwshSpectreConsole/public/formatting/Format-SpectreBreakdownChart.ps1 +++ b/PwshSpectreConsole/public/formatting/Format-SpectreBreakdownChart.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Format-SpectreBreakdownChart { <# @@ -43,7 +42,7 @@ function Format-SpectreBreakdownChart { [Switch]$HideTagValues ) begin { - $chart = [BreakdownChart]::new() + $chart = [Spectre.Console.BreakdownChart]::new() $chart.Width = $Width if ($HideTags) { $chart.ShowTags = $false @@ -55,10 +54,10 @@ function Format-SpectreBreakdownChart { process { if ($Data -is [array]) { foreach ($dataItem in $Data) { - [BreakdownChartExtensions]::AddItem($chart, $dataItem.Label, $dataItem.Value, ($dataItem.Color | Convert-ToSpectreColor)) | Out-Null + [Spectre.Console.BreakdownChartExtensions]::AddItem($chart, $dataItem.Label, $dataItem.Value, ($dataItem.Color | Convert-ToSpectreColor)) | Out-Null } } else { - [BreakdownChartExtensions]::AddItem($chart, $Data.Label, $Data.Value, ($Data.Color | Convert-ToSpectreColor)) | Out-Null + [Spectre.Console.BreakdownChartExtensions]::AddItem($chart, $Data.Label, $Data.Value, ($Data.Color | Convert-ToSpectreColor)) | Out-Null } } end { diff --git a/PwshSpectreConsole/public/formatting/Format-SpectreColumns.ps1 b/PwshSpectreConsole/public/formatting/Format-SpectreColumns.ps1 index 5063e1a6..52e2413a 100644 --- a/PwshSpectreConsole/public/formatting/Format-SpectreColumns.ps1 +++ b/PwshSpectreConsole/public/formatting/Format-SpectreColumns.ps1 @@ -1,5 +1,4 @@ using module "..\..\private\completions\Completers.psm1" -using namespace Spectre.Console function Format-SpectreColumns { <# @@ -13,7 +12,7 @@ function Format-SpectreColumns { .PARAMETER Data An array of objects containing the data to be displayed in the columns. #> - [Reflection.AssemblyMetadata("title", "New-SpectreColumn")] + [Reflection.AssemblyMetadata("title", "Format-SpectreColumns")] param ( [Parameter(ValueFromPipeline, Mandatory)] [array] $Data, @@ -26,28 +25,28 @@ function Format-SpectreColumns { process { if ($Data -is [array]) { foreach ($dataItem in $Data) { - if ($dataItem -is [Rendering.Renderable]) { + if ($dataItem -is [Spectre.Console.Rendering.Renderable]) { $columnItems += $dataItem } elseif ($dataItem -is [string]) { - $columnItems += [Text]::new($dataItem) + $columnItems += [Spectre.Console.Text]::new($dataItem) } else { throw "Data item must be a spectre renderable object or string" } } } else { - if ($Data -is [Rendering.Renderable]) { + if ($Data -is [Spectre.Console.Rendering.Renderable]) { $columnItems += $Data } elseif ($Data -is [string]) { - $columnItems += [Text]::new($Data) + $columnItems += [Spectre.Console.Text]::new($Data) } else { throw "Data item must be a spectre renderable object or string" } } } end { - $columns = [Columns]::new($columnItems) + $columns = [Spectre.Console.Columns]::new($columnItems) $columns.Expand = $Expand - $columns.Padding = [Padding]::new($Padding, $Padding, $Padding, $Padding) + $columns.Padding = [Spectre.Console.Padding]::new($Padding, $Padding, $Padding, $Padding) return $columns } diff --git a/PwshSpectreConsole/public/formatting/Format-SpectreJson.ps1 b/PwshSpectreConsole/public/formatting/Format-SpectreJson.ps1 index aaab45a3..3d4da3f8 100644 --- a/PwshSpectreConsole/public/formatting/Format-SpectreJson.ps1 +++ b/PwshSpectreConsole/public/formatting/Format-SpectreJson.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Format-SpectreJson { <# @@ -60,17 +59,22 @@ function Format-SpectreJson { [ColorThemeTransformationAttribute()] [hashtable] $JsonStyle = @{ MemberStyle = $script:AccentColor - BracesStyle = [Color]::Red - BracketsStyle = [Color]::Orange1 + BracesStyle = [Spectre.Console.Color]::Red + BracketsStyle = [Spectre.Console.Color]::Orange1 ColonStyle = $script:AccentColor CommaStyle = $script:AccentColor - StringStyle = [Color]::White - NumberStyle = [Color]::Red - BooleanStyle = [Color]::LightSkyBlue1 + StringStyle = [Spectre.Console.Color]::White + NumberStyle = [Spectre.Console.Color]::Red + BooleanStyle = [Spectre.Console.Color]::LightSkyBlue1 NullStyle = $script:DefaultValueColor } ) begin { + $requiredJsonStyleKeys = @('MemberStyle', 'BracesStyle', 'BracketsStyle', 'ColonStyle', 'CommaStyle', 'StringStyle', 'NumberStyle', 'BooleanStyle', 'NullStyle') + if (($requiredJsonStyleKeys | ForEach-Object { $JsonStyle.Keys -contains $_ }) -contains $false) { + throw "JsonStyle must contain the following keys: $($requiredJsonStyleKeys -join ', ')" + } + $collector = [System.Collections.Generic.List[psobject]]::new() $splat = @{ WarningAction = 'Ignore' @@ -141,7 +145,7 @@ function Format-SpectreJson { return } try { - $json = [Json.JsonText]::new(($collector | ConvertTo-Json @splat)) + $json = [Spectre.Console.Json.JsonText]::new(($collector | ConvertTo-Json @splat)) } catch { Write-Error "Failed to convert to json, $_" return diff --git a/PwshSpectreConsole/public/formatting/Format-SpectrePanel.ps1 b/PwshSpectreConsole/public/formatting/Format-SpectrePanel.ps1 index 38ac5dfc..9a4b266a 100644 --- a/PwshSpectreConsole/public/formatting/Format-SpectrePanel.ps1 +++ b/PwshSpectreConsole/public/formatting/Format-SpectrePanel.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Format-SpectrePanel { <# @@ -50,15 +49,15 @@ function Format-SpectrePanel { [switch] $Expand, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor, + [Spectre.Console.Color] $Color = $script:AccentColor, [ValidateScript({ $_ -gt 0 -and $_ -le (Get-HostWidth) }, ErrorMessage = "Value '{0}' is invalid. Cannot be negative or exceed console width.")] [int]$Width, [ValidateScript({ $_ -gt 0 -and $_ -le (Get-HostHeight) }, ErrorMessage = "Value '{0}' is invalid. Cannot be negative or exceed console height.")] [int]$Height ) - $panel = [Panel]::new($Data) + $panel = [Spectre.Console.Panel]::new($Data) if ($Header) { - $panel.Header = [PanelHeader]::new($Header) + $panel.Header = [Spectre.Console.PanelHeader]::new($Header) } if ($width) { $panel.Width = $Width @@ -67,8 +66,8 @@ function Format-SpectrePanel { $panel.Height = $Height } $panel.Expand = $Expand - $panel.Border = [BoxBorder]::$Border - $panel.BorderStyle = [Style]::new($Color) + $panel.Border = [Spectre.Console.BoxBorder]::$Border + $panel.BorderStyle = [Spectre.Console.Style]::new($Color) return $panel } diff --git a/PwshSpectreConsole/public/formatting/Format-SpectrePath.ps1 b/PwshSpectreConsole/public/formatting/Format-SpectrePath.ps1 new file mode 100644 index 00000000..861525e1 --- /dev/null +++ b/PwshSpectreConsole/public/formatting/Format-SpectrePath.ps1 @@ -0,0 +1,47 @@ +using module "..\..\private\completions\Completers.psm1" +using module "..\..\private\completions\Transformers.psm1" + +function Format-SpectrePath { + <# + .SYNOPSIS + Formats a path into a Spectre Console Path which supports highlighting and truncating. + + .DESCRIPTION + Formats a path into a Spectre Console Path which supports highlighting and truncating. + + .PARAMETER Path + The array of objects to be formatted into Json. + + .EXAMPLE + TODO Example + #> + [Reflection.AssemblyMetadata("title", "Format-SpectrePath")] + param( + [Parameter(ValueFromPipeline, Mandatory)] + [string] $Path, + [ValidateSet([SpectreConsoleJustify], ErrorMessage = "Value '{0}' is invalid. Try one of: {1}")] + [string] $Alignment = "Left", + [ValidateSpectreColorTheme()] + [ColorThemeTransformationAttribute()] + [hashtable] $PathStyle = @{ + RootColor = $script:AccentColor + SeparatorColor = $script:DefaultValueColor + StemColor = [Spectre.Console.Color]::Orange1 + LeafColor = [Spectre.Console.Color]::Red + } + ) + + $requiredPathKeys = @("RootColor", "SeparatorColor", "StemColor", "LeafColor") + if (($requiredPathKeys | ForEach-Object { $PathStyle.Keys -contains $_ }) -contains $false) { + throw "PathStyle must contain the following keys: $($requiredPathKeys -join ', ')" + } + + $textPath = [Spectre.Console.TextPath]::new($Path) + $textPath.Justification = [Spectre.Console.Justify]::$Alignment + $textPath = [Spectre.Console.TextPathExtensions]::RootColor($textPath, $PathStyle.RootColor) + $textPath = [Spectre.Console.TextPathExtensions]::SeparatorColor($textPath, $PathStyle.SeparatorColor) + $textPath = [Spectre.Console.TextPathExtensions]::StemColor($textPath, $PathStyle.StemColor) + $textPath = [Spectre.Console.TextPathExtensions]::LeafColor($textPath, $PathStyle.LeafColor) + + return $textPath +} diff --git a/PwshSpectreConsole/public/formatting/Format-SpectreRows.ps1 b/PwshSpectreConsole/public/formatting/Format-SpectreRows.ps1 new file mode 100644 index 00000000..61b47a9f --- /dev/null +++ b/PwshSpectreConsole/public/formatting/Format-SpectreRows.ps1 @@ -0,0 +1,51 @@ +using module "..\..\private\completions\Completers.psm1" + +function Format-SpectreRows { + <# + .SYNOPSIS + Renders a collection of renderables in rows to the console. + + .DESCRIPTION + This function creates a spectre rows widget that renders a collection of renderables in autosized rows to the console. + Rows can contain renderable items, see https://spectreconsole.net/widgets/rows for more information. + + .PARAMETER Data + An array of objects containing the data to be displayed in the rows. + #> + [Reflection.AssemblyMetadata("title", "Format-SpectreRows")] + param ( + [Parameter(ValueFromPipeline, Mandatory)] + [array] $Data, + [switch] $Expand + ) + begin { + $rowItems = @() + } + process { + if ($Data -is [array]) { + foreach ($dataItem in $Data) { + if ($dataItem -is [Spectre.Console.Rendering.Renderable]) { + $rowItems += $dataItem + } elseif ($dataItem -is [string]) { + $rowItems += [Spectre.Console.Text]::new($dataItem) + } else { + throw "Data item must be a spectre renderable object or string" + } + } + } else { + if ($Data -is [Spectre.Console.Rendering.Renderable]) { + $rowItems += $Data + } elseif ($Data -is [string]) { + $rowItems += [Spectre.Console.Text]::new($Data) + } else { + throw "Data item must be a spectre renderable object or string" + } + } + } + end { + $rows = [Spectre.Console.Rows]::new($rowItems) + $rows.Expand = $Expand + + return $rows + } +} diff --git a/PwshSpectreConsole/public/formatting/Format-SpectreTable.ps1 b/PwshSpectreConsole/public/formatting/Format-SpectreTable.ps1 index 1a579df7..cf33e1e8 100644 --- a/PwshSpectreConsole/public/formatting/Format-SpectreTable.ps1 +++ b/PwshSpectreConsole/public/formatting/Format-SpectreTable.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Format-SpectreTable { <# @@ -99,13 +98,13 @@ function Format-SpectreTable { [string] $Border = "Double", [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor, + [Spectre.Console.Color] $Color = $script:AccentColor, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $HeaderColor = $script:DefaultTableHeaderColor, + [Spectre.Console.Color] $HeaderColor = $script:DefaultTableHeaderColor, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $TextColor = $script:DefaultTableTextColor, + [Spectre.Console.Color] $TextColor = $script:DefaultTableTextColor, [ValidateScript({ $_ -gt 0 -and $_ -le (Get-HostWidth) }, ErrorMessage = "Value '{0}' is invalid. Cannot be negative or exceed console width.")] [int] $Width, [switch] $HideHeaders, @@ -120,9 +119,9 @@ function Format-SpectreTable { $FormatTableParams = @{} $collector = [System.Collections.Generic.List[psobject]]::new() $renderables = @{} - $table = [Table]::new() - $table.Border = [TableBorder]::$Border - $table.BorderStyle = [Style]::new($Color) + $table = [Spectre.Console.Table]::new() + $table.Border = [Spectre.Console.TableBorder]::$Border + $table.BorderStyle = [Spectre.Console.Style]::new($Color) switch ($PSBoundParameters.Keys) { 'Width' { $table.Width = $Width } 'HideHeaders' { $table.ShowHeaders = $false } @@ -184,13 +183,13 @@ function Format-SpectreTable { $row = New-TableRow -Entry $item.FormatPropertyFieldList.propertyValue -Renderables $renderables -Color $TextColor @rowoptions } if ($AllowMarkup) { - $table = [TableExtensions]::AddRow($table, [Markup[]]$row) + $table = [Spectre.Console.TableExtensions]::AddRow($table, [Spectre.Console.Markup[]]$row) } else { - $table = [TableExtensions]::AddRow($table, [Rendering.Renderable[]]$row) + $table = [Spectre.Console.TableExtensions]::AddRow($table, [Spectre.Console.Rendering.Renderable[]]$row) } } if ($Title -And -Not $rowoptions.scalar) { - $table.Title = [TableTitle]::new($Title, [Style]::new($Color)) + $table.Title = [Spectre.Console.TableTitle]::new($Title, [Spectre.Console.Style]::new($Color)) } return $table diff --git a/PwshSpectreConsole/public/formatting/Format-SpectreTree.ps1 b/PwshSpectreConsole/public/formatting/Format-SpectreTree.ps1 index a30042e8..3482127f 100644 --- a/PwshSpectreConsole/public/formatting/Format-SpectreTree.ps1 +++ b/PwshSpectreConsole/public/formatting/Format-SpectreTree.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Format-SpectreTree { <# @@ -55,17 +54,17 @@ function Format-SpectreTree { [string] $Guide = "Line", [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor + [Spectre.Console.Color] $Color = $script:AccentColor ) - $tree = [Tree]::new($Data.Value) - $tree.Guide = [TreeGuide]::$Guide + $tree = [Spectre.Console.Tree]::new($Data.Value) + $tree.Guide = [Spectre.Console.TreeGuide]::$Guide if ($Data.Children) { Add-SpectreTreeNode -Node $tree -Children $Data.Children } - $tree.Style = [Style]::new($Color) + $tree.Style = [Spectre.Console.Style]::new($Color) return $tree } \ No newline at end of file diff --git a/PwshSpectreConsole/public/formatting/New-SpectreChartItem.ps1 b/PwshSpectreConsole/public/formatting/New-SpectreChartItem.ps1 index 257b9493..17a8a8d0 100644 --- a/PwshSpectreConsole/public/formatting/New-SpectreChartItem.ps1 +++ b/PwshSpectreConsole/public/formatting/New-SpectreChartItem.ps1 @@ -1,7 +1,6 @@ using module "..\..\private\models\SpectreChartItem.psm1" using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console <# .SYNOPSIS @@ -39,7 +38,7 @@ function New-SpectreChartItem { [Parameter(Mandatory)] [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color]$Color + [Spectre.Console.Color]$Color ) return [SpectreChartItem]::new($Label, $Value, $Color) diff --git a/PwshSpectreConsole/public/images/Get-SpectreImage.ps1 b/PwshSpectreConsole/public/images/Get-SpectreImage.ps1 index b9e503d6..b9073c39 100644 --- a/PwshSpectreConsole/public/images/Get-SpectreImage.ps1 +++ b/PwshSpectreConsole/public/images/Get-SpectreImage.ps1 @@ -1,35 +1,34 @@ -using namespace Spectre.Console - -function Get-SpectreImage { - <# - .SYNOPSIS - Displays an image in the console using CanvasImage. - - .DESCRIPTION - Displays an image in the console using CanvasImage. The image can be resized to a maximum width if desired. - - .PARAMETER ImagePath - The path to the image file to be displayed. - - .PARAMETER MaxWidth - The maximum width of the image. If not specified, the image will be displayed at its original size. - - .EXAMPLE - Get-SpectreImage -ImagePath "..\..\..\PwshSpectreConsole\private\images\smiley.png" -MaxWidth 40 - #> - [Reflection.AssemblyMetadata("title", "Get-SpectreImage")] - param ( - [string] $ImagePath, - [int] $MaxWidth - ) - $imagePathResolved = Resolve-Path $ImagePath - if (-not (Test-Path $imagePathResolved)) { - throw "The specified image path '$resolvedImagePath' does not exist." - } - - $image = [CanvasImage]::new($imagePathResolved) - if ($MaxWidth) { - $image.MaxWidth = $MaxWidth - } - Write-AnsiConsole $image + +function Get-SpectreImage { + <# + .SYNOPSIS + Displays an image in the console using CanvasImage. + + .DESCRIPTION + Displays an image in the console using CanvasImage. The image can be resized to a maximum width if desired. + + .PARAMETER ImagePath + The path to the image file to be displayed. + + .PARAMETER MaxWidth + The maximum width of the image. If not specified, the image will be displayed at its original size. + + .EXAMPLE + Get-SpectreImage -ImagePath "..\..\..\PwshSpectreConsole\private\images\smiley.png" -MaxWidth 40 + #> + [Reflection.AssemblyMetadata("title", "Get-SpectreImage")] + param ( + [string] $ImagePath, + [int] $MaxWidth + ) + $imagePathResolved = Resolve-Path $ImagePath + if (-not (Test-Path $imagePathResolved)) { + throw "The specified image path '$resolvedImagePath' does not exist." + } + + $image = [Spectre.Console.CanvasImage]::new($imagePathResolved) + if ($MaxWidth) { + $image.MaxWidth = $MaxWidth + } + Write-AnsiConsole $image } \ No newline at end of file diff --git a/PwshSpectreConsole/public/progress/Invoke-SpectreCommandWithStatus.ps1 b/PwshSpectreConsole/public/progress/Invoke-SpectreCommandWithStatus.ps1 index d1e3c510..9f9a6e21 100644 --- a/PwshSpectreConsole/public/progress/Invoke-SpectreCommandWithStatus.ps1 +++ b/PwshSpectreConsole/public/progress/Invoke-SpectreCommandWithStatus.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Invoke-SpectreCommandWithStatus { <# @@ -47,12 +46,12 @@ function Invoke-SpectreCommandWithStatus { [string] $Title, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor + [Spectre.Console.Color] $Color = $script:AccentColor ) $splat = @{ Title = $Title - Spinner = [Spinner+Known]::$Spinner - SpinnerStyle = [Style]::new($Color) + Spinner = [Spectre.Console.Spinner+Known]::$Spinner + SpinnerStyle = [Spectre.Console.Style]::new($Color) ScriptBlock = $ScriptBlock } Start-AnsiConsoleStatus @splat diff --git a/PwshSpectreConsole/public/prompts/Read-SpectreConfirm.ps1 b/PwshSpectreConsole/public/prompts/Read-SpectreConfirm.ps1 index 52fbf857..cfcd958c 100644 --- a/PwshSpectreConsole/public/prompts/Read-SpectreConfirm.ps1 +++ b/PwshSpectreConsole/public/prompts/Read-SpectreConfirm.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Read-SpectreConfirm { <# @@ -38,21 +37,21 @@ function Read-SpectreConfirm { [string] $ConfirmFailure, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor + [Spectre.Console.Color] $Color = $script:AccentColor ) # This is much fiddlier but it exposes the ability to set the color scheme. The confirmationprompt is just a textprompt with two choices hard coded to y/n: # https://github.com/spectreconsole/spectre.console/blob/63b940cf0eb127a8cd891a4fe338aa5892d502c5/src/Spectre.Console/Prompts/ConfirmationPrompt.cs#L71 - $confirmationPrompt = [TextPrompt[string]]::new($Prompt) - $confirmationPrompt = [TextPromptExtensions]::AddChoice($confirmationPrompt, "y") - $confirmationPrompt = [TextPromptExtensions]::AddChoice($confirmationPrompt, "n") + $confirmationPrompt = [Spectre.Console.TextPrompt[string]]::new($Prompt) + $confirmationPrompt = [Spectre.Console.TextPromptExtensions]::AddChoice($confirmationPrompt, "y") + $confirmationPrompt = [Spectre.Console.TextPromptExtensions]::AddChoice($confirmationPrompt, "n") if ($DefaultAnswer -ne "none") { - $confirmationPrompt = [TextPromptExtensions]::DefaultValue($confirmationPrompt, $DefaultAnswer) + $confirmationPrompt = [Spectre.Console.TextPromptExtensions]::DefaultValue($confirmationPrompt, $DefaultAnswer) } # This is how I added the default colors with Set-SpectreColors so you don't have to keep passing them through and get a consistent TUI color scheme - $confirmationPrompt.DefaultValueStyle = [Style]::new($script:DefaultValueColor) - $confirmationPrompt.ChoicesStyle = [Style]::new($Color) + $confirmationPrompt.DefaultValueStyle = [Spectre.Console.Style]::new($script:DefaultValueColor) + $confirmationPrompt.ChoicesStyle = [Spectre.Console.Style]::new($Color) $confirmationPrompt.InvalidChoiceMessage = "[red]Please select one of the available options[/]" # Invoke-SpectrePromptAsync supports ctrl-c diff --git a/PwshSpectreConsole/public/prompts/Read-SpectreMultiSelection.ps1 b/PwshSpectreConsole/public/prompts/Read-SpectreMultiSelection.ps1 index 0c686c2e..f1b862e1 100644 --- a/PwshSpectreConsole/public/prompts/Read-SpectreMultiSelection.ps1 +++ b/PwshSpectreConsole/public/prompts/Read-SpectreMultiSelection.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Read-SpectreMultiSelection { <# @@ -11,7 +10,7 @@ function Read-SpectreMultiSelection { This function displays a multi-selection prompt using Spectre Console and returns the selected choices. The prompt allows the user to select one or more choices from a list of options. The function supports customizing the title, choices, choice label property, color, and page size of the prompt. .PARAMETER Title - The title of the prompt. Defaults to "What are your favourite [color]?". + The title of the prompt. Defaults to "What are your favourite [Spectre.Console.Color]?". .PARAMETER Choices The list of choices to display in the selection prompt. ChoiceLabelProperty is required if the choices are complex objects rather than an array of strings. @@ -42,11 +41,11 @@ function Read-SpectreMultiSelection { [string] $ChoiceLabelProperty, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor, + [Spectre.Console.Color] $Color = $script:AccentColor, [int] $PageSize = 5, [switch] $AllowEmpty ) - $spectrePrompt = [MultiSelectionPrompt[string]]::new() + $spectrePrompt = [Spectre.Console.MultiSelectionPrompt[string]]::new() $choiceLabels = $Choices $choiceObjects = $Choices | Where-Object { $_ -isnot [string] } @@ -62,12 +61,12 @@ function Read-SpectreMultiSelection { throw "You have duplicate labels in your select list, this is ambiguous so a selection cannot be made" } - $spectrePrompt = [MultiSelectionPromptExtensions]::AddChoices($spectrePrompt, [string[]]$choiceLabels) + $spectrePrompt = [Spectre.Console.MultiSelectionPromptExtensions]::AddChoices($spectrePrompt, [string[]]$choiceLabels) $spectrePrompt.Title = $Title $spectrePrompt.PageSize = $PageSize $spectrePrompt.WrapAround = $true $spectrePrompt.Required = !$AllowEmpty - $spectrePrompt.HighlightStyle = [Style]::new($Color) + $spectrePrompt.HighlightStyle = [Spectre.Console.Style]::new($Color) $spectrePrompt.InstructionsText = "[$($script:DefaultValueColor.ToMarkup())](Press [$($script:AccentColor.ToMarkup())]space[/] to toggle a choice and press [$($script:AccentColor.ToMarkup())][/] to submit your answer)[/]" $spectrePrompt.MoreChoicesText = "[$($script:DefaultValueColor.ToMarkup())](Move up and down to reveal more choices)[/]" $selected = Invoke-SpectrePromptAsync -Prompt $spectrePrompt diff --git a/PwshSpectreConsole/public/prompts/Read-SpectreMultiSelectionGrouped.ps1 b/PwshSpectreConsole/public/prompts/Read-SpectreMultiSelectionGrouped.ps1 index fe0a7a41..b1192826 100644 --- a/PwshSpectreConsole/public/prompts/Read-SpectreMultiSelectionGrouped.ps1 +++ b/PwshSpectreConsole/public/prompts/Read-SpectreMultiSelectionGrouped.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Read-SpectreMultiSelectionGrouped { <# @@ -11,7 +10,7 @@ function Read-SpectreMultiSelectionGrouped { Displays a multi-selection prompt with grouped choices and returns the selected choices. The prompt allows the user to select one or more choices from a list of options. The choices can be grouped into categories, and the user can select choices from each category. .PARAMETER Title - The title of the prompt. The default value is "What are your favourite [color]?". + The title of the prompt. The default value is "What are your favourite [Spectre.Console.Color]?". .PARAMETER Choices An array of choice groups. Each group is a hashtable with two keys: "Name" and "Choices". The "Name" key is a string that represents the name of the group, and the "Choices" key is an array of strings that represents the choices in the group. @@ -58,11 +57,11 @@ function Read-SpectreMultiSelectionGrouped { [string] $ChoiceLabelProperty, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor, + [Spectre.Console.Color] $Color = $script:AccentColor, [int] $PageSize = 10, [switch] $AllowEmpty ) - $spectrePrompt = [MultiSelectionPrompt[string]]::new() + $spectrePrompt = [Spectre.Console.MultiSelectionPrompt[string]]::new() $choiceLabels = $Choices.Choices $flattenedChoices = $Choices.Choices @@ -83,14 +82,14 @@ function Read-SpectreMultiSelectionGrouped { if ($ChoiceLabelProperty) { $choiceLabels = $choiceLabels | Select-Object -ExpandProperty $ChoiceLabelProperty } - $spectrePrompt = [MultiSelectionPromptExtensions]::AddChoiceGroup($spectrePrompt, $group.Name, [string[]]$choiceLabels) + $spectrePrompt = [Spectre.Console.MultiSelectionPromptExtensions]::AddChoiceGroup($spectrePrompt, $group.Name, [string[]]$choiceLabels) } $spectrePrompt.Title = $Title $spectrePrompt.PageSize = $PageSize $spectrePrompt.WrapAround = $true $spectrePrompt.Required = !$AllowEmpty - $spectrePrompt.HighlightStyle = [Style]::new($Color) + $spectrePrompt.HighlightStyle = [Spectre.Console.Style]::new($Color) $spectrePrompt.InstructionsText = "[$($script:DefaultValueColor.ToMarkup())](Press [$($script:AccentColor.ToMarkup())]space[/] to toggle a choice and press [$($script:AccentColor.ToMarkup())][/] to submit your answer)[/]" $spectrePrompt.MoreChoicesText = "[$($script:DefaultValueColor.ToMarkup())](Move up and down to reveal more choices)[/]" $selected = Invoke-SpectrePromptAsync -Prompt $spectrePrompt diff --git a/PwshSpectreConsole/public/prompts/Read-SpectreSelection.ps1 b/PwshSpectreConsole/public/prompts/Read-SpectreSelection.ps1 index d2b664eb..c5bd7382 100644 --- a/PwshSpectreConsole/public/prompts/Read-SpectreSelection.ps1 +++ b/PwshSpectreConsole/public/prompts/Read-SpectreSelection.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Read-SpectreSelection { <# @@ -49,14 +48,14 @@ function Read-SpectreSelection { [string] $ChoiceLabelProperty, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor, + [Spectre.Console.Color] $Color = $script:AccentColor, [int] $PageSize = 5, [switch] $EnableSearch, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $SearchHighlightColor = $script:AccentColor.Blend([Spectre.Console.Color]::White, 0.7) + [Spectre.Console.Color] $SearchHighlightColor = $script:AccentColor.Blend([Spectre.Console.Color]::White, 0.7) ) - $spectrePrompt = [SelectionPrompt[string]]::new() + $spectrePrompt = [Spectre.Console.SelectionPrompt[string]]::new() $choiceLabels = $Choices if ($ChoiceLabelProperty) { @@ -68,14 +67,14 @@ function Read-SpectreSelection { throw "You have duplicate labels in your select list, this is ambiguous so a selection cannot be made" } - $spectrePrompt = [SelectionPromptExtensions]::AddChoices($spectrePrompt, [string[]]$choiceLabels) + $spectrePrompt = [Spectre.Console.SelectionPromptExtensions]::AddChoices($spectrePrompt, [string[]]$choiceLabels) $spectrePrompt.Title = $Title $spectrePrompt.PageSize = $PageSize $spectrePrompt.WrapAround = $true - $spectrePrompt.HighlightStyle = [Style]::new($Color) + $spectrePrompt.HighlightStyle = [Spectre.Console.Style]::new($Color) $spectrePrompt.MoreChoicesText = "[$($script:DefaultValueColor.ToMarkup())](Move up and down to reveal more choices)[/]" $spectrePrompt.SearchEnabled = $EnableSearch - $spectrePrompt.SearchHighlightStyle = [Style]::new($SearchHighlightColor) + $spectrePrompt.SearchHighlightStyle = [Spectre.Console.Style]::new($SearchHighlightColor) $selected = Invoke-SpectrePromptAsync -Prompt $spectrePrompt diff --git a/PwshSpectreConsole/public/prompts/Read-SpectreText.ps1 b/PwshSpectreConsole/public/prompts/Read-SpectreText.ps1 index fb965906..ef4781b7 100644 --- a/PwshSpectreConsole/public/prompts/Read-SpectreText.ps1 +++ b/PwshSpectreConsole/public/prompts/Read-SpectreText.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Read-SpectreText { <# @@ -52,21 +51,21 @@ function Read-SpectreText { [string] $DefaultAnswer, [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $AnswerColor, + [Spectre.Console.Color] $AnswerColor, [switch] $AllowEmpty, [string[]] $Choices ) - $spectrePrompt = [TextPrompt[string]]::new($Question, [System.StringComparer]::InvariantCultureIgnoreCase) - $spectrePrompt.DefaultValueStyle = [Style]::new($script:DefaultValueColor) + $spectrePrompt = [Spectre.Console.TextPrompt[string]]::new($Question, [System.StringComparer]::InvariantCultureIgnoreCase) + $spectrePrompt.DefaultValueStyle = [Spectre.Console.Style]::new($script:DefaultValueColor) if ($DefaultAnswer) { - $spectrePrompt = [TextPromptExtensions]::DefaultValue($spectrePrompt, $DefaultAnswer) + $spectrePrompt = [Spectre.Console.TextPromptExtensions]::DefaultValue($spectrePrompt, $DefaultAnswer) } if ($AnswerColor) { - $spectrePrompt.PromptStyle = [Style]::new($AnswerColor) + $spectrePrompt.PromptStyle = [Spectre.Console.Style]::new($AnswerColor) } $spectrePrompt.AllowEmpty = $AllowEmpty if ($null -ne $Choices) { - $spectrePrompt = [TextPromptExtensions]::AddChoices($spectrePrompt, $Choices) + $spectrePrompt = [Spectre.Console.TextPromptExtensions]::AddChoices($spectrePrompt, $Choices) } return Invoke-SpectrePromptAsync -Prompt $spectrePrompt } diff --git a/PwshSpectreConsole/public/writing/Get-SpectreEscapedText.ps1 b/PwshSpectreConsole/public/writing/Get-SpectreEscapedText.ps1 index a8801c0a..52f32bcd 100644 --- a/PwshSpectreConsole/public/writing/Get-SpectreEscapedText.ps1 +++ b/PwshSpectreConsole/public/writing/Get-SpectreEscapedText.ps1 @@ -1,26 +1,25 @@ -using namespace Spectre.Console - -function Get-SpectreEscapedText { - <# - .SYNOPSIS - Escapes text for use in Spectre Console. - [ShaunLawrie/PwshSpectreConsole/issues/5](https://github.com/ShaunLawrie/PwshSpectreConsole/issues/5) - - .DESCRIPTION - This function escapes text for use where Spectre Console accepts markup. It is intended to be used as a helper function for other functions that output text to the console using Spectre Console which contains special characters that need escaping. - See [https://spectreconsole.net/markup](https://spectreconsole.net/markup) for more information about the markup language used in Spectre Console. - - .PARAMETER Text - The text to be escaped. - - .EXAMPLE - $data = "][[][red]]][[/][][][" - Format-SpectrePanel -Title "Unescaped data" -Data "I want escaped $($data | Get-SpectreEscapedText) [yellow]and[/] [red]unescaped[/] data" - #> - [Reflection.AssemblyMetadata("title", "Get-SpectreEscapedText")] - param ( - [Parameter(ValueFromPipeline, Mandatory)] - [string] $Text - ) - return [Markup]::Escape($Text) + +function Get-SpectreEscapedText { + <# + .SYNOPSIS + Escapes text for use in Spectre Console. + [ShaunLawrie/PwshSpectreConsole/issues/5](https://github.com/ShaunLawrie/PwshSpectreConsole/issues/5) + + .DESCRIPTION + This function escapes text for use where Spectre Console accepts markup. It is intended to be used as a helper function for other functions that output text to the console using Spectre Console which contains special characters that need escaping. + See [https://spectreconsole.net/markup](https://spectreconsole.net/markup) for more information about the markup language used in Spectre Console. + + .PARAMETER Text + The text to be escaped. + + .EXAMPLE + $data = "][[][red]]][[/][][][" + Format-SpectrePanel -Title "Unescaped data" -Data "I want escaped $($data | Get-SpectreEscapedText) [yellow]and[/] [red]unescaped[/] data" + #> + [Reflection.AssemblyMetadata("title", "Get-SpectreEscapedText")] + param ( + [Parameter(ValueFromPipeline, Mandatory)] + [string] $Text + ) + return [Spectre.Console.Markup]::Escape($Text) } \ No newline at end of file diff --git a/PwshSpectreConsole/public/writing/Write-SpectreCalendar.ps1 b/PwshSpectreConsole/public/writing/Write-SpectreCalendar.ps1 index 4293552f..ff0f7c6d 100644 --- a/PwshSpectreConsole/public/writing/Write-SpectreCalendar.ps1 +++ b/PwshSpectreConsole/public/writing/Write-SpectreCalendar.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Write-SpectreCalendar { <# @@ -49,7 +48,7 @@ function Write-SpectreCalendar { [string] $Alignment = "Left", [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor, + [Spectre.Console.Color] $Color = $script:AccentColor, [ValidateSet([SpectreConsoleTableBorder], ErrorMessage = "Value '{0}' is invalid. Try one of: {1}")] [string] $Border = "Double", [cultureinfo] $Culture = [cultureinfo]::CurrentCulture, @@ -57,13 +56,13 @@ function Write-SpectreCalendar { [Switch] $HideHeader, [Switch] $PassThru ) - $calendar = [Calendar]::new($date) - $calendar.Alignment = [Justify]::$Alignment - $calendar.Border = [TableBorder]::$Border - $calendar.BorderStyle = [Style]::new($Color) + $calendar = [Spectre.Console.Calendar]::new($date) + $calendar.Alignment = [Spectre.Console.Justify]::$Alignment + $calendar.Border = [Spectre.Console.TableBorder]::$Border + $calendar.BorderStyle = [Spectre.Console.Style]::new($Color) $calendar.Culture = $Culture - $calendar.HeaderStyle = [Style]::new($Color) - $calendar.HighlightStyle = [Style]::new($Color) + $calendar.HeaderStyle = [Spectre.Console.Style]::new($Color) + $calendar.HighlightStyle = [Spectre.Console.Style]::new($Color) if ($HideHeader) { $calendar.ShowHeader = $false } @@ -74,7 +73,7 @@ function Write-SpectreCalendar { foreach ($event in $events.GetEnumerator()) { # Calendar events don't appear to support Culture. $eventDate = $event.Name -as [datetime] - $calendar = [CalendarExtensions]::AddCalendarEvent($calendar, $event.value, $eventDate.Year, $eventDate.Month, $eventDate.Day) + $calendar = [Spectre.Console.CalendarExtensions]::AddCalendarEvent($calendar, $event.value, $eventDate.Year, $eventDate.Month, $eventDate.Day) } $outputData += $calendar.CalendarEvents | Sort-Object -Property Day | Format-SpectreTable -Border $Border -Color $Color } diff --git a/PwshSpectreConsole/public/writing/Write-SpectreFigletText.ps1 b/PwshSpectreConsole/public/writing/Write-SpectreFigletText.ps1 index 02475e62..892f97e6 100644 --- a/PwshSpectreConsole/public/writing/Write-SpectreFigletText.ps1 +++ b/PwshSpectreConsole/public/writing/Write-SpectreFigletText.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Write-SpectreFigletText { <# @@ -36,13 +35,13 @@ function Write-SpectreFigletText { [string] $Alignment = "Left", [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor, + [Spectre.Console.Color] $Color = $script:AccentColor, [string] $FigletFontPath, [switch] $PassThru ) $figletFont = Read-FigletFont -FigletFontPath $FigletFontPath - $figletText = [FigletText]::new($figletFont, $Text) - $figletText.Justification = [Justify]::$Alignment + $figletText = [Spectre.Console.FigletText]::new($figletFont, $Text) + $figletText.Justification = [Spectre.Console.Justify]::$Alignment $figletText.Color = $Color if ($PassThru) { diff --git a/PwshSpectreConsole/public/writing/Write-SpectreHost.ps1 b/PwshSpectreConsole/public/writing/Write-SpectreHost.ps1 index 7660f832..14740ad6 100644 --- a/PwshSpectreConsole/public/writing/Write-SpectreHost.ps1 +++ b/PwshSpectreConsole/public/writing/Write-SpectreHost.ps1 @@ -1,4 +1,3 @@ -using namespace Spectre.Console function Write-SpectreHost { <# @@ -31,7 +30,7 @@ function Write-SpectreHost { return $Message } - if ($Message -is [Rendering.Renderable]) { + if ($Message -is [Spectre.Console.Rendering.Renderable]) { Write-AnsiConsole $Message return } diff --git a/PwshSpectreConsole/public/writing/Write-SpectreRule.ps1 b/PwshSpectreConsole/public/writing/Write-SpectreRule.ps1 index 5c2f218e..3b58defa 100644 --- a/PwshSpectreConsole/public/writing/Write-SpectreRule.ps1 +++ b/PwshSpectreConsole/public/writing/Write-SpectreRule.ps1 @@ -1,6 +1,5 @@ using module "..\..\private\completions\Completers.psm1" using module "..\..\private\completions\Transformers.psm1" -using namespace Spectre.Console function Write-SpectreRule { <# @@ -30,11 +29,11 @@ function Write-SpectreRule { [string] $Alignment = "Left", [ColorTransformationAttribute()] [ArgumentCompletionsSpectreColors()] - [Color] $Color = $script:AccentColor, + [Spectre.Console.Color] $Color = $script:AccentColor, [switch] $PassThru ) - $rule = [Rule]::new("[$($Color.ToMarkup())]$Title[/]") - $rule.Justification = [Justify]::$Alignment + $rule = [Spectre.Console.Rule]::new("[$($Color.ToMarkup())]$Title[/]") + $rule.Justification = [Spectre.Console.Justify]::$Alignment if ($PassThru) { return $rule