github.com/wtfutil/wtf@v0.43.0/modules/hackernews/widget.go (about) 1 package hackernews 2 3 import ( 4 "fmt" 5 "net/url" 6 "strings" 7 8 "github.com/rivo/tview" 9 "github.com/wtfutil/wtf/utils" 10 "github.com/wtfutil/wtf/view" 11 ) 12 13 type Widget struct { 14 view.ScrollableWidget 15 16 stories []Story 17 settings *Settings 18 err error 19 } 20 21 func NewWidget(tviewApp *tview.Application, redrawChan chan bool, pages *tview.Pages, settings *Settings) *Widget { 22 widget := &Widget{ 23 ScrollableWidget: view.NewScrollableWidget(tviewApp, redrawChan, pages, settings.Common), 24 25 settings: settings, 26 } 27 28 widget.SetRenderFunction(widget.Render) 29 widget.initializeKeyboardControls() 30 31 return widget 32 } 33 34 /* -------------------- Exported Functions -------------------- */ 35 36 func (widget *Widget) Refresh() { 37 if widget.Disabled() { 38 return 39 } 40 41 storyIds, err := GetStories(widget.settings.storyType) 42 if err != nil { 43 widget.err = err 44 widget.stories = nil 45 widget.SetItemCount(0) 46 } else { 47 var stories []Story 48 for idx := 0; idx < widget.settings.numberOfStories; idx++ { 49 story, e := GetStory(storyIds[idx]) 50 if e == nil { 51 stories = append(stories, story) 52 } 53 } 54 widget.stories = stories 55 widget.SetItemCount(len(stories)) 56 } 57 58 widget.Render() 59 } 60 61 // Render sets up the widget data for redrawing to the screen 62 func (widget *Widget) Render() { 63 widget.Redraw(widget.content) 64 } 65 66 /* -------------------- Unexported Functions -------------------- */ 67 68 func (widget *Widget) content() (string, string, bool) { 69 title := fmt.Sprintf("%s - %s stories", widget.CommonSettings().Title, widget.settings.storyType) 70 71 if widget.err != nil { 72 return title, widget.err.Error(), true 73 } 74 75 if len(widget.stories) == 0 { 76 return title, "No stories to display", false 77 } 78 79 var str string 80 for idx, story := range widget.stories { 81 u, _ := url.Parse(story.URL) 82 83 row := fmt.Sprintf( 84 `[%s]%2d. %s [lightblue](%s)[white]`, 85 widget.RowColor(idx), 86 idx+1, 87 story.Title, 88 strings.TrimPrefix(u.Host, "www."), 89 ) 90 91 str += utils.HighlightableHelper(widget.View, row, idx, len(story.Title)) 92 } 93 94 return title, str, false 95 } 96 97 func (widget *Widget) openComments() { 98 story := widget.selectedStory() 99 if story != nil { 100 utils.OpenFile(story.CommentLink()) 101 } 102 } 103 104 func (widget *Widget) openStory() { 105 story := widget.selectedStory() 106 if story != nil { 107 utils.OpenFile(story.Link()) 108 } 109 } 110 111 func (widget *Widget) selectedStory() *Story { 112 var story *Story 113 114 sel := widget.GetSelected() 115 if sel >= 0 && widget.stories != nil && sel < len(widget.stories) { 116 story = &widget.stories[sel] 117 } 118 119 return story 120 }