Private/Presentation/DashboardAccessibility.ps1

function Set-DashboardControlAccessibility {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][System.Windows.FrameworkElement]$Control,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Name,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Description
    )

    [System.Windows.Automation.AutomationProperties]::SetName($Control, $Name)
    [System.Windows.Automation.AutomationProperties]::SetHelpText($Control, $Description)
    if ($null -eq $Control.ToolTip) { $Control.ToolTip = $Description }
    [System.Windows.Controls.ToolTipService]::SetShowOnDisabled($Control, $true)
}

function Initialize-DashboardAccessibility {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][System.Windows.Window]$Window,
        [Parameter(Mandatory)][System.Windows.FrameworkElement]$SettingsView
    )

    $controls = @{
        btnExit = @('Exit dashboard', 'Close the dashboard and stop its background workers.')
        tabMain = @('Dashboard views', 'Switch views using Ctrl+Tab or Ctrl+Shift+Tab.')
        cmbMapStyle = @('Map background', 'Choose satellite imagery or a vector map background.')
        cmbMapProjection = @('Map projection', 'Choose a flat map or globe view.')
        btnToggleMarketData = @('Toggle market data panel', 'Show or hide news, currency, and stock data.')
        btnToggleWorldClocks = @('Toggle world clocks panel', 'Show or hide local clocks for exchanges.')
        btnOverlays = @('Choose map overlays', 'Open the map layers. Use Tab to select a layer and Escape to close.')
        chkExchangeLocations = @('Exchange locations', 'Show or hide exchange markers; source rights and catalog coverage are disclosed in the overlay status.')
        chkFinancialCentres = @('Financial centres', 'Show or hide selected curated financial-centre markers; source rights and coverage are disclosed in the overlay status.')
        btnZoomIn = @('Zoom in on map', 'Increase the map zoom.')
        btnZoomOut = @('Zoom out on map', 'Decrease the map zoom.')
        btnZoomReset = @('Reset map view', 'Reset map zoom and position.')
        btnGlobeSpin = @('Toggle globe rotation', 'Start or stop automatic globe rotation.')
        chkTerminator = @('Day and night overlay', 'Show or hide the daylight boundary.')
        chkTimeZoneBands = @('Time zone bands', 'Show or hide time zone bands.')
        chkPoliticalBounds = @('Country borders', 'Show or hide country boundaries.')
        chkTZBoundaries = @('Time zone boundaries', 'Show or hide time zone boundaries.')
        chkEarthquakes = @('Earthquake layer', 'Show or hide USGS earthquake markers and source status.')
        chkVolcanoes = @('Volcano layer', 'Show or hide Smithsonian volcano markers and source status.')
        chkNaturalEvents = @('Natural event layer', 'Show or hide configured natural event markers and source status.')
        chkDatacenters = @('U.S. datacentres', 'Show or hide incomplete U.S. data-center locations from the IM3 Atlas; source and ODbL attribution are disclosed.')
        chkConflictZones = @('Conflict zone layer', 'Show or hide the bundled conflict zone context.')
        chkSubmarineCables = @('Submarine cable layer', 'Show or hide bundled submarine cable routes.')
        chkPowerPlants = @('Power plant layer', 'Show or hide bundled power plant locations.')
        btnTabNews = @('Financial news', 'Show attributed news stories and source filters.')
        btnTabFx = @('Foreign exchange rates', 'Show reference currency rates and their freshness.')
        btnTabCrypto = @('Cryptocurrency prices', 'Show cryptocurrency prices and source status.')
        btnTabIndices = @('Market indices', 'Show index ETF proxies and source status.')
        btnTabCommodities = @('Commodity prices', 'Show commodity ETF proxies and display currency.')
        btnTabStocks = @('Stock watchlist', 'Add stocks and manage saved watchlist presets.')
        btnCloseFlyout = @('Close exchange details', 'Close exchange details and return focus to the exchange control. Escape also closes details.')
        mapAreaSplitter = @('Resize map and countdown areas', 'Use arrow keys to resize the map and countdown areas.')
        txtFilter = @('Filter exchanges', 'Filter exchanges by name, code, country, symbol, or city.')
        btnSelectAll = @('Select all visible exchanges', 'Activate all exchanges in the filtered list.')
        btnDeselectAll = @('Deselect all visible exchanges', 'Deactivate all exchanges in the filtered list.')
        gridExchanges = @('Exchange selection and schedules', 'Navigate exchange rows with arrow keys. Use Space in an Active cell to change its selection.')
        chkNotify30 = @('Thirty minute closing notification', 'Enable or disable notifications thirty minutes before close.')
        chkNotify15 = @('Fifteen minute closing notification', 'Enable or disable notifications fifteen minutes before close.')
        chkNotify5 = @('Five minute closing notification', 'Enable or disable notifications five minutes before close.')
        chkAlwaysOnTop = @('Keep dashboard on top', 'Keep the dashboard above other windows.')
        chkShowGridLines = @('Map grid lines', 'Show or hide grid lines on satellite maps.')
        btnRefresh = @('Refresh exchange schedules', 'Reload the exchange schedule data.')
        btnResetDefaults = @('Reset default exchanges', 'Restore the default exchange selections.')
    }
    foreach ($entry in $controls.GetEnumerator()) {
        $control = $Window.FindName($entry.Key)
        if ($null -eq $control) { throw "Dashboard accessibility control '$($entry.Key)' was not found." }
        Set-DashboardControlAccessibility -Control $control -Name $entry.Value[0] -Description $entry.Value[1]
    }
    foreach ($tab in $Window.FindName('tabMain').Items) {
        $label = ([string]$tab.Header).Trim()
        Set-DashboardControlAccessibility -Control $tab -Name "$label view" -Description "Switch to the $label view."
    }
    $settings = @{
        txtFredKey = @('FRED API key', 'Enter a replacement FRED key. Stored keys are never displayed.')
        txtAlphaVantageKey = @('Alpha Vantage API key', 'Enter a replacement Alpha Vantage key. Stored keys are never displayed.')
        txtCoinMarketCapKey = @('CoinMarketCap API key', 'Enter a replacement CoinMarketCap Basic key. Stored keys are never displayed.')
        btnSaveApiKeys = @('Save API keys securely', 'Save entered keys in the selected secure credential backend.')
        cmbSecretsBackend = @('Credential storage backend', 'Choose the secure backend used to store provider keys.')
    }
    foreach ($entry in $settings.GetEnumerator()) {
        $control = $SettingsView.FindName($entry.Key)
        if ($null -eq $control) { throw "Credential accessibility control '$($entry.Key)' was not found." }
        Set-DashboardControlAccessibility -Control $control -Name $entry.Value[0] -Description $entry.Value[1]
    }
}

