Files
museion/Museion/FocusChrome.swift
T
AlexKucera d07d41859a fix(workspace): audit fixes — dedupe failure chip, width-guard mentor overlay, a11y, NSColor bridge (#87)
Reviewer fan-out (ponytail/security/general) synthesis:
- one failure surface in focus (chip carries it; toolbar stays recessed)
- draft '⌘S saves' cue in focus (drafts have no autosave)
- mentor reveal honors the #17 width verdict
- hidden overlay panels leave the accessibility tree
- NSColor(DesignTokens.background) bridge replaces the twin constant
- HoverZone width plumbing deleted, zoneWidth hoisted as the knob
- single >=1100 threshold read in WorkspaceView
2026-10-09 11:42:14 +02:00

192 lines
6.2 KiB
Swift

//
// FocusChrome.swift
// Museion
//
// #21 (map #21): focus-mode machinery — the edge hover sensor, the overlay
// panel that reveals recessed panes (rail+library left, mentor right), and
// the soft caret centering. Panes NEVER push the measure: revealed panels
// float above the surface and slide off when hover ends. Animation feel is
// the fog's "slide curve" knob — calibrate here if not-calm.
//
import AppKit
import SwiftUI
// MARK: - Edge hover sensor
/// Edge hover sensor: a tracking-area strip down one window edge that reports
/// pointer enter/leave and is transparent to clicks (`hitTest → nil`) — hover
/// must never steal a click from the text underneath.
struct HoverZone: NSViewRepresentable {
enum Edge { case leading, trailing }
/// Calibration knob: edge sensor strip width (pt).
static let zoneWidth: CGFloat = 14
var edge: Edge
var onHover: @MainActor (Bool) -> Void
final class SensorView: NSView {
var edge: Edge = .leading
var onHover: ((Bool) -> Void)?
private var trackingArea: NSTrackingArea?
override func updateTrackingAreas() {
super.updateTrackingAreas()
if let trackingArea {
removeTrackingArea(trackingArea)
}
let stripX = edge == .leading ? 0 : max(0, bounds.width - HoverZone.zoneWidth)
let area = NSTrackingArea(
rect: NSRect(x: stripX, y: 0, width: min(HoverZone.zoneWidth, bounds.width), height: bounds.height),
options: [.mouseEnteredAndExited, .activeInActiveApp],
owner: self,
userInfo: nil,
)
addTrackingArea(area)
trackingArea = area
}
override func mouseEntered(with _: NSEvent) {
onHover?(true)
}
override func mouseExited(with _: NSEvent) {
onHover?(false)
}
/// Click-through: a sensor, not a surface.
override func hitTest(_: NSPoint) -> NSView? {
nil
}
}
func makeNSView(context _: Context) -> SensorView {
let view = SensorView()
configure(view)
return view
}
func updateNSView(_ view: SensorView, context _: Context) {
configure(view)
}
private func configure(_ view: SensorView) {
view.edge = edge
view.onHover = onHover
}
}
// MARK: - Overlay panel
/// A recessed pane revealed by edge hover: the sensor strip runs down the
/// window edge; the panel slides in from that edge, floating OVER the measure
/// (never pushing it), and slides out after a short grace when hover ends —
/// the grace covers the pointer's transit from zone to panel.
struct FocusOverlayPanel<Content: View>: View {
let edge: HoverZone.Edge
let panelWidth: CGFloat
@ViewBuilder var content: () -> Content
@State private var revealed = false
@State private var hideTask: Task<Void, Never>?
private let revealAnimation = Animation.easeOut(duration: 0.2)
private let hideAnimation = Animation.easeIn(duration: 0.15)
/// Grace covering the pointer's transit from the edge zone onto the panel.
private let transitGrace: Duration = .milliseconds(140)
var body: some View {
ZStack(alignment: edge == .leading ? .leading : .trailing) {
HoverZone(edge: edge) { hover($0) }
.frame(maxWidth: .infinity, maxHeight: .infinity)
content()
.background(DesignTokens.surface)
.shadow(color: .black.opacity(0.10), radius: 12, y: 0)
.frame(maxHeight: .infinity)
.allowsHitTesting(revealed)
.accessibilityHidden(!revealed)
.onHover { hover($0) }
.opacity(revealed ? 1 : 0)
.offset(x: revealed ? 0 : hiddenOffset)
}
}
/// Park just past the edge while hidden (8pt of clearance so the shadow
/// doesn't bleed in).
private var hiddenOffset: CGFloat {
edge == .leading ? -panelWidth - 8 : panelWidth + 8
}
private func hover(_ inside: Bool) {
hideTask?.cancel()
if inside {
if !revealed {
withAnimation(revealAnimation) { revealed = true }
}
} else {
hideTask = Task {
try? await Task.sleep(for: transitGrace)
guard !Task.isCancelled else { return }
withAnimation(hideAnimation) { revealed = false }
}
}
}
}
// MARK: - Soft caret centering (#21)
/// Soft caret centering (the Neo input, softened): keep the caret inside a
/// comfort band around the visible center WHILE TYPING — `centerCaretWhileTyping`
/// is called from `textDidChange` only, so scrollback and drag-selection never
/// get fought. No jump at the document bottom: the clamp parks the scroll at
/// the document edge and follows line by line as the document grows.
nonisolated enum CaretCentering {
/// Comfort band half-height (pt) around the visible center.
static let band: CGFloat = 60
/// The visible-origin Y that parks the caret back at the center, or nil
/// when it already sits inside the band (or the document clamp leaves the
/// origin where it is — e.g. typing at the very end of a short document).
/// Pure math — pinned by FocusModeTests.
static func targetOffset(
caretY: CGFloat,
visibleMinY: CGFloat,
visibleHeight: CGFloat,
documentHeight: CGFloat,
) -> CGFloat? {
let center = visibleMinY + visibleHeight / 2
guard abs(caretY - center) > band else { return nil }
let raw = caretY - visibleHeight / 2
let clamped = min(max(0, raw), max(0, documentHeight - visibleHeight))
guard abs(clamped - visibleMinY) > 0.5 else { return nil }
return clamped
}
/// Applied: animate the scroll so the caret settles back toward the
/// center. Typing only — never route scroll or selection events here.
@MainActor
static func centerCaretWhileTyping(textView: NSTextView) {
guard let window = textView.window else { return }
let sel = textView.selectedRange()
guard sel.length == 0, sel.location >= 0 else { return }
// firstRect(forCharacterRange:) answers in SCREEN coordinates.
let screenRect = textView.firstRect(forCharacterRange: sel, actualRange: nil)
let caret = textView.convert(window.convertFromScreen(screenRect), from: nil)
guard let clip = textView.enclosingScrollView?.contentView else { return }
let visible = textView.visibleRect
guard let target = targetOffset(
caretY: caret.midY,
visibleMinY: visible.minY,
visibleHeight: visible.height,
documentHeight: textView.bounds.height,
) else { return }
NSAnimationContext.runAnimationGroup { ctx in
ctx.duration = 0.18
ctx.allowsImplicitAnimation = true
clip.animator().setBoundsOrigin(NSPoint(x: visible.minX, y: target))
}
}
}