-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.go
452 lines (371 loc) · 11.3 KB
/
root.go
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
package ui
import (
"context"
"errors"
"fmt"
"github.com/gdamore/tcell/v2"
"github.com/mbpolan/lull/internal/events"
"github.com/mbpolan/lull/internal/network"
"github.com/mbpolan/lull/internal/state"
"github.com/mbpolan/lull/internal/util"
"github.com/rivo/tview"
"strings"
"time"
)
var application *tview.Application
const (
rootPageMain string = "main"
rootPageModal string = "modal"
)
// Root is a top-level container for all application UI components.
type Root struct {
pages *tview.Pages
flex *tview.Flex
collection *Collection
content *Content
StatusBar *StatusBar
buildMeta *util.BuildMeta
currentModal string
lastFocus tview.Primitive
network *network.Manager
state *state.Manager
}
// NewRoot returns a new Root instance.
func NewRoot(app *tview.Application, stateManager *state.Manager, buildMeta *util.BuildMeta) *Root {
application = app
r := new(Root)
r.buildMeta = buildMeta
r.currentModal = ""
r.network = network.NewNetworkManager(r.handleRequestFinished)
r.state = stateManager
r.build()
events.Dispatcher().Subscribe(r, []events.Code{events.EventNavigateRight, events.EventNavigateLeft})
return r
}
// GetApplication returns the shared instance of tview.Application.
func GetApplication() *tview.Application {
return application
}
func (r *Root) HandleEvent(code events.Code, payload events.Payload) {
switch code {
case events.EventNavigateRight:
// navigate right from collection
if payload.Sender == r.collection {
r.content.SetFocus(ContentURLBox)
}
case events.EventNavigateLeft:
// navigate left from content
if payload.Sender == r.content {
r.collection.SetFocus()
}
default:
break
}
}
// Widget returns a primitive widget containing this component.
func (r *Root) Widget() tview.Primitive {
return r.pages
}
func (r *Root) build() {
r.pages = tview.NewPages()
// create child widgets
r.collection = NewCollection(r.state)
r.collection.SetItemActivatedHandler(r.handleCollectionItemAction)
r.content = NewContent(r.state)
r.StatusBar = NewStatusBar()
// arrange the collection and content in a flex layout
mc := tview.NewFlex()
mc.AddItem(r.collection.Widget(), 25, 0, false)
mc.AddItem(r.content.Widget(), 0, 1, true)
// arrange the main content flex layout and the status bar in a parent flex
r.flex = tview.NewFlex()
r.flex.SetDirection(tview.FlexRow)
r.flex.AddItem(mc, 0, 1, true)
r.flex.AddItem(r.StatusBar.Widget(), 1, 0, false)
r.flex.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
if event.Modifiers()&tcell.ModCtrl > 0 {
if r.handleControlKeyAction(event.Key(), event.Rune()) {
return nil
}
} else if event.Modifiers()&tcell.ModShift == tcell.ModShift {
if r.handleShiftKeyAction(event.Key(), event.Rune()) {
return nil
}
}
return event
})
// create pages containing the main content and various modals that can be opened
r.pages.AddAndSwitchToPage(rootPageMain, r.flex, true)
// set initial focus on the url box
r.content.SetFocus(ContentURLBox)
}
func (r *Root) handleControlKeyAction(code tcell.Key, key rune) bool {
switch code {
case tcell.KeyCtrlA:
r.showAboutModal()
case tcell.KeyCtrlL:
r.collection.SetFocus()
case tcell.KeyCtrlR:
r.content.SetFocus(ContentRequestBody)
case tcell.KeyCtrlY:
r.content.SetFocus(ContentResponseBody)
case tcell.KeyCtrlG:
r.sendCurrentRequest()
case tcell.KeyCtrlS:
r.showSaveCurrentRequest()
default:
return false
}
return true
}
func (r *Root) handleShiftKeyAction(code tcell.Key, key rune) bool {
switch code {
case tcell.KeyRight:
if !r.content.Widget().HasFocus() {
r.content.SetFocus(ContentURLBox)
}
case tcell.KeyLeft:
if !r.collection.Widget().HasFocus() {
r.collection.SetFocus()
}
default:
return false
}
return true
}
func (r *Root) pathToSelectedCollectionItemGroup() []*state.CollectionItem {
item := r.state.Get().SelectedItem
if item == nil {
// really shouldn't happen; default to collection root
item = r.state.Get().Collection
}
// if this item is not a group, select its parent
if !item.IsGroup {
item = item.Parent
}
return append(item.Ancestors(), item)
}
func (r *Root) handleCollectionItemAction(action CollectionItemAction, item *state.CollectionItem) {
switch action {
case CollectionItemRename:
r.handleRenameSelectedItem(item)
case CollectionItemAdd:
r.handleAddItem(item)
case CollectionItemDelete:
r.handleDeleteSelectedItem(item)
case CollectionItemClone:
r.handleCloneSelectedItem(item)
case CollectionItemOpen:
r.setCurrentRequest(item)
}
}
func (r *Root) handleRenameSelectedItem(item *state.CollectionItem) {
text := fmt.Sprintf("Current request name: [yellow]%s", item.Name)
m := NewTextInputModal("Rename Item", text, "New Name", r.renameSelectedItem, r.hideCurrentModal)
r.showModal(m.Widget())
}
func (r *Root) handleAddItem(item *state.CollectionItem) {
parent := item
if !item.IsGroup {
parent = item.Parent
}
// generate a unique name amongst the children of this group
unique := func(name string) bool {
for _, i := range parent.Children {
if i.Name == name {
return false
}
}
return true
}
name := ""
for i := 1; i > 0; i++ {
name = fmt.Sprintf("Request %d", i)
if unique(name) {
break
}
}
newItem := state.NewCollectionRequest(name, "GET", "", parent)
parent.AddChild(newItem)
r.state.Get().SelectedItem = newItem
r.state.Get().ActiveItem = newItem
r.collection.Reload()
r.content.Reload()
}
func (r *Root) handleDeleteSelectedItem(item *state.CollectionItem) {
text := fmt.Sprintf("Are you sure you want to delete [yellow]%s?", item.Name)
m := NewPromptModal("Delete Item", text, r.deleteSelectedItem, r.hideCurrentModal)
r.showModal(m.Widget())
}
func (r *Root) handleCloneSelectedItem(item *state.CollectionItem) {
text := fmt.Sprintf("Clone request [yellow]%s", item.Name)
m := NewTextInputModal("Clone Item", text, "Name", r.cloneSelectedItem, r.hideCurrentModal)
r.showModal(m.Widget())
}
func (r *Root) deleteSelectedItem() {
item := r.state.Get().SelectedItem
if item == nil {
return
}
// remove this item from the collection
r.state.Get().RemoveCollectionItem(item)
// find another item to select
candidate := r.state.Get().FirstCollectionItem(func(i *state.CollectionItem) bool {
return !i.IsGroup
})
// if there are no other items to activate, create a new one first
if candidate == nil {
candidate = state.NewCollectionRequest("Unnamed", "GET", "", r.state.Get().Collection)
r.state.Get().Collection.AddChild(candidate)
}
// if we're deleting the currently active item, set it to the candidate item as well
// the active item will be set to nil if that's the case as a result of the call to RemoveCollectionItem above
if r.state.Get().ActiveItem == nil {
r.state.Get().ActiveItem = candidate
r.content.Reload()
}
r.state.Get().SelectedItem = candidate
r.collection.Reload()
r.hideCurrentModal()
}
func (r *Root) renameSelectedItem(text string) {
item := r.state.Get().SelectedItem
if item == nil {
return
}
// rename this item and reload our content
item.Name = text
r.collection.Reload()
r.content.Reload()
r.hideCurrentModal()
}
func (r *Root) cloneSelectedItem(text string) {
item := r.state.Get().SelectedItem
if item == nil {
return
}
// cloning a group item means we need to do a deep copy of all its children as well
if item.IsGroup {
// TODO
} else {
newItem := state.NewCollectionRequest(text, item.Method, item.URL, item.Parent)
item.Parent.InsertChildAfter(newItem, item)
// automatically select and activate the newly cloned item
r.state.Get().ActiveItem = newItem
r.state.Get().SelectedItem = newItem
}
r.collection.Reload()
r.content.Reload()
r.hideCurrentModal()
}
func (r *Root) showSaveCurrentRequest() {
// collect ancestors and form a path
ancestors := r.pathToSelectedCollectionItemGroup()
path := make([]string, len(ancestors))
for _, i := range ancestors {
path = append(path, i.Name)
}
text := fmt.Sprintf("Request will be saved under [yellow]%s", strings.Join(path, " > "))
m := NewTextInputModal("Save Request", text, "Name", r.handleSaveCurrentRequest, r.hideCurrentModal)
r.showModal(m.Widget())
}
func (r *Root) handleSaveCurrentRequest(name string) {
active := r.state.Get().ActiveItem
if active == nil {
return
}
path := r.pathToSelectedCollectionItemGroup()
leaf := path[len(path)-1]
// collect current request information and add it to the collection
item := state.NewCollectionRequest(name, active.Method, active.URL, leaf)
item.RequestBody = active.RequestBody
item.Result = active.Result
leaf.AddChild(item)
r.collection.Reload()
r.hideCurrentModal()
r.state.SetDirty()
}
func (r *Root) handleCancelCurrentRequest() {
r.network.CancelCurrent()
r.hideCurrentModal()
}
func (r *Root) setCurrentRequest(item *state.CollectionItem) {
if r.state.Get().ActiveItem == item {
return
}
// reload views to synchronize with app state
r.state.Get().ActiveItem = item
r.content.Reload()
r.state.SetDirty()
}
func (r *Root) showModal(modal tview.Primitive) {
r.lastFocus = GetApplication().GetFocus()
r.pages.AddPage(rootPageModal, modal, true, true)
}
func (r *Root) hideCurrentModal() {
r.pages.RemovePage(rootPageModal)
if r.lastFocus != nil {
GetApplication().SetFocus(r.lastFocus)
r.lastFocus = nil
}
}
func (r *Root) sendCurrentRequest() {
item := r.state.Get().ActiveItem
if item == nil {
return
}
var m *AlertModal
if err := r.network.SendRequest(item); err != nil {
m = NewAlertModal("Error", fmt.Sprintf("Can't send this request: %s", err.Error()), "OK", r.hideCurrentModal)
} else {
m = NewAlertModal("Sending", "Request is in flight...", "Cancel", r.handleCancelCurrentRequest)
}
r.showModal(m.Widget())
}
func (r *Root) handleRequestFinished(item *state.CollectionItem, result *network.Result) {
if result.Error != nil {
item.Result = nil
r.state.Get().LastError = result.Error
// if the error is because the request was cancelled, we don't need to show any modals
if errors.Is(result.Error, context.Canceled) {
return
}
GetApplication().QueueUpdateDraw(func() {
m := NewAlertModal("Error", fmt.Sprintf("Could not send request. Error: %s", result.Error.Error()), "OK", r.hideCurrentModal)
r.hideCurrentModal()
r.showModal(m.Widget())
r.content.Reload()
r.state.SetDirty()
})
return
}
r.state.Get().LastError = nil
item.Result = &state.HTTPResult{
Response: result.Response,
Payload: result.Payload,
PayloadError: result.PayloadError,
Duration: result.EndTime.Sub(result.StartTime),
}
GetApplication().QueueUpdateDraw(func() {
r.hideCurrentModal()
r.content.Reload()
r.state.SetDirty()
})
}
func (r *Root) showAboutModal() {
commitShort := r.buildMeta.Commit
if len(commitShort) > 7 {
commitShort = r.buildMeta.Commit[0:7]
}
dateFriendly := r.buildMeta.Date
date, err := time.Parse(time.RFC3339, r.buildMeta.Date)
if err == nil {
dateFriendly = date.Format("2006-01-02 15:04:05")
}
info := fmt.Sprintf("lull is a lightweight, keyboard-friendly REST\nclient. Join the development at\n")
info = fmt.Sprintf("%shttps://github.com/mbpolan/lull\n\n", info)
info = fmt.Sprintf("%sVersion %s (%s)\n", info, r.buildMeta.Version, commitShort)
info = fmt.Sprintf("%sBuilt on %s", info, dateFriendly)
m := NewAlertModal("About", info, "OK", r.hideCurrentModal)
r.showModal(m.Widget())
}