# Interactive folder picker shared by the launcher and the TUI. # With fzf: browse folders, create a new one, or type a path. Without fzf: plain prompt. # Returns the chosen full path, or $null when cancelled (Esc / empty input and no default). function ConvertTo-FullFolderPath { param([string]$Path) if([string]::IsNullOrWhiteSpace($Path)) { return $null } $p = $Path.Trim().Trim('"', "'") -replace '^~', $HOME [IO.Path]::GetFullPath($p) } function Select-FolderPath { param( [Parameter(Mandatory)] [string]$Prompt, [string]$StartPath = (Get-Location).Path, # Used when the fallback prompt gets an empty answer [string]$Default ) if(-not (Get-Command fzf -ErrorAction SilentlyContinue)) { $suffix = if($Default) { " (Enter = $Default)" } else { "" } $typed = Read-Host "$Prompt$suffix" if([string]::IsNullOrWhiteSpace($typed)) { $typed = $Default } return (ConvertTo-FullFolderPath $typed) } # Start at the nearest folder that exists (the default root may not exist yet) $current = ConvertTo-FullFolderPath $StartPath while($current -and -not (Test-Path -LiteralPath $current -PathType Container)) { $current = Split-Path -Path $current -Parent } if(-not $current) { $current = (Get-Location).Path } while($true) { $entries = @("[Use this folder]", "[Create new folder]", "[Type path manually]") $parent = Split-Path -Path $current -Parent if($parent) { $entries += ".." } $entries += Get-ChildItem -LiteralPath $current -Directory -ErrorAction SilentlyContinue | Sort-Object Name | ForEach-Object { "$($_.Name)/" } $choice = $entries | fzf --header="$Prompt [current: $current]" if(-not $choice) { return $null } switch ($choice) { "[Use this folder]" { return $current } "[Create new folder]" { $name = (Read-Host "New folder name (inside $current)").Trim() if([string]::IsNullOrWhiteSpace($name)) { continue } if($name.IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0) { Write-Host "Invalid folder name." -ForegroundColor Yellow; continue } $newPath = Join-Path $current $name try { New-Item -ItemType Directory -Path $newPath -Force -ErrorAction Stop | Out-Null; $current = $newPath } catch { Write-Host "Could not create folder: $($_.Exception.Message)" -ForegroundColor Yellow } continue } "[Type path manually]" { $typed = Read-Host "Enter path"; if(-not [string]::IsNullOrWhiteSpace($typed)) { return (ConvertTo-FullFolderPath $typed) }; continue } ".." { $current = $parent; continue } default { $current = Join-Path $current ($choice.TrimEnd('/')); continue } } } }