-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDiffTextViewRepresentable.swift
More file actions
84 lines (77 loc) · 2.72 KB
/
DiffTextViewRepresentable.swift
File metadata and controls
84 lines (77 loc) · 2.72 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
import AppKit
import SwiftUI
struct DiffTextViewRepresentable: NSViewRepresentable {
let result: TextDiffResult?
let original: String
let updated: String
let updatedBinding: Binding<String>?
let style: TextDiffStyle
let mode: TextDiffComparisonMode
let showsInvisibleCharacters: Bool
let isRevertActionsEnabled: Bool
let onRevertAction: ((TextDiffRevertAction) -> Void)?
func makeCoordinator() -> Coordinator {
Coordinator()
}
func makeNSView(context: Context) -> NSTextDiffView {
let view: NSTextDiffView
if let result {
view = NSTextDiffView(result: result, style: style)
} else {
view = NSTextDiffView(
original: original,
updated: updated,
style: style,
mode: mode
)
}
view.setContentCompressionResistancePriority(.required, for: .vertical)
view.setContentHuggingPriority(.required, for: .vertical)
context.coordinator.update(
updatedBinding: updatedBinding,
onRevertAction: onRevertAction
)
view.showsInvisibleCharacters = showsInvisibleCharacters
view.isRevertActionsEnabled = result == nil ? isRevertActionsEnabled : false
view.onRevertAction = { [coordinator = context.coordinator] action in
coordinator.handle(action)
}
return view
}
func updateNSView(_ view: NSTextDiffView, context: Context) {
context.coordinator.update(
updatedBinding: updatedBinding,
onRevertAction: onRevertAction
)
view.onRevertAction = { [coordinator = context.coordinator] action in
coordinator.handle(action)
}
view.showsInvisibleCharacters = showsInvisibleCharacters
view.isRevertActionsEnabled = result == nil ? isRevertActionsEnabled : false
if let result {
view.setContent(result: result, style: style)
} else {
view.setContent(
original: original,
updated: updated,
style: style,
mode: mode
)
}
}
final class Coordinator {
private var updatedBinding: Binding<String>?
private var onRevertAction: ((TextDiffRevertAction) -> Void)?
func update(
updatedBinding: Binding<String>?,
onRevertAction: ((TextDiffRevertAction) -> Void)?
) {
self.updatedBinding = updatedBinding
self.onRevertAction = onRevertAction
}
func handle(_ action: TextDiffRevertAction) {
updatedBinding?.wrappedValue = action.resultingUpdated
onRevertAction?(action)
}
}
}