-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCommandPanelView.swift
384 lines (342 loc) · 11 KB
/
CommandPanelView.swift
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
import Bonzai
import SwiftUI
@MainActor
final class CommandPanelViewPublisher: ObservableObject {
@MainActor
@Published private(set) var state: CommandPanelView.CommandState
@MainActor
init(state: CommandPanelView.CommandState = .ready) {
self.state = state
}
@MainActor
func publish(_ newState: CommandPanelView.CommandState) {
self.state = newState
}
}
struct CommandPanelView: View {
enum CommandState: Hashable, Equatable {
case ready
case running
case error(String)
case done(String)
}
@ObservedObject var publisher: CommandPanelViewPublisher
@State var output: String = ""
@State var command: ScriptCommand
let onChange: (String) -> Void
let onSubmit: (ScriptCommand) -> Void
let action: () -> Void
init(publisher: CommandPanelViewPublisher,
command: ScriptCommand,
onChange: @escaping (String) -> Void,
onSubmit: @escaping (ScriptCommand) -> Void,
action: @escaping () -> Void) {
self.command = command
self.publisher = publisher
self.onChange = onChange
self.onSubmit = onSubmit
self.action = action
}
var body: some View {
VStack(spacing: 0) {
CommandPanelHeaderView(
state: publisher.state,
name: command.name,
action: action
)
.roundedContainer(padding: 4, margin: 4)
ScrollView {
VStack(spacing: 8) {
switch command.source {
case .path(let source):
let viewModel = CommandViewModel.Kind.ScriptModel(
id: command.id,
source: .path(source),
scriptExtension: command.kind,
variableName: "",
execution: .concurrent
)
ScriptCommandContentView(viewModel, meta: .init(name: "Name", namePlaceholder: ""), onSubmit: {
onSubmit(command)
}, onAction: { action in
switch action {
case .updateSource(let scriptModel):
switch scriptModel.source {
case .inline(let contents):
onChange(contents)
default: break
}
default: break
}
})
.roundedContainer(padding: 4, margin: 4)
case .inline(let source):
let viewModel = CommandViewModel.Kind.ScriptModel(
id: command.id,
source: .inline(source),
scriptExtension: command.kind,
variableName: "",
execution: .concurrent
)
ScriptCommandContentView(viewModel, meta: .init(name: "Name", namePlaceholder: ""), onSubmit: {
onSubmit(command)
}, onAction: { action in
switch action {
case .updateSource(let scriptModel):
switch scriptModel.source {
case .inline(let contents), .path(let contents):
command.source.contents = contents
onChange(contents)
}
default: break
}
})
.roundedContainer(padding: 4, margin: 4)
}
CommandPanelOutputView(state: publisher.state)
.frame(maxWidth: .infinity)
.roundedContainer(padding: 4, margin: 4)
}
}
}
.roundedContainer(padding: 8, margin: 4)
.frame(minWidth: 200, minHeight: 200)
}
@MainActor
static func preview(_ state: CommandPanelView.CommandState, command: ScriptCommand) -> some View {
let publisher = CommandPanelViewPublisher(state: state)
return CommandPanelView(publisher: publisher, command: command, onChange: { _ in }, onSubmit: { _ in }) {
switch publisher.state {
case .ready: publisher.publish(.running)
case .running: publisher.publish(.error("ops!"))
case .error: publisher.publish(.done("done"))
case .done: publisher.publish(.ready)
}
}
.padding()
}
}
private struct CommandPanelHeaderView: View {
let state: CommandPanelView.CommandState
let name: String
let action: () -> Void
var body: some View {
HStack {
ScriptIconView(size: 24)
Text(name)
.font(.headline)
Spacer()
Button(action: action,
label: {
Text(Self.buttonText(state))
.frame(minWidth: 80)
})
.buttonStyle(.zen(.init(color: Self.buttonColor(state))))
.fixedSize()
.animation(.easeIn, value: state)
}
}
private static func buttonColor(_ state: CommandPanelView.CommandState) -> ZenColor {
switch state {
case .ready: .systemGray
case .running: .accentColor
case .error: .systemRed
case .done: .systemGreen
}
}
private static func buttonText(_ state: CommandPanelView.CommandState) -> String {
switch state {
case .ready: "Run"
case .running: "Cancel"
case .error: "Run again…"
case .done: "Run"
}
}
}
private struct CommandPanelOutputView: View {
let state: CommandPanelView.CommandState
var body: some View {
switch state {
case .ready:
Color.clear
case .running:
ProgressView()
.padding()
case .error(let contents):
CommandPanelErrorView(contents: contents)
case .done(let contents):
CommandPanelSuccessView(contents: contents)
}
}
}
private struct CommandPanelErrorView: View {
let contents: String
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 4) {
Text("[Exit Code]")
ZenDivider(.vertical)
Text("Error Message")
.frame(maxWidth: .infinity, alignment: .leading)
ErrorIconView(size: 16)
}
.font(.headline)
.padding(8)
.background(
LinearGradient(stops: [
.init(color: Color(.systemRed).opacity(0.4), location: 0),
.init(color: Color(.systemRed.withSystemEffect(.disabled)).opacity(0.2), location: 1),
], startPoint: .top, endPoint: .bottom)
)
ZenDivider()
Text(contents)
.textSelection(.enabled)
.fontDesign(.monospaced)
.frame(maxWidth: .infinity, alignment: .leading)
.font(.system(.callout))
.padding(8)
}
}
}
}
private struct CommandPanelSuccessView: View {
private let searchSets = [
SearchSet(regexPattern: { _ in "\\{|\\}|\\[|\\]|\"" },
color: Color(.controlAccentColor.withSystemEffect(.pressed))),
SearchSet(regexPattern: { _ in "\\d+" },
color: Color(.systemRed.withAlphaComponent(0.7))),
]
let contents: String
var body: some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 4) {
Text("Result")
.frame(maxWidth: .infinity, alignment: .leading)
}
.font(.headline)
.padding(8)
.background(
LinearGradient(stops: [
.init(color: Color(.systemGreen).opacity(0.2), location: 0),
.init(color: Color(.systemGreen.withSystemEffect(.disabled)).opacity(0.1), location: 1),
], startPoint: .top, endPoint: .bottom)
)
ZenDivider()
Text(AttributedString(contents).syntaxHighlight(searchSets: searchSets).linkDetector(contents))
.textSelection(.enabled)
.allowsTightening(true)
.fontDesign(.monospaced)
.frame(maxWidth: .infinity, alignment: .leading)
.font(.system(.callout))
.padding(8)
}
}
}
let prCommand = ScriptCommand(
kind: .shellScript,
source: .inline("gh pr ls"),
meta: .init(name: "This is a script")
)
let prCommandResult = """
Showing 1 of 1 open pull request in zenangst/KeyboardCowboy
ID TITLE BRANCH CREATED AT
#453 Feature Keyboard Cowboy stats feature/keyboard-cowboy-stats about 4 months ago
"""
let prCommandWithJQ = ScriptCommand(
kind: .shellScript,
source: .inline("gh pr ls --json url,title,number,headRefName,reviewDecision,changedFiles,deletions"),
meta: .init(name: "Run GitHub CLI with jq")
)
let prCommandWithJQResult = """
[
{
"changedFiles": 2,
"deletions": 0,
"headRefName": "feature/keyboard-cowboy-stats",
"number": 453,
"reviewDecision": "",
"title": "Feature Keyboard Cowboy stats",
"url": "https://github.com/zenangst/KeyboardCowboy/pull/453"
}
]
"""
#Preview("gh pr ls - with JQ") { CommandPanelView.preview(.done(prCommandWithJQResult), command: prCommandWithJQ) }
#Preview("gh pr ls") { CommandPanelView.preview(.done(prCommandResult), command: prCommand) }
#Preview("Error") { CommandPanelView.preview(.error("Oh shit!"), command: prCommand) }
#Preview("Ready") { CommandPanelView.preview(.ready, command: prCommand) }
extension AttributedString {
func linkDetector(_ originalString: String) -> AttributedString {
var attributedString = self
let types = NSTextCheckingResult.CheckingType.link.rawValue
guard let detector = try? NSDataDetector(types: types) else {
return attributedString
}
let matches = detector.matches(
in: originalString,
options: [],
range: NSRange(location: 0, length: originalString.count)
)
for match in matches {
let range = match.range
let startIndex = attributedString.index(
attributedString.startIndex,
offsetByCharacters: range.lowerBound
)
let endIndex = attributedString.index(
startIndex,
offsetByCharacters: range.length
)
switch match.resultType {
case .link:
if let url = match.url {
attributedString[startIndex..<endIndex].link = url
attributedString[startIndex..<endIndex].foregroundColor = Color(nsColor: .controlAccentColor.withSystemEffect(.deepPressed))
}
default:
continue
}
}
return attributedString
}
func syntaxHighlight(searchSets: [SearchSet]) -> AttributedString {
var attrInText: AttributedString = self
searchSets.forEach { searchSet in
searchSet.words?.forEach({ word in
guard let regex = try? Regex<Substring>(searchSet.regexPattern(word))
else {
fatalError("Failed to create regular expession")
}
processMatches(attributedText: &attrInText,
regex: regex,
color: searchSet.color)
})
}
return attrInText
}
private func processMatches(attributedText: inout AttributedString,
regex: Regex<Substring>,
color: Color) {
let orignalText: String = (
attributedText.characters.compactMap { c in
String(c)
} as [String]).joined()
orignalText.matches(of: regex).forEach { match in
if let swiftRange = Range(match.range, in: attributedText) {
attributedText[swiftRange].foregroundColor = NSColor(color)
}
}
}
}
struct SearchSet {
let words: [String]?
let regexPattern: (String) -> String
let color: Color
init(words: [String]? = nil,
regexPattern: @escaping (String) -> String,
color: Color) {
self.words = words ?? [""]
self.regexPattern = regexPattern
self.color = color
}
}