-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathreply-view.go
1032 lines (953 loc) · 27.7 KB
/
reply-view.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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"image"
"image/color"
"log"
"net/url"
"os/exec"
"runtime"
"strings"
"time"
"gioui.org/io/clipboard"
"gioui.org/io/key"
"gioui.org/layout"
"gioui.org/unit"
"gioui.org/widget"
"gioui.org/widget/material"
"github.com/inkeliz/giohyperlink"
"git.sr.ht/~athorp96/forest-ex/expiration"
forest "git.sr.ht/~whereswaldon/forest-go"
"git.sr.ht/~whereswaldon/forest-go/fields"
"git.sr.ht/~whereswaldon/forest-go/store"
"git.sr.ht/~whereswaldon/forest-go/twig"
materials "gioui.org/x/component"
"git.sr.ht/~whereswaldon/sprig/anim"
"git.sr.ht/~whereswaldon/sprig/core"
"git.sr.ht/~whereswaldon/sprig/ds"
"git.sr.ht/~whereswaldon/sprig/icons"
sprigWidget "git.sr.ht/~whereswaldon/sprig/widget"
sprigTheme "git.sr.ht/~whereswaldon/sprig/widget/theme"
)
type FilterState uint8
const (
Off FilterState = iota
Conversation
Message
)
const replyCoverAnimationTime = 100 * time.Millisecond
// FocusTracker keeps track of which message (if any) is focused and the status
// of ancestor/descendant messages relative to that message.
type FocusTracker struct {
Pending *ds.ReplyData
Focused *ds.ReplyData
Ancestry []*fields.QualifiedHash
Descendants []*fields.QualifiedHash
// Whether the Ancestry and Descendants need to be regenerated because the
// contents of the replylist changed
stateRefreshNeeded bool
}
// SetFocus requests that the provided ReplyData become the focused message.
func (f *FocusTracker) SetFocus(focused *ds.ReplyData) {
f.stateRefreshNeeded = true
f.Focused = focused
}
// SetFocusDeferred requests that the provided ReplyData become the focused message
// at the next state refresh.
func (f *FocusTracker) SetFocusDeferred(focused *ds.ReplyData) {
f.stateRefreshNeeded = true
f.Pending = focused
}
// Invalidate notifies the FocusTracker that its Ancestry and Descendants lists
// are possibly incorrect as a result of a state change elsewhere.
func (f *FocusTracker) Invalidate() {
f.stateRefreshNeeded = true
}
// RefreshNodeStatus updates the Ancestry and Descendants of the FocusTracker
// using the provided store to look them up. If the FocusTracker has not been
// invalidated since this method was last invoked, this method will return
// false and do nothing.
func (f *FocusTracker) RefreshNodeStatus(s store.ExtendedStore) bool {
if f.stateRefreshNeeded {
f.stateRefreshNeeded = false
if f.Pending != nil {
f.Focused, f.Pending = f.Pending, nil
}
if f.Focused == nil {
f.Ancestry = nil
f.Descendants = nil
return true
}
f.Ancestry, _ = s.AncestryOf(f.Focused.ID)
f.Descendants, _ = s.DescendantsOf(f.Focused.ID)
return true
}
return false
}
// StatusFor returns one of these statuses for a ReplyData, depending on
// what is currently focused:
// - Selected
// - Ancestor
// - Descendant
func (f *FocusTracker) StatusFor(rd ds.ReplyData) (status sprigWidget.ReplyStatus) {
if f.Focused == nil || f.Focused.ID == nil {
return
}
if rd.ID.Equals(f.Focused.ID) {
return sprigWidget.Selected
}
for _, id := range f.Ancestry {
if id.Equals(rd.ID) {
return sprigWidget.Ancestor
}
}
for _, id := range f.Descendants {
if id.Equals(rd.ID) {
return sprigWidget.Descendant
}
}
if f.Focused.ConversationID != nil &&
f.Focused.ConversationID.Equals(rd.ConversationID) {
return sprigWidget.Sibling
}
return
}
// ReplyListView manages the state and layout of the reply list view in
// Sprig's UI.
type ReplyListView struct {
manager ViewManager
core.App
CopyReplyButton widget.Clickable
sprigWidget.MessageList
ds.AlphaReplyList
FocusTracker
sprigWidget.Composer
replyListCover materials.ScrimState
FilterButton widget.Clickable
CreateReplyButton widget.Clickable
CreateConversationButton widget.Clickable
JumpToBottomButton, JumpToTopButton widget.Clickable
HideDescendantsButton widget.Clickable
LoadMoreHistoryButton widget.Clickable
// how many nodes of history does the view want
HistoryRequestCount int
FilterState
ds.HiddenTracker
PrefilterPosition layout.Position
ShouldRequestKeyboardFocus bool
// Cache the number of replies during update.
replyCount int
// Maximum number of visible replies encountered.
maxRepliesVisible int
// Loading if replies are loading.
loading bool
}
var _ View = &ReplyListView{}
// NewReplyListView constructs a ReplyList that relies on the provided App.
func NewReplyListView(app core.App) View {
c := &ReplyListView{
App: app,
HistoryRequestCount: 2048,
}
c.MessageList.Animation.Normal = anim.Normal{
Duration: time.Millisecond * 100,
}
c.MessageList.ShouldHide = func(r ds.ReplyData) bool {
return c.HiddenTracker.IsHidden(r.ID) || c.shouldFilter(c.statusOf(r))
}
c.MessageList.StatusOf = func(r ds.ReplyData) sprigWidget.ReplyStatus {
return c.statusOf(r)
}
c.MessageList.UserIsActive = func(identity *fields.QualifiedHash) bool {
return c.Status().IsActive(identity)
}
c.MessageList.HiddenChildren = func(r ds.ReplyData) int {
return c.HiddenTracker.NumDescendants(r.ID)
}
c.replyListCover = materials.ScrimState{
VisibilityAnimation: materials.VisibilityAnimation{
Duration: replyCoverAnimationTime,
State: materials.Invisible,
},
}
c.loading = true
go func() {
defer func() { c.loading = false }()
c.AlphaReplyList.FilterWith(func(rd ds.ReplyData) bool {
td := rd.Metadata
if _, ok := td.Values[twig.Key{Name: "invisible", Version: 1}]; ok {
return false
}
if expired, err := expiration.IsExpiredTwig(rd.Metadata); err != nil || expired {
return false
}
return true
})
c.MessageList.Axis = layout.Vertical
// ensure that we are notified when we need to refresh the state of visible nodes
c.Arbor().Store().SubscribeToNewMessages(func(node forest.Node) {
go func() {
var rd ds.ReplyData
if !rd.Populate(node, c.Arbor().Store()) {
return
}
c.AlphaReplyList.Insert(rd)
c.FocusTracker.Invalidate()
c.manager.RequestInvalidate()
c.HiddenTracker.Process(node)
}()
})
c.MessageList.ScrollToEnd = true
c.MessageList.Position.BeforeEnd = false
c.loadMoreHistory()
}()
return c
}
// Filtered returns whether or not the ReplyList is currently filtering
// its contents.
func (c *ReplyListView) Filtered() bool {
return c.FilterState != Off
}
// HandleIntent processes requests from other views in the application.
func (c *ReplyListView) HandleIntent(intent Intent) {}
// BecomeVisible handles setup for when this view becomes the visible
// view in the application.
func (c *ReplyListView) BecomeVisible() {
}
// NavItem returns the top-level navigation information for this view.
func (c *ReplyListView) NavItem() *materials.NavItem {
return &materials.NavItem{
Name: "Messages",
Icon: icons.ChatIcon,
}
}
// AppBarData returns the app bar actions for this view.
func (c *ReplyListView) AppBarData() (bool, string, []materials.AppBarAction, []materials.OverflowAction) {
th := c.Theme().Current().Theme
return true, "Messages", []materials.AppBarAction{
materials.SimpleIconAction(
&c.CreateConversationButton,
icons.CreateConversationIcon,
materials.OverflowAction{
Name: "Create Conversation",
Tag: &c.CreateConversationButton,
},
),
{
OverflowAction: materials.OverflowAction{
Name: "Filter by selected",
Tag: &c.FilterButton,
},
Layout: func(gtx C, bg, fg color.NRGBA) D {
var buttonForeground, buttonBackground color.NRGBA
var buttonText string
btn := material.ButtonLayout(th, &c.FilterButton)
switch c.FilterState {
case Conversation:
buttonForeground = bg
buttonBackground = fg
buttonBackground.A = 150
buttonText = "Cvn"
case Message:
buttonForeground = bg
buttonBackground = fg
buttonText = "Msg"
default:
buttonForeground = fg
buttonBackground = bg
buttonText = "Off"
}
btn.Background = buttonBackground
return btn.Layout(gtx, func(gtx C) D {
return layout.UniformInset(unit.Dp(12)).Layout(gtx, func(gtx C) D {
return layout.Flex{Alignment: layout.Middle}.Layout(gtx,
layout.Rigid(func(gtx C) D {
icon := icons.FilterIcon
sz := gtx.Dp(unit.Dp(24))
gtx.Constraints = layout.Exact(image.Pt(sz, sz))
return icon.Layout(gtx, buttonForeground)
}),
layout.Rigid(func(gtx C) D {
gtx.Constraints.Max.X = gtx.Dp(unit.Dp(40))
gtx.Constraints.Min.X = gtx.Constraints.Max.X
label := material.Body1(th, buttonText)
label.Color = buttonForeground
label.MaxLines = 1
return layout.Inset{Left: unit.Dp(6)}.Layout(gtx, label.Layout)
}),
)
})
})
},
},
}, []materials.OverflowAction{
{
Name: "Jump to top",
Tag: &c.JumpToTopButton,
},
{
Name: "Jump to bottom",
Tag: &c.JumpToBottomButton,
},
{
Name: "Load more history",
Tag: &c.LoadMoreHistoryButton,
},
}
}
// getContextualActions returns the contextual app bar actions for this
// view (rather than the standard, non-contexual bar actions).
func (c *ReplyListView) getContextualActions() ([]materials.AppBarAction, []materials.OverflowAction) {
return []materials.AppBarAction{
materials.SimpleIconAction(
&c.CopyReplyButton,
icons.CopyIcon,
materials.OverflowAction{
Name: "Copy reply text",
Tag: &c.CopyReplyButton,
},
),
materials.SimpleIconAction(
&c.CreateReplyButton,
icons.ReplyIcon,
materials.OverflowAction{
Name: "Reply to selected",
Tag: &c.CreateReplyButton,
},
),
{
OverflowAction: materials.OverflowAction{
Name: "Hide/Show descendants",
Tag: &c.HideDescendantsButton,
},
Layout: func(gtx C, bg, fg color.NRGBA) D {
btn := materials.SimpleIconButton(bg, fg, &c.HideDescendantsButton, icons.ExpandIcon)
btn.Background = bg
btn.Color = fg
focusedID := c.FocusTracker.Focused.ID
if c.HiddenTracker.IsAnchor(focusedID) {
btn.Icon = icons.ExpandIcon
} else {
btn.Icon = icons.CollapseIcon
}
return btn.Layout(gtx)
},
},
}, []materials.OverflowAction{}
}
// triggerReplyContextMenu changes the app bar to contextual mode and
// populates its actions with contextual options.
func (c *ReplyListView) triggerReplyContextMenu(gtx layout.Context) {
actions, overflow := c.getContextualActions()
c.manager.RequestContextualBar(gtx, "Message Operations", actions, overflow)
}
// dismissReplyContextMenu returns the app bar to non-contextual mode.
func (c *ReplyListView) dismissReplyContextMenu(gtx layout.Context) {
c.manager.DismissContextualBar(gtx)
}
// moveFocusUp shifts the focused message up by one, if possible.
func (c *ReplyListView) moveFocusUp() {
c.moveFocus(-1)
}
// moveFocusDown shifts the focused message down by one, if possible.
func (c *ReplyListView) moveFocusDown() {
c.moveFocus(1)
}
// moveFocus shifts the focused message by the provided amount, if possible.
func (c *ReplyListView) moveFocus(indexIncrement int) {
if c.Focused == nil {
return
}
currentIndex := c.AlphaReplyList.IndexForID(c.Focused.ID)
if currentIndex < 0 {
return
}
c.AlphaReplyList.WithReplies(func(replies []ds.ReplyData) {
for {
currentIndex += indexIncrement
if currentIndex >= len(replies) || currentIndex < 0 {
break
}
status := c.statusOf(replies[currentIndex])
if c.shouldFilter(status) {
continue
}
c.FocusTracker.SetFocus(&replies[currentIndex])
c.ensureFocusedVisible(currentIndex)
break
}
})
}
// ensureFocusedVisible attempts to ensure that the message at the
// provided index in the list being displayed is currently visible.
func (c *ReplyListView) ensureFocusedVisible(focusedIndex int) {
currentFirst := c.MessageList.Position.First
notInFirstFive := currentFirst+5 > focusedIndex
if currentFirst <= focusedIndex && notInFirstFive {
return
}
c.MessageList.Position.First = focusedIndex
c.MessageList.Position.Offset = 0
c.MessageList.Position.BeforeEnd = true
}
// moveFocusEnd shifts the focused message to the end of the list of
// replies.
func (c *ReplyListView) moveFocusEnd(replies []ds.ReplyData) {
if len(replies) < 1 {
return
}
c.SetFocus(&replies[len(replies)-1])
c.requestKeyboardFocus()
c.MessageList.Position.BeforeEnd = false
}
// moveFocusStart shifts the focused message to the beginning of the
// list of replies.
func (c *ReplyListView) moveFocusStart(replies []ds.ReplyData) {
if len(replies) < 1 {
return
}
c.SetFocus(&replies[0])
c.requestKeyboardFocus()
c.MessageList.Position.BeforeEnd = true
c.MessageList.Position.First = 0
c.MessageList.Position.Offset = 0
}
// reveal the reply at the given index.
func (c *ReplyListView) reveal(index int) {
if c.replyCount < 1 || index > c.replyCount-1 {
return
}
c.FocusTracker.Invalidate()
c.requestKeyboardFocus()
c.MessageList.Position.BeforeEnd = true
c.MessageList.Position.First = index
}
// refreshNodeStatus triggers a check for changes to status updates and
// triggers animations if statuses have changed.
func (c *ReplyListView) refreshNodeStatus(gtx C) {
if c.FocusTracker.RefreshNodeStatus(c.Arbor().Store()) {
c.MessageList.Animation.Start(gtx.Now)
}
}
// toggleFilter cycles between filter states.
func (c *ReplyListView) toggleFilter() {
switch c.FilterState {
case Conversation:
c.FilterState = Message
case Message:
c.MessageList.Position = c.PrefilterPosition
c.FilterState = Off
default:
c.PrefilterPosition = c.MessageList.Position
c.FilterState = Conversation
}
}
// copyFocused writes the contents of the focused message into the
// clipboard.
func (c *ReplyListView) copyFocused(gtx layout.Context) {
reply := c.Focused
clipboard.WriteOp{
Text: reply.Content,
}.Add(gtx.Ops)
}
// startReply begins replying to the focused message.
func (c *ReplyListView) startReply() {
data := c.Focused
c.replyListCover.Disappear(time.Now())
c.Composer.StartReply(*data)
}
// sendReply sends the reply with the current contents of the editor.
func (c *ReplyListView) sendReply() {
c.replyListCover.Disappear(time.Now())
replyText := c.Composer.Text()
if replyText == "" {
return
}
var (
newReplies []*forest.Reply
author *forest.Identity
parent forest.Node
has bool
)
replyText = strings.TrimSpace(replyText)
nodeBuilder, err := c.Settings().Builder()
if err != nil {
log.Printf("failed acquiring node builder: %v", err)
}
author = nodeBuilder.User
if c.Composer.ComposingConversation() {
if c.Community.Value != "" {
chosenString := c.Community.Value
c.Arbor().Communities().WithCommunities(func(communities []*forest.Community) {
for _, community := range communities {
if community.ID().String() == chosenString {
parent = community
break
}
}
})
}
} else {
parent, has, err = c.Arbor().Store().Get(c.ReplyingTo.ID)
if err != nil {
log.Printf("failed finding parent node %v in store: %v", c.ReplyingTo.ID, err)
return
} else if !has {
log.Printf("parent node %v is not in store: %v", c.ReplyingTo.ID, err)
return
}
}
for _, paragraph := range strings.Split(replyText, "\n\n") {
if paragraph != "" {
reply, err := nodeBuilder.NewReply(parent, paragraph, []byte{})
if err != nil {
log.Printf("failed creating new conversation: %v", err)
} else {
newReplies = append(newReplies, reply)
}
parent = reply
}
}
c.postReplies(author, newReplies)
c.resetReplyState()
}
// postReplies actually adds the replies to the store of history (and
// causes them to be sent because the sprout working is watching the
// store for updates).
func (c *ReplyListView) postReplies(author *forest.Identity, replies []*forest.Reply) {
go func() {
for _, reply := range replies {
if err := c.Arbor().Store().Add(author); err != nil {
log.Printf("failed adding replying identity to store: %v", err)
return
}
if err := c.Arbor().Store().Add(reply); err != nil {
log.Printf("failed adding reply to store: %v", err)
return
}
}
}()
}
// processMessagePointerEvents checks for specific pointer interactions
// with messages in the list and handles them.
func (c *ReplyListView) processMessagePointerEvents(gtx C) {
tryOpenLink := func(word string) {
if !strings.HasPrefix(word, "http") {
return
}
if u, err := url.ParseRequestURI(word); err == nil {
var args []string
switch runtime.GOOS {
case "darwin":
args = []string{"open"}
case "windows":
args = []string{"cmd", "/c", "start"}
default:
args = []string{"xdg-open"}
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
cmd := exec.CommandContext(ctx, args[0], append(args[1:], u.String())...)
if out, err := cmd.CombinedOutput(); err != nil {
log.Printf("failed opening link: %s %s\n", string(out), err)
}
}
}
clicked := func(c *sprigWidget.Polyclick) (widget.Click, bool) {
clicks := c.Clicks()
if len(clicks) == 0 {
return widget.Click{}, false
}
return clicks[len(clicks)-1], true
}
focus := func(handler *sprigWidget.Reply) {
reply, _, _ := c.Arbor().Store().Get(handler.Hash)
var data ds.ReplyData
data.Populate(reply, c.Arbor().Store())
c.SetFocus(&data)
}
for i := range c.ReplyStates.Buffer {
handler := &c.ReplyStates.Buffer[i]
if click, ok := clicked(&handler.Polyclick); ok {
if click.Modifiers.Contain(key.ModCtrl) {
for _, word := range strings.Fields(handler.Content) {
go tryOpenLink(word)
}
} else {
c.requestKeyboardFocus()
clickedOnFocused := handler.Hash.Equals(c.Focused.ID)
if !clickedOnFocused {
focus(handler)
c.dismissReplyContextMenu(gtx)
}
}
if click.NumClicks > 1 {
c.toggleFilter()
}
}
if handler.Polyclick.LongPressed() {
focus(handler)
c.Haptic().Buzz()
c.triggerReplyContextMenu(gtx)
}
}
}
// startConversation triggers composition of a new conversation message.
func (c *ReplyListView) startConversation() {
c.replyListCover.Appear(time.Now())
c.Composer.StartConversation()
}
// Update updates the state of the view in response to user input events.
func (c *ReplyListView) Update(gtx layout.Context) {
c.replyCount = func() (count int) {
c.AlphaReplyList.WithReplies(func(replies []ds.ReplyData) {
count = len(replies)
})
return count
}()
jumpStart := func() {
c.AlphaReplyList.WithReplies(func(replies []ds.ReplyData) {
c.moveFocusStart(replies)
})
}
jumpEnd := func() {
c.AlphaReplyList.WithReplies(func(replies []ds.ReplyData) {
c.moveFocusEnd(replies)
})
}
// Dismiss the composer if the scrim is clicked
if c.replyListCover.Clicked(gtx) {
c.replyListCover.Disappear(gtx.Now)
c.hideEditor()
}
for _, event := range gtx.Events(c) {
switch event := event.(type) {
case key.Event:
if event.State == key.Press {
switch event.Name {
case "D", key.NameDeleteBackward:
if event.Modifiers.Contain(key.ModShift) {
c.toggleConversationHidden()
} else {
c.toggleDescendantsHidden()
}
case "K", key.NameUpArrow:
c.moveFocusUp()
case "J", key.NameDownArrow:
c.moveFocusDown()
case key.NameHome:
jumpStart()
case "G":
if !event.Modifiers.Contain(key.ModShift) {
jumpStart()
break
}
fallthrough
case key.NameEnd:
jumpEnd()
case key.NameReturn, key.NameEnter:
c.startReply()
case "C":
if event.Modifiers.Contain(key.ModShortcut) {
c.copyFocused(gtx)
} else {
c.startConversation()
}
case key.NameSpace, "F":
c.toggleFilter()
case "[":
if event.Modifiers.Contain(key.ModCtrl) {
c.hideEditor()
}
case key.NameEscape:
c.hideEditor()
}
}
}
}
for _, e := range c.Composer.Events() {
switch e {
case sprigWidget.ComposerSubmitted:
c.sendReply()
case sprigWidget.ComposerCancelled:
c.resetReplyState()
}
}
overflowTag := c.manager.SelectedOverflowTag()
if overflowTag == &c.JumpToBottomButton || c.JumpToBottomButton.Clicked(gtx) {
jumpEnd()
}
if overflowTag == &c.JumpToTopButton || c.JumpToTopButton.Clicked(gtx) {
jumpStart()
}
if overflowTag == &c.HideDescendantsButton || c.HideDescendantsButton.Clicked(gtx) {
c.toggleDescendantsHidden()
}
c.processMessagePointerEvents(gtx)
c.refreshNodeStatus(gtx)
if c.FilterButton.Clicked(gtx) || overflowTag == &c.FilterButton {
c.toggleFilter()
}
if c.Focused != nil && (c.CopyReplyButton.Clicked(gtx) || overflowTag == &c.CopyReplyButton) {
c.copyFocused(gtx)
}
if c.Focused != nil && (c.CreateReplyButton.Clicked(gtx) || overflowTag == &c.CreateReplyButton) {
c.startReply()
}
if c.CreateConversationButton.Clicked(gtx) || overflowTag == &c.CreateConversationButton {
c.startConversation()
}
if c.LoadMoreHistoryButton.Clicked(gtx) || overflowTag == &c.LoadMoreHistoryButton {
go c.loadMoreHistory()
}
for _, event := range c.MessageList.Events() {
switch event.Type {
case sprigWidget.LinkLongPress:
c.Haptic().Buzz()
case sprigWidget.LinkOpen:
giohyperlink.Open(event.Data)
}
}
}
// toggleDescendantsHidden makes the descendants of the current message
// hidden (or reverses it).
func (c *ReplyListView) toggleDescendantsHidden() {
focusedID := c.FocusTracker.Focused.ID
if err := c.HiddenTracker.ToggleAnchor(focusedID, c.Arbor().Store()); err != nil {
log.Printf("Failed hiding descendants of selected: %v", err)
}
}
// toggleConversationHidden makes the descendants of the current message's
// conversation hidden (or reverses it).
func (c *ReplyListView) toggleConversationHidden() {
focusedID := c.FocusTracker.Focused.ConversationID
if focusedID.Equals(fields.NullHash()) {
// if the focused message is the root of a conversation, use its own ID
focusedID = c.FocusTracker.Focused.ID
}
c.WithReplies(func(replies []ds.ReplyData) {
for _, rd := range replies {
if rd.ID.Equals(focusedID) {
c.SetFocus(&rd)
if err := c.HiddenTracker.ToggleAnchor(rd.ID, c.Arbor().Store()); err != nil {
log.Printf("Failed hiding descendants of selected: %v", err)
}
return
}
}
})
}
// loadMoreHistory attempts to fetch more history from disk.
func (c *ReplyListView) loadMoreHistory() {
const newNodeTarget = 1024
var (
nodes []forest.Node
err error
)
load := func() {
nodes, err = c.Arbor().Store().Recent(fields.NodeTypeReply, c.HistoryRequestCount)
c.HistoryRequestCount += newNodeTarget
if err != nil {
log.Printf("failed loading extra history: %v", err)
return
}
}
load()
var populated []ds.ReplyData
for i := range nodes {
var rd ds.ReplyData
if rd.Populate(nodes[i], c.Arbor().Store()) {
populated = append(populated, rd)
}
}
if len(populated) < newNodeTarget {
load()
}
c.AlphaReplyList.Insert(populated...)
}
// resetReplyState erases the current contents of the message composer.
func (c *ReplyListView) resetReplyState() {
c.replyListCover.Disappear(time.Now())
c.Composer.Reset()
}
// statusOf returns the current UI status of a reply.
func (c *ReplyListView) statusOf(reply ds.ReplyData) (status sprigWidget.ReplyStatus) {
if c.HiddenTracker.IsAnchor(reply.ID) {
status |= sprigWidget.Anchor
}
if c.HiddenTracker.IsHidden(reply.ID) {
status |= sprigWidget.Hidden
}
if c.Focused == nil {
status |= sprigWidget.None
return
}
if c.Focused != nil && reply.ID.Equals(c.Focused.ID) {
status |= sprigWidget.Selected
return
}
for _, id := range c.Ancestry {
if id.Equals(reply.ID) {
status |= sprigWidget.Ancestor
return
}
}
for _, id := range c.Descendants {
if id.Equals(reply.ID) {
status |= sprigWidget.Descendant
return
}
}
if reply.Depth == 1 {
status |= sprigWidget.ConversationRoot
return
}
if c.Focused.ConversationID != nil && !c.Focused.ConversationID.Equals(fields.NullHash()) {
if c.Focused.ConversationID.Equals(reply.ConversationID) {
status |= sprigWidget.Sibling
return
}
}
status |= sprigWidget.None
return
}
// shouldDisplayEditor returns whether the composer should be visible.
func (c *ReplyListView) shouldDisplayEditor() bool {
return c.Composer.Composing()
}
// hideEditor makes the editor invisible.
func (c *ReplyListView) hideEditor() {
c.replyListCover.Disappear(time.Now())
c.Composer.Reset()
c.requestKeyboardFocus()
}
// Declare the set of keyboard shortcuts this page is interested in.
var keySet = key.Set(strings.Join([]string{
"(Shift)-D",
"(Shift)-" + key.NameDeleteBackward,
"K",
"J",
key.NameHome,
"(Shift)-G",
key.NameEnd,
key.NameReturn,
key.NameEnter,
"(Short)-C",
"F",
key.NameSpace,
}, "|"))
// Layout renders the whole view into the provided context.
func (c *ReplyListView) Layout(gtx layout.Context) layout.Dimensions {
theme := c.Theme().Current()
c.ShouldRequestKeyboardFocus = false
return layout.Stack{}.Layout(gtx,
layout.Expanded(func(gtx C) D {
sprigTheme.Rect{
Color: theme.Background.Default.Bg,
Size: layout.FPt(gtx.Constraints.Max),
}.Layout(gtx)
return layout.Dimensions{}
}),
layout.Stacked(func(gtx C) D {
return layout.Flex{Axis: layout.Vertical}.Layout(gtx,
layout.Flexed(1, func(gtx C) D {
// Cover the reply list with a scrim if the
// list is supposed to be hidden entirely
return layout.Stack{}.Layout(gtx,
layout.Stacked(func(gtx C) D {
return c.layoutReplyList(gtx)
}),
layout.Expanded(func(gtx C) D {
return materials.NewScrim(theme.Theme, &c.replyListCover, theme.FadeAlpha).Layout(gtx)
}),
)
}),
layout.Rigid(func(gtx C) D {
if c.shouldDisplayEditor() {
key.InputOp{
Tag: c,
Keys: key.NameEscape + "|Ctrl-[",
}.Add(gtx.Ops)
return c.layoutEditor(gtx)
} else {
key.InputOp{
Keys: keySet,
Tag: c,
}.Add(gtx.Ops)
key.FocusOp{Tag: c}.Add(gtx.Ops)
}
return layout.Dimensions{}
}),
)
}))
}
const (
buttonWidthDp = 20
scrollSlotWidthDp = 12
)
// shouldFilter returns whether the provided status should be filtered based
// on the current filter state.
func (c *ReplyListView) shouldFilter(status sprigWidget.ReplyStatus) bool {
if status&sprigWidget.Hidden > 0 {
return true
}
switch c.FilterState {
case Conversation:
return status&sprigWidget.None > 0 || status&sprigWidget.ConversationRoot > 0
case Message:
return status&sprigWidget.Sibling > 0 || status&sprigWidget.None > 0 || status&sprigWidget.ConversationRoot > 0
default:
return false
}
}
// layoutReplyList renders the list of replies into the provided graphics context.
func (c *ReplyListView) layoutReplyList(gtx layout.Context) layout.Dimensions {
gtx.Constraints.Min = gtx.Constraints.Max
var (
dims layout.Dimensions
th = c.Theme().Current()
)
if c.loading {
return layout.Center.Layout(gtx, func(gtx C) D {
return material.Loader(th.Theme).Layout(gtx)
})
}
c.AlphaReplyList.WithReplies(func(replies []ds.ReplyData) {
if c.Focused == nil && len(replies) > 0 {
c.moveFocusEnd(replies)
}
ml := sprigTheme.MessageList(th, &c.MessageList, &c.CreateReplyButton, replies)
if !c.Filtered() {
ml.Prefixes = []layout.Widget{
func(gtx C) D {
return layout.Center.Layout(gtx, func(gtx C) D {
return layout.UniformInset(unit.Dp(4)).Layout(gtx, func(gtx C) D {