55 lines
2.1 KiB
Swift
55 lines
2.1 KiB
Swift
import SwiftUI
|
|
import AppKit
|
|
|
|
/// A native hit target avoids Form/plain-Button hit-testing ambiguity on the swatch.
|
|
struct CustomColorWell: NSViewRepresentable {
|
|
let preferences: AppearancePreferences
|
|
let picker: CustomColorPicker
|
|
@Environment(\.locale) private var locale
|
|
|
|
func makeNSView(context: Context) -> SwatchButton {
|
|
let button = SwatchButton()
|
|
return button
|
|
}
|
|
|
|
func updateNSView(_ button: SwatchButton, context: Context) {
|
|
button.setAccessibilityLabel(AppLocalization.string("accent.custom", locale: locale))
|
|
button.open = { picker.show(for: preferences) }
|
|
button.swatchColor = NSColor(srgbRed: preferences.red, green: preferences.green, blue: preferences.blue, alpha: 1)
|
|
}
|
|
|
|
func sizeThatFits(_ proposal: ProposedViewSize, nsView: SwatchButton, context: Context) -> CGSize? {
|
|
CGSize(width: 44, height: 26)
|
|
}
|
|
|
|
final class SwatchButton: NSButton {
|
|
var swatchColor = NSColor.systemBlue { didSet { needsDisplay = true } }
|
|
override var intrinsicContentSize: NSSize { NSSize(width: 44, height: 26) }
|
|
|
|
override func draw(_ dirtyRect: NSRect) {
|
|
// Draw the actual RGB color inside bounds; no scalable SF Symbol/cell image.
|
|
let shape = NSBezierPath(roundedRect: bounds.insetBy(dx: 4, dy: 4), xRadius: 4, yRadius: 4)
|
|
(isHighlighted ? swatchColor.withAlphaComponent(0.7) : swatchColor).setFill()
|
|
shape.fill()
|
|
NSColor.separatorColor.setStroke()
|
|
shape.lineWidth = 1
|
|
shape.stroke()
|
|
}
|
|
|
|
var open: () -> Void = {}
|
|
override init(frame frameRect: NSRect) {
|
|
super.init(frame: frameRect)
|
|
bezelStyle = .rounded
|
|
isBordered = false
|
|
wantsLayer = true
|
|
layer?.masksToBounds = true
|
|
title = ""
|
|
target = self
|
|
action = #selector(openPicker)
|
|
}
|
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
|
@objc func openPicker() { open() }
|
|
}
|
|
}
|