function Initialize-DashboardOverlayKeyboard {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][System.Windows.Controls.Primitives.Popup]$Popup,
        [Parameter(Mandatory)][System.Windows.Controls.Primitives.ToggleButton]$Button,
        [Parameter(Mandatory)][System.Windows.Controls.Control]$InitialControl
    )

    [System.Windows.Input.KeyboardNavigation]::SetTabNavigation($Popup.Child, 'Cycle')
    $Popup.Add_Opened({ [void]$InitialControl.Focus() }.GetNewClosure())
    $Popup.Child.Add_PreviewKeyDown({
            param($sender, $eventArgs)
            if ($eventArgs.Key -eq [System.Windows.Input.Key]::Escape) {
                $Popup.IsOpen = $false
                [void]$Button.Focus()
                $eventArgs.Handled = $true
            }
        }.GetNewClosure())
}

function Initialize-DashboardExchangeDetailsKeyboard {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][System.Windows.FrameworkElement]$Panel,
        [Parameter(Mandatory)][System.Windows.Controls.Button]$CloseButton,
        [Parameter(Mandatory)][System.Management.Automation.FunctionInfo]$CloseCommand
    )
    $CloseButton.Add_Click({ & $CloseCommand }.GetNewClosure())
    [System.Windows.Input.KeyboardNavigation]::SetTabNavigation($Panel, 'Cycle')
    $Panel.Add_PreviewKeyDown({
            param($sender, $eventArgs)
            if ($eventArgs.Key -eq [System.Windows.Input.Key]::Escape) {
                & $CloseCommand
                $eventArgs.Handled = $true
            }
        }.GetNewClosure())
}

