Files
helder/Sources/HelderUI/State/WorkspaceModel+ContextActions.swift
T
2026-10-30 13:21:45 +01:00

166 lines
7.7 KiB
Swift

import CoreGraphics
import Foundation
import HelderCore
import HelderServices
extension WorkspaceModel {
/// Runs a context-menu action; one the config or the Explorer guards asks first through the confirm overlay.
public func perform(_ action: ContextAction) {
let anchor = takeMenuAnchor()
if let request = sourceControl?.confirmation(for: action) ?? explorer?.confirmation(for: action) {
overlay.present(.confirm(request))
} else {
execute(action, anchor: anchor)
}
}
func showContextMenu(_ target: ContextTarget, anchor: CGPoint) {
overlay.present(.contextMenu(ContextMenuRequest(
target: target,
header: ContextActions.header(for: target, projectName: name),
entries: ContextActions.entries(for: target),
anchor: anchor
)))
}
/// Closes an open context menu and returns where it stood, so a prompt it opens appears in the same place.
private func takeMenuAnchor() -> CGPoint {
guard case let .contextMenu(menu) = overlay.current else { return defaultAnchor }
overlay.dismiss()
return menu.anchor
}
var defaultAnchor: CGPoint {
CGPoint(x: (layout.span(of: .editor)?.lowerBound ?? 0) + 60, y: 150)
}
func confirmPending() {
guard case let .confirm(request) = overlay.current else { return }
overlay.dismiss()
execute(request.action, anchor: defaultAnchor)
}
// MARK: Row menus
/// ⌘→ in the Explorer: the selected row's menu, beside the column at the row's height.
func openRowMenu() {
guard layout.activePanel == .explorer, let row = selectedTreeRow() else { return }
showContextMenu(ExplorerStore.target(for: row.row),
anchor: rowMenuAnchor(.explorer, frame: rowFrames[.tree(row.row.path)],
estimate: row.index, rowHeight: Metrics.explorerRow))
}
func selectedTreeRow() -> (row: TreeRow, index: Int)? {
guard let explorer else { return nil }
let rows = explorer.rows(showHidden: layout.showHidden)
guard let index = rows.firstIndex(where: { $0.path == explorer.selectedPath }) else { return nil }
return (rows[index], index)
}
/// Row menus open beside the column, never over its rows, level with the row; a row that never
/// reported its frame is placed by its index, which is off once the list scrolls.
func rowMenuAnchor(_ panel: Panel, frame: CGRect?, estimate index: Int, rowHeight: CGFloat) -> CGPoint {
let x = layout.span(of: panel)?.upperBound ?? 220
let y = frame.map { $0.minY + 4 } ?? Metrics.titleBar + Metrics.panelHeader + CGFloat(index) * rowHeight + 4
return CGPoint(x: x, y: y)
}
// MARK: Running actions
/// Runs an action that needs no (more) confirmation. The stores are read before any await,
/// so an action still running after a project switch never lands in the new project.
func execute(_ action: ContextAction, anchor: CGPoint) {
let sourceControl = sourceControl, explorer = explorer, editor = editor
switch action {
case let .passOnReference(reference, code):
closeGitView()
overlay.present(.passOn(PassOnRequest(reference: reference, code: code, anchor: anchor)))
case let .openFile(path):
closeGitView()
open(path)
case let .commit(andPush):
track { await sourceControl?.commit(andPush: andPush) }
case let .passOnFileName(name):
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
case let .bouwen(name):
passToAgent("/bouwen \(name)", toast: "/bouwen \(name)")
case let .waitWhat(kind):
if let text = terminal.selection(kind)?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty {
passToAgent("/wait-what `\(text)`", toast: "/wait-what")
}
case let .readAloudText(text):
readAloud.read(text)
case let .readAloudFile(path):
readAloudFile(path)
case let .readAloudTerminalSelection(kind):
let text = terminal.selection(kind)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let prose = MarkdownSpeech.plainText(MarkdownParser.parse(text))
if !readAloud.read(prose.isEmpty ? text : prose) { toasts.show("Nothing to read") }
case let .plak(text):
sendToPlak(text)
case let .plakTerminalSelection(kind):
sendToPlak(terminal.selection(kind) ?? "")
case let .newFile(directory):
overlay.present(.namePrompt(NamePromptRequest(purpose: .newFile(inDirectory: directory), anchor: anchor)))
case let .newFolder(directory):
overlay.present(.namePrompt(NamePromptRequest(purpose: .newFolder(inDirectory: directory), anchor: anchor)))
case let .rename(path, isDirectory):
overlay.present(.namePrompt(NamePromptRequest(purpose: .rename(path: path, isDirectory: isDirectory),
initialName: PathUtils.basename(path), anchor: anchor)))
case let .showDiff(path, line):
if editor?.activePath == path { editor?.openDiff(atLine: line) }
case let .copyTerminalSelection(kind):
if let text = terminal.selection(kind) { app.system.copy(text) }
case let .pasteIntoTerminal(kind):
if let text = app.system.pasteboardText() { terminal.paste(text, into: kind) }
case let .gitDiscard(paths):
track {
await sourceControl?.discard(paths)
for path in paths where editor?.isLoaded(path) == true { await editor?.reloadFromDisk(path) }
}
case let .delete(path, isDirectory):
track {
guard await explorer?.deleteEntry(path, isDirectory: isDirectory) == true else { return }
editor?.forget(path, isDirectory: isDirectory)
await sourceControl?.refresh()
}
default:
track { _ = await explorer?.perform(action) }
}
}
private func sendToPlak(_ text: String) {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty { toasts.show("Nothing to send") } else { app.system.sendToPlak(trimmed) }
}
/// The open file is read from its buffer, unsaved edits included; any other file from disk.
private func readAloudFile(_ path: String) {
let live = editor.flatMap { $0.activePath == path && $0.isLoaded(path) ? $0.text(for: path) : nil }
let files = services?.files
track {
var text = live
if text == nil, case let .text(disk)? = try? await files?.readText(path) { text = disk }
guard !Task.isCancelled else { return }
let prose = MarkdownSpeech.plainText(MarkdownParser.parse(text ?? ""))
if !self.readAloud.read(prose) { self.toasts.show("Nothing to read", detail: path) }
}
}
func submitName(_ name: String) {
guard case let .namePrompt(request) = overlay.current else { return }
overlay.dismiss()
guard let explorer else { return }
let sourceControl = sourceControl, editor = editor
track {
guard let path = await explorer.submitName(name, for: request.purpose) else { return }
switch request.purpose {
case .newFile: if self.editor === editor { self.open(path) }
case .newFolder: break
case let .rename(old, isDirectory): editor?.remap(from: old, to: path, isDirectory: isDirectory)
}
await sourceControl?.refresh()
}
}
}