Branchwell

Textley / app · textley.ai / Sources / Textley / Preferences.swift

Raw 8.4 KB on 63b71f34cfe61bc6553e8463e803a45424bff4d3
1import AppKit
2import Observation
3import SwiftUI
4import TextleyCore
5
6struct EditorPreferences: Codable, Equatable {
7 var fontSize: Double = 13
8 var wrap = false
9 var lineNumbers = true
10
11 func validated() throws -> Self {
12 guard fontSize.isFinite, (9...32).contains(fontSize) else {
13 throw CocoaError(.fileReadCorruptFile, userInfo: [NSLocalizedDescriptionKey: "The editor font size must be between 9 and 32."])
14 }
15 return self
16 }
17}
18
19@MainActor @Observable
20final class Preferences {
21 private struct Backup: Codable {
22 let version: Int
23 let editor: EditorPreferences
24 }
25
26 var editor: EditorPreferences {
27 didSet {
28 if let data = try? JSONEncoder().encode(editor) { defaults.set(data, forKey: "editorPreferences") }
29 }
30 }
31
32 @ObservationIgnored private let defaults: UserDefaults
33
34 init(defaults: UserDefaults = .standard) {
35 self.defaults = defaults
36 if let data = defaults.data(forKey: "editorPreferences"),
37 let saved = try? JSONDecoder().decode(EditorPreferences.self, from: data).validated() {
38 editor = saved
39 } else {
40 editor = EditorPreferences()
41 }
42 }
43
44 func export(to url: URL) throws {
45 let encoder = JSONEncoder()
46 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
47 try TextFileAccess.write(encoder.encode(Backup(version: 1, editor: editor)), to: url)
48 }
49
50 func restore(from url: URL) throws {
51 let backup = try JSONDecoder().decode(Backup.self, from: TextFileAccess.read(url))
52 guard backup.version == 1 else {
53 throw CocoaError(.fileReadCorruptFile, userInfo: [NSLocalizedDescriptionKey: "This settings backup uses an unsupported version."])
54 }
55 editor = try backup.editor.validated()
56 }
57}
58
59struct SettingsView: View {
60 static let contentSize = CGSize(width: 760, height: 596)
61
62 enum Page: String, CaseIterable, Identifiable {
63 case editor = "Editor"
64 case integrations = "Integrations"
65
66 var id: Self { self }
67
68 var symbol: String {
69 switch self {
70 case .editor: "text.alignleft"
71 case .integrations: "point.3.connected.trianglepath.dotted"
72 }
73 }
74 }
75
76 @Bindable var preferences: Preferences
77 let mcp: TextleyMCPService
78 @State private var selection: Page
79
80 init(preferences: Preferences, mcp: TextleyMCPService, initialPage: Page = .editor) {
81 self.preferences = preferences
82 self.mcp = mcp
83 _selection = State(initialValue: initialPage)
84 }
85
86 var body: some View {
87 HStack(spacing: 0) {
88 sidebar
89
90 Divider()
91
92 VStack(alignment: .leading, spacing: 0) {
93 Text(selection.rawValue)
94 .font(.system(size: 24, weight: .semibold))
95 .accessibilityAddTraits(.isHeader)
96 .padding(.horizontal, 26)
97 .padding(.top, 24)
98 .padding(.bottom, 8)
99 switch selection {
100 case .editor: editorSettings
101 case .integrations: MCPSettingsView(service: mcp)
102 }
103 }
104 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
105 .background(Color(nsColor: .windowBackgroundColor))
106 }
107 .frame(width: Self.contentSize.width, height: Self.contentSize.height)
108 .tint(TextleyTheme.accent)
109 }
110
111 private var sidebar: some View {
112 TextleyGlassGroup(spacing: 4) {
113 VStack(spacing: 6) {
114 ForEach(Page.allCases) { page in
115 Button { selection = page } label: {
116 let label = Label(page.rawValue, systemImage: page.symbol)
117 .font(.system(size: 14, weight: .semibold))
118 .foregroundStyle(.primary)
119 .frame(maxWidth: .infinity, alignment: .leading)
120 .padding(.horizontal, 10)
121 .padding(.vertical, 8)
122 .contentShape(Rectangle())
123 if selection == page {
124 label.textleyGlassSurface(
125 RoundedRectangle(cornerRadius: 10), tint: TextleyTheme.accent.opacity(0.18), interactive: true
126 )
127 } else {
128 label
129 }
130 }
131 .buttonStyle(.plain)
132 .accessibilityAddTraits(selection == page ? .isSelected : [])
133 }
134 Spacer()
135 }
136 .padding(.horizontal, 10)
137 .padding(.top, 18)
138 }
139 .frame(width: 170)
140 .background(.regularMaterial)
141 .accessibilityElement(children: .contain)
142 .accessibilityLabel("Settings sections")
143 }
144
145 private var editorSettings: some View {
146 Form {
147 Section("Text display") {
148 LabeledContent("Font size") {
149 Stepper(value: $preferences.editor.fontSize, in: 9...32) {
150 Text("\(Int(preferences.editor.fontSize)) pt")
151 .monospacedDigit()
152 }
153 .accessibilityLabel("Font size")
154 .accessibilityValue("\(Int(preferences.editor.fontSize)) points")
155 }
156 Toggle("Show line numbers", isOn: $preferences.editor.lineNumbers)
157 Toggle("Soft wrap", isOn: $preferences.editor.wrap)
158 }
159 Section("Backup") {
160 HStack {
161 Button { exportSettings() } label: {
162 Label("Export Settings…", systemImage: "square.and.arrow.up")
163 }
164 Button { importSettings() } label: {
165 Label("Import Settings…", systemImage: "square.and.arrow.down")
166 }
167 }
168 .labelStyle(.titleAndIcon)
169 }
170 #if TEXTLEY_SPARKLE
171 Section("Updates") {
172 Toggle("Automatically install updates", isOn: Binding(
173 get: { TextleyUpdates.shared.automaticUpdates },
174 set: { TextleyUpdates.shared.setAutomaticUpdates($0) }
175 ))
176 Button("Check for Updates…") { TextleyUpdates.shared.check() }
177 .disabled(!TextleyUpdates.shared.canCheck)
178 }
179 #endif
180 }
181 .formStyle(.grouped)
182 .font(.system(size: 14))
183 .buttonStyle(SettingsActionButtonStyle())
184 }
185
186 private func exportSettings() {
187 let panel = NSSavePanel()
188 panel.allowedContentTypes = [.json]
189 panel.nameFieldStringValue = "Textley Settings.json"
190 guard panel.runModal() == .OK, let url = panel.url else { return }
191 do { try preferences.export(to: url) } catch { NSApp.presentError(error) }
192 }
193
194 private func importSettings() {
195 let panel = NSOpenPanel()
196 panel.allowedContentTypes = [.json]
197 panel.canChooseDirectories = false
198 guard panel.runModal() == .OK, let url = panel.url else { return }
199 let alert = NSAlert()
200 alert.messageText = "Restore Text Editor settings?"
201 alert.informativeText = "This will replace your current editor settings."
202 alert.addButton(withTitle: "Restore")
203 alert.addButton(withTitle: "Cancel")
204 guard alert.runModal() == .alertFirstButtonReturn else { return }
205 do { try preferences.restore(from: url) } catch { NSApp.presentError(error) }
206 }
207}
208
209struct SettingsActionButtonStyle: ButtonStyle {
210 @Environment(\.isEnabled) private var isEnabled
211
212 func makeBody(configuration: Configuration) -> some View {
213 let shape = RoundedRectangle(cornerRadius: 8)
214 let label = configuration.label
215 .font(.system(size: 14, weight: .semibold))
216 .foregroundStyle(Color.primary.opacity(isEnabled ? 1 : 0.76))
217 .padding(.horizontal, 12)
218 .padding(.vertical, 7)
219 .contentShape(shape)
220
221 if isEnabled {
222 label.textleyGlassSurface(shape, interactive: true)
223 .opacity(configuration.isPressed ? 0.82 : 1)
224 } else {
225 label
226 .background(Color.primary.opacity(0.06), in: shape)
227 .overlay { shape.strokeBorder(Color.primary.opacity(0.16)) }
228 }
229 }
230}