function Open-DashboardLink {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][AllowEmptyString()][AllowNull()][string]$Uri,
        [Parameter(Mandatory)][System.Windows.Controls.TextBlock]$Metadata,
        [ValidateNotNullOrEmpty()][string]$LinkType = 'article'
    )

    try {
        $parsedUri = $null
        if (-not [uri]::TryCreate($Uri, [System.UriKind]::Absolute, [ref]$parsedUri) -or
            $parsedUri.Scheme -notin @('http', 'https')) {
            throw 'The link must have an absolute HTTP or HTTPS link.'
        }
        Start-Process -FilePath $Uri -ErrorAction Stop
    }
    catch {
        $message = ConvertTo-SanitizedDiagnosticText -Text $_.Exception.Message
        $Metadata.Text = "Cannot open ${LinkType}: $message"
        Write-Verbose $Metadata.Text
    }
}

function Open-DashboardArticle {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][AllowEmptyString()][AllowNull()][string]$Uri,
        [Parameter(Mandatory)][System.Windows.Controls.TextBlock]$Metadata
    )
    Open-DashboardLink -Uri $Uri -Metadata $Metadata -LinkType 'article'
}

function New-DashboardLinkButton {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][System.Windows.UIElement]$Content,
        [Parameter(Mandatory)][System.Windows.Controls.TextBlock]$Metadata,
        [Parameter(Mandatory)][string]$Name,
        [Parameter(Mandatory)][string]$Description,
        [Parameter(Mandatory)][AllowEmptyString()][AllowNull()][string]$Uri,
        [ValidateNotNullOrEmpty()][string]$LinkType = 'article'
    )

    $button = [System.Windows.Controls.Button]::new()
    $button.Content = $Content
    $button.Tag = $Uri
    $button.SetResourceReference([System.Windows.FrameworkElement]::StyleProperty, 'DashboardArticleButtonStyle')
    Set-DashboardControlAccessibility -Control $button -Name $Name -Description $Description
    $openCommand = Get-Command Open-DashboardLink -CommandType Function -ErrorAction Stop
    $originalMetadata = $Metadata.Text
    $button.Add_Click({
            param($sender, $eventArgs)
            $Metadata.Text = $originalMetadata
            & $openCommand -Uri ([string]$sender.Tag) -Metadata $Metadata -LinkType $LinkType
        }.GetNewClosure())
    $button
}

function New-DashboardNewsArticleButton {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][System.Windows.UIElement]$Content,
        [Parameter(Mandatory)][System.Windows.Controls.TextBlock]$Metadata,
        [Parameter(Mandatory)][string]$Title,
        [Parameter(Mandatory)][string]$Source,
        [Parameter(Mandatory)][AllowEmptyString()][AllowNull()][string]$Uri
    )
    New-DashboardLinkButton -Content $Content -Metadata $Metadata -Uri $Uri `
        -Name "Open article: $Title" `
        -Description "Read the original article from $Source. Press Enter or Space to open it."
}

function New-DashboardExchangeButton {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][System.Windows.UIElement]$Content,
        [Parameter(Mandatory)][string]$Code,
        [Parameter(Mandatory)][string]$Name
    )
    $button = [System.Windows.Controls.Button]::new()
    $button.Content = $Content
    $button.Tag = $Code
    $button.SetResourceReference([System.Windows.FrameworkElement]::StyleProperty, 'DashboardExchangeButtonStyle')
    Set-DashboardControlAccessibility -Control $button -Name "Exchange details: $Name" `
        -Description 'Press Enter or Space to open exchange details. Escape closes details and returns focus.'
    $showCommand = Get-Command Show-ExchangeFlyout -CommandType Function -ErrorAction Stop
    $button.Add_Click({
            param($sender, $eventArgs)
            & $showCommand -ExchangeCode ([string]$sender.Tag) -Invoker $sender
            $eventArgs.Handled = $true
        }.GetNewClosure())
    $button
}