import AppKit import SwiftUI import TextleyCore import WebKit struct WorkspaceView: View { unowned let controller: EditorWindow private var workspace: WindowDocuments { controller.documents } private var preferences: Preferences { controller.application.preferences } var body: some View { VStack(spacing: 0) { toolbar Divider() HSplitView { if workspace.showsSidebar { sidebar.frame(minWidth: 155, idealWidth: 205, maxWidth: 260) } if let document = workspace.active { documentView(document) .frame(minWidth: 390, maxWidth: .infinity, maxHeight: .infinity) } else { ContentUnavailableView { Label("No File Open", systemImage: "doc") } actions: { Button("New Document") { controller.application.newTab() } .textleyGlassButton(prominent: true) Button("Open…") { controller.application.openPanel() } .textleyGlassButton() } .frame(minWidth: 390, maxWidth: .infinity, maxHeight: .infinity) } } } .tint(TextleyTheme.accent) .onChange(of: workspace.selectedID, initial: true) { _, _ in controller.syncWindow() controller.focusActive() } .onChange(of: workspace.active?.isShowingMarkdownPreview) { _, isShowingPreview in if isShowingPreview == false, workspace.active?.showsFind == false { controller.focusActive() } } .onChange(of: workspace.active?.isDirty) { _, _ in controller.syncWindow() } .onChange(of: workspace.active?.url) { _, _ in controller.syncWindow() } } private var toolbar: some View { HStack(spacing: 8) { TextleyGlassGroup(spacing: 5) { HStack(spacing: 8) { toolbarButton("Toggle Sidebar", icon: "sidebar.left") { workspace.showsSidebar.toggle() } toolbarButton("New Document", icon: "square.and.pencil") { controller.application.newTab() } toolbarButton("Open Folder", icon: "folder.badge.plus") { controller.application.openFolderPanel() } } } Spacer() if let document = workspace.active, document.language == .markdown { @Bindable var document = document Picker("Markdown View", selection: $document.showsPreview) { Text("Markdown").tag(false) Text("Preview").tag(true) } .pickerStyle(.segmented) .labelsHidden() .fixedSize() } } .padding(.horizontal, 12) .padding(.vertical, 8) .background(.bar) } private var sidebar: some View { List { Section("Open Files") { ForEach(workspace.tabs) { document in TabRow(document: document, isSelected: document.id == workspace.selectedID, controller: controller) } } if !workspace.vaults.isEmpty { Section("Folders") { ForEach(workspace.vaults) { vault in @Bindable var vault = vault DisclosureGroup(isExpanded: $vault.isExpanded) { if vault.isAvailable { OutlineGroup(vault.entries, children: \.children) { entry in if entry.isFolder { FinderLabeledName(entry.name, symbol: "folder", colors: entry.finderColors) .contextMenu { FinderColorMenu(url: entry.url) } } else { Button { controller.application.openFiles([entry.url], in: controller) } label: { FinderLabeledName(entry.name, symbol: entry.isImage ? "photo" : "doc.text", colors: entry.finderColors) } .buttonStyle(.plain) .help(entry.url.path) .contextMenu { FinderColorMenu(url: entry.url) } } } } else { Text("Folder unavailable").foregroundStyle(.secondary) } } label: { FinderLabeledName(vault.url.lastPathComponent, symbol: "folder", colors: vault.finderColors) .help(vault.url.path) .contextMenu { if vault.isAvailable { FinderColorMenu(url: vault.url) } Button("Reveal in Finder") { NSWorkspace.shared.activateFileViewerSelecting([vault.url]) } Button("Remove from Sidebar") { controller.removeVault(vault) } } } } } } } .listStyle(.sidebar) .scrollContentBackground(.hidden) .background(.regularMaterial) .accessibilityLabel("Open files and folders") } @ViewBuilder private func documentView(_ document: EditorDocument) -> some View { if document.isImage { ImageTab(document: document) } else { VStack(spacing: 0) { if document.isShowingMarkdownPreview { MarkdownPane(source: document.text, version: document.change, assetVersion: document.previewRevision, fileURL: document.url) .id(document.id) .frame(maxWidth: .infinity, maxHeight: .infinity) } else { if document.showsFind { FindBar(document: document).id(document.id) Divider() } EditorSurface(document: document, preferences: preferences.editor) .frame(maxWidth: .infinity, maxHeight: .infinity) } if document.showsStarterHint { Divider() Text("Type to start. ⌘S to save · ⌘O to open a file") .font(.callout) .foregroundStyle(.secondary) .accessibilityLabel("Type to start. Command S to save, or Command O to open a file.") .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 12) .padding(.vertical, 8) .background(.bar) } Divider() statusBar(document) } } } private func statusBar(_ document: EditorDocument) -> some View { HStack(spacing: 12) { Text(document.caret).font(.caption.monospacedDigit()).accessibilityLabel(document.caret) Spacer() TextleyGlassGroup(spacing: 4) { HStack(spacing: 7) { statusMenu("Syntax", value: document.language.rawValue) { Button("Automatic") { document.languageOverride = nil } Divider() ForEach(SyntaxLanguage.allCases) { language in Button(language.rawValue) { document.languageOverride = language } } } statusMenu("Encoding", value: document.format.encoding.rawValue) { ForEach(TextEncoding.allCases) { encoding in Button(encoding.rawValue) { document.changeFormat(TextFileFormat(encoding: encoding, lineEnding: document.format.lineEnding)) } } } statusMenu("Line endings", value: document.format.lineEnding.rawValue) { ForEach(LineEnding.allCases) { ending in Button(ending.rawValue) { document.changeFormat(TextFileFormat(encoding: document.format.encoding, lineEnding: ending)) } } } } } } .fixedSize(horizontal: false, vertical: true) .font(.caption) .padding(.horizontal, 10) .padding(.vertical, 6) .background(.bar) } private func statusMenu(_ title: String, value: String, @ViewBuilder content: () -> Content) -> some View { Menu(value, content: content) .menuStyle(.borderlessButton) .fixedSize() .padding(.horizontal, 8) .padding(.vertical, 3) .textleyGlassSurface(Capsule(), interactive: true) .accessibilityLabel(title) .accessibilityValue(value) } private func toolbarButton(_ title: String, icon: String, action: @escaping () -> Void) -> some View { Button(action: action) { Image(systemName: icon) .font(.system(size: 19, weight: .medium)) .frame(width: 28, height: 26) .foregroundStyle(TextleyTheme.accent) } .textleyGlassButton() .buttonBorderShape(.capsule) .accessibilityLabel(title) .help(title) } } private struct TabRow: View { let document: EditorDocument let isSelected: Bool unowned let controller: EditorWindow @State private var finderColors: [FinderColorLabel] = [] var body: some View { HStack(spacing: 5) { Button { controller.select(document) } label: { FinderLabeledName(document.title, symbol: document.isImage ? "photo" : "doc.text", colors: finderColors) .frame(maxWidth: .infinity, alignment: .leading) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityAddTraits(isSelected ? .isSelected : []) .accessibilityValue(document.isDirty ? "Unsaved changes" : "") if document.isDirty { Circle().fill(.secondary).frame(width: 6, height: 6).accessibilityHidden(true) } Button { controller.closeTab(document) } label: { Image(systemName: "xmark").font(.caption2.weight(.semibold)) } .buttonStyle(.borderless) .accessibilityLabel("Close " + document.title) } .padding(.horizontal, 5) .padding(.vertical, 4) .background { if isSelected { Color.clear.textleyGlassSurface( RoundedRectangle(cornerRadius: 8), tint: TextleyTheme.accent.opacity(0.18) ) } } .help(document.url?.path ?? document.title) .task(id: document.url) { finderColors = [] guard let url = document.url else { return } while !Task.isCancelled { let colors = await Task.detached(priority: .utility) { FinderColorLabel.colors(at: url) }.value guard !Task.isCancelled else { return } finderColors = colors try? await Task.sleep(for: .seconds(2)) } } .contextMenu { if let url = document.url { FinderColorMenu(url: url) } Button("Move to New Window") { controller.moveToNewWindow(document) } Button("Close Tab") { controller.closeTab(document) } } } } private struct FinderLabeledName: View { let name: String let symbol: String let colors: [FinderColorLabel] init(_ name: String, symbol: String, colors: [FinderColorLabel]) { self.name = name self.symbol = symbol self.colors = colors } var body: some View { HStack(spacing: 6) { Label(name, systemImage: symbol) .lineLimit(1) if !colors.isEmpty { Spacer(minLength: 3) HStack(spacing: 3) { ForEach(colors, id: \.self) { label in Circle().fill(Color(nsColor: label.color)).frame(width: 7, height: 7) } } .accessibilityElement(children: .ignore) .accessibilityLabel("Finder colors: " + colors.map(\.name).joined(separator: ", ")) } } } } private struct FinderColorMenu: View { let url: URL var body: some View { let selected = FinderColorLabel.standardColors(at: url) Menu("Finder Color Labels") { ForEach(FinderColorLabel.allCases, id: \.self) { label in Button { do { try label.toggle(at: url) } catch { NSApp.presentError(error) } } label: { if selected.contains(label) { Label(label.name, systemImage: "checkmark") } else { Text(label.name) } } .accessibilityAddTraits(selected.contains(label) ? .isSelected : []) } } } } private struct FindBar: View { private enum Field: Hashable { case find, replace } @Bindable var document: EditorDocument @FocusState private var focusedField: Field? var body: some View { VStack(alignment: .leading, spacing: 5) { HStack { searchField("Find", text: $document.search.pattern, field: .find) .onSubmit { document.findNext() } Text(document.findMessage).font(.caption).foregroundStyle(.secondary).lineLimit(1) .accessibilityLabel(document.findMessage) Button { document.findNext(backward: true) } label: { Image(systemName: "chevron.up") } .accessibilityLabel("Previous Match") Button { document.findNext() } label: { Image(systemName: "chevron.down") } .accessibilityLabel("Next Match") Button { document.closeFind() } label: { Image(systemName: "xmark") } .accessibilityLabel("Close Find") } HStack { searchField("Replace", text: $document.replacement, field: .replace) Button("Replace") { document.replaceOne() }.disabled(document.search.pattern.isEmpty) Button("Replace All") { document.replaceAll() }.disabled(document.search.pattern.isEmpty) } HStack(spacing: 12) { Toggle("Match Case", isOn: $document.search.matchCase) Toggle("Whole Word", isOn: $document.search.wholeWord).disabled(document.search.isRegex) Toggle("Wrap", isOn: $document.search.wraps) Toggle("Regex", isOn: $document.search.isRegex) } .toggleStyle(.switch) .controlSize(.mini) .tint(TextleyTheme.accent) } .font(.callout) .textleyGlassButton() .buttonBorderShape(.capsule) .padding(8) .background(.bar) .onAppear { focusedField = .find } .onChange(of: document.focusFind) { _, _ in focusedField = .find } .onChange(of: document.search) { _, _ in document.scheduleFindCount() } .onExitCommand { document.closeFind() } } private func searchField(_ title: String, text: Binding, field: Field) -> some View { TextField(title, text: text) .textFieldStyle(.plain) .focused($focusedField, equals: field) .padding(.horizontal, 10) .padding(.vertical, 5) .textleyGlassSurface(Capsule()) .overlay { if focusedField == field { Capsule().strokeBorder(TextleyTheme.accent, lineWidth: 1) .allowsHitTesting(false) } } } } private struct EditorSurface: NSViewRepresentable { let document: EditorDocument let preferences: EditorPreferences func makeNSView(context: Context) -> NSView { NSView() } func updateNSView(_ host: NSView, context: Context) { let scroll = document.scroll if scroll.superview !== host { host.subviews.forEach { $0.removeFromSuperview() } let point = scroll.contentView.bounds.origin scroll.removeFromSuperview() scroll.frame = host.bounds scroll.autoresizingMask = [.width, .height] host.addSubview(scroll) document.apply(preferences) scroll.tile() if document.editor.frame.width < scroll.contentSize.width { document.editor.setFrameSize(NSSize(width: scroll.contentSize.width, height: document.editor.frame.height)) } scroll.contentView.scroll(to: point) scroll.reflectScrolledClipView(scroll.contentView) } else { document.apply(preferences) } } } private struct ImageTab: View { let document: EditorDocument var body: some View { VStack(spacing: 0) { if let image = document.image { GeometryReader { geometry in Image(nsImage: image).resizable().scaledToFit() .frame(width: geometry.size.width, height: geometry.size.height) .padding(12) .accessibilityLabel(document.title) } .padding(12) Divider() Text("\(Int(document.imageSize.width)) × \(Int(document.imageSize.height)) px") .font(.caption.monospacedDigit()) .padding(5) .frame(maxWidth: .infinity, alignment: .trailing) } else { ContentUnavailableView("Image Unavailable", systemImage: "photo") } } .frame(maxWidth: .infinity, maxHeight: .infinity) } } private struct MarkdownPane: NSViewRepresentable { let source: String let version: Int let assetVersion: Int let fileURL: URL? func makeCoordinator() -> Renderer { Renderer() } func makeNSView(context: Context) -> WKWebView { let configuration = WKWebViewConfiguration() configuration.websiteDataStore = .nonPersistent() configuration.defaultWebpagePreferences.allowsContentJavaScript = false let web = WKWebView(frame: .zero, configuration: configuration) web.navigationDelegate = context.coordinator web.setAccessibilityLabel("Markdown preview") return web } func updateNSView(_ web: WKWebView, context: Context) { context.coordinator.update(web, source: source, version: version, assetVersion: assetVersion, fileURL: fileURL) } @MainActor final class Renderer: NSObject, WKNavigationDelegate { private var task: Task? private var latestSource: String? private var latestVersion: Int? private var latestAssetVersion: Int? private var latestURL: URL? func update(_ web: WKWebView, source: String, version: Int, assetVersion: Int, fileURL: URL?) { guard latestVersion != version || latestAssetVersion != assetVersion || latestURL != fileURL || latestSource != source else { return } latestSource = source latestVersion = version latestAssetVersion = assetVersion latestURL = fileURL task?.cancel() task = Task { [weak web] in try? await Task.sleep(for: .milliseconds(180)) guard !Task.isCancelled else { return } let html = await Task.detached(priority: .userInitiated) { MarkdownPreview.html(for: source, fileURL: fileURL) }.value guard !Task.isCancelled else { return } web?.loadHTMLString(html, baseURL: nil) } } func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if action.navigationType == .linkActivated, let url = action.request.url, ["https", "http", "mailto"].contains(url.scheme?.lowercased() ?? "") { NSWorkspace.shared.open(url) decisionHandler(.cancel) return } decisionHandler(action.request.url?.absoluteString.hasPrefix("about:blank") == true ? .allow : .cancel) } } }