Sources/Orgstar/BufferTabs.swift
80 lines · 3363 bytes
1import AppKit
2import OrgApp
3import SwiftUI
4
5/// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's
6/// split view loops on its size constraints in short windows, so this sets a width instead.
7struct PaneDivider: View {
8 @Binding var width: Double
9 let range: ClosedRange<Double>
10 @State private var start: Double?
11
12 var body: some View {
13 Rectangle()
14 .fill(Color(nsColor: .separatorColor))
15 .frame(width: 1)
16 .frame(maxHeight: .infinity)
17 .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in
18 if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() }
19 }
20 .gesture(DragGesture(minimumDistance: 1).onChanged { drag in
21 let base = start ?? width
22 start = base
23 width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound)
24 }.onEnded { _ in start = nil }))
25 .accessibilityHidden(true)
26 }
27}
28
29/// A tab for each open buffer: click to show it, × to close it, a dot for unsaved edits.
30struct BufferTabs: View {
31 let session: DocumentSession
32 @Environment(\.orgTheme) private var theme
33
34 var body: some View {
35 ScrollView(.horizontal, showsIndicators: false) {
36 HStack(spacing: 0) {
37 ForEach(session.openPaths, id: \.self) { path in
38 tab(path)
39 }
40 }
41 }
42 .frame(height: 28)
43 .background { Rectangle().fill(theme.color("modeline-background").map(AnyShapeStyle.init) ?? AnyShapeStyle(.bar)) }
44 .overlay(alignment: .bottom) { Divider() }
45 }
46
47 private func tab(_ path: String) -> some View {
48 let current = path == session.path
49 return HStack(spacing: 6) {
50 Text(session.bufferName(path))
51 .lineLimit(1)
52 .foregroundStyle(current ? .primary : .secondary)
53 .accessibilityAddTraits(current ? [.isButton, .isSelected] : .isButton)
54 .accessibilityAction { session.open(path) }
55 Button {
56 if path == session.path {
57 if UnsavedChanges.resolve(session) { session.kill(path) }
58 } else if UnsavedChanges.resolve(session, paths: [path]) {
59 session.kill(path)
60 }
61 } label: {
62 Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark")
63 .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold))
64 .frame(width: 12, height: 12)
65 }
66 .buttonStyle(.borderless)
67 .help("Close")
68 .accessibilityLabel("Close \(session.bufferName(path))" + (session.dirtyPaths.contains(path) ? ", unsaved" : ""))
69 }
70 .font(.callout)
71 .padding(.horizontal, 12)
72 .frame(maxHeight: .infinity)
73 // A shape, not a color: a color background runs up under the toolbar.
74 .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) }
75 .overlay(alignment: .trailing) { Divider() }
76 .contentShape(Rectangle())
77 .onTapGesture { session.open(path) }
78 .help(path)
79 }
80}