/
Pane.swift
94 lines (82 loc) · 2.12 KB
/
Pane.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import SwiftUI
/**
Represents a type that can be converted to `SettingsPane`.
Acts as type-eraser for `Settings.Pane<T>`.
*/
public protocol SettingsPaneConvertible {
/**
Convert `self` to equivalent `SettingsPane`.
*/
func asSettingsPane() -> SettingsPane
}
@available(macOS 10.15, *)
extension Settings {
/**
Create a SwiftUI-based settings pane.
SwiftUI equivalent of the `SettingsPane` protocol.
*/
public struct Pane<Content: View>: View, SettingsPaneConvertible {
let identifier: PaneIdentifier
let title: String
let toolbarIcon: NSImage
let content: Content
public init(
identifier: PaneIdentifier,
title: String,
toolbarIcon: NSImage,
contentView: () -> Content
) {
self.identifier = identifier
self.title = title
self.toolbarIcon = toolbarIcon
self.content = contentView()
}
public var body: some View { content }
public func asSettingsPane() -> SettingsPane {
PaneHostingController(pane: self)
}
}
/**
Hosting controller enabling `Settings.Pane` to be used alongside AppKit `NSViewController`'s.
*/
public final class PaneHostingController<Content: View>: NSHostingController<Content>, SettingsPane {
public let paneIdentifier: PaneIdentifier
public let paneTitle: String
public let toolbarItemIcon: NSImage
init(
identifier: PaneIdentifier,
title: String,
toolbarIcon: NSImage,
content: Content
) {
self.paneIdentifier = identifier
self.paneTitle = title
self.toolbarItemIcon = toolbarIcon
super.init(rootView: content)
}
public convenience init(pane: Pane<Content>) {
self.init(
identifier: pane.identifier,
title: pane.title,
toolbarIcon: pane.toolbarIcon,
content: pane.content
)
}
@available(*, unavailable)
@objc
dynamic required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
@available(macOS 10.15, *)
extension View {
/**
Applies font and color for a label used for describing a setting.
*/
public func preferenceDescription() -> some View {
font(.system(size: 11.0))
// TODO: Use `.foregroundStyle` when targeting macOS 12.
.foregroundColor(.secondary)
}
}