Textley / app · textley.ai / Sources / Textley / WorkspaceView.swift
| 1 | import AppKit |
| 2 | import SwiftUI |
| 3 | import TextleyCore |
| 4 | import WebKit |
| 5 | |
| 6 | struct WorkspaceView: View { |
| 7 | unowned let controller: EditorWindow |
| 8 | |
| 9 | private var workspace: WindowDocuments { controller.documents } |
| 10 | private var preferences: Preferences { controller.application.preferences } |
| 11 | |
| 12 | var body: some View { |
| 13 | VStack(spacing: 0) { |
| 14 | toolbar |
| 15 | Divider() |
| 16 | HSplitView { |
| 17 | if workspace.showsSidebar { sidebar.frame(minWidth: 155, idealWidth: 205, maxWidth: 260) } |
| 18 | if let document = workspace.active { |
| 19 | documentView(document) |
| 20 | .frame(minWidth: 390, maxWidth: .infinity, maxHeight: .infinity) |
| 21 | } else { |
| 22 | ContentUnavailableView { |
| 23 | Label("No File Open", systemImage: "doc") |
| 24 | } actions: { |
| 25 | Button("New Document") { controller.application.newTab() } |
| 26 | .textleyGlassButton(prominent: true) |
| 27 | Button("Open…") { controller.application.openPanel() } |
| 28 | .textleyGlassButton() |
| 29 | } |
| 30 | .frame(minWidth: 390, maxWidth: .infinity, maxHeight: .infinity) |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | .tint(TextleyTheme.accent) |
| 35 | .onChange(of: workspace.selectedID, initial: true) { _, _ in |
| 36 | controller.syncWindow() |
| 37 | controller.focusActive() |
| 38 | } |
| 39 | .onChange(of: workspace.active?.isShowingMarkdownPreview) { _, isShowingPreview in |
| 40 | if isShowingPreview == false, workspace.active?.showsFind == false { controller.focusActive() } |
| 41 | } |
| 42 | .onChange(of: workspace.active?.isDirty) { _, _ in controller.syncWindow() } |
| 43 | .onChange(of: workspace.active?.url) { _, _ in controller.syncWindow() } |
| 44 | } |
| 45 | |
| 46 | private var toolbar: some View { |
| 47 | HStack(spacing: 8) { |
| 48 | TextleyGlassGroup(spacing: 5) { |
| 49 | HStack(spacing: 8) { |
| 50 | toolbarButton("Toggle Sidebar", icon: "sidebar.left") { workspace.showsSidebar.toggle() } |
| 51 | toolbarButton("New Document", icon: "square.and.pencil") { controller.application.newTab() } |
| 52 | toolbarButton("Open Folder", icon: "folder.badge.plus") { controller.application.openFolderPanel() } |
| 53 | } |
| 54 | } |
| 55 | Spacer() |
| 56 | if let document = workspace.active, document.language == .markdown { |
| 57 | @Bindable var document = document |
| 58 | Picker("Markdown View", selection: $document.showsPreview) { |
| 59 | Text("Markdown").tag(false) |
| 60 | Text("Preview").tag(true) |
| 61 | } |
| 62 | .pickerStyle(.segmented) |
| 63 | .labelsHidden() |
| 64 | .fixedSize() |
| 65 | } |
| 66 | } |
| 67 | .padding(.horizontal, 12) |
| 68 | .padding(.vertical, 8) |
| 69 | .background(.bar) |
| 70 | } |
| 71 | |
| 72 | private var sidebar: some View { |
| 73 | List { |
| 74 | Section("Open Files") { |
| 75 | ForEach(workspace.tabs) { document in |
| 76 | TabRow(document: document, isSelected: document.id == workspace.selectedID, controller: controller) |
| 77 | } |
| 78 | } |
| 79 | if !workspace.vaults.isEmpty { |
| 80 | Section("Folders") { |
| 81 | ForEach(workspace.vaults) { vault in |
| 82 | @Bindable var vault = vault |
| 83 | DisclosureGroup(isExpanded: $vault.isExpanded) { |
| 84 | if vault.isAvailable { |
| 85 | OutlineGroup(vault.entries, children: \.children) { entry in |
| 86 | if entry.isFolder { |
| 87 | FinderLabeledName(entry.name, symbol: "folder", colors: entry.finderColors) |
| 88 | .contextMenu { FinderColorMenu(url: entry.url) } |
| 89 | } else { |
| 90 | Button { |
| 91 | controller.application.openFiles([entry.url], in: controller) |
| 92 | } label: { |
| 93 | FinderLabeledName(entry.name, symbol: entry.isImage ? "photo" : "doc.text", |
| 94 | colors: entry.finderColors) |
| 95 | } |
| 96 | .buttonStyle(.plain) |
| 97 | .help(entry.url.path) |
| 98 | .contextMenu { FinderColorMenu(url: entry.url) } |
| 99 | } |
| 100 | } |
| 101 | } else { |
| 102 | Text("Folder unavailable").foregroundStyle(.secondary) |
| 103 | } |
| 104 | } label: { |
| 105 | FinderLabeledName(vault.url.lastPathComponent, symbol: "folder", colors: vault.finderColors) |
| 106 | .help(vault.url.path) |
| 107 | .contextMenu { |
| 108 | if vault.isAvailable { FinderColorMenu(url: vault.url) } |
| 109 | Button("Reveal in Finder") { NSWorkspace.shared.activateFileViewerSelecting([vault.url]) } |
| 110 | Button("Remove from Sidebar") { controller.removeVault(vault) } |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | .listStyle(.sidebar) |
| 118 | .scrollContentBackground(.hidden) |
| 119 | .background(.regularMaterial) |
| 120 | .accessibilityLabel("Open files and folders") |
| 121 | } |
| 122 | |
| 123 | @ViewBuilder |
| 124 | private func documentView(_ document: EditorDocument) -> some View { |
| 125 | if document.isImage { |
| 126 | ImageTab(document: document) |
| 127 | } else { |
| 128 | VStack(spacing: 0) { |
| 129 | if document.isShowingMarkdownPreview { |
| 130 | MarkdownPane(source: document.text, version: document.change, assetVersion: document.previewRevision, fileURL: document.url) |
| 131 | .id(document.id) |
| 132 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 133 | } else { |
| 134 | if document.showsFind { |
| 135 | FindBar(document: document).id(document.id) |
| 136 | Divider() |
| 137 | } |
| 138 | EditorSurface(document: document, preferences: preferences.editor) |
| 139 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 140 | } |
| 141 | if document.showsStarterHint { |
| 142 | Divider() |
| 143 | Text("Type to start. ⌘S to save · ⌘O to open a file") |
| 144 | .font(.callout) |
| 145 | .foregroundStyle(.secondary) |
| 146 | .accessibilityLabel("Type to start. Command S to save, or Command O to open a file.") |
| 147 | .frame(maxWidth: .infinity, alignment: .leading) |
| 148 | .padding(.horizontal, 12) |
| 149 | .padding(.vertical, 8) |
| 150 | .background(.bar) |
| 151 | } |
| 152 | Divider() |
| 153 | statusBar(document) |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | private func statusBar(_ document: EditorDocument) -> some View { |
| 159 | HStack(spacing: 12) { |
| 160 | Text(document.caret).font(.caption.monospacedDigit()).accessibilityLabel(document.caret) |
| 161 | Spacer() |
| 162 | TextleyGlassGroup(spacing: 4) { |
| 163 | HStack(spacing: 7) { |
| 164 | statusMenu("Syntax", value: document.language.rawValue) { |
| 165 | Button("Automatic") { document.languageOverride = nil } |
| 166 | Divider() |
| 167 | ForEach(SyntaxLanguage.allCases) { language in |
| 168 | Button(language.rawValue) { document.languageOverride = language } |
| 169 | } |
| 170 | } |
| 171 | statusMenu("Encoding", value: document.format.encoding.rawValue) { |
| 172 | ForEach(TextEncoding.allCases) { encoding in |
| 173 | Button(encoding.rawValue) { |
| 174 | document.changeFormat(TextFileFormat(encoding: encoding, lineEnding: document.format.lineEnding)) |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | statusMenu("Line endings", value: document.format.lineEnding.rawValue) { |
| 179 | ForEach(LineEnding.allCases) { ending in |
| 180 | Button(ending.rawValue) { |
| 181 | document.changeFormat(TextFileFormat(encoding: document.format.encoding, lineEnding: ending)) |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | .fixedSize(horizontal: false, vertical: true) |
| 189 | .font(.caption) |
| 190 | .padding(.horizontal, 10) |
| 191 | .padding(.vertical, 6) |
| 192 | .background(.bar) |
| 193 | } |
| 194 | |
| 195 | private func statusMenu<Content: View>(_ title: String, value: String, @ViewBuilder content: () -> Content) -> some View { |
| 196 | Menu(value, content: content) |
| 197 | .menuStyle(.borderlessButton) |
| 198 | .fixedSize() |
| 199 | .padding(.horizontal, 8) |
| 200 | .padding(.vertical, 3) |
| 201 | .textleyGlassSurface(Capsule(), interactive: true) |
| 202 | .accessibilityLabel(title) |
| 203 | .accessibilityValue(value) |
| 204 | } |
| 205 | |
| 206 | private func toolbarButton(_ title: String, icon: String, action: @escaping () -> Void) -> some View { |
| 207 | Button(action: action) { |
| 208 | Image(systemName: icon) |
| 209 | .font(.system(size: 19, weight: .medium)) |
| 210 | .frame(width: 28, height: 26) |
| 211 | .foregroundStyle(TextleyTheme.accent) |
| 212 | } |
| 213 | .textleyGlassButton() |
| 214 | .buttonBorderShape(.capsule) |
| 215 | .accessibilityLabel(title) |
| 216 | .help(title) |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | private struct TabRow: View { |
| 221 | let document: EditorDocument |
| 222 | let isSelected: Bool |
| 223 | unowned let controller: EditorWindow |
| 224 | @State private var finderColors: [FinderColorLabel] = [] |
| 225 | |
| 226 | var body: some View { |
| 227 | HStack(spacing: 5) { |
| 228 | Button { |
| 229 | controller.select(document) |
| 230 | } label: { |
| 231 | FinderLabeledName(document.title, symbol: document.isImage ? "photo" : "doc.text", colors: finderColors) |
| 232 | .frame(maxWidth: .infinity, alignment: .leading) |
| 233 | .contentShape(Rectangle()) |
| 234 | } |
| 235 | .buttonStyle(.plain) |
| 236 | .accessibilityAddTraits(isSelected ? .isSelected : []) |
| 237 | .accessibilityValue(document.isDirty ? "Unsaved changes" : "") |
| 238 | if document.isDirty { |
| 239 | Circle().fill(.secondary).frame(width: 6, height: 6).accessibilityHidden(true) |
| 240 | } |
| 241 | Button { |
| 242 | controller.closeTab(document) |
| 243 | } label: { |
| 244 | Image(systemName: "xmark").font(.caption2.weight(.semibold)) |
| 245 | } |
| 246 | .buttonStyle(.borderless) |
| 247 | .accessibilityLabel("Close " + document.title) |
| 248 | } |
| 249 | .padding(.horizontal, 5) |
| 250 | .padding(.vertical, 4) |
| 251 | .background { |
| 252 | if isSelected { |
| 253 | Color.clear.textleyGlassSurface( |
| 254 | RoundedRectangle(cornerRadius: 8), tint: TextleyTheme.accent.opacity(0.18) |
| 255 | ) |
| 256 | } |
| 257 | } |
| 258 | .help(document.url?.path ?? document.title) |
| 259 | .task(id: document.url) { |
| 260 | finderColors = [] |
| 261 | guard let url = document.url else { return } |
| 262 | while !Task.isCancelled { |
| 263 | let colors = await Task.detached(priority: .utility) { FinderColorLabel.colors(at: url) }.value |
| 264 | guard !Task.isCancelled else { return } |
| 265 | finderColors = colors |
| 266 | try? await Task.sleep(for: .seconds(2)) |
| 267 | } |
| 268 | } |
| 269 | .contextMenu { |
| 270 | if let url = document.url { FinderColorMenu(url: url) } |
| 271 | Button("Move to New Window") { controller.moveToNewWindow(document) } |
| 272 | Button("Close Tab") { controller.closeTab(document) } |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | private struct FinderLabeledName: View { |
| 278 | let name: String |
| 279 | let symbol: String |
| 280 | let colors: [FinderColorLabel] |
| 281 | |
| 282 | init(_ name: String, symbol: String, colors: [FinderColorLabel]) { |
| 283 | self.name = name |
| 284 | self.symbol = symbol |
| 285 | self.colors = colors |
| 286 | } |
| 287 | |
| 288 | var body: some View { |
| 289 | HStack(spacing: 6) { |
| 290 | Label(name, systemImage: symbol) |
| 291 | .lineLimit(1) |
| 292 | if !colors.isEmpty { |
| 293 | Spacer(minLength: 3) |
| 294 | HStack(spacing: 3) { |
| 295 | ForEach(colors, id: \.self) { label in |
| 296 | Circle().fill(Color(nsColor: label.color)).frame(width: 7, height: 7) |
| 297 | } |
| 298 | } |
| 299 | .accessibilityElement(children: .ignore) |
| 300 | .accessibilityLabel("Finder colors: " + colors.map(\.name).joined(separator: ", ")) |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | private struct FinderColorMenu: View { |
| 307 | let url: URL |
| 308 | |
| 309 | var body: some View { |
| 310 | let selected = FinderColorLabel.standardColors(at: url) |
| 311 | Menu("Finder Color Labels") { |
| 312 | ForEach(FinderColorLabel.allCases, id: \.self) { label in |
| 313 | Button { |
| 314 | do { try label.toggle(at: url) } catch { NSApp.presentError(error) } |
| 315 | } label: { |
| 316 | if selected.contains(label) { |
| 317 | Label(label.name, systemImage: "checkmark") |
| 318 | } else { |
| 319 | Text(label.name) |
| 320 | } |
| 321 | } |
| 322 | .accessibilityAddTraits(selected.contains(label) ? .isSelected : []) |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | private struct FindBar: View { |
| 329 | private enum Field: Hashable { case find, replace } |
| 330 | |
| 331 | @Bindable var document: EditorDocument |
| 332 | @FocusState private var focusedField: Field? |
| 333 | |
| 334 | var body: some View { |
| 335 | VStack(alignment: .leading, spacing: 5) { |
| 336 | HStack { |
| 337 | searchField("Find", text: $document.search.pattern, field: .find) |
| 338 | .onSubmit { document.findNext() } |
| 339 | Text(document.findMessage).font(.caption).foregroundStyle(.secondary).lineLimit(1) |
| 340 | .accessibilityLabel(document.findMessage) |
| 341 | Button { document.findNext(backward: true) } label: { Image(systemName: "chevron.up") } |
| 342 | .accessibilityLabel("Previous Match") |
| 343 | Button { document.findNext() } label: { Image(systemName: "chevron.down") } |
| 344 | .accessibilityLabel("Next Match") |
| 345 | Button { document.closeFind() } label: { Image(systemName: "xmark") } |
| 346 | .accessibilityLabel("Close Find") |
| 347 | } |
| 348 | HStack { |
| 349 | searchField("Replace", text: $document.replacement, field: .replace) |
| 350 | Button("Replace") { document.replaceOne() }.disabled(document.search.pattern.isEmpty) |
| 351 | Button("Replace All") { document.replaceAll() }.disabled(document.search.pattern.isEmpty) |
| 352 | } |
| 353 | HStack(spacing: 12) { |
| 354 | Toggle("Match Case", isOn: $document.search.matchCase) |
| 355 | Toggle("Whole Word", isOn: $document.search.wholeWord).disabled(document.search.isRegex) |
| 356 | Toggle("Wrap", isOn: $document.search.wraps) |
| 357 | Toggle("Regex", isOn: $document.search.isRegex) |
| 358 | } |
| 359 | .toggleStyle(.switch) |
| 360 | .controlSize(.mini) |
| 361 | .tint(TextleyTheme.accent) |
| 362 | } |
| 363 | .font(.callout) |
| 364 | .textleyGlassButton() |
| 365 | .buttonBorderShape(.capsule) |
| 366 | .padding(8) |
| 367 | .background(.bar) |
| 368 | .onAppear { focusedField = .find } |
| 369 | .onChange(of: document.focusFind) { _, _ in focusedField = .find } |
| 370 | .onChange(of: document.search) { _, _ in document.scheduleFindCount() } |
| 371 | .onExitCommand { document.closeFind() } |
| 372 | } |
| 373 | |
| 374 | private func searchField(_ title: String, text: Binding<String>, field: Field) -> some View { |
| 375 | TextField(title, text: text) |
| 376 | .textFieldStyle(.plain) |
| 377 | .focused($focusedField, equals: field) |
| 378 | .padding(.horizontal, 10) |
| 379 | .padding(.vertical, 5) |
| 380 | .textleyGlassSurface(Capsule()) |
| 381 | .overlay { |
| 382 | if focusedField == field { |
| 383 | Capsule().strokeBorder(TextleyTheme.accent, lineWidth: 1) |
| 384 | .allowsHitTesting(false) |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | private struct EditorSurface: NSViewRepresentable { |
| 391 | let document: EditorDocument |
| 392 | let preferences: EditorPreferences |
| 393 | |
| 394 | func makeNSView(context: Context) -> NSView { NSView() } |
| 395 | |
| 396 | func updateNSView(_ host: NSView, context: Context) { |
| 397 | let scroll = document.scroll |
| 398 | if scroll.superview !== host { |
| 399 | host.subviews.forEach { $0.removeFromSuperview() } |
| 400 | let point = scroll.contentView.bounds.origin |
| 401 | scroll.removeFromSuperview() |
| 402 | scroll.frame = host.bounds |
| 403 | scroll.autoresizingMask = [.width, .height] |
| 404 | host.addSubview(scroll) |
| 405 | document.apply(preferences) |
| 406 | scroll.tile() |
| 407 | if document.editor.frame.width < scroll.contentSize.width { |
| 408 | document.editor.setFrameSize(NSSize(width: scroll.contentSize.width, height: document.editor.frame.height)) |
| 409 | } |
| 410 | scroll.contentView.scroll(to: point) |
| 411 | scroll.reflectScrolledClipView(scroll.contentView) |
| 412 | } else { |
| 413 | document.apply(preferences) |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | private struct ImageTab: View { |
| 419 | let document: EditorDocument |
| 420 | |
| 421 | var body: some View { |
| 422 | VStack(spacing: 0) { |
| 423 | if let image = document.image { |
| 424 | GeometryReader { geometry in |
| 425 | Image(nsImage: image).resizable().scaledToFit() |
| 426 | .frame(width: geometry.size.width, height: geometry.size.height) |
| 427 | .padding(12) |
| 428 | .accessibilityLabel(document.title) |
| 429 | } |
| 430 | .padding(12) |
| 431 | Divider() |
| 432 | Text("\(Int(document.imageSize.width)) × \(Int(document.imageSize.height)) px") |
| 433 | .font(.caption.monospacedDigit()) |
| 434 | .padding(5) |
| 435 | .frame(maxWidth: .infinity, alignment: .trailing) |
| 436 | } else { |
| 437 | ContentUnavailableView("Image Unavailable", systemImage: "photo") |
| 438 | } |
| 439 | } |
| 440 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | private struct MarkdownPane: NSViewRepresentable { |
| 445 | let source: String |
| 446 | let version: Int |
| 447 | let assetVersion: Int |
| 448 | let fileURL: URL? |
| 449 | |
| 450 | func makeCoordinator() -> Renderer { Renderer() } |
| 451 | |
| 452 | func makeNSView(context: Context) -> WKWebView { |
| 453 | let configuration = WKWebViewConfiguration() |
| 454 | configuration.websiteDataStore = .nonPersistent() |
| 455 | configuration.defaultWebpagePreferences.allowsContentJavaScript = false |
| 456 | let web = WKWebView(frame: .zero, configuration: configuration) |
| 457 | web.navigationDelegate = context.coordinator |
| 458 | web.setAccessibilityLabel("Markdown preview") |
| 459 | return web |
| 460 | } |
| 461 | |
| 462 | func updateNSView(_ web: WKWebView, context: Context) { |
| 463 | context.coordinator.update(web, source: source, version: version, assetVersion: assetVersion, fileURL: fileURL) |
| 464 | } |
| 465 | |
| 466 | @MainActor |
| 467 | final class Renderer: NSObject, WKNavigationDelegate { |
| 468 | private var task: Task<Void, Never>? |
| 469 | private var latestSource: String? |
| 470 | private var latestVersion: Int? |
| 471 | private var latestAssetVersion: Int? |
| 472 | private var latestURL: URL? |
| 473 | |
| 474 | func update(_ web: WKWebView, source: String, version: Int, assetVersion: Int, fileURL: URL?) { |
| 475 | guard latestVersion != version || latestAssetVersion != assetVersion || latestURL != fileURL || latestSource != source else { return } |
| 476 | latestSource = source |
| 477 | latestVersion = version |
| 478 | latestAssetVersion = assetVersion |
| 479 | latestURL = fileURL |
| 480 | task?.cancel() |
| 481 | task = Task { [weak web] in |
| 482 | try? await Task.sleep(for: .milliseconds(180)) |
| 483 | guard !Task.isCancelled else { return } |
| 484 | let html = await Task.detached(priority: .userInitiated) { MarkdownPreview.html(for: source, fileURL: fileURL) }.value |
| 485 | guard !Task.isCancelled else { return } |
| 486 | web?.loadHTMLString(html, baseURL: nil) |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, |
| 491 | decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { |
| 492 | if action.navigationType == .linkActivated, let url = action.request.url, |
| 493 | ["https", "http", "mailto"].contains(url.scheme?.lowercased() ?? "") { |
| 494 | NSWorkspace.shared.open(url) |
| 495 | decisionHandler(.cancel) |
| 496 | return |
| 497 | } |
| 498 | decisionHandler(action.request.url?.absoluteString.hasPrefix("about:blank") == true ? .allow : .cancel) |
| 499 | } |
| 500 | } |
| 501 | } |