- Untrack config.yaml (now gitignored) and add config.example.yaml with blank credentials; install.sh copies the example and sets mode 600 - Reserve room for the appended source link when asking Claude for a post, count length the way X does, and refuse over-length tweets before posting - Return https://x.com/i/status/<id> for posted tweets - Track which platforms each queued post reached so a partial failure can be retried without double-posting - Write config, state, posts and dismissed files atomically with 0600 - Keep refreshed Twitter tokens in memory if saving them fails, and log the failure instead of writing to the hidden stderr - Exit with a clear message on corrupt data files instead of panicking - Surface save errors in the UI; show status/error messages on home - Add tests for X length counting, the post store, and token updates Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1111 lines
29 KiB
Go
1111 lines
29 KiB
Go
package ui
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/charmbracelet/bubbles/list"
|
|
"github.com/charmbracelet/bubbles/spinner"
|
|
"github.com/charmbracelet/bubbles/textarea"
|
|
tea "github.com/charmbracelet/bubbletea"
|
|
"github.com/charmbracelet/lipgloss"
|
|
|
|
claudeapi "coremarketing/internal/api/claude"
|
|
"coremarketing/internal/api/twitter"
|
|
"coremarketing/internal/config"
|
|
"coremarketing/internal/fetcher"
|
|
"coremarketing/internal/models"
|
|
"coremarketing/internal/state"
|
|
"coremarketing/internal/store"
|
|
)
|
|
|
|
// --- view states ---
|
|
|
|
type viewState int
|
|
|
|
const (
|
|
viewHome viewState = iota
|
|
viewFetching
|
|
viewContentBrowser
|
|
viewGenerating
|
|
viewPostPreview
|
|
viewGeneratedPosts
|
|
viewPosting
|
|
viewResult
|
|
)
|
|
|
|
// --- tea messages ---
|
|
|
|
type fetchDoneMsg struct {
|
|
result fetcher.Result
|
|
}
|
|
|
|
type prefetchDoneMsg struct {
|
|
appName string
|
|
result fetcher.Result
|
|
}
|
|
|
|
type generateDoneMsg struct {
|
|
post string
|
|
}
|
|
|
|
type batchGenerateMsg struct {
|
|
contents []string
|
|
sourceURLs []string
|
|
}
|
|
|
|
type batchPostedMsg struct {
|
|
posted map[string][]string // post ID → platforms newly published to
|
|
urls []string
|
|
errors []string
|
|
}
|
|
|
|
type errMsg struct {
|
|
err error
|
|
from viewState
|
|
}
|
|
|
|
// --- content list items & delegate ---
|
|
|
|
type appListItem struct {
|
|
app models.Application
|
|
count int
|
|
loaded bool
|
|
}
|
|
|
|
func (i appListItem) FilterValue() string { return i.app.Name }
|
|
func (i appListItem) Title() string {
|
|
if !i.loaded {
|
|
return "(…) " + i.app.Name
|
|
}
|
|
if i.count > 0 {
|
|
return fmt.Sprintf("(%d) %s", i.count, i.app.Name)
|
|
}
|
|
return i.app.Name
|
|
}
|
|
func (i appListItem) Description() string { return i.app.Description }
|
|
|
|
type contentListItem struct {
|
|
models.ContentItem
|
|
}
|
|
|
|
func (i contentListItem) FilterValue() string { return i.Author + " " + i.Body }
|
|
func (i contentListItem) Title() string { return string(i.Source) }
|
|
func (i contentListItem) Description() string { return i.Body }
|
|
|
|
type selectableDelegate struct {
|
|
selected map[string]bool
|
|
}
|
|
|
|
const maxBodyLines = 4
|
|
|
|
func (d selectableDelegate) Height() int { return 2 + maxBodyLines + 1 }
|
|
func (d selectableDelegate) Spacing() int { return 0 }
|
|
func (d selectableDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil }
|
|
|
|
func (d selectableDelegate) Render(w io.Writer, m list.Model, index int, item list.Item) {
|
|
ci, ok := item.(contentListItem)
|
|
if !ok {
|
|
return
|
|
}
|
|
isFocused := index == m.Index()
|
|
isSelected := d.selected[ci.ID]
|
|
|
|
check := checkboxOff
|
|
if isSelected {
|
|
check = checkboxOn
|
|
}
|
|
|
|
source := fmt.Sprintf("%-14s", string(ci.Source))
|
|
line1 := fmt.Sprintf("%s %s @%s · %s", check, source, ci.AuthorHandle, ci.PublishedAt.Format("Jan 2"))
|
|
|
|
// Build display text: title (if set) + body
|
|
displayText := ci.Body
|
|
if ci.ContentItem.Title != "" {
|
|
displayText = ci.ContentItem.Title + "\n" + ci.Body
|
|
}
|
|
bodyWidth := m.Width() - 6
|
|
if bodyWidth < 20 {
|
|
bodyWidth = 20
|
|
}
|
|
wrapped := wordWrap(displayText, bodyWidth)
|
|
if len(wrapped) > maxBodyLines {
|
|
wrapped = wrapped[:maxBodyLines]
|
|
last := wrapped[maxBodyLines-1]
|
|
if utf8.RuneCountInString(last) > bodyWidth-1 {
|
|
runes := []rune(last)
|
|
wrapped[maxBodyLines-1] = string(runes[:bodyWidth-1]) + "…"
|
|
} else {
|
|
wrapped[maxBodyLines-1] += "…"
|
|
}
|
|
}
|
|
|
|
urlLine := " " + ci.URL
|
|
|
|
var s1, s2, s3 lipgloss.Style
|
|
if isFocused {
|
|
s1 = lipgloss.NewStyle().Foreground(colorPurple).Bold(true)
|
|
s2 = lipgloss.NewStyle().Foreground(colorWhite)
|
|
s3 = lipgloss.NewStyle().Foreground(colorGray)
|
|
} else {
|
|
s1 = lipgloss.NewStyle().Foreground(colorWhite)
|
|
s2 = lipgloss.NewStyle().Foreground(colorGray)
|
|
s3 = lipgloss.NewStyle().Foreground(colorFaint)
|
|
}
|
|
if isSelected {
|
|
s1 = s1.Foreground(colorGreen)
|
|
}
|
|
|
|
fmt.Fprintln(w, s1.Render(line1))
|
|
for i := 0; i < maxBodyLines; i++ {
|
|
if i < len(wrapped) {
|
|
fmt.Fprintln(w, s2.Render(" "+wrapped[i]))
|
|
} else {
|
|
fmt.Fprintln(w, "")
|
|
}
|
|
}
|
|
fmt.Fprintln(w, s3.Render(urlLine))
|
|
}
|
|
|
|
// --- generated post list items & delegate ---
|
|
|
|
type genPostItem struct {
|
|
store.GeneratedPost
|
|
}
|
|
|
|
func (i genPostItem) FilterValue() string { return i.AppName + " " + i.Content }
|
|
func (i genPostItem) Title() string { return i.AppName }
|
|
func (i genPostItem) Description() string { return i.Content }
|
|
|
|
type genPostDelegate struct {
|
|
selected map[string]bool
|
|
maxLength int
|
|
}
|
|
|
|
func (d genPostDelegate) Height() int { return 4 }
|
|
func (d genPostDelegate) Spacing() int { return 0 }
|
|
func (d genPostDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil }
|
|
|
|
func (d genPostDelegate) Render(w io.Writer, m list.Model, index int, item list.Item) {
|
|
pi, ok := item.(genPostItem)
|
|
if !ok {
|
|
return
|
|
}
|
|
isFocused := index == m.Index()
|
|
isSelected := d.selected[pi.ID]
|
|
|
|
check := checkboxOff
|
|
if isSelected {
|
|
check = checkboxOn
|
|
}
|
|
|
|
line1 := fmt.Sprintf("%s %s · %s", check, pi.AppName, pi.GeneratedAt.Format("Jan 2, 3:04pm"))
|
|
line2 := " " + truncate(pi.Content, 80)
|
|
line3 := " " + fmt.Sprintf("%d / %d chars on X", twitter.TweetLength(pi.Content, pi.SourceURL), d.maxLength)
|
|
if pi.SourceURL != "" {
|
|
line3 += " (incl. link)"
|
|
}
|
|
if len(pi.PostedTo) > 0 {
|
|
line3 += " · already posted to " + strings.Join(pi.PostedTo, ", ")
|
|
}
|
|
|
|
var s1, s2, s3 lipgloss.Style
|
|
if isFocused {
|
|
s1 = lipgloss.NewStyle().Foreground(colorPurple).Bold(true)
|
|
s2 = lipgloss.NewStyle().Foreground(colorWhite)
|
|
s3 = lipgloss.NewStyle().Foreground(colorGray)
|
|
} else {
|
|
s1 = lipgloss.NewStyle().Foreground(colorWhite)
|
|
s2 = lipgloss.NewStyle().Foreground(colorGray)
|
|
s3 = lipgloss.NewStyle().Foreground(colorFaint)
|
|
}
|
|
if isSelected {
|
|
s1 = s1.Foreground(colorGreen)
|
|
}
|
|
|
|
fmt.Fprintln(w, s1.Render(line1))
|
|
fmt.Fprintln(w, s2.Render(line2))
|
|
fmt.Fprintln(w, s3.Render(line3))
|
|
fmt.Fprintln(w, "")
|
|
}
|
|
|
|
// --- posting client interface ---
|
|
|
|
type postingClient interface {
|
|
PostTweet(ctx context.Context, text string) (string, error)
|
|
}
|
|
|
|
type linkedinPostingClient interface {
|
|
PostUpdate(ctx context.Context, text, sourceURL string) (string, error)
|
|
}
|
|
|
|
// --- main model ---
|
|
|
|
type Model struct {
|
|
view viewState
|
|
|
|
cfg *config.Config
|
|
appState *state.State
|
|
postStore *store.Store
|
|
dismissed *store.DismissedStore
|
|
fetch *fetcher.Fetcher
|
|
claude *claudeapi.Client
|
|
poster postingClient
|
|
liPoster linkedinPostingClient
|
|
|
|
appList list.Model
|
|
contentList list.Model
|
|
selDelegate selectableDelegate
|
|
selected map[string]bool
|
|
|
|
genList list.Model
|
|
genDelegate genPostDelegate
|
|
genSelected map[string]bool
|
|
|
|
spinner spinner.Model
|
|
textarea textarea.Model
|
|
|
|
selectedApp *models.Application
|
|
fetchResult fetcher.Result
|
|
prefetchResults map[string]fetcher.Result
|
|
pendingItemIDs map[string]bool
|
|
|
|
generatedPost string
|
|
pendingSourceURL string
|
|
|
|
resultURLs []string
|
|
resultErrors []string
|
|
statusMsg string
|
|
errorMsg string
|
|
fetchLabel string
|
|
|
|
width int
|
|
height int
|
|
}
|
|
|
|
func New(cfg *config.Config, st *state.State, ps *store.Store, ds *store.DismissedStore, f *fetcher.Fetcher, cl *claudeapi.Client, poster postingClient, liPoster linkedinPostingClient) Model {
|
|
s := spinner.New()
|
|
s.Spinner = spinner.Dot
|
|
s.Style = spinnerStyle
|
|
|
|
ta := textarea.New()
|
|
ta.CharLimit = cfg.Posting.MaxLength * 2
|
|
ta.ShowLineNumbers = false
|
|
|
|
items := make([]list.Item, len(cfg.Applications))
|
|
for i, app := range cfg.Applications {
|
|
items[i] = appListItem{app: app}
|
|
}
|
|
appList := list.New(items, list.NewDefaultDelegate(), 60, 20)
|
|
appList.Title = "Select Application"
|
|
appList.SetShowStatusBar(false)
|
|
appList.SetFilteringEnabled(true)
|
|
appList.Styles.Title = titleStyle
|
|
|
|
return Model{
|
|
view: viewHome,
|
|
cfg: cfg,
|
|
appState: st,
|
|
postStore: ps,
|
|
dismissed: ds,
|
|
fetch: f,
|
|
claude: cl,
|
|
poster: poster,
|
|
liPoster: liPoster,
|
|
appList: appList,
|
|
selected: map[string]bool{},
|
|
genSelected: map[string]bool{},
|
|
prefetchResults: map[string]fetcher.Result{},
|
|
spinner: s,
|
|
textarea: ta,
|
|
}
|
|
}
|
|
|
|
func (m Model) Init() tea.Cmd {
|
|
cmds := []tea.Cmd{m.spinner.Tick}
|
|
for _, app := range m.cfg.Applications {
|
|
cmds = append(cmds, m.doPrefetch(app))
|
|
}
|
|
return tea.Batch(cmds...)
|
|
}
|
|
|
|
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|
switch msg := msg.(type) {
|
|
|
|
case tea.WindowSizeMsg:
|
|
m.width = msg.Width
|
|
m.height = msg.Height
|
|
m.appList.SetSize(msg.Width-4, msg.Height-8)
|
|
if m.view == viewContentBrowser {
|
|
m.contentList.SetSize(msg.Width-4, msg.Height-10)
|
|
}
|
|
if m.view == viewGeneratedPosts {
|
|
m.genList.SetSize(msg.Width-4, msg.Height-10)
|
|
}
|
|
m.textarea.SetWidth(msg.Width - 6)
|
|
m.textarea.SetHeight(8)
|
|
|
|
case spinner.TickMsg:
|
|
var cmd tea.Cmd
|
|
m.spinner, cmd = m.spinner.Update(msg)
|
|
return m, cmd
|
|
|
|
case fetchDoneMsg:
|
|
m.selected = map[string]bool{}
|
|
|
|
var visible []models.ContentItem
|
|
for _, item := range msg.result.Items {
|
|
if !m.dismissed.IsDismissed(item.ID) {
|
|
visible = append(visible, item)
|
|
}
|
|
}
|
|
m.fetchResult = msg.result
|
|
m.fetchResult.Items = visible
|
|
|
|
items := make([]list.Item, len(visible))
|
|
for i, item := range visible {
|
|
items[i] = contentListItem{item}
|
|
}
|
|
m.selDelegate = selectableDelegate{selected: m.selected}
|
|
m.contentList = list.New(items, m.selDelegate, m.width-4, m.height-10)
|
|
m.contentList.Title = fmt.Sprintf("Content for %s [Space=select Enter=generate d=dismiss]", m.selectedApp.Name)
|
|
m.contentList.SetShowStatusBar(true)
|
|
m.contentList.SetFilteringEnabled(true)
|
|
m.contentList.Styles.Title = titleStyle
|
|
|
|
if len(msg.result.Errors) > 0 {
|
|
m.statusMsg = warningStyle.Render("⚠ Some sources failed: " + strings.Join(msg.result.Errors, "; "))
|
|
} else {
|
|
m.statusMsg = ""
|
|
}
|
|
if len(msg.result.Items) == 0 {
|
|
m.errorMsg = "No content found. Try adjusting your lookback window or check your API credentials."
|
|
}
|
|
m.view = viewContentBrowser
|
|
|
|
case generateDoneMsg:
|
|
m.generatedPost = msg.post
|
|
m.textarea.SetValue(msg.post)
|
|
focusCmd := m.textarea.Focus()
|
|
m.appState.SetLastChecked(m.selectedApp.Name, time.Now())
|
|
if err := m.appState.Save(); err != nil {
|
|
m.errorMsg = "Could not save state: " + err.Error()
|
|
}
|
|
removeUsedItems(&m)
|
|
m.view = viewPostPreview
|
|
return m, focusCmd
|
|
|
|
case batchGenerateMsg:
|
|
for i, content := range msg.contents {
|
|
m.postStore.Add(m.selectedApp.Name, content, msg.sourceURLs[i])
|
|
}
|
|
m.appState.SetLastChecked(m.selectedApp.Name, time.Now())
|
|
removeUsedItems(&m)
|
|
m.statusMsg = successStyle.Render(fmt.Sprintf("✓ %d posts saved to queue — press p to review", len(msg.contents)))
|
|
if err := m.postStore.Save(); err != nil {
|
|
m.statusMsg = ""
|
|
m.errorMsg = "Could not save generated posts: " + err.Error()
|
|
} else if err := m.appState.Save(); err != nil {
|
|
m.errorMsg = "Could not save state: " + err.Error()
|
|
}
|
|
m.view = viewHome
|
|
return m, nil
|
|
|
|
case prefetchDoneMsg:
|
|
m.prefetchResults[msg.appName] = msg.result
|
|
rebuildAppList(&m)
|
|
return m, nil
|
|
|
|
case batchPostedMsg:
|
|
// Record per-platform success, then drop posts that are now published
|
|
// everywhere posting is configured. Partially posted ones stay queued
|
|
// so the failed platform can be retried without double-posting.
|
|
for id, platforms := range msg.posted {
|
|
for _, p := range platforms {
|
|
m.postStore.MarkPosted(id, p)
|
|
}
|
|
}
|
|
done := map[string]bool{}
|
|
for _, p := range m.postStore.Posts {
|
|
if (m.poster == nil || p.HasPosted(store.PlatformX)) &&
|
|
(m.liPoster == nil || p.HasPosted(store.PlatformLinkedIn)) {
|
|
done[p.ID] = true
|
|
}
|
|
}
|
|
m.postStore.Remove(done)
|
|
m.resultURLs = msg.urls
|
|
m.resultErrors = msg.errors
|
|
if err := m.postStore.Save(); err != nil {
|
|
m.resultErrors = append(m.resultErrors, "Could not save post queue (posted items may reappear): "+err.Error())
|
|
}
|
|
m.view = viewResult
|
|
|
|
case errMsg:
|
|
m.errorMsg = msg.err.Error()
|
|
m.view = msg.from
|
|
return m, nil
|
|
|
|
case tea.KeyMsg:
|
|
switch msg.String() {
|
|
case "ctrl+c":
|
|
return m, tea.Quit
|
|
}
|
|
|
|
switch m.view {
|
|
case viewHome:
|
|
return m.updateHome(msg)
|
|
case viewContentBrowser:
|
|
return m.updateContentBrowser(msg)
|
|
case viewPostPreview:
|
|
return m.updatePostPreview(msg)
|
|
case viewGeneratedPosts:
|
|
return m.updateGeneratedPosts(msg)
|
|
case viewResult:
|
|
switch msg.String() {
|
|
case "enter", "q", "esc":
|
|
m.view = viewHome
|
|
m.errorMsg = ""
|
|
m.statusMsg = ""
|
|
m.resultURLs = nil
|
|
m.resultErrors = nil
|
|
m.selectedApp = nil
|
|
}
|
|
}
|
|
}
|
|
|
|
return m, nil
|
|
}
|
|
|
|
func (m Model) updateHome(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|
switch msg.String() {
|
|
case "q", "esc":
|
|
return m, tea.Quit
|
|
case "p":
|
|
m.genSelected = map[string]bool{}
|
|
m.genList = m.buildGenList()
|
|
m.view = viewGeneratedPosts
|
|
return m, nil
|
|
case "enter":
|
|
item, ok := m.appList.SelectedItem().(appListItem)
|
|
if !ok {
|
|
return m, nil
|
|
}
|
|
app := item.app
|
|
m.selectedApp = &app
|
|
m.errorMsg = ""
|
|
m.statusMsg = ""
|
|
if result, ok := m.prefetchResults[app.Name]; ok {
|
|
return m, func() tea.Msg { return fetchDoneMsg{result: result} }
|
|
}
|
|
since := m.appState.GetLastChecked(app.Name, m.cfg.Settings.DefaultLookbackDays)
|
|
m.fetchLabel = fmt.Sprintf("Fetching content for %s since %s…", app.Name, since.Format("Jan 2"))
|
|
m.view = viewFetching
|
|
return m, tea.Batch(m.spinner.Tick, m.doFetch(app, since))
|
|
}
|
|
var cmd tea.Cmd
|
|
m.appList, cmd = m.appList.Update(msg)
|
|
return m, cmd
|
|
}
|
|
|
|
func (m Model) updateContentBrowser(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|
switch msg.String() {
|
|
case "q", "esc":
|
|
m.view = viewHome
|
|
m.errorMsg = ""
|
|
return m, nil
|
|
case " ":
|
|
item, ok := m.contentList.SelectedItem().(contentListItem)
|
|
if !ok {
|
|
return m, nil
|
|
}
|
|
m.selected[item.ID] = !m.selected[item.ID]
|
|
m.selDelegate.selected = m.selected
|
|
m.contentList.SetDelegate(m.selDelegate)
|
|
return m, nil
|
|
case "d":
|
|
item, ok := m.contentList.SelectedItem().(contentListItem)
|
|
if !ok {
|
|
return m, nil
|
|
}
|
|
m.dismissed.Dismiss(item.ID)
|
|
if err := m.dismissed.Save(); err != nil {
|
|
m.errorMsg = "Could not save: " + err.Error()
|
|
return m, nil
|
|
}
|
|
// Remove from content list
|
|
current := m.contentList.Items()
|
|
filtered := make([]list.Item, 0, len(current)-1)
|
|
for _, it := range current {
|
|
if ci, ok := it.(contentListItem); ok && ci.ID != item.ID {
|
|
filtered = append(filtered, it)
|
|
}
|
|
}
|
|
m.contentList.SetItems(filtered)
|
|
// Keep fetchResult in sync for the item count display
|
|
fItems := m.fetchResult.Items[:0]
|
|
for _, fi := range m.fetchResult.Items {
|
|
if fi.ID != item.ID {
|
|
fItems = append(fItems, fi)
|
|
}
|
|
}
|
|
m.fetchResult.Items = fItems
|
|
// Keep prefetchResults in sync so home screen counts are accurate
|
|
if m.selectedApp != nil {
|
|
if result, ok := m.prefetchResults[m.selectedApp.Name]; ok {
|
|
pItems := result.Items[:0]
|
|
for _, fi := range result.Items {
|
|
if fi.ID != item.ID {
|
|
pItems = append(pItems, fi)
|
|
}
|
|
}
|
|
result.Items = pItems
|
|
m.prefetchResults[m.selectedApp.Name] = result
|
|
}
|
|
}
|
|
delete(m.selected, item.ID)
|
|
return m, nil
|
|
case "enter":
|
|
var chosen []models.ContentItem
|
|
for _, raw := range m.contentList.Items() {
|
|
ci, ok := raw.(contentListItem)
|
|
if ok && m.selected[ci.ID] {
|
|
chosen = append(chosen, ci.ContentItem)
|
|
}
|
|
}
|
|
if len(chosen) == 0 {
|
|
m.errorMsg = "Select at least one item with Space before pressing Enter."
|
|
return m, nil
|
|
}
|
|
m.errorMsg = ""
|
|
m.view = viewGenerating
|
|
m.pendingItemIDs = make(map[string]bool, len(chosen))
|
|
for _, item := range chosen {
|
|
m.pendingItemIDs[item.ID] = true
|
|
}
|
|
if len(chosen) == 1 {
|
|
m.pendingSourceURL = firstSourceURL(chosen)
|
|
return m, tea.Batch(m.spinner.Tick, m.doGenerate(chosen))
|
|
}
|
|
return m, tea.Batch(m.spinner.Tick, m.doBatchGenerate(chosen))
|
|
}
|
|
|
|
var cmd tea.Cmd
|
|
m.contentList, cmd = m.contentList.Update(msg)
|
|
return m, cmd
|
|
}
|
|
|
|
func (m Model) updatePostPreview(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|
switch msg.String() {
|
|
case "ctrl+r":
|
|
var chosen []models.ContentItem
|
|
for _, raw := range m.contentList.Items() {
|
|
ci, ok := raw.(contentListItem)
|
|
if ok && m.selected[ci.ID] {
|
|
chosen = append(chosen, ci.ContentItem)
|
|
}
|
|
}
|
|
m.view = viewGenerating
|
|
m.textarea.Blur()
|
|
m.pendingItemIDs = make(map[string]bool, len(chosen))
|
|
for _, item := range chosen {
|
|
m.pendingItemIDs[item.ID] = true
|
|
}
|
|
m.pendingSourceURL = firstSourceURL(chosen)
|
|
return m, tea.Batch(m.spinner.Tick, m.doGenerate(chosen))
|
|
case "ctrl+s", "enter", "esc":
|
|
// Prefer textarea value (captures edits); fall back to the original
|
|
// generated post in case the textarea state is not yet initialised.
|
|
text := strings.TrimSpace(m.textarea.Value())
|
|
if text == "" {
|
|
text = strings.TrimSpace(m.generatedPost)
|
|
}
|
|
if text == "" {
|
|
m.view = viewContentBrowser
|
|
m.textarea.Blur()
|
|
return m, nil
|
|
}
|
|
m.postStore.Add(m.selectedApp.Name, text, m.pendingSourceURL)
|
|
if err := m.postStore.Save(); err != nil {
|
|
m.errorMsg = "Could not save post: " + err.Error()
|
|
return m, nil
|
|
}
|
|
m.textarea.Blur()
|
|
m.errorMsg = ""
|
|
m.view = viewHome
|
|
return m, nil
|
|
}
|
|
|
|
var cmd tea.Cmd
|
|
m.textarea, cmd = m.textarea.Update(msg)
|
|
return m, cmd
|
|
}
|
|
|
|
func (m Model) updateGeneratedPosts(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|
switch msg.String() {
|
|
case "q", "esc":
|
|
m.view = viewHome
|
|
m.errorMsg = ""
|
|
return m, nil
|
|
case " ":
|
|
item, ok := m.genList.SelectedItem().(genPostItem)
|
|
if !ok {
|
|
return m, nil
|
|
}
|
|
m.genSelected[item.ID] = !m.genSelected[item.ID]
|
|
m.genDelegate.selected = m.genSelected
|
|
m.genList.SetDelegate(m.genDelegate)
|
|
return m, nil
|
|
case "d":
|
|
// Delete selected posts from the store
|
|
if len(m.genSelected) == 0 {
|
|
m.errorMsg = "Select posts with Space first."
|
|
return m, nil
|
|
}
|
|
m.postStore.Remove(m.genSelected)
|
|
if err := m.postStore.Save(); err != nil {
|
|
m.errorMsg = "Could not save: " + err.Error()
|
|
return m, nil
|
|
}
|
|
m.genSelected = map[string]bool{}
|
|
m.genList = m.buildGenList()
|
|
m.errorMsg = ""
|
|
return m, nil
|
|
case "ctrl+p":
|
|
if m.poster == nil && m.liPoster == nil {
|
|
m.errorMsg = "Posting is not configured. Set credentials in config.yaml."
|
|
return m, nil
|
|
}
|
|
var chosen []store.GeneratedPost
|
|
for _, raw := range m.genList.Items() {
|
|
pi, ok := raw.(genPostItem)
|
|
if ok && m.genSelected[pi.ID] {
|
|
chosen = append(chosen, pi.GeneratedPost)
|
|
}
|
|
}
|
|
if len(chosen) == 0 {
|
|
m.errorMsg = "Select at least one post with Space before posting."
|
|
return m, nil
|
|
}
|
|
m.errorMsg = ""
|
|
m.view = viewPosting
|
|
return m, tea.Batch(m.spinner.Tick, m.doPostBatch(chosen))
|
|
}
|
|
|
|
var cmd tea.Cmd
|
|
m.genList, cmd = m.genList.Update(msg)
|
|
return m, cmd
|
|
}
|
|
|
|
func (m Model) View() string {
|
|
switch m.view {
|
|
case viewHome:
|
|
return m.renderHome()
|
|
case viewFetching:
|
|
return m.renderSpinner(m.fetchLabel)
|
|
case viewContentBrowser:
|
|
return m.renderContentBrowser()
|
|
case viewGenerating:
|
|
return m.renderSpinner("Generating post with Claude…")
|
|
case viewPostPreview:
|
|
return m.renderPostPreview()
|
|
case viewGeneratedPosts:
|
|
return m.renderGeneratedPosts()
|
|
case viewPosting:
|
|
return m.renderSpinner(fmt.Sprintf("Posting to @%s…", m.cfg.Posting.TwitterHandle))
|
|
case viewResult:
|
|
return m.renderResult()
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// --- view renderers ---
|
|
|
|
func (m Model) renderHome() string {
|
|
var sb strings.Builder
|
|
sb.WriteString(m.header("CoreMarketing — Social Curator"))
|
|
sb.WriteString("\n")
|
|
|
|
if n := len(m.postStore.Posts); n > 0 {
|
|
sb.WriteString(" " + successStyle.Render(fmt.Sprintf("● %d post(s) ready to publish", n)) + "\n")
|
|
}
|
|
if m.errorMsg != "" {
|
|
sb.WriteString(" " + errorStyle.Render(m.errorMsg) + "\n")
|
|
}
|
|
if m.statusMsg != "" {
|
|
sb.WriteString(" " + m.statusMsg + "\n")
|
|
}
|
|
|
|
sb.WriteString(m.appList.View())
|
|
sb.WriteString("\n")
|
|
|
|
hints := []string{
|
|
keyHint("↑↓", "navigate"),
|
|
keyHint("/", "filter"),
|
|
keyHint("enter", "fetch content"),
|
|
}
|
|
if len(m.postStore.Posts) > 0 {
|
|
hints = append(hints, keyHint("p", "view posts"))
|
|
}
|
|
hints = append(hints, keyHint("q", "quit"))
|
|
sb.WriteString(m.renderStatusBar(hints...))
|
|
return sb.String()
|
|
}
|
|
|
|
func (m Model) renderSpinner(label string) string {
|
|
var sb strings.Builder
|
|
sb.WriteString(m.header("CoreMarketing — Social Curator"))
|
|
sb.WriteString("\n\n")
|
|
sb.WriteString(" " + m.spinner.View() + " " + label + "\n")
|
|
return sb.String()
|
|
}
|
|
|
|
func (m Model) renderContentBrowser() string {
|
|
var sb strings.Builder
|
|
title := "Social Curator"
|
|
if m.selectedApp != nil {
|
|
title += " — " + m.selectedApp.Name
|
|
}
|
|
sb.WriteString(m.header(title))
|
|
sb.WriteString("\n")
|
|
|
|
if m.errorMsg != "" {
|
|
sb.WriteString(" " + errorStyle.Render(m.errorMsg) + "\n")
|
|
}
|
|
if m.statusMsg != "" {
|
|
sb.WriteString(" " + m.statusMsg + "\n")
|
|
}
|
|
|
|
selCount := 0
|
|
for _, v := range m.selected {
|
|
if v {
|
|
selCount++
|
|
}
|
|
}
|
|
sb.WriteString(lipgloss.NewStyle().Foreground(colorGray).Render(
|
|
fmt.Sprintf(" %d item(s) found · %d selected\n", len(m.fetchResult.Items), selCount),
|
|
))
|
|
sb.WriteString(m.contentList.View())
|
|
sb.WriteString("\n")
|
|
sb.WriteString(m.renderStatusBar(
|
|
keyHint("↑↓", "navigate"),
|
|
keyHint("space", "select/deselect"),
|
|
keyHint("enter", "generate post"),
|
|
keyHint("d", "dismiss forever"),
|
|
keyHint("esc", "back"),
|
|
))
|
|
return sb.String()
|
|
}
|
|
|
|
func (m Model) renderPostPreview() string {
|
|
var sb strings.Builder
|
|
sb.WriteString(m.header("Post Preview — Edit then Save"))
|
|
sb.WriteString("\n")
|
|
|
|
text := m.textarea.Value()
|
|
charCount := twitter.TweetLength(text, m.pendingSourceURL)
|
|
limit := m.cfg.Posting.MaxLength
|
|
|
|
var countStyle lipgloss.Style
|
|
switch {
|
|
case charCount > limit:
|
|
countStyle = charCountOver
|
|
case charCount > limit-20:
|
|
countStyle = charCountWarn
|
|
default:
|
|
countStyle = charCountOK
|
|
}
|
|
|
|
countLine := countStyle.Render(fmt.Sprintf(" %d / %d characters", charCount, limit))
|
|
if m.pendingSourceURL != "" {
|
|
countLine += countStyle.Render(fmt.Sprintf(" (incl. %d for the source link)", twitter.URLReserve(m.pendingSourceURL)))
|
|
}
|
|
if charCount > limit {
|
|
countLine += " " + errorStyle.Render(fmt.Sprintf("(%d over!)", charCount-limit))
|
|
}
|
|
sb.WriteString(countLine + "\n\n")
|
|
sb.WriteString(borderStyle.Width(m.width - 4).Render(m.textarea.View()))
|
|
sb.WriteString("\n\n")
|
|
|
|
if m.errorMsg != "" {
|
|
sb.WriteString(" " + errorStyle.Render(m.errorMsg) + "\n")
|
|
}
|
|
|
|
sb.WriteString(m.renderStatusBar(
|
|
keyHint("enter/esc", "save to queue"),
|
|
keyHint("ctrl+r", "regenerate"),
|
|
))
|
|
return sb.String()
|
|
}
|
|
|
|
func (m Model) renderGeneratedPosts() string {
|
|
var sb strings.Builder
|
|
sb.WriteString(m.header("Generated Posts — Select to Publish"))
|
|
sb.WriteString("\n")
|
|
|
|
if m.errorMsg != "" {
|
|
sb.WriteString(" " + errorStyle.Render(m.errorMsg) + "\n")
|
|
}
|
|
|
|
selCount := 0
|
|
for _, v := range m.genSelected {
|
|
if v {
|
|
selCount++
|
|
}
|
|
}
|
|
sb.WriteString(lipgloss.NewStyle().Foreground(colorGray).Render(
|
|
fmt.Sprintf(" %d post(s) · %d selected\n", len(m.postStore.Posts), selCount),
|
|
))
|
|
|
|
if len(m.postStore.Posts) == 0 {
|
|
sb.WriteString("\n " + lipgloss.NewStyle().Foreground(colorGray).Render("No generated posts yet. Fetch content and generate some first.") + "\n")
|
|
} else {
|
|
sb.WriteString(m.genList.View())
|
|
}
|
|
|
|
sb.WriteString("\n")
|
|
sb.WriteString(m.renderStatusBar(
|
|
keyHint("↑↓", "navigate"),
|
|
keyHint("space", "select/deselect"),
|
|
keyHint("ctrl+p", "post selected"),
|
|
keyHint("d", "delete selected"),
|
|
keyHint("esc", "back"),
|
|
))
|
|
return sb.String()
|
|
}
|
|
|
|
func (m Model) renderResult() string {
|
|
var sb strings.Builder
|
|
sb.WriteString(m.header("CoreMarketing — Result"))
|
|
sb.WriteString("\n\n")
|
|
|
|
if len(m.resultErrors) > 0 {
|
|
sb.WriteString(" " + errorStyle.Render("Errors:") + "\n")
|
|
for _, e := range m.resultErrors {
|
|
sb.WriteString(" " + lipgloss.NewStyle().Foreground(colorRed).Render("• "+e) + "\n")
|
|
}
|
|
sb.WriteString("\n")
|
|
}
|
|
if len(m.resultURLs) > 0 {
|
|
sb.WriteString(" " + successStyle.Render(fmt.Sprintf("✓ %d post(s) published:", len(m.resultURLs))) + "\n")
|
|
for _, u := range m.resultURLs {
|
|
sb.WriteString(" " + lipgloss.NewStyle().Foreground(colorPurple).Render("• "+u) + "\n")
|
|
}
|
|
}
|
|
|
|
sb.WriteString("\n")
|
|
sb.WriteString(m.renderStatusBar(keyHint("enter", "return to home")))
|
|
return sb.String()
|
|
}
|
|
|
|
// --- helpers ---
|
|
|
|
func (m Model) header(title string) string {
|
|
return headerStyle.Width(m.width).Render(" " + title)
|
|
}
|
|
|
|
func (m Model) renderStatusBar(hints ...string) string {
|
|
return statusBarStyle.Render(" " + strings.Join(hints, " · "))
|
|
}
|
|
|
|
func (m Model) buildGenList() list.Model {
|
|
items := make([]list.Item, len(m.postStore.Posts))
|
|
for i, p := range m.postStore.Posts {
|
|
items[i] = genPostItem{p}
|
|
}
|
|
m.genDelegate = genPostDelegate{selected: m.genSelected, maxLength: m.cfg.Posting.MaxLength}
|
|
l := list.New(items, m.genDelegate, m.width-4, m.height-10)
|
|
l.Title = "Generated Posts [Space=select Ctrl+P=post d=delete]"
|
|
l.SetShowStatusBar(false)
|
|
l.SetFilteringEnabled(false)
|
|
l.Styles.Title = titleStyle
|
|
return l
|
|
}
|
|
|
|
func wordWrap(s string, width int) []string {
|
|
var lines []string
|
|
for _, paragraph := range strings.Split(s, "\n") {
|
|
paragraph = strings.TrimSpace(paragraph)
|
|
if paragraph == "" {
|
|
continue
|
|
}
|
|
var current strings.Builder
|
|
for _, word := range strings.Fields(paragraph) {
|
|
wordLen := utf8.RuneCountInString(word)
|
|
if current.Len() == 0 {
|
|
current.WriteString(word)
|
|
} else if utf8.RuneCountInString(current.String())+1+wordLen <= width {
|
|
current.WriteByte(' ')
|
|
current.WriteString(word)
|
|
} else {
|
|
lines = append(lines, current.String())
|
|
current.Reset()
|
|
current.WriteString(word)
|
|
}
|
|
}
|
|
if current.Len() > 0 {
|
|
lines = append(lines, current.String())
|
|
}
|
|
}
|
|
return lines
|
|
}
|
|
|
|
func firstSourceURL(items []models.ContentItem) string {
|
|
for _, item := range items {
|
|
if item.URL != "" {
|
|
return item.URL
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func truncate(s string, n int) string {
|
|
r := []rune(s)
|
|
if len(r) > n {
|
|
return string(r[:n-3]) + "..."
|
|
}
|
|
return s
|
|
}
|
|
|
|
// --- async commands ---
|
|
|
|
func removeUsedItems(m *Model) {
|
|
if m.selectedApp == nil || len(m.pendingItemIDs) == 0 {
|
|
return
|
|
}
|
|
result, ok := m.prefetchResults[m.selectedApp.Name]
|
|
if !ok {
|
|
return
|
|
}
|
|
filtered := result.Items[:0]
|
|
for _, item := range result.Items {
|
|
if !m.pendingItemIDs[item.ID] {
|
|
filtered = append(filtered, item)
|
|
}
|
|
}
|
|
result.Items = filtered
|
|
m.prefetchResults[m.selectedApp.Name] = result
|
|
rebuildAppList(m)
|
|
m.pendingItemIDs = nil
|
|
}
|
|
|
|
func rebuildAppList(m *Model) {
|
|
idx := m.appList.Index()
|
|
items := make([]list.Item, len(m.cfg.Applications))
|
|
for i, app := range m.cfg.Applications {
|
|
item := appListItem{app: app}
|
|
if result, ok := m.prefetchResults[app.Name]; ok {
|
|
count := 0
|
|
for _, ri := range result.Items {
|
|
if !m.dismissed.IsDismissed(ri.ID) {
|
|
count++
|
|
}
|
|
}
|
|
item.count = count
|
|
item.loaded = true
|
|
}
|
|
items[i] = item
|
|
}
|
|
m.appList.SetItems(items)
|
|
m.appList.Select(idx)
|
|
}
|
|
|
|
func (m Model) doPrefetch(app models.Application) tea.Cmd {
|
|
return func() tea.Msg {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
since := m.appState.GetLastChecked(app.Name, m.cfg.Settings.DefaultLookbackDays)
|
|
result := m.fetch.FetchForApp(ctx, &app, since)
|
|
return prefetchDoneMsg{appName: app.Name, result: result}
|
|
}
|
|
}
|
|
|
|
func (m Model) doFetch(app models.Application, since time.Time) tea.Cmd {
|
|
return func() tea.Msg {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
return fetchDoneMsg{result: m.fetch.FetchForApp(ctx, &app, since)}
|
|
}
|
|
}
|
|
|
|
func (m Model) doGenerate(items []models.ContentItem) tea.Cmd {
|
|
app := m.selectedApp
|
|
cl := m.claude
|
|
limit := m.cfg.Posting.MaxLength - twitter.URLReserve(firstSourceURL(items))
|
|
return func() tea.Msg {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
post, err := cl.GeneratePost(ctx, app, items, limit)
|
|
if err != nil {
|
|
return errMsg{err: err, from: viewContentBrowser}
|
|
}
|
|
return generateDoneMsg{post: post}
|
|
}
|
|
}
|
|
|
|
func (m Model) doBatchGenerate(items []models.ContentItem) tea.Cmd {
|
|
app := m.selectedApp
|
|
cl := m.claude
|
|
maxLength := m.cfg.Posting.MaxLength
|
|
return func() tea.Msg {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
|
defer cancel()
|
|
var contents, sourceURLs []string
|
|
for _, item := range items {
|
|
limit := maxLength - twitter.URLReserve(item.URL)
|
|
post, err := cl.GeneratePost(ctx, app, []models.ContentItem{item}, limit)
|
|
if err != nil {
|
|
return errMsg{err: err, from: viewContentBrowser}
|
|
}
|
|
contents = append(contents, post)
|
|
sourceURLs = append(sourceURLs, item.URL)
|
|
}
|
|
return batchGenerateMsg{contents: contents, sourceURLs: sourceURLs}
|
|
}
|
|
}
|
|
|
|
func (m Model) doPostBatch(posts []store.GeneratedPost) tea.Cmd {
|
|
poster := m.poster
|
|
liPoster := m.liPoster
|
|
maxLength := m.cfg.Posting.MaxLength
|
|
return func() tea.Msg {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
defer cancel()
|
|
posted := map[string][]string{}
|
|
var urls, errs []string
|
|
for _, p := range posts {
|
|
if poster != nil && !p.HasPosted(store.PlatformX) {
|
|
if n := twitter.TweetLength(p.Content, p.SourceURL); n > maxLength {
|
|
errs = append(errs, fmt.Sprintf("%s (X): post is %d characters including the link, limit is %d — delete it and regenerate a shorter one", p.AppName, n, maxLength))
|
|
} else {
|
|
text := p.Content
|
|
if p.SourceURL != "" {
|
|
text += "\n\n" + p.SourceURL
|
|
}
|
|
u, err := poster.PostTweet(ctx, text)
|
|
if err != nil {
|
|
errs = append(errs, fmt.Sprintf("%s (X): %v", p.AppName, err))
|
|
} else {
|
|
urls = append(urls, u)
|
|
posted[p.ID] = append(posted[p.ID], store.PlatformX)
|
|
}
|
|
}
|
|
}
|
|
|
|
if liPoster != nil && !p.HasPosted(store.PlatformLinkedIn) {
|
|
u, err := liPoster.PostUpdate(ctx, p.Content, p.SourceURL)
|
|
if err != nil {
|
|
errs = append(errs, fmt.Sprintf("%s (LinkedIn): %v", p.AppName, err))
|
|
} else {
|
|
urls = append(urls, u)
|
|
posted[p.ID] = append(posted[p.ID], store.PlatformLinkedIn)
|
|
}
|
|
}
|
|
}
|
|
return batchPostedMsg{posted: posted, urls: urls, errors: errs}
|
|
}
|
|
}
|