feat(panel): close with Esc without a click and render Markdown

Esc: make the panel key when shown (closeWithEscape, default on) without activating the app; the source app stays frontmost and Replace still targets it. Handle Esc with SwiftUI's exit command, which also works from the popover and after clicking controls. Add TranslationPanel.canBecomeKey and amend ADR-009.\n\nMarkdown: add MarkdownPresentation in SprachmittlerText (Foundation inline parser plus a conservative block parser for headings, lists, quotes, fenced code and rules), a SwiftUI MarkdownTranslationView, and a renderMarkdown setting (default on). JSON, HTML and code sources are never rendered; only http/https links open; images become alt text; Copy and Replace keep the raw Markdown (ADR-021).\n\nVerified: make verify green; synthetic Esc closes the panel and closes an open language popover first; a live Markdown translation rendered heading, bold/italic, inline code, list, quote, code block and link; Copy returned the raw Markdown; Replace still changed the TextEdit selection with the panel key.
This commit is contained in:
schihei committed 2026-11-26 15:26:30 +01:00
1 parent d126124f97
commit a3e544fbe4
22 files changed
+1072 -250

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
import AppKit
import SprachmittlerText
import SwiftUI
/// Renders a translation as formatted Markdown. Copy and Replace still use the raw translation.
struct MarkdownTranslationView: View {
let markdown: String
let fontSize: Int
let isRTL: Bool
private let blocks: [MarkdownBlock]
init(markdown: String, fontSize: Int, isRTL: Bool) {
self.markdown = markdown
self.fontSize = fontSize
self.isRTL = isRTL
blocks = MarkdownPresentation.blocks(in: markdown)
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(blocks.indices, id: \.self) { index in
block(blocks[index])
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.environment(\.layoutDirection, isRTL ? .rightToLeft : .leftToRight)
.environment(\.openURL, OpenURLAction { url in
guard MarkdownPresentation.isAllowedLink(url) else { return .discarded }
NSWorkspace.shared.open(url)
return .handled
})
.accessibilityElement(children: .contain)
.accessibilityLabel(String(localized: "Translation"))
}
private var baseSize: CGFloat {
CGFloat(fontSize)
}
@ViewBuilder private func block(_ block: MarkdownBlock) -> some View {
switch block {
case let .paragraph(text):
inlineText(text, size: baseSize)
case let .heading(level, text):
inlineText(text, size: baseSize * headingScale(level), weight: .bold)
.accessibilityAddTraits(.isHeader)
case let .listItem(ordered, number, indent, text):
HStack(alignment: .firstTextBaseline, spacing: 6) {
Text(ordered ? "\(number)." : "•")
.font(.system(size: baseSize, weight: ordered ? .regular : .bold))
.foregroundStyle(.secondary)
.frame(minWidth: ordered ? 18 : 12, alignment: .trailing)
.accessibilityHidden(true)
inlineText(text, size: baseSize)
}
.padding(.leading, CGFloat(indent) * 14)
case let .quote(text):
HStack(alignment: .top, spacing: 8) {
Rectangle()
.fill(.secondary.opacity(0.35))
.frame(width: 3)
.accessibilityHidden(true)
inlineText(text, size: baseSize)
.foregroundStyle(.secondary)
}
case let .codeBlock(_, text):
ScrollView(.horizontal, showsIndicators: false) {
Text(verbatim: text)
.font(.system(size: baseSize * 0.95, design: .monospaced))
.textSelection(.enabled)
.fixedSize(horizontal: true, vertical: false)
.padding(10)
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(.primary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))
.environment(\.layoutDirection, .leftToRight)
case .rule:
Divider()
.padding(.vertical, 2)
}
}
private func inlineText(_ text: String, size: CGFloat, weight: Font.Weight = .regular) -> some View {
Text(styled(text, size: size))
.font(.system(size: size, weight: weight))
.textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
private func styled(_ text: String, size: CGFloat) -> AttributedString {
var attributed = MarkdownPresentation.inline(text)
let runs = attributed.runs.compactMap { run -> (Range<AttributedString.Index>, InlinePresentationIntent)? in
guard let intent = run.inlinePresentationIntent else { return nil }
let relevant = intent.contains(.stronglyEmphasized)
|| intent.contains(.emphasized)
|| intent.contains(.code)
return relevant ? (run.range, intent) : nil
}
for (range, intent) in runs {
if intent.contains(.code) {
var font = Font.system(size: size * 0.95, design: .monospaced)
if intent.contains(.stronglyEmphasized) {
font = font.bold()
}
if intent.contains(.emphasized) {
font = font.italic()
}
attributed[range].font = font
} else {
var font = Font.system(
size: size,
weight: intent.contains(.stronglyEmphasized) ? .bold : .regular
)
if intent.contains(.emphasized) {
font = font.italic()
}
attributed[range].font = font
}
}
return attributed
}
private func headingScale(_ level: Int) -> CGFloat {
switch level {
case 1: 1.6
case 2: 1.45
case 3: 1.3
case 4: 1.2
case 5: 1.12
default: 1.06
}
}
}
+8 -4
View File
@@ -2,16 +2,17 @@ import AppKit
import SprachmittlerCore
import SwiftUI
/// The non-activating floating panel. It never activates the app or steals focus.
/// The non-activating floating panel. It never activates the app. While visible it can be the key
/// window so Esc and the keyboard shortcuts work without a click.
@MainActor
final class PanelController: NSObject, NSWindowDelegate {
private let panel: NSPanel
private let panel: TranslationPanel
private let viewModel: PanelViewModel
/// Creates the panel and its SwiftUI content.
init(viewModel: PanelViewModel) {
self.viewModel = viewModel
panel = NSPanel(
panel = TranslationPanel(
contentRect: NSRect(x: 0, y: 0, width: 540, height: 520),
styleMask: [.titled, .fullSizeContentView, .nonactivatingPanel],
backing: .buffered,
@@ -21,7 +22,7 @@ final class PanelController: NSObject, NSWindowDelegate {
panel.delegate = self
panel.isFloatingPanel = true
panel.isMovable = true
panel.becomesKeyOnlyIfNeeded = true
panel.becomesKeyOnlyIfNeeded = false
panel.level = .floating
panel.hidesOnDeactivate = false
panel.isMovableByWindowBackground = true
@@ -50,6 +51,9 @@ final class PanelController: NSObject, NSWindowDelegate {
positionNearMouse()
}
panel.orderFrontRegardless()
if viewModel.configuration.closeWithEscape {
panel.makeKey()
}
}
/// Hides the panel and cancels/releases its content.
+222
View File
@@ -0,0 +1,222 @@
import AppKit
import SprachmittlerCore
import SprachmittlerText
import SwiftUI
extension PanelView {
private var rendersMarkdown: Bool {
!model.translation.isEmpty
&& model.configuration.renderMarkdown
&& MarkdownPresentation.shouldRender(
source: model.source?.text ?? "",
translation: model.translation
)
}
var translationArea: some View {
ScrollView {
translationContent
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(minHeight: 120, maxHeight: 260)
.padding(10)
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
.overlay(alignment: .topTrailing) {
if model.phase == .translating || model.phase == .streaming {
ProgressView()
.controlSize(.small)
.padding(8)
.accessibilityLabel(String(localized: "Translating"))
}
}
}
@ViewBuilder var translationContent: some View {
if rendersMarkdown {
MarkdownTranslationView(
markdown: model.translation,
fontSize: model.configuration.translationFontSize,
isRTL: model.configuration.target.isRTL
)
} else {
Text(translationText)
.font(.system(size: CGFloat(model.configuration.translationFontSize)))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundStyle(model.translation.isEmpty ? .secondary : .primary)
.environment(
\.layoutDirection,
model.configuration.target.isRTL ? .rightToLeft : .leftToRight
)
.accessibilityLabel(String(localized: "Translation"))
}
}
var translationText: String {
if !model.translation.isEmpty {
return model.translation
}
switch model.phase {
case .translating, .streaming:
return String(localized: "Translating…")
case .failed:
return String(localized: "No translation.")
case .idle, .ready:
return String(localized: "No translation yet.")
}
}
@ViewBuilder var warningArea: some View {
if model.sameLanguageWarning != nil {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "info.circle.fill").foregroundStyle(.blue)
Text("This text already appears to be in \(model.configuration.target.localizedDisplayName).")
.font(.callout)
Spacer()
Button(String(localized: "Translate anyway")) {
model.dismissSameLanguageWarning()
}
.controlSize(.small)
}
.padding(8)
.background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
}
ForEach(Array(visibleWarnings.enumerated()), id: \.offset) { _, warning in
HStack(alignment: .top, spacing: 8) {
Image(systemName: warning.isBlocking ? "exclamationmark.triangle.fill" : "exclamationmark.circle")
.foregroundStyle(warning.isBlocking ? .orange : .secondary)
Text(warning.panelMessage)
.font(.callout)
Spacer()
}
.padding(8)
.background(
(warning.isBlocking ? Color.orange : Color.secondary)
.opacity(0.08),
in: RoundedRectangle(cornerRadius: 8)
)
.accessibilityLabel(warning.panelMessage)
}
}
var visibleWarnings: [TranslationWarning] {
model.warnings.filter { warning in
if case .sameLanguage = warning {
return false
}
return true
}
}
@ViewBuilder var errorArea: some View {
if let message = model.errorMessage, model.phase == .failed {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "exclamationmark.octagon.fill")
.foregroundStyle(.red)
VStack(alignment: .leading, spacing: 6) {
Text(message)
.font(.callout)
if let action = model.recoveryAction {
recoveryButton(action)
}
}
Spacer()
}
.padding(8)
.background(.red.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
.accessibilityLabel(message)
}
}
@ViewBuilder func recoveryButton(_ action: RecoveryAction) -> some View {
switch action {
case .startOllama:
if let url = URL(string: "https://ollama.com/download") {
Link(String(localized: "Download Ollama"), destination: url)
.controlSize(.small)
}
case let .pullModel(modelName):
Button(String(localized: "Copy pull command")) {
model.copy("ollama pull \(modelName)")
}
.controlSize(.small)
case .openSettings:
if model.error == .accessibilityNotTrusted, let url = accessibilitySettingsURL {
Button(String(localized: "Open Accessibility Settings")) {
NSWorkspace.shared.open(url)
}
.controlSize(.small)
} else {
Button(String(localized: "Open Settings")) {
openSettings()
}
.controlSize(.small)
}
case .copyInstead:
Button(String(localized: "Copy instead")) {
model.copyTranslation()
}
.controlSize(.small)
case .shortenText:
EmptyView()
case .retry:
Button(String(localized: "Retry")) {
Task { await model.retry() }
}
.controlSize(.small)
case .none:
EmptyView()
}
}
var accessibilitySettingsURL: URL? {
URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
}
var footer: some View {
HStack(spacing: 10) {
Button {
model.copyTranslation()
} label: {
Label(
model.didCopy ? String(localized: "Copied") : String(localized: "Copy"),
systemImage: "doc.on.doc"
)
}
.keyboardShortcut("c", modifiers: .command)
.disabled(!model.canCopy)
.accessibilityLabel(String(localized: "Copy translation"))
Button {
Task { await model.retry() }
} label: {
Label(String(localized: "Retry"), systemImage: "arrow.clockwise")
}
.keyboardShortcut("r", modifiers: .command)
.disabled(model.source == nil)
.accessibilityLabel(String(localized: "Retry translation"))
Spacer()
Button {
onClose()
} label: {
Text(String(localized: "Close"))
}
.keyboardShortcut(.cancelAction)
.accessibilityLabel(String(localized: "Close panel"))
Button {
Task { await model.replaceSelection() }
} label: {
Text(String(localized: "Replace"))
}
.keyboardShortcut(.return, modifiers: .command)
.buttonStyle(.borderedProminent)
.disabled(!model.canReplace)
.help(model.replaceUnavailableReason ?? String(localized: "Replace the selection"))
.accessibilityLabel(String(localized: "Replace selection"))
}
}
}
+2 -195
View File
@@ -1,5 +1,6 @@
import AppKit
import SprachmittlerCore
import SprachmittlerText
import SwiftUI
/// The translation panel view. It never activates the app.
@@ -7,7 +8,7 @@ struct PanelView: View {
@Bindable var model: PanelViewModel
let onClose: @MainActor () -> Void
@Environment(\.openSettings) private var openSettings
@Environment(\.openSettings) var openSettings
@State private var showLanguagePicker = false
@State private var showSource = true
@@ -127,198 +128,4 @@ struct PanelView: View {
.help(showSource ? String(localized: "Hide source") : String(localized: "Show source"))
.accessibilityLabel(String(localized: "Source text"))
}
private var translationArea: some View {
ScrollView {
Text(translationText)
.font(.system(size: CGFloat(model.configuration.translationFontSize)))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundStyle(model.translation.isEmpty ? .secondary : .primary)
.environment(
\.layoutDirection,
model.configuration.target.isRTL ? .rightToLeft : .leftToRight
)
.accessibilityLabel(String(localized: "Translation"))
}
.frame(minHeight: 120, maxHeight: 260)
.padding(10)
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
.overlay(alignment: .topTrailing) {
if model.phase == .translating || model.phase == .streaming {
ProgressView()
.controlSize(.small)
.padding(8)
.accessibilityLabel(String(localized: "Translating"))
}
}
}
private var translationText: String {
if !model.translation.isEmpty {
return model.translation
}
switch model.phase {
case .translating, .streaming:
return String(localized: "Translating…")
case .failed:
return String(localized: "No translation.")
case .idle, .ready:
return String(localized: "No translation yet.")
}
}
@ViewBuilder private var warningArea: some View {
if model.sameLanguageWarning != nil {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "info.circle.fill").foregroundStyle(.blue)
Text("This text already appears to be in \(model.configuration.target.localizedDisplayName).")
.font(.callout)
Spacer()
Button(String(localized: "Translate anyway")) {
model.dismissSameLanguageWarning()
}
.controlSize(.small)
}
.padding(8)
.background(.blue.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
}
ForEach(Array(visibleWarnings.enumerated()), id: \.offset) { _, warning in
HStack(alignment: .top, spacing: 8) {
Image(systemName: warning.isBlocking ? "exclamationmark.triangle.fill" : "exclamationmark.circle")
.foregroundStyle(warning.isBlocking ? .orange : .secondary)
Text(warning.panelMessage)
.font(.callout)
Spacer()
}
.padding(8)
.background(
(warning.isBlocking ? Color.orange : Color.secondary)
.opacity(0.08),
in: RoundedRectangle(cornerRadius: 8)
)
.accessibilityLabel(warning.panelMessage)
}
}
private var visibleWarnings: [TranslationWarning] {
model.warnings.filter { warning in
if case .sameLanguage = warning {
return false
}
return true
}
}
@ViewBuilder private var errorArea: some View {
if let message = model.errorMessage, model.phase == .failed {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "exclamationmark.octagon.fill")
.foregroundStyle(.red)
VStack(alignment: .leading, spacing: 6) {
Text(message)
.font(.callout)
if let action = model.recoveryAction {
recoveryButton(action)
}
}
Spacer()
}
.padding(8)
.background(.red.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
.accessibilityLabel(message)
}
}
@ViewBuilder private func recoveryButton(_ action: RecoveryAction) -> some View {
switch action {
case .startOllama:
if let url = URL(string: "https://ollama.com/download") {
Link(String(localized: "Download Ollama"), destination: url)
.controlSize(.small)
}
case let .pullModel(modelName):
Button(String(localized: "Copy pull command")) {
model.copy("ollama pull \(modelName)")
}
.controlSize(.small)
case .openSettings:
if model.error == .accessibilityNotTrusted, let url = accessibilitySettingsURL {
Button(String(localized: "Open Accessibility Settings")) {
NSWorkspace.shared.open(url)
}
.controlSize(.small)
} else {
Button(String(localized: "Open Settings")) {
openSettings()
}
.controlSize(.small)
}
case .copyInstead:
Button(String(localized: "Copy instead")) {
model.copyTranslation()
}
.controlSize(.small)
case .shortenText:
EmptyView()
case .retry:
Button(String(localized: "Retry")) {
Task { await model.retry() }
}
.controlSize(.small)
case .none:
EmptyView()
}
}
private var accessibilitySettingsURL: URL? {
URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
}
private var footer: some View {
HStack(spacing: 10) {
Button {
model.copyTranslation()
} label: {
Label(
model.didCopy ? String(localized: "Copied") : String(localized: "Copy"),
systemImage: "doc.on.doc"
)
}
.keyboardShortcut("c", modifiers: .command)
.disabled(!model.canCopy)
.accessibilityLabel(String(localized: "Copy translation"))
Button {
Task { await model.retry() }
} label: {
Label(String(localized: "Retry"), systemImage: "arrow.clockwise")
}
.keyboardShortcut("r", modifiers: .command)
.disabled(model.source == nil)
.accessibilityLabel(String(localized: "Retry translation"))
Spacer()
Button {
onClose()
} label: {
Text(String(localized: "Close"))
}
.keyboardShortcut(.cancelAction)
.accessibilityLabel(String(localized: "Close panel"))
Button {
Task { await model.replaceSelection() }
} label: {
Text(String(localized: "Replace"))
}
.keyboardShortcut(.return, modifiers: .command)
.buttonStyle(.borderedProminent)
.disabled(!model.canReplace)
.help(model.replaceUnavailableReason ?? String(localized: "Replace the selection"))
.accessibilityLabel(String(localized: "Replace selection"))
}
}
}
+13
View File
@@ -0,0 +1,13 @@
import AppKit
/// The translation panel. It can become the key window without activating the app, so Esc and the
/// keyboard shortcuts work as soon as it is shown.
final class TranslationPanel: NSPanel {
override var canBecomeKey: Bool {
true
}
override var canBecomeMain: Bool {
false
}
}