// // 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. // #162 (map #158): the chrome lineage GROWS the Cold Turkey lock — the // corner dot, arm-bar, readout, and completion note live here too. // 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: View { let edge: HoverZone.Edge let panelWidth: CGFloat @ViewBuilder var content: () -> Content @State private var revealed = false @State private var hideTask: Task? 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: - Cold Turkey chrome (#162, map #158) /// The Cold Turkey seat: one bottom-center position, one lineage — the /// arm-bar before Start, the live readout while locked, the completion /// note on quiet return (never two at once, per the contract render). /// Seat = BARE mono on the focus ground — no chip box; Start's accent /// fill is the only boxed element anywhere in the lineage. struct ColdTurkeySeat: View { @Environment(AppGateState.self) private var gate var body: some View { let lock = gate.writingLock ZStack { if lock.showsArmBar, !lock.isLocked { ColdTurkeyArmBar() .transition(.opacity) } else if lock.isLocked, let run = lock.run { ColdTurkeyReadout(run: run, now: lock.now) .transition(.opacity) } else if let note = lock.completionNote { ColdTurkeyNote(text: note) .transition(.opacity) } } .padding(.bottom, 46) .animation(.easeInOut(duration: 0.2), value: lock.isLocked) .animation(.easeInOut(duration: 0.2), value: lock.showsArmBar) .animation(.easeInOut(duration: 1.2), value: lock.completionNote) } } /// The arm-bar (#160): minutes|words selector + value stepper/entry + /// Start, quiet and non-modal on the focus ground. Esc dismisses — the /// hidden cancel-action button is the PostEditorView ⌘S rail (key /// equivalents ride the menu machinery, which DOES reach behind the /// hosting view — unlike `.onExitCommand`, the #109 Esc probe). /// Amendment (2026-11-04, live dogfood): the bar carries a chip that /// BLENDS into the focus ground — the ground's own color, the faintest /// token hairline, no shadow. The bare seat let the document text show /// through and obscure the controls; blending, not transparency, is the /// ruling now. The value is directly typeable (± steppers stay for the /// coarse moves); defaults 250 words / 5 minutes. private struct ColdTurkeyArmBar: View { @Environment(AppGateState.self) private var gate @State private var minutes = false /// The typeable value for the selected kind — parsed and clamped at /// every read (Start, steppers, submit), so unsubmitted or garbage /// text can never arm an out-of-range block. Switching kinds resets /// it to that kind's default. @State private var fieldText = String(WritingLockState.ArmScale.words.defaultValue) private var scale: WritingLockState.ArmScale { minutes ? .minutes : .words } private var value: Int { scale.parse(fieldText) } private var goal: WritingGoal { minutes ? .minutes(value) : .words(value) } /// Rewrite the field to the clamped value (submit, kind switch). private func commitField() { fieldText = String(value) } var body: some View { VStack(spacing: 9) { HStack(spacing: 14) { selectorButton("Words", isOn: !minutes) { minutes = false fieldText = String(WritingLockState.ArmScale.words.defaultValue) } selectorButton("Minutes", isOn: minutes) { minutes = true fieldText = String(WritingLockState.ArmScale.minutes.defaultValue) } } HStack(spacing: 10) { stepButton("−") { fieldText = String(scale.clamp(value - scale.step)) } HStack(alignment: .firstTextBaseline, spacing: 7) { TextField("", text: $fieldText) .textFieldStyle(.plain) .font(.system(size: 13, design: DesignTokens.mono)) .kerning(0.5) .multilineTextAlignment(.center) .foregroundStyle(DesignTokens.foreground) .frame(width: 56) .onSubmit(commitField) Text(minutes ? "MIN" : "WORDS") .font(.system(size: 10, design: DesignTokens.mono)) .kerning(0.8) .textCase(.uppercase) .foregroundStyle(DesignTokens.muted) } stepButton("+") { fieldText = String(scale.clamp(value + scale.step)) } Button("Start") { gate.startWritingLock(goal: goal) } .buttonStyle(.plain) .font(.system(size: 11, design: DesignTokens.mono)) .kerning(0.7) .textCase(.uppercase) .foregroundStyle(DesignTokens.surface) .padding(.horizontal, 16) .frame(height: 28) .background(DesignTokens.accent, in: RoundedRectangle(cornerRadius: 6)) } Text("esc dismisses · nothing armed yet") .font(.system(size: 9, design: DesignTokens.mono)) .kerning(0.8) .textCase(.uppercase) .foregroundStyle(DesignTokens.muted.opacity(0.7)) } .padding(.horizontal, 16) .padding(.vertical, 12) .blendingChip() .background { Button("") { gate.writingLock.showsArmBar = false } .keyboardShortcut(.cancelAction) .opacity(0) .frame(width: 1, height: 1) .accessibilityHidden(true) } } /// Selector tab: mono-10 uppercase, the selected kind carries a 2px /// accent underline (the render's `border-bottom` language). private func selectorButton(_ title: String, isOn: Bool, action: @escaping () -> Void) -> some View { Button(action: action) { Text(title) .font(.system(size: 10, design: DesignTokens.mono)) .kerning(0.8) .textCase(.uppercase) .foregroundStyle(isOn ? DesignTokens.foreground : DesignTokens.muted) .padding(.bottom, 3) .overlay(alignment: .bottom) { if isOn { Rectangle() .fill(DesignTokens.accent) .frame(height: 2) } } } .buttonStyle(.plain) } /// Bare stepper — no box (ruling 1: Start is the only boxed element). private func stepButton(_ glyph: String, action: @escaping () -> Void) -> some View { Button(action: action) { Text(glyph) .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.foreground) .frame(width: 26, height: 26) } .buttonStyle(.plain) } } /// The live readout while locked: numerals + unit (numerals only — the /// piece title is ruled absent) over the 2px progress hairline. Near /// goal (inside the last 20 %) the numerals flip terracotta. private struct ColdTurkeyReadout: View { let run: WritingGoalRun let now: Date private var progress: Double { run.progress(now: now) } var body: some View { let shape = WritingLockState.readout(run, now: now) VStack(spacing: 3) { HStack(alignment: .firstTextBaseline, spacing: 7) { Text(shape.numerals) .font(.system(size: 13, design: DesignTokens.mono)) .kerning(0.65) .foregroundStyle( WritingLockState.isNearGoal(progress: progress) ? DesignTokens.accent.opacity(0.8) : DesignTokens.foreground, ) Text(shape.unit) .font(.system(size: 10, design: DesignTokens.mono)) .kerning(0.8) .textCase(.uppercase) .foregroundStyle(DesignTokens.muted) } ZStack(alignment: .leading) { Rectangle() .fill(DesignTokens.foreground.opacity(0.06)) .frame(width: 148, height: 2) Rectangle() .fill(DesignTokens.accent) .frame(width: max(0, 148 * progress), height: 2) } .clipShape(Capsule()) } .padding(.horizontal, 16) .padding(.vertical, 8) .blendingChip() .allowsHitTesting(false) } } /// The completion note: `● 500 words · 14:02`, bare mono, fading ~6 s /// (the fade task lives in the state; the transition lives here). private struct ColdTurkeyNote: View { let text: String var body: some View { HStack(spacing: 8) { Text("●") .foregroundStyle(DesignTokens.accent) Text(text) .foregroundStyle(DesignTokens.muted) } .font(.system(size: 11, design: DesignTokens.mono)) .kerning(0.88) .textCase(.uppercase) .padding(.horizontal, 14) .padding(.vertical, 8) .blendingChip() .allowsHitTesting(false) } } /// The persistent dot (#160 ruling 6): the quiet always-there Cold /// Turkey presence in plain focus — muted 6px pip tucked bottom-right, /// terracotta + label on hover, click opens the arm-bar. Hidden while /// the bar is up or a block runs, and wherever there is nothing prose /// to lock (Posts + drafts + the guest, never Outline — #158 settle 11). struct ColdTurkeyDot: View { @Environment(AppGateState.self) private var gate var model: PostsModel @State private var hover = false var body: some View { let lock = gate.writingLock if !lock.isLocked, !lock.showsArmBar, model.canArmWritingLock { Button { lock.showsArmBar = true } label: { HStack(spacing: 8) { Circle() .fill(hover ? DesignTokens.accent : DesignTokens.muted) .frame(width: 6, height: 6) if hover { Text("Cold Turkey") .font(.system(size: 10, design: DesignTokens.mono)) .kerning(0.8) .textCase(.uppercase) .foregroundStyle(DesignTokens.muted.opacity(0.85)) .transition(.opacity) } } .padding(6) } .buttonStyle(.plain) .onHover { hover = $0 } .animation(.easeInOut(duration: 0.15), value: hover) .padding(.bottom, 12) .padding(.trailing, 14) .help("Start Cold Turkey") .accessibilityLabel("Start Cold Turkey") } } } /// The 2026-11-04 dogfood amendment's chip, ONE definition for the /// seat's three surfaces (arm-bar, readout, note): the focus ground's /// own color + the token hairline (the faintest line the palette has), /// no shadow — blending, not transparency. Padding stays per-site. private extension View { func blendingChip() -> some View { background(DesignTokens.background, in: RoundedRectangle(cornerRadius: DesignTokens.radius)) .overlay( RoundedRectangle(cornerRadius: DesignTokens.radius) .strokeBorder(DesignTokens.border), ) } } // 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 } /// #21 calibration defect: typing at the document END (the natural /// writing position) parked at the bottom clamp and no-oped — the caret /// rode the lower edge forever. Breathing room: pad the document by /// half the viewport so the clamp can center the last lines (and the /// first — the inset is symmetric). ponytail: window resizes between /// updateNSView passes re-sync on the next keystroke via the guard. /// Calibration amendment (2026-10-09): typewriter is EDITOR-WIDE, not /// focus-gated — Alexander's call at the #88 gate; revert = restore the /// focused guard at the call sites. @MainActor static func syncTypewriterInset(textView: NSTextView) { guard let clip = textView.enclosingScrollView?.contentView else { return } let target = clip.bounds.height / 2 guard textView.textContainerInset.height != target else { return } textView.textContainerInset = NSSize(width: 0, height: target) // Re-clamp the origin to the resized document (short-doc floor). textView.scrollRangeToVisible(textView.selectedRange()) } /// 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 } syncTypewriterInset(textView: textView) 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)) } } }