forked from manaflow-ai/cmux
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMarkdownPanelView.swift
More file actions
590 lines (541 loc) · 21.1 KB
/
Copy pathMarkdownPanelView.swift
File metadata and controls
590 lines (541 loc) · 21.1 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import AppKit
import Bonsplit
import SwiftUI
import MarkdownUI
/// SwiftUI view that renders a MarkdownPanel's content using MarkdownUI.
struct MarkdownPanelView: View {
@ObservedObject var panel: MarkdownPanel
let isFocused: Bool
let isVisibleInUI: Bool
let portalPriority: Int
let onRequestPanelFocus: () -> Void
@State private var focusFlashOpacity: Double = 0.0
@State private var focusFlashAnimationGeneration: Int = 0
@Environment(\.colorScheme) private var colorScheme
var body: some View {
Group {
if panel.isFileUnavailable {
fileUnavailableView
} else {
markdownContentView
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(backgroundColor)
.overlay {
RoundedRectangle(cornerRadius: FocusFlashPattern.ringCornerRadius)
.stroke(cmuxAccentColor().opacity(focusFlashOpacity), lineWidth: 3)
.shadow(color: cmuxAccentColor().opacity(focusFlashOpacity * 0.35), radius: 10)
.padding(FocusFlashPattern.ringInset)
.allowsHitTesting(false)
}
.overlay {
if isVisibleInUI {
// Observe left-clicks without intercepting them so markdown text
// selection and link activation continue to use the native path.
MarkdownPointerObserver(onPointerDown: onRequestPanelFocus)
}
}
.overlay(alignment: .top) {
if let state = panel.searchState {
MarkdownSearchOverlay(
panelId: panel.id,
searchState: state,
onNext: { panel.findNext() },
onPrevious: { panel.findPrevious() },
onClose: { panel.hideFind() }
)
}
}
.onChange(of: panel.focusFlashToken) { _ in
triggerFocusFlashAnimation()
}
}
// MARK: - Content
private var markdownContentView: some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
// File path breadcrumb
filePathHeader
.padding(.horizontal, 24)
.padding(.top, 16)
.padding(.bottom, 8)
Divider()
.padding(.horizontal, 16)
// Rendered markdown
Markdown(panel.content)
.markdownTheme(cmuxMarkdownTheme)
.textSelection(.enabled)
.padding(.horizontal, 24)
.padding(.vertical, 16)
}
}
}
private var filePathHeader: some View {
HStack(spacing: 6) {
Image(systemName: "doc.richtext")
.foregroundColor(.secondary)
.font(.system(size: 12))
Text(panel.filePath)
.font(.system(size: 11, design: .monospaced))
.foregroundColor(.secondary)
.lineLimit(1)
.truncationMode(.middle)
Spacer()
}
}
private var fileUnavailableView: some View {
VStack(spacing: 12) {
Image(systemName: "doc.questionmark")
.font(.system(size: 40))
.foregroundColor(.secondary)
Text(String(localized: "markdown.fileUnavailable.title", defaultValue: "File unavailable"))
.font(.headline)
.foregroundColor(.primary)
Text(panel.filePath)
.font(.system(size: 12, design: .monospaced))
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
.textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 24)
Text(String(localized: "markdown.fileUnavailable.message", defaultValue: "The file may have been moved or deleted."))
.font(.caption)
.foregroundColor(.secondary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
// MARK: - Theme
private var backgroundColor: Color {
colorScheme == .dark
? Color(nsColor: NSColor(white: 0.12, alpha: 1.0))
: Color(nsColor: NSColor(white: 0.98, alpha: 1.0))
}
private var cmuxMarkdownTheme: Theme {
let isDark = colorScheme == .dark
return Theme()
// Text
.text {
ForegroundColor(isDark ? .white.opacity(0.9) : .primary)
FontSize(14)
}
// Headings
.heading1 { configuration in
VStack(alignment: .leading, spacing: 8) {
configuration.label
.markdownTextStyle {
FontWeight(.bold)
FontSize(28)
ForegroundColor(isDark ? .white : .primary)
}
Divider()
}
.markdownMargin(top: 24, bottom: 16)
}
.heading2 { configuration in
VStack(alignment: .leading, spacing: 6) {
configuration.label
.markdownTextStyle {
FontWeight(.bold)
FontSize(22)
ForegroundColor(isDark ? .white : .primary)
}
Divider()
}
.markdownMargin(top: 20, bottom: 12)
}
.heading3 { configuration in
configuration.label
.markdownTextStyle {
FontWeight(.semibold)
FontSize(18)
ForegroundColor(isDark ? .white : .primary)
}
.markdownMargin(top: 16, bottom: 8)
}
.heading4 { configuration in
configuration.label
.markdownTextStyle {
FontWeight(.semibold)
FontSize(16)
ForegroundColor(isDark ? .white : .primary)
}
.markdownMargin(top: 12, bottom: 6)
}
.heading5 { configuration in
configuration.label
.markdownTextStyle {
FontWeight(.medium)
FontSize(14)
ForegroundColor(isDark ? .white : .primary)
}
.markdownMargin(top: 10, bottom: 4)
}
.heading6 { configuration in
configuration.label
.markdownTextStyle {
FontWeight(.medium)
FontSize(13)
ForegroundColor(isDark ? .white.opacity(0.7) : .secondary)
}
.markdownMargin(top: 8, bottom: 4)
}
// Code blocks
.codeBlock { configuration in
ScrollView(.horizontal, showsIndicators: true) {
configuration.label
.markdownTextStyle {
FontFamilyVariant(.monospaced)
FontSize(13)
ForegroundColor(isDark ? Color(red: 0.9, green: 0.9, blue: 0.9) : Color(red: 0.2, green: 0.2, blue: 0.2))
}
.padding(12)
}
.background(isDark
? Color(nsColor: NSColor(white: 0.08, alpha: 1.0))
: Color(nsColor: NSColor(white: 0.93, alpha: 1.0)))
.clipShape(RoundedRectangle(cornerRadius: 6))
.markdownMargin(top: 8, bottom: 8)
}
// Inline code
.code {
FontFamilyVariant(.monospaced)
FontSize(13)
ForegroundColor(isDark ? Color(red: 0.85, green: 0.6, blue: 0.95) : Color(red: 0.6, green: 0.2, blue: 0.7))
BackgroundColor(isDark
? Color(nsColor: NSColor(white: 0.18, alpha: 1.0))
: Color(nsColor: NSColor(white: 0.92, alpha: 1.0)))
}
// Block quotes
.blockquote { configuration in
HStack(spacing: 0) {
RoundedRectangle(cornerRadius: 1.5)
.fill(isDark ? Color.white.opacity(0.2) : Color.gray.opacity(0.4))
.frame(width: 3)
configuration.label
.markdownTextStyle {
ForegroundColor(isDark ? .white.opacity(0.6) : .secondary)
FontSize(14)
}
.padding(.leading, 12)
}
.markdownMargin(top: 8, bottom: 8)
}
// Links
.link {
ForegroundColor(Color.accentColor)
}
// Strong
.strong {
FontWeight(.semibold)
}
// Tables
.table { configuration in
configuration.label
.markdownTableBorderStyle(.init(color: isDark ? .white.opacity(0.15) : .gray.opacity(0.3)))
.markdownTableBackgroundStyle(
.alternatingRows(
isDark
? Color(nsColor: NSColor(white: 0.14, alpha: 1.0))
: Color(nsColor: NSColor(white: 0.96, alpha: 1.0)),
isDark
? Color(nsColor: NSColor(white: 0.10, alpha: 1.0))
: Color(nsColor: NSColor(white: 1.0, alpha: 1.0))
)
)
.markdownMargin(top: 8, bottom: 8)
}
// Thematic break (horizontal rule)
.thematicBreak {
Divider()
.markdownMargin(top: 16, bottom: 16)
}
// List items
.listItem { configuration in
configuration.label
.markdownMargin(top: 4, bottom: 4)
}
// Paragraphs
.paragraph { configuration in
configuration.label
.markdownMargin(top: 4, bottom: 8)
}
}
// MARK: - Focus Flash
private func triggerFocusFlashAnimation() {
focusFlashAnimationGeneration &+= 1
let generation = focusFlashAnimationGeneration
focusFlashOpacity = FocusFlashPattern.values.first ?? 0
for segment in FocusFlashPattern.segments {
DispatchQueue.main.asyncAfter(deadline: .now() + segment.delay) {
guard focusFlashAnimationGeneration == generation else { return }
withAnimation(focusFlashAnimation(for: segment.curve, duration: segment.duration)) {
focusFlashOpacity = segment.targetOpacity
}
}
}
}
private func focusFlashAnimation(for curve: FocusFlashCurve, duration: TimeInterval) -> Animation {
switch curve {
case .easeIn:
return .easeIn(duration: duration)
case .easeOut:
return .easeOut(duration: duration)
}
}
}
// MARK: - MarkdownSearchOverlay
/// Find bar overlay for MarkdownPanelView. Mirrors BrowserSearchOverlay's visual style
/// and drag-to-corner behaviour, but uses a SwiftUI TextField since markdown panels
/// have no webview focus concerns.
struct MarkdownSearchOverlay: View {
let panelId: UUID
@ObservedObject var searchState: MarkdownSearchState
let onNext: () -> Void
let onPrevious: () -> Void
let onClose: () -> Void
@FocusState private var isSearchFieldFocused: Bool
@State private var corner: Corner = .topRight
@State private var dragOffset: CGSize = .zero
@State private var barSize: CGSize = .zero
private let padding: CGFloat = 8
var body: some View {
GeometryReader { geo in
HStack(spacing: 4) {
TextField(
String(localized: "search.placeholder", defaultValue: "Search"),
text: $searchState.needle
)
.focused($isSearchFieldFocused)
.textFieldStyle(.plain)
.frame(width: 180)
.padding(.leading, 8)
.padding(.trailing, 50)
.padding(.vertical, 6)
.background(Color.primary.opacity(0.1))
.cornerRadius(6)
.overlay(alignment: .trailing) {
counterView
}
.onSubmit {
let isShift = NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false
if isShift {
onPrevious()
} else {
onNext()
}
}
.onExitCommand {
onClose()
}
Button(action: {
#if DEBUG
dlog("markdown.findbar.next panel=\(panelId.uuidString.prefix(5))")
#endif
onNext()
}) {
Image(systemName: "chevron.up")
}
.buttonStyle(SearchButtonStyle())
.safeHelp(String(localized: "search.nextMatch.help", defaultValue: "Next match (Return)"))
Button(action: {
#if DEBUG
dlog("markdown.findbar.prev panel=\(panelId.uuidString.prefix(5))")
#endif
onPrevious()
}) {
Image(systemName: "chevron.down")
}
.buttonStyle(SearchButtonStyle())
.safeHelp(String(localized: "search.previousMatch.help", defaultValue: "Previous match (Shift+Return)"))
Button(action: {
#if DEBUG
dlog("markdown.findbar.close panel=\(panelId.uuidString.prefix(5))")
#endif
onClose()
}) {
Image(systemName: "xmark")
}
.buttonStyle(SearchButtonStyle())
.safeHelp(String(localized: "search.close.help", defaultValue: "Close (Esc)"))
}
.padding(8)
.background(.background)
.clipShape(RoundedRectangle(cornerRadius: 8))
.shadow(radius: 4)
.onAppear {
#if DEBUG
dlog("markdown.findbar.appear panel=\(panelId.uuidString.prefix(5))")
#endif
isSearchFieldFocused = true
}
.background(
GeometryReader { barGeo in
Color.clear.onAppear {
barSize = barGeo.size
}
}
)
.padding(padding)
.offset(dragOffset)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: corner.alignment)
.gesture(
DragGesture()
.onChanged { value in
dragOffset = value.translation
}
.onEnded { value in
let centerPos = centerPosition(for: corner, in: geo.size, barSize: barSize)
let newCenter = CGPoint(
x: centerPos.x + value.translation.width,
y: centerPos.y + value.translation.height
)
withAnimation(.easeOut(duration: 0.2)) {
corner = closestCorner(to: newCenter, in: geo.size)
dragOffset = .zero
}
}
)
}
}
@ViewBuilder
private var counterView: some View {
if let currentIndex = searchState.currentIndex {
Text("\(currentIndex + 1)/\(searchState.matches.count)")
.font(.caption)
.foregroundColor(.secondary)
.monospacedDigit()
.padding(.trailing, 8)
} else if !searchState.needle.isEmpty {
Text("0/0")
.font(.caption)
.foregroundColor(.secondary)
.monospacedDigit()
.padding(.trailing, 8)
}
}
// MARK: - Corner drag helpers (mirrors BrowserSearchOverlay)
enum Corner {
case topLeft, topRight, bottomLeft, bottomRight
var alignment: Alignment {
switch self {
case .topLeft: return .topLeading
case .topRight: return .topTrailing
case .bottomLeft: return .bottomLeading
case .bottomRight: return .bottomTrailing
}
}
}
private func centerPosition(for corner: Corner, in containerSize: CGSize, barSize: CGSize) -> CGPoint {
let halfWidth = barSize.width / 2 + padding
let halfHeight = barSize.height / 2 + padding
switch corner {
case .topLeft: return CGPoint(x: halfWidth, y: halfHeight)
case .topRight: return CGPoint(x: containerSize.width - halfWidth, y: halfHeight)
case .bottomLeft: return CGPoint(x: halfWidth, y: containerSize.height - halfHeight)
case .bottomRight: return CGPoint(x: containerSize.width - halfWidth, y: containerSize.height - halfHeight)
}
}
private func closestCorner(to point: CGPoint, in containerSize: CGSize) -> Corner {
let midX = containerSize.width / 2
let midY = containerSize.height / 2
if point.x < midX {
return point.y < midY ? .topLeft : .bottomLeft
}
return point.y < midY ? .topRight : .bottomRight
}
}
// MARK: - MarkdownPointerObserver
private struct MarkdownPointerObserver: NSViewRepresentable {
let onPointerDown: () -> Void
func makeNSView(context: Context) -> MarkdownPanelPointerObserverView {
let view = MarkdownPanelPointerObserverView()
view.onPointerDown = onPointerDown
return view
}
func updateNSView(_ nsView: MarkdownPanelPointerObserverView, context: Context) {
nsView.onPointerDown = onPointerDown
}
}
final class MarkdownPanelPointerObserverView: NSView {
var onPointerDown: (() -> Void)?
private var eventMonitor: Any?
private weak var forwardedMouseTarget: NSView?
override var mouseDownCanMoveWindow: Bool { false }
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
installEventMonitorIfNeeded()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
if let eventMonitor {
NSEvent.removeMonitor(eventMonitor)
}
}
override func hitTest(_ point: NSPoint) -> NSView? {
guard PaneFirstClickFocusSettings.isEnabled(),
window?.isKeyWindow != true,
bounds.contains(point) else { return nil }
return self
}
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
PaneFirstClickFocusSettings.isEnabled()
}
override func mouseDown(with event: NSEvent) {
onPointerDown?()
forwardedMouseTarget = forwardedTarget(for: event)
forwardedMouseTarget?.mouseDown(with: event)
}
override func mouseDragged(with event: NSEvent) {
forwardedMouseTarget?.mouseDragged(with: event)
}
override func mouseUp(with event: NSEvent) {
forwardedMouseTarget?.mouseUp(with: event)
forwardedMouseTarget = nil
}
func shouldHandle(_ event: NSEvent) -> Bool {
guard event.type == .leftMouseDown,
let window,
event.window === window,
!isHiddenOrHasHiddenAncestor else { return false }
if PaneFirstClickFocusSettings.isEnabled(), window.isKeyWindow != true {
return false
}
let point = convert(event.locationInWindow, from: nil)
return bounds.contains(point)
}
func handleEventIfNeeded(_ event: NSEvent) -> NSEvent {
guard shouldHandle(event) else { return event }
DispatchQueue.main.async { [weak self] in
self?.onPointerDown?()
}
return event
}
private func installEventMonitorIfNeeded() {
guard eventMonitor == nil else { return }
eventMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) { [weak self] event in
self?.handleEventIfNeeded(event) ?? event
}
}
private func forwardedTarget(for event: NSEvent) -> NSView? {
guard let window else {
#if DEBUG
NSLog("MarkdownPanelPointerObserverView.forwardedTarget skipped, window=0 contentView=0")
#endif
return nil
}
guard let contentView = window.contentView else {
#if DEBUG
NSLog("MarkdownPanelPointerObserverView.forwardedTarget skipped, window=1 contentView=0")
#endif
return nil
}
isHidden = true
defer { isHidden = false }
let point = contentView.convert(event.locationInWindow, from: nil)
let target = contentView.hitTest(point)
return target === self ? nil : target
}
}