import AppKit import SwiftUI /// A 1pt hairline divider that resizes what is next to it. The pointer target reaches 3pt past the line /// on both sides; hover and drag turn the line amber. `onDrag` receives the movement since the last call. public struct Splitter: View { var axis: Axis var onDrag: (Double) -> Void var onEnd: () -> Void @State private var isHovered = false @State private var isDragging = false @State private var last: CGFloat = 0 /// `.vertical` is a column divider dragged left and right; `.horizontal` a row divider dragged up and down. public init(_ axis: Axis = .vertical, onDrag: @escaping (Double) -> Void, onEnd: @escaping () -> Void = {}) { self.axis = axis self.onDrag = onDrag self.onEnd = onEnd } public var body: some View { Rectangle() .fill(isHovered || isDragging ? Palette.amber : Palette.raised) .frame(width: axis == .vertical ? Metrics.hairline : nil, height: axis == .horizontal ? Metrics.hairline : nil) .overlay { Color.clear .frame(width: axis == .vertical ? Metrics.splitterHitArea : nil, height: axis == .horizontal ? Metrics.splitterHitArea : nil) .contentShape(Rectangle()) .onHover(perform: hover) .gesture(drag) } .zIndex(5) .animation(Metrics.smallControlTransition, value: isHovered || isDragging) } private var drag: some Gesture { DragGesture(minimumDistance: 0, coordinateSpace: .global) .onChanged { value in let position = axis == .vertical ? value.translation.width : value.translation.height if !isDragging { isDragging = true last = 0 } onDrag(Double(position - last)) last = position } .onEnded { _ in isDragging = false last = 0 if !isHovered { NSCursor.pop() } onEnd() } } private func hover(_ inside: Bool) { guard inside != isHovered else { return } isHovered = inside if isDragging { return } if inside { (axis == .vertical ? NSCursor.resizeLeftRight : NSCursor.resizeUpDown).push() } else { NSCursor.pop() } } }