diff --git a/CHANGELOG.md b/CHANGELOG.md index 4438576..cee7414 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added +- Meeting Notes. `[[calendars]]` in the user config lists ICS calendar feeds, and `spc m` (`:meetings`) opens the Meeting picker on Today's Meetings from all of them: `h` / `l` change day, `t` returns to Today, `r` refreshes. `enter` opens the Meeting's Meeting Note, or creates it in `meetings_folder` from `meeting_template` and links it under `meetings_heading` in that day's Daily Note. Recurring and moved Meetings and real-world timezones are handled, and feeds are cached so the picker opens at once and works offline. + ## [0.5.0] - 2026-10-08 ### Added diff --git a/README.md b/README.md index 10244f3..223b43f 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ The editor is vim: counts, motions, `d`/`c`/`y`, `>`/`<` (one tab per level), te | `spc /` | search the Vault | `:grep [query]` | | `spc b` | Backlinks to this Note | `:backlinks` | | `spc z` | new Zettel, linked from here | `:zettel [title]` | +| `spc m` | Today's Meetings | `:meetings` | | `spc n` | new Note | `:new ` | | | rename / delete this Note | `:rename `, `:delete` | | `spc e` | toggle the sidebar | `:sidebar` | @@ -125,6 +126,36 @@ The Task List (`spc t`) groups open Tasks into Overdue, Today, Upcoming and No d The Task Editor is a form for one Task: its Description (text and `#tags`), Status (open, in progress, done, cancelled), Due, Scheduled and Start dates, and Priority. Open it with `spc T` or `:task` on a Task's line, or `e` in the Task List; the Task List's `a` opens it empty. `tab` / `shift+tab` move between rows, `space`, `←` and `→` change Status and Priority, and the date rows take ISO dates or `today`, `fri`, `+3d`…, saved as ISO dates. An empty date row removes the field. `enter` saves, unless a date row isn't a date, and `esc` discards the edits. Saving rebuilds the line as checkbox, Description, then its fields (each in its own format, new ones in the line's format or `task_format`), then any `^block-id`; fields the form doesn't show, like `[created:: …]` or `✅ …`, are kept. In the open Note the save is one undoable change to the buffer; other Notes are rewritten on disk. +## Meetings + +pholio reads your Meetings from ICS calendar feeds (the secret iCal address that Google Calendar, Outlook and Fastmail give you) and makes a Meeting Note for each one you pick. It never changes your calendar. Add each feed to the user config, not the Vault config, because feed URLs are secrets: + +```toml +[[calendars]] +name = "work" +url = "https://calendar.google.com/calendar/ical/…/basic.ics" +color = "steelblue" # optional: a CSS colour name or "#rrggbb" +``` + +`spc m` (or `:meetings`) opens the Meeting picker on Today: every timed Meeting from every calendar, sorted by start, with the calendar's name in its colour (`color`, else the feed's own, else dimmed). Meetings that have ended are dimmed, and a `✓` marks a Meeting that already has a Meeting Note. `h` / `l` (or `←` / `→`) move a day back or forward, `t` returns to Today, `r` refreshes every calendar, `/` filters, and `esc` closes it. + +`enter` opens the Meeting's Meeting Note, or creates it in `meetings/YYYY-MM-DD-HHmm-.md` from `templates/meeting.md` (a built-in Template if that file is missing) and adds a back-link under `## Meetings` in that day's Daily Note, if it exists. The Meeting Note's frontmatter records the Meeting's `meeting_uid`, so picking the same Meeting again opens it wherever it now is under `meetings/`, even after the Meeting has moved. + +Calendars are fetched in the background at startup and again when the picker opens if they're over 15 minutes old. The last good copy of each is cached, so the picker opens with Meetings at once and still works offline; a calendar that can't be fetched says why on the picker's info line. + +Meeting templates can use the daily placeholders (`{{date}}` is the Meeting's day and `{{title}}` its title) plus `{{start}}`, `{{end}}` (both taking `:FMT`, `HH:mm` by default), `{{daily}}` (a Link to that day's Daily Note), `{{attendees}}`, `{{location}}`, `{{link}}` (the video-call link) and `{{description}}`. pholio adds the `meeting_uid` line itself, so a Template doesn't need one. The built-in Template, to copy to `templates/meeting.md` as a starting point: + +```markdown +# {{title}} + +{{start}}–{{end}} · {{daily}} +Attendees: {{attendees}} +Location: {{location}} +Link: {{link}} + +## Notes +``` + ## Configuration Every key has a default, so no config file is needed. pholio never writes to these files. @@ -139,6 +170,7 @@ Every key has a default, so no config file is needed. pholio never writes to the | `wrap` | `true` | soft word-wrap; `false` scrolls sideways | | `conceal` | `true` | hide `[[ ]]`, `**`, `~~`, backticks and link URLs off the cursor line | | `open_daily_on_startup` | `true` | | +| `[[calendars]]` | | ICS feeds of Meetings: `name`, `url` and optional `color` (see [Meetings](#meetings)) | **Vault config**, `<vault>/.pholio/config.toml` (these keys can also go in the user config; the Vault file wins): @@ -152,6 +184,9 @@ Every key has a default, so no config file is needed. pholio never writes to the | `new_note_folder` | `""` (the Vault root) | | `tasks_heading` | `"## Tasks"` (where the Task List's `a` adds Tasks) | | `task_format` | `"dataview"` (or `"emoji"`: the Task Format pholio writes done dates in) | +| `meetings_folder` | `"meetings"` | +| `meeting_template` | `"templates/meeting.md"` | +| `meetings_heading` | `"## Meetings"` (where Meeting Note back-links go in the Daily Note) | Daily templates can use `{{date}}`, `{{date:FMT}}`, `{{time}}`, `{{time:FMT}}`, `{{title}}`, `{{yesterday}}` and `{{tomorrow}}`, with moment-style formats such as `{{date:dddd, MMMM D}}`. diff --git a/go.mod b/go.mod index f07871b..236e024 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( charm.land/lipgloss/v2 v2.0.6 github.com/BurntSushi/toml v1.6.0 github.com/alecthomas/chroma/v2 v2.27.0 + github.com/arran4/golang-ical v0.3.7 github.com/charmbracelet/colorprofile v0.4.3 github.com/charmbracelet/x/ansi v0.11.8 github.com/charmbracelet/x/exp/golden v0.1.0 @@ -14,6 +15,8 @@ require ( github.com/charmbracelet/x/vt v0.0.0-20261004011457-ad85c59fdf4e github.com/clipperhouse/uax29/v2 v2.7.0 github.com/fsnotify/fsnotify v1.10.1 + github.com/teambition/rrule-go v1.8.2 + golang.org/x/image v0.47.0 ) require ( @@ -31,5 +34,5 @@ require ( github.com/rivo/uniseg v0.4.7 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect golang.org/x/sync v0.22.0 // indirect - golang.org/x/sys v0.47.0 // indirect + golang.org/x/sys v0.49.0 // indirect ) diff --git a/go.sum b/go.sum index b0a0b4d..118e44c 100644 --- a/go.sum +++ b/go.sum @@ -10,6 +10,8 @@ github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r github.com/alecthomas/chroma/v2 v2.27.0/go.mod h1:NjJ3ciIgrqBNeIkWZ4e46nseoLDslxU1LmfCoL+wcY8= github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs= github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/arran4/golang-ical v0.3.7 h1:ONEzzLJqP9aQpXzO6ArsdRshApsWIr6hkMV28RdIw0k= +github.com/arran4/golang-ical v0.3.7/go.mod h1:OnguFgjN0Hmx8jzpmWcC+AkHio94ujmLHKoaef7xQh8= github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o= github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= @@ -36,10 +38,14 @@ github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSE github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2/v2 v2.2.1 h1:mf4KkFUj0gJuarK8P+LgiS+Lit7m9N1yAwEfPbee7R0= github.com/dlclark/regexp2/v2 v2.2.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= @@ -48,13 +54,23 @@ github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/a github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/teambition/rrule-go v1.8.2 h1:lIjpjvWTj9fFUZCmuoVDrKVOtdiyzbzc93qTmRVe/J8= +github.com/teambition/rrule-go v1.8.2/go.mod h1:Ieq5AbrKGciP1V//Wq8ktsTXwSwJHDD5mD/wLBGl3p4= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo= +golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/app/app.go b/internal/app/app.go index 52e2009..3def29e 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -83,6 +83,7 @@ type Model struct { recent []string // Notes opened this session, newest first (find.go) complete *completion // the [[ popup (complete.go) + feeds *feeds // the calendars' Meetings (meetings.go) } // New opens the Note at path. A missing file opens as an empty buffer, and @@ -96,6 +97,7 @@ func New(deps Deps, path string) (Model, error) { deps: deps, vault: filepath.Dir(path), wrap: true, conceal: true, sideOn: true, sideW: config.DefaultState().SidebarWidth, exq: &exQueue{}, appearance: defaultAppearance(), + feeds: &feeds{byURL: map[string]*feed{}}, } file, e, err := m.openEngine(path) if err != nil { @@ -144,9 +146,9 @@ func (m Model) rel(path string) string { return filepath.Base(path) } -// Init implements tea.Model: it starts listening for watcher Notices and -// scanning the Vault index. -func (m Model) Init() tea.Cmd { return tea.Batch(m.listen(), m.scanIndex()) } +// Init implements tea.Model: it starts listening for watcher Notices, +// scanning the Vault index and fetching the calendars. +func (m Model) Init() tea.Cmd { return tea.Batch(m.listen(), m.scanIndex(), m.startFeeds()) } // Update implements tea.Model. func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { @@ -188,6 +190,10 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m, cmd = m.grepTick(msg) case grepResultMsg: m = m.grepResult(msg) + case meetingsMsg: + m = m.meetingsArrived(msg) + case cachedMsg: + m = m.cacheArrived(msg) case indexSyncMsg: if msg.gen == m.syncGen { m = m.syncIndex() diff --git a/internal/app/daily.go b/internal/app/daily.go index 220a5c1..02f355e 100644 --- a/internal/app/daily.go +++ b/internal/app/daily.go @@ -91,9 +91,8 @@ func (m Model) ensureDaily(day time.Time) (string, error) { // openDaily (spc d, :today, :daily) opens day's Daily Note, creating it // from the Template once the open buffer has been dealt with. func (m Model) openDaily(day time.Time) (Model, tea.Cmd) { - return m.openThen(m.dailyNotes().Path(day), func(m Model) error { - _, err := m.ensureDaily(day) - return err + return m.openThen(m.dailyNotes().Path(day), func(m Model) (string, error) { + return m.ensureDaily(day) }, nil) } diff --git a/internal/app/export_test.go b/internal/app/export_test.go index 37ccdc3..b540e5b 100644 --- a/internal/app/export_test.go +++ b/internal/app/export_test.go @@ -1,6 +1,8 @@ package app import ( + "fmt" + tea "charm.land/bubbletea/v2" "github.com/tedkulp/pholio/internal/engine" @@ -56,6 +58,27 @@ func (m Model) PaletteSlots() []string { return out } +// PaletteDetailStyles are how the open palette's visible rows draw their +// Detail when unselected: a raw colour as "#rrggbb", else the theme slot. +func (m Model) PaletteDetailStyles() []string { + if m.overlay == nil { + return nil + } + var out []string + for _, it := range m.overlay.p.Visible() { + switch { + case it.DetailColor != nil: + r, g, b, _ := it.DetailColor.RGBA() + out = append(out, fmt.Sprintf("#%02x%02x%02x", r>>8, g>>8, b>>8)) + case it.DetailSlot != "": + out = append(out, string(it.DetailSlot)) + default: + out = append(out, "overlay.hint") + } + } + return out +} + // PaletteRows are the open palette's visible rows as "group | text | // detail", or nil when no palette is open. func (m Model) PaletteRows() []string { diff --git a/internal/app/help_test.go b/internal/app/help_test.go index bd59f6e..69d2b7d 100644 --- a/internal/app/help_test.go +++ b/internal/app/help_test.go @@ -32,7 +32,7 @@ func TestSpcQuestionOpensHelp(t *testing.T) { } func TestLeaderHintListsHelp(t *testing.T) { - m := keys(resize(shell(t, shellVault(), "/vault/a.md"), 120, 12), space) + m := keys(resize(shell(t, shellVault(), "/vault/a.md"), 140, 12), space) golden.RequireEqual(t, rows(m)[10]) } diff --git a/internal/app/keymap.go b/internal/app/keymap.go index f49b4be..c64b3cc 100644 --- a/internal/app/keymap.go +++ b/internal/app/keymap.go @@ -43,6 +43,7 @@ const ( actTreeDelete action = "tree-delete" actTasks action = "tasks" actEditTask action = "edit-task" + actMeetings action = "meetings" actHelp action = "help" ) @@ -104,6 +105,7 @@ var bindings = []binding{ {scopeLeader, "n", actNewNote, "new"}, {scopeLeader, "t", actTasks, "tasks"}, {scopeLeader, "T", actEditTask, "edit Task"}, + {scopeLeader, "m", actMeetings, "meetings"}, {scopeLeader, "q", actQuit, "quit"}, {scopeLeader, "?", actHelp, "help"}, @@ -149,6 +151,7 @@ var exCommands = []exCommand{ {"delete", actDeleteNote, "delete Note"}, {"tasks", actTasks, "tasks"}, {"task", actEditTask, "edit Task"}, + {"meetings", actMeetings, "meetings"}, } // handler runs an action. arg is an ex command's argument, else "". @@ -188,6 +191,7 @@ func init() { actTreeDelete: func(m Model, _ string) (Model, tea.Cmd) { return m.treeDelete() }, actTasks: func(m Model, _ string) (Model, tea.Cmd) { return m.showTaskList(taskView{}) }, actEditTask: func(m Model, _ string) (Model, tea.Cmd) { return m.editTaskAtCursor() }, + actMeetings: func(m Model, _ string) (Model, tea.Cmd) { return m.showMeetings() }, actHelp: func(m Model, _ string) (Model, tea.Cmd) { return m.showHelp(), nil }, } } diff --git a/internal/app/meeting_notes_test.go b/internal/app/meeting_notes_test.go new file mode 100644 index 0000000..1673ce8 --- /dev/null +++ b/internal/app/meeting_notes_test.go @@ -0,0 +1,320 @@ +package app_test + +import ( + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/tedkulp/pholio/internal/app" + "github.com/tedkulp/pholio/internal/config" + "github.com/tedkulp/pholio/internal/seam/seamtest" +) + +// reviewUID is the meeting_uid of the Design review Meeting the tests +// pick: its UID and its start in UTC. +var reviewUID = "review@example.test/" + time.Date(2026, 10, 12, 14, 0, 0, 0, time.Local).UTC().Format("20060102T150405Z") + +// meetingNotesVault opens /vault/a.md at meetingDay with one calendar +// serving the 14:00 Design review, plus files. +func meetingNotesVault(t *testing.T, files map[string]string) (app.Model, *seamtest.MemFS) { + t.Helper() + return meetingNotesVaultWith(t, vevent("review@example.test", "Design review", 14, 0, 60), files) +} + +func meetingNotesVaultWith(t *testing.T, meeting string, files map[string]string) (app.Model, *seamtest.MemFS) { + t.Helper() + all := map[string]string{ + userConfig: calendarsConfig("work", feed(t, 200, vcalendar(meeting))), + "/vault/a.md": "hi\n", + } + for p, s := range files { + all[p] = s + } + fsys := seamtest.NewMemFS(all) + s, err := config.Startup(fsys, dirs, "/home/u", "/vault/a.md") + if err != nil { + t.Fatal(err) + } + m, err := app.New(app.Deps{FS: fsys, Clock: seamtest.NewClock(meetingDay)}, "/vault/a.md") + if err != nil { + t.Fatal(err) + } + return resize(m.WithSession(s), 100, 20), fsys +} + +// openMeetings opens the Meeting picker and lets every feed arrive. +func openMeetings(t *testing.T, m app.Model) app.Model { + t.Helper() + m, cmd := pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + return drive(t, m, cmd) +} + +func fileText(t *testing.T, fsys *seamtest.MemFS, p string) string { + t.Helper() + b, err := fsys.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +const reviewNote = "/vault/meetings/2026-10-12-1400-design-review.md" + +func TestEnterCreatesTheMeetingNoteFromTheBuiltInTemplate(t *testing.T) { + m, fsys := meetingNotesVault(t, nil) + + m = press(openMeetings(t, m), enter) + + want := "---\nmeeting_uid: \"" + reviewUID + "\"\n---\n" + + "# Design review\n\n14:00–15:00 · [[2026-10-12]]\nAttendees: \nLocation: \nLink: \n\n## Notes\n" + if got := fileText(t, fsys, reviewNote); got != want { + t.Errorf("Meeting Note =\n%q\nwant\n%q", got, want) + } + if m.Path() != reviewNote || m.Text() != want { + t.Errorf("open = %s %q, want the new Meeting Note", m.Path(), m.Text()) + } + if got := m.Cursor().Line; got != 10 { + t.Errorf("cursor line = %d, want 10 (## Notes, the last line)", got) + } + if got := messageLine(m); got != "Created meetings/2026-10-12-1400-design-review.md (no Daily Note for 2026-10-12)" { + t.Errorf("message = %q", got) + } + if _, err := fsys.Stat(reviewDaily); err == nil { + t.Error("the back-link created the Daily Note") + } + viewHas(t, m, "NORMAL") + if m = press(m, ctrlO); m.Path() != "/vault/a.md" { + t.Errorf("ctrl-o went to %s, want /vault/a.md", m.Path()) + } +} + +func TestMeetingTemplateFrontmatterGetsTheMeetingUID(t *testing.T) { + m, fsys := meetingNotesVault(t, map[string]string{ + "/vault/templates/meeting.md": "---\ntags: [meeting]\n---\n# {{title}} {{date}} {{start:h:mm A}}–{{end}} at {{time}} {{unknown}}\n", + }) + + _ = press(openMeetings(t, m), enter) + + want := "---\nmeeting_uid: \"" + reviewUID + "\"\ntags: [meeting]\n---\n# Design review 2026-10-12 2:00 PM–15:00 at 08:00 {{unknown}}\n" + if got := fileText(t, fsys, reviewNote); got != want { + t.Errorf("Meeting Note =\n%q\nwant\n%q", got, want) + } +} + +func TestTheMeetingNoteHasTheMeetingsDetails(t *testing.T) { + meeting := strings.Replace(vevent("review@example.test", "Design review", 14, 0, 60), "END:VEVENT", + "ATTENDEE;CN=Ada Example:mailto:ada@example.test\r\nATTENDEE:mailto:bob@example.test\r\n"+ + "LOCATION:Room 4\\, Floor 2\r\nDESCRIPTION:Join https://acme.zoom.us/j/1\\nBring notes\r\nEND:VEVENT", 1) + m, fsys := meetingNotesVaultWith(t, meeting, map[string]string{ + "/vault/templates/meeting.md": "{{attendees}}|{{location}}|{{link}}|{{description}}\n", + }) + + _ = press(openMeetings(t, m), enter) + + want := "---\nmeeting_uid: \"" + reviewUID + "\"\n---\n" + + "Ada Example, bob@example.test|Room 4, Floor 2|https://acme.zoom.us/j/1|Join https://acme.zoom.us/j/1\nBring notes\n" + if got := fileText(t, fsys, reviewNote); got != want { + t.Errorf("Meeting Note =\n%q\nwant\n%q", got, want) + } +} + +func TestMeetingTemplateWithoutFrontmatterGetsANewBlock(t *testing.T) { + m, fsys := meetingNotesVault(t, map[string]string{ + "/vault/.pholio/config.toml": "meetings_folder = \"mtg\"\nmeeting_template = \"t/m.md\"\n", + "/vault/t/m.md": "# {{title}}\n", + }) + + _ = press(openMeetings(t, m), enter) + + want := "---\nmeeting_uid: \"" + reviewUID + "\"\n---\n# Design review\n" + if got := fileText(t, fsys, "/vault/mtg/2026-10-12-1400-design-review.md"); got != want { + t.Errorf("Meeting Note =\n%q\nwant\n%q", got, want) + } +} + +func TestAMeetingNoteNameCollisionCountsUp(t *testing.T) { + m, fsys := meetingNotesVault(t, map[string]string{ + reviewNote: "# another Meeting\n", + "/vault/meetings/2026-10-12-1400-design-review-2.md": "---\nmeeting_uid: \"other@example.test/20261012T120000Z\"\n---\n", + }) + + m = press(openMeetings(t, m), enter) + + if want := "/vault/meetings/2026-10-12-1400-design-review-3.md"; m.Path() != want { + t.Errorf("opened %s, want %s", m.Path(), want) + } + if got := fileText(t, fsys, reviewNote); got != "# another Meeting\n" { + t.Errorf("the other Meeting's Note changed: %q", got) + } +} + +func TestAnUntitledMeetingIsNamedMeeting(t *testing.T) { + meeting := strings.Replace(vevent("x@example.test", "", 9, 0, 30), "SUMMARY:\r\n", "", 1) + m, fsys := meetingNotesVaultWith(t, meeting, map[string]string{"/vault/templates/meeting.md": "# {{title}}\n"}) + + _ = press(openMeetings(t, m), enter) + + if got := fileText(t, fsys, "/vault/meetings/2026-10-12-0900-meeting.md"); !strings.HasSuffix(got, "---\n# Untitled meeting\n") { + t.Errorf("Meeting Note = %q", got) + } +} + +func TestAMovedOccurrenceKeepsItsMeetingNote(t *testing.T) { + // A daily Design review from 14:00 on meetingDay, whose first + // occurrence was moved to 16:00. + series := strings.Replace(vevent("review@example.test", "Design review", 14, 0, 60), "SUMMARY:", "RRULE:FREQ=DAILY\r\nSUMMARY:", 1) + moved := strings.Replace(vevent("review@example.test", "Design review", 16, 0, 60), "SUMMARY:", + "RECURRENCE-ID:"+strings.TrimPrefix(reviewUID, "review@example.test/")+"\r\nSUMMARY:", 1) + existing := "/vault/meetings/notes-from-review.md" + m, _ := meetingNotesVaultWith(t, series+moved, map[string]string{ + existing: "---\nmeeting_uid: \"" + reviewUID + "\"\n---\n# Review\n", + }) + + m = openMeetings(t, m) + if got := m.PaletteSelected(); got != "✓ 16:00–17:00 Design review" { + t.Errorf("row = %q, want the moved occurrence, ticked", got) + } + if m = press(m, enter); m.Path() != existing { + t.Errorf("opened %s, want %s", m.Path(), existing) + } +} + +func TestAMeetingWithAMeetingNoteIsTickedAndReopened(t *testing.T) { + existing := "/vault/meetings/notes-from-review.md" + m, _ := meetingNotesVault(t, map[string]string{ + existing: "---\ntitle: x\nmeeting_uid: \"" + reviewUID + "\"\n---\n# Review\n\nnotes\n", + }) + + m = openMeetings(t, m) + if got := m.PaletteSelected(); got != "✓ 14:00–15:00 Design review" { + t.Errorf("row = %q, want it ticked", got) + } + m = press(m, enter) + + if m.Path() != existing { + t.Errorf("opened %s, want %s", m.Path(), existing) + } + if got := m.Cursor(); got.Line != 0 { + t.Errorf("cursor = %v, want the usual start", got) + } + if got := messageLine(m); got != "" { + t.Errorf("message = %q, want none", got) + } +} + +const reviewDaily = "/vault/daily/2026-10-12.md" + +func TestCreatingAMeetingNoteLinksItFromTheDailyNote(t *testing.T) { + m, fsys := meetingNotesVault(t, map[string]string{ + reviewDaily: "# Mon\n\n## Meetings\n- 09:00 [[standup]]\n\n## Tasks\n- [ ] x\n", + }) + + m = press(openMeetings(t, m), enter) + + want := "# Mon\n\n## Meetings\n- 09:00 [[standup]]\n- 14:00 [[2026-10-12-1400-design-review]]\n\n## Tasks\n- [ ] x\n" + if got := fileText(t, fsys, reviewDaily); got != want { + t.Errorf("Daily Note =\n%q\nwant\n%q", got, want) + } + if got := messageLine(m); got != "Created meetings/2026-10-12-1400-design-review.md" { + t.Errorf("message = %q", got) + } +} + +func TestTheMeetingsHeadingIsAddedWhenMissing(t *testing.T) { + m, fsys := meetingNotesVault(t, map[string]string{ + "/vault/.pholio/config.toml": "meetings_heading = \"### Calls\"\n", + reviewDaily: "# Mon\n\n## Meetings\n", + }) + + _ = press(openMeetings(t, m), enter) + + want := "# Mon\n\n## Meetings\n\n### Calls\n- 14:00 [[2026-10-12-1400-design-review]]\n" + if got := fileText(t, fsys, reviewDaily); got != want { + t.Errorf("Daily Note =\n%q\nwant\n%q", got, want) + } +} + +func TestTheBackLinkReachesTheOpenDailyNote(t *testing.T) { + m, fsys := meetingNotesVault(t, map[string]string{reviewDaily: "## Meetings\n"}) + m = ex(m, "e "+reviewDaily) + + m = press(openMeetings(t, m), enter) + + want := "## Meetings\n- 14:00 [[2026-10-12-1400-design-review]]\n" + if got := fileText(t, fsys, reviewDaily); got != want { + t.Errorf("Daily Note =\n%q\nwant\n%q", got, want) + } + if m = press(m, ctrlO); m.Path() != reviewDaily || m.Text() != want { + t.Errorf("ctrl-o = %s %q, want the Daily Note with the back-link", m.Path(), m.Text()) + } +} + +func TestTheBackLinkReachesADirtyOpenDailyNote(t *testing.T) { + for _, tc := range []struct{ answer, want string }{ + {"y", "## Meetings\nmine\n- 14:00 [[2026-10-12-1400-design-review]]\n"}, + {"n", "## Meetings\n- 14:00 [[2026-10-12-1400-design-review]]\n"}, + } { + t.Run(tc.answer, func(t *testing.T) { + m, fsys := meetingNotesVault(t, map[string]string{reviewDaily: "## Meetings\n"}) + m = press(typeKeys(ex(m, "e "+reviewDaily), "omine"), esc) + + m = press(openMeetings(t, m), enter) + m = typeKeys(m, tc.answer) + + if got := fileText(t, fsys, reviewDaily); got != tc.want { + t.Errorf("Daily Note =\n%q\nwant\n%q", got, tc.want) + } + if m.Path() != reviewNote { + t.Errorf("opened %s, want the Meeting Note", m.Path()) + } + }) + } +} + +func TestAMeetingNoteInASubfolderIsFound(t *testing.T) { + existing := "/vault/meetings/2026/10/notes-from-review.md" + m, _ := meetingNotesVault(t, map[string]string{ + existing: "---\nmeeting_uid: \"" + reviewUID + "\"\n---\n# Review\n", + }) + + m = openMeetings(t, m) + if got := m.PaletteSelected(); got != "✓ 14:00–15:00 Design review" { + t.Errorf("row = %q, want it ticked", got) + } + if m = press(m, enter); m.Path() != existing { + t.Errorf("opened %s, want %s", m.Path(), existing) + } +} + +func TestANoteAppearingWhileAskedIsNotOverwritten(t *testing.T) { + m, fsys := meetingNotesVault(t, nil) + m = press(typeKeys(m, "omine"), esc) + + m = press(openMeetings(t, m), enter) // asks to save a.md first + if err := fsys.WriteFile(reviewNote, []byte("# someone else's\n")); err != nil { + t.Fatal(err) + } + m = typeKeys(m, "y") + + if got := fileText(t, fsys, reviewNote); got != "# someone else's\n" { + t.Errorf("the Note that appeared was overwritten: %q", got) + } + if want := "/vault/meetings/2026-10-12-1400-design-review-2.md"; m.Path() != want { + t.Errorf("opened %s, want %s", m.Path(), want) + } +} + +func TestACRLFTemplateFrontmatterGetsTheMeetingUID(t *testing.T) { + m, fsys := meetingNotesVault(t, map[string]string{ + "/vault/templates/meeting.md": "---\r\ntags: [meeting]\r\n---\r\n# {{title}}\r\n", + }) + + _ = press(openMeetings(t, m), enter) + + want := "---\r\nmeeting_uid: \"" + reviewUID + "\"\r\ntags: [meeting]\r\n---\r\n# Design review\r\n" + if got := fileText(t, fsys, reviewNote); got != want { + t.Errorf("Meeting Note =\n%q\nwant\n%q", got, want) + } +} diff --git a/internal/app/meetingnote.go b/internal/app/meetingnote.go new file mode 100644 index 0000000..8ad614a --- /dev/null +++ b/internal/app/meetingnote.go @@ -0,0 +1,222 @@ +package app + +import ( + "errors" + "fmt" + "io/fs" + "path" + "path/filepath" + "slices" + "strconv" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/tedkulp/pholio/internal/calendar" + "github.com/tedkulp/pholio/internal/daily" + "github.com/tedkulp/pholio/internal/dates" + "github.com/tedkulp/pholio/internal/engine" + "github.com/tedkulp/pholio/internal/index" + "github.com/tedkulp/pholio/internal/tasks" +) + +// meetingTemplate is the built-in meeting Template, used when +// meeting_template is missing. +const meetingTemplate = "# {{title}}\n\n{{start}}–{{end}} · {{daily}}\nAttendees: {{attendees}}\nLocation: {{location}}\nLink: {{link}}\n\n## Notes\n" + +// meetingUID is a Meeting's identity as written in its Meeting Note's +// meeting_uid: line: its UID and its original start in UTC, so a moved +// occurrence keeps its Meeting Note. +func meetingUID(mt calendar.Meeting) string { + return mt.UID + "/" + mt.Original.Format(calendar.DateTime+"Z") +} + +// meetingNotes maps the meeting_uid of each Meeting Note under +// meetings_folder to its path. +func (m Model) meetingNotes() map[string]string { + notes := map[string]string{} + m.findMeetingNotes(m.abs(m.config().MeetingsFolder), notes) + return notes +} + +// findMeetingNotes adds the Meeting Notes under dir to notes. +func (m Model) findMeetingNotes(dir string, notes map[string]string) { + entries, _ := m.deps.FS.ReadDir(dir) // no folder: no Meeting Notes + for _, e := range entries { + p := filepath.Join(dir, e.Name()) + if e.IsDir() { + m.findMeetingNotes(p, notes) + continue + } + if !index.IsNote(e.Name()) { + continue + } + if data, err := m.deps.FS.ReadFile(p); err == nil { + if uid, ok := frontmatterMeetingUID(string(data)); ok { + notes[uid] = p + } + } + } +} + +// frontmatterMeetingUID is the meeting_uid: in a Note's frontmatter, if any. +func frontmatterMeetingUID(s string) (string, bool) { + lines := strings.Split(s, "\n") + if strings.TrimRight(lines[0], "\r") != "---" { + return "", false + } + for _, l := range lines[1:] { + l = strings.TrimRight(l, "\r") + if l == "---" { + break + } + if v, ok := strings.CutPrefix(l, "meeting_uid:"); ok { + v = strings.TrimSpace(v) + if u, err := strconv.Unquote(v); err == nil { + return u, true + } + return v, true + } + } + return "", false +} + +// openMeeting opens mt's Meeting Note, creating it first if it has none. +func (m Model) openMeeting(mt calendar.Meeting) (Model, tea.Cmd) { + if p, ok := m.meetingNotes()[meetingUID(mt)]; ok { + return m.openNote(p) + } + return m.createMeetingNote(mt) +} + +// meetingRel is the Vault-relative path for mt's new Meeting Note: +// <meetings_folder>/YYYY-MM-DD-HHmm-<slug>.md, with -n before the .md +// when n > 1. +func (m Model) meetingRel(mt calendar.Meeting, n int) string { + s := slug(mt.Title) + if s == "" { + s = "meeting" + } + base := path.Join(m.config().MeetingsFolder, mt.Start.In(m.now().Location()).Format("2006-01-02-1504")+"-"+s) + if n > 1 { + return fmt.Sprintf("%s-%d.md", base, n) + } + return base + ".md" +} + +// meetingNoteText is mt's Meeting Note made from tmpl, with its +// meeting_uid: line in the frontmatter. +func (m Model) meetingNoteText(tmpl string, mt calendar.Meeting) string { + now := m.now() + start := mt.Start.In(now.Location()) + title := mt.Title + if title == "" { + title = "Untitled meeting" + } + text := daily.Render(tmpl, daily.Vars{ + Day: start, + Now: now, + Title: title, + Times: map[string]time.Time{"start": start, "end": mt.End.In(now.Location())}, + Text: map[string]string{ + "daily": "[[" + start.Format(dates.ISO) + "]]", + "attendees": strings.Join(mt.Attendees, ", "), + "location": mt.Location, + "link": mt.Link, + "description": mt.Description, + }, + }) + uid := "meeting_uid: " + strconv.Quote(meetingUID(mt)) + for _, eol := range []string{"\n", "\r\n"} { + if rest, ok := strings.CutPrefix(text, "---"+eol); ok { + return "---" + eol + uid + eol + rest + } + } + return "---\n" + uid + "\n---\n" + text +} + +// createMeetingNote writes mt's Meeting Note from the meeting Template +// once the open buffer has been dealt with, and opens it on its last line. +func (m Model) createMeetingNote(mt calendar.Meeting) (Model, tea.Cmd) { + tmpl := meetingTemplate + data, err := m.deps.FS.ReadFile(m.abs(m.config().MeetingTemplate)) + switch { + case err == nil: + tmpl = string(data) + case !errors.Is(err, fs.ErrNotExist): + return m.say("reading the meeting Template: "+err.Error(), true), nil + } + n := 1 // the first name free now; a file may take it before the write + for { + if _, err := m.deps.FS.Stat(m.abs(m.meetingRel(mt, n))); err != nil { + break + } + n++ + } + rel := m.meetingRel(mt, n) + text := []byte(m.meetingNoteText(tmpl, mt)) + start := mt.Start.In(m.now().Location()) + noDaily := "" + return m.openThen(m.abs(rel), func(m Model) (string, error) { + if err := m.deps.FS.MkdirAll(filepath.Dir(m.abs(rel))); err != nil { + return "", fmt.Errorf("creating Meeting Note: %w", err) + } + // Never over a file that appeared since: count up past it. + for ; ; n++ { + rel = m.meetingRel(mt, n) + err := m.deps.FS.Create(m.abs(rel), text) + if err == nil { + break + } + if !errors.Is(err, fs.ErrExist) { + return "", fmt.Errorf("creating Meeting Note: %w", err) + } + } + p := m.abs(rel) + if m.deps.Watch != nil { + m.deps.Watch.Wrote(p, text) + } + if ix := m.index(); ix != nil { + ix.Update(p, text) + } + linked, err := m.linkMeetingNote(start, "- "+start.Format("15:04")+" [["+linkName(rel)+"]]") + if !linked { + noDaily = " (no Daily Note for " + start.Format(dates.ISO) + ")" + } + return p, err + }, func(m Model) Model { + e := m.ed.Engine() + e.SetCursor(engine.Pos{Line: e.Buf.LineCount() - 1}) + return m.say("Created "+rel+noDaily, false) + }) +} + +// linkMeetingNote appends line, a Meeting Note's back-link, under +// meetings_heading in day's Daily Note, adding the heading when it is +// missing. linked is false when that Daily Note does not exist. +// +// It runs once the open buffer has been dealt with (saved or discarded) +// and just before switching to the Meeting Note, so it always writes the +// file, even when the Daily Note is the open Note. +func (m Model) linkMeetingNote(day time.Time, line string) (linked bool, err error) { + path := m.dailyNotes().Path(day) + if _, err := m.deps.FS.Stat(path); errors.Is(err, fs.ErrNotExist) { + return false, nil + } + heading := m.config().MeetingsHeading + err = tasks.EditFile(m.otherFile(), path, func(lines []string) []string { + at := tasks.SectionAt(lines, heading, func(l string) bool { return strings.TrimSpace(l) != "" }) + if at < 0 { + if n := len(lines); n > 0 && strings.TrimSpace(lines[n-1]) != "" { + lines = append(lines, "") + } + return append(lines, heading, line) + } + return slices.Insert(lines, at, line) + }) + if err != nil { + return true, fmt.Errorf("linking the Meeting Note from %s: %w", m.rel(path), err) + } + return true, nil +} diff --git a/internal/app/meetings.go b/internal/app/meetings.go new file mode 100644 index 0000000..28cdf8a --- /dev/null +++ b/internal/app/meetings.go @@ -0,0 +1,287 @@ +package app + +import ( + "cmp" + "fmt" + "image/color" + "net/http" + "path/filepath" + "slices" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/tedkulp/pholio/internal/calendar" + "github.com/tedkulp/pholio/internal/config" + "github.com/tedkulp/pholio/internal/palette" + "github.com/tedkulp/pholio/internal/theme" +) + +// staleAfter is how old a calendar's last fetch may be before opening the +// picker fetches it again. +const staleAfter = 15 * time.Minute + +// feeds is every calendar's Meetings as last fetched, shared by copies of +// the Model, so the startup fetch fills the picker opened later. +type feeds struct { + byURL map[string]*feed + picker *meetingState // the picker last opened +} + +// feed is one calendar's Meetings and how its fetches went. +type feed struct { + ms []calendar.Meeting + fetched time.Time // when ms were fetched; zero when there are none + fetching bool + err error // why the last fetch failed, or nil +} + +// meetingState is an open Meeting picker. +type meetingState struct { + open bool // the picker is still up + day time.Time // the day shown + failed []string // one status line per failing calendar + notes map[string]string // meeting_uid → Meeting Note path +} + +// meetingRow is a Meeting, the name of the calendar it came from and that +// calendar's colour (nil for overlay.hint). +type meetingRow struct { + calendar.Meeting + cal string + color color.Color +} + +// meetingsMsg is one calendar's fetch result. +type meetingsMsg struct { + url string + ms []calendar.Meeting + err error +} + +// cachedMsg is one calendar's Meetings read from the cache, fetched then. +type cachedMsg struct { + url string + ms []calendar.Meeting + fetched time.Time +} + +// calendarCache is where feed bodies are cached, or "" for no cache. +func (m Model) calendarCache() string { + if m.session == nil || m.session.Dirs.CacheHome == "" { + return "" + } + return filepath.Join(m.session.Dirs.CacheHome, "pholio", "calendars") +} + +// feed is c's feed. +func (m Model) feed(c config.Calendar) *feed { + f, ok := m.feeds.byURL[c.URL] + if !ok { + f = &feed{} + m.feeds.byURL[c.URL] = f + } + return f +} + +// startFeeds (at startup) reads every calendar's cache and fetches every +// calendar, all in the background. +func (m Model) startFeeds() tea.Cmd { + cmds := []tea.Cmd{m.fetchFeeds(true)} + if dir := m.calendarCache(); dir != "" { + for _, c := range m.config().Calendars { + cmds = append(cmds, func() tea.Msg { + ms, at, err := calendar.Cached(dir, c.URL) + if err != nil { + return nil // nothing cached + } + return cachedMsg{url: c.URL, ms: ms, fetched: at} + }) + } + } + return tea.Batch(cmds...) +} + +// fetchFeeds fetches every calendar not already being fetched, one +// goroutine each: all of them when force is set, else those not fetched +// successfully in the last staleAfter. +func (m Model) fetchFeeds(force bool) tea.Cmd { + client := &http.Client{Timeout: calendar.Timeout} + dir := m.calendarCache() + var cmds []tea.Cmd + for _, c := range m.config().Calendars { + f := m.feed(c) + if f.fetching || !force && m.now().Sub(f.fetched) <= staleAfter { + continue + } + f.fetching = true + cmds = append(cmds, func() tea.Msg { + ms, err := calendar.Fetch(client, c.URL, dir) + return meetingsMsg{url: c.URL, ms: ms, err: err} + }) + } + return tea.Batch(cmds...) +} + +// showMeetings (spc m, :meetings) opens the Meeting picker on Today with +// what is known, and fetches the calendars whose data is stale. +func (m Model) showMeetings() (Model, tea.Cmd) { + if len(m.config().Calendars) == 0 { + where := "the user config" + if m.session != nil { + where = config.UserConfigPath(m.session.Dirs) + } + return m.say("no calendars: add [[calendars]] to "+where, true), nil + } + day := m.today() + st := &meetingState{open: true, day: day, notes: m.meetingNotes()} + m.feeds.picker = st + cmd := m.fetchFeeds(false) + p := palette.New("", palette.List). + WithPlaceholder("/ to filter"). + WithHint("h/l day · t today · r refresh · enter open/create · esc close"). + WithInfo(func(string) []string { return st.failed }) + m = m.showPalette(m.meetingItems(p, st), func(m Model, ev palette.Event) (Model, tea.Cmd) { + switch { + case ev.Kind == palette.Closed || ev.Kind == palette.Chosen: + st.open = false + if r, ok := ev.Item.Value.(meetingRow); ok && ev.Kind == palette.Chosen { + return m.openMeeting(r.Meeting) + } + case ev.Kind == palette.Key && ev.Key == "r": + cmd := m.fetchFeeds(true) + m.overlay.p = m.meetingItems(m.overlay.p, st) + return m, cmd + case ev.Kind == palette.Key: + switch ev.Key { + case "h", "left": + st.day = st.day.AddDate(0, 0, -1) + case "l", "right": + st.day = st.day.AddDate(0, 0, 1) + case "t": + st.day = m.today() + default: + return m, nil + } + m.overlay.p = m.meetingItems(m.overlay.p, st) + } + return m, nil + }) + return m, cmd +} + +// meetingsArrived stores one calendar's fetch and redraws an open picker. +func (m Model) meetingsArrived(msg meetingsMsg) Model { + f, ok := m.feeds.byURL[msg.url] + if !ok { + return m + } + f.fetching, f.err = false, msg.err + if msg.err == nil { + f.ms, f.fetched = msg.ms, m.now() + } + return m.redrawMeetings() +} + +// cacheArrived stores one calendar's cached Meetings, unless a fetch has +// already brought newer ones, and redraws an open picker. +func (m Model) cacheArrived(msg cachedMsg) Model { + f, ok := m.feeds.byURL[msg.url] + if !ok || !f.fetched.IsZero() { + return m + } + f.ms, f.fetched = msg.ms, msg.fetched + return m.redrawMeetings() +} + +// redrawMeetings refills the picker if it is open. +func (m Model) redrawMeetings() Model { + if st := m.feeds.picker; st != nil && st.open && m.overlay != nil { + m.overlay.p = m.meetingItems(m.overlay.p, st) + } + return m +} + +// meetingItems titles p with st's day and fills it with that day's +// Meetings from every calendar, sorted by start, and notes the failing +// calendars in st. Meetings that have ended are dimmed. +func (m Model) meetingItems(p palette.Model, st *meetingState) palette.Model { + var rows []meetingRow + st.failed = nil + loading, cached := false, false + for _, c := range m.config().Calendars { + f := m.feed(c) + loading = loading || f.fetching + cached = cached || !f.fetched.IsZero() + for _, mt := range calendar.On(f.ms, st.day) { + rows = append(rows, meetingRow{mt, c.Name, calendarColor(c.Color, mt.CalendarColor)}) + } + switch { + case f.err == nil: + case f.fetched.IsZero(): + st.failed = append(st.failed, c.Name+": "+f.err.Error()) + default: + st.failed = append(st.failed, c.Name+": offline, showing data from "+ago(m.now().Sub(f.fetched))) + } + } + slices.SortStableFunc(rows, func(a, b meetingRow) int { return cmp.Compare(a.Start.UnixNano(), b.Start.UnixNano()) }) + loc := st.day.Location() + items := make([]palette.Item, len(rows)) + for i, r := range rows { + gutter := " " + if _, ok := st.notes[meetingUID(r.Meeting)]; ok { + gutter = "✓ " + } + items[i] = palette.Item{ + Text: gutter + r.Start.In(loc).Format("15:04") + "–" + r.End.In(loc).Format("15:04") + " " + r.Title, + Detail: r.cal, + DetailColor: r.color, + Value: r, + } + if !r.End.After(m.now()) { + items[i].Slot, items[i].DetailColor = theme.OverlayHint, nil + } + } + empty := "no Meetings" + if loading && !cached { + empty = "Loading…" + } + return p.WithTitle(meetingsTitle(st.day, m.today())).WithEmpty(empty).SetItems(items) +} + +// calendarColor is the configured colour, else the feed's COLOR, else nil +// (overlay.hint). An unreadable feed COLOR is ignored. +func calendarColor(configured, feed string) color.Color { + for _, s := range []string{configured, feed} { + if c, err := theme.ParseCSSColor(s); err == nil { + return c + } + } + return nil +} + +// meetingsTitle is "Meetings · Mon 12 Oct", with " (today)", +// " (yesterday)" or " (tomorrow)" when day is one of those. +func meetingsTitle(day, today time.Time) string { + title := "Meetings · " + day.Format("Mon 2 Jan") + switch day.Format(time.DateOnly) { + case today.Format(time.DateOnly): + title += " (today)" + case today.AddDate(0, 0, -1).Format(time.DateOnly): + title += " (yesterday)" + case today.AddDate(0, 0, 1).Format(time.DateOnly): + title += " (tomorrow)" + } + return title +} + +// ago is d as "5m ago", "2h ago" or "3d ago". +func ago(d time.Duration) string { + switch { + case d < time.Hour: + return fmt.Sprintf("%dm ago", int(d.Minutes())) + case d < 48*time.Hour: + return fmt.Sprintf("%dh ago", int(d.Hours())) + } + return fmt.Sprintf("%dd ago", int(d.Hours()/24)) +} diff --git a/internal/app/meetings_test.go b/internal/app/meetings_test.go new file mode 100644 index 0000000..d6a0a59 --- /dev/null +++ b/internal/app/meetings_test.go @@ -0,0 +1,413 @@ +package app_test + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + + "github.com/tedkulp/pholio/internal/app" + "github.com/tedkulp/pholio/internal/config" + "github.com/tedkulp/pholio/internal/seam/seamtest" +) + +// meetingDay is 08:00 local on Monday 2026-10-12. +var meetingDay = time.Date(2026, 10, 12, 8, 0, 0, 0, time.Local) + +// vevent is a synthetic Meeting starting at hh:mm local on meetingDay. +func vevent(uid, title string, hh, mm, minutes int) string { + return veventOn(12, uid, title, hh, mm, minutes) +} + +// veventOn is vevent on day (of October 2026). +func veventOn(day int, uid, title string, hh, mm, minutes int) string { + start := time.Date(2026, 10, day, hh, mm, 0, 0, time.Local).UTC() + end := start.Add(time.Duration(minutes) * time.Minute) + return "BEGIN:VEVENT\r\nUID:" + uid + "\r\nDTSTAMP:20261001T000000Z\r\n" + + "DTSTART:" + start.Format("20060102T150405Z") + "\r\nDTEND:" + end.Format("20060102T150405Z") + "\r\n" + + "SUMMARY:" + title + "\r\nEND:VEVENT\r\n" +} + +func vcalendar(events ...string) string { + return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//pholio//test//EN\r\n" + strings.Join(events, "") + "END:VCALENDAR\r\n" +} + +// feed serves body, or status when it isn't 200, and returns its URL. +func feed(t *testing.T, status int, body string) string { + t.Helper() + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(s.Close) + return s.URL +} + +// calendarsConfig is a user config with a [[calendars]] entry per name, url +// pair. +func calendarsConfig(pairs ...string) string { + var b strings.Builder + for i := 0; i+1 < len(pairs); i += 2 { + b.WriteString("[[calendars]]\nname = \"" + pairs[i] + "\"\nurl = \"" + pairs[i+1] + "\"\n") + } + return b.String() +} + +// meetingsApp opens /vault/a.md at meetingDay with userCfg as the user +// config and an empty calendar cache. +func meetingsApp(t *testing.T, userCfg string) app.Model { + t.Helper() + return meetingsAppAt(t, t.TempDir(), seamtest.NewClock(meetingDay), userCfg) +} + +// meetingsAppAt is meetingsApp with the cache home and clock given. +func meetingsAppAt(t *testing.T, cacheHome string, clock *seamtest.Clock, userCfg string) app.Model { + t.Helper() + fsys := seamtest.NewMemFS(map[string]string{userConfig: userCfg, "/vault/a.md": "hi\n"}) + d := dirs + d.CacheHome = cacheHome + s, err := config.Startup(fsys, d, "/home/u", "/vault/a.md") + if err != nil { + t.Fatal(err) + } + m, err := app.New(app.Deps{FS: fsys, Clock: clock}, "/vault/a.md") + if err != nil { + t.Fatal(err) + } + return resize(m.WithSession(s), 100, 20) +} + +// liveFeed is a feed whose answer can change, counting its fetches. +type liveFeed struct { + url string + status atomic.Int64 + body atomic.Value // string + hits atomic.Int32 +} + +func newLiveFeed(t *testing.T, body string) *liveFeed { + t.Helper() + f := &liveFeed{} + f.set(200, body) + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + f.hits.Add(1) + w.WriteHeader(int(f.status.Load())) + _, _ = w.Write([]byte(f.body.Load().(string))) + })) + t.Cleanup(s.Close) + f.url = s.URL + return f +} + +func (f *liveFeed) set(status int, body string) { + f.status.Store(int64(status)) + f.body.Store(body) +} + +// setFetched backdates every cached feed under cacheHome to at. +func setFetched(t *testing.T, cacheHome string, at time.Time) { + t.Helper() + files, _ := filepath.Glob(filepath.Join(cacheHome, "pholio", "calendars", "*.ics")) + if len(files) == 0 { + t.Fatal("nothing cached") + } + for _, f := range files { + if err := os.Chtimes(f, at, at); err != nil { + t.Fatal(err) + } + } +} + +// pressing presses k and returns the command it gave, unrun. +func pressing(m app.Model, k tea.KeyPressMsg) (app.Model, tea.Cmd) { + next, cmd := m.Update(k) + return next.(app.Model), cmd +} + +func viewHas(t *testing.T, m app.Model, s string) { + t.Helper() + if v := ansi.Strip(m.View().Content); !strings.Contains(v, s) { + t.Errorf("view does not show %q:\n%s", s, v) + } +} + +func TestSpcMListsTodaysMeetingsFromEveryCalendar(t *testing.T) { + work := feed(t, 200, vcalendar( + vevent("review@example.test", "Design review", 14, 0, 60), + vevent("standup@example.test", "Standup", 9, 30, 15), + )) + home := feed(t, 200, vcalendar( + vevent("dentist@example.test", "Dentist", 11, 0, 45), + "BEGIN:VEVENT\r\nUID:holiday@example.test\r\nDTSTAMP:20261001T000000Z\r\nDTSTART;VALUE=DATE:20261012\r\nSUMMARY:Holiday\r\nEND:VEVENT\r\n", + )) + m := meetingsApp(t, calendarsConfig("work", work, "home", home)) + + m, cmd := pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + viewHas(t, m, "Meetings · Mon 12 Oct (today)") + viewHas(t, m, "Loading…") + m = drive(t, m, cmd) + + want := []string{ + " | 09:30–09:45 Standup | work", + " | 11:00–11:45 Dentist | home", + " | 14:00–15:00 Design review | work", + } + if got := m.PaletteRows(); !reflect.DeepEqual(got, want) { + t.Errorf("rows = %q\nwant %q", got, want) + } + if got := m.PaletteSelected(); got != " 09:30–09:45 Standup" { + t.Errorf("selected = %q, want the first row", got) + } + if m = press(m, esc); m.PaletteRows() != nil { + t.Error("esc left the picker open") + } +} + +func TestMeetingsExCommandOpensThePicker(t *testing.T) { + m := meetingsApp(t, calendarsConfig("work", feed(t, 200, vcalendar(vevent("a@example.test", "Standup", 9, 30, 15))))) + + m, cmd := pressing(typeKeys(m, ":meetings"), enter) + m = drive(t, m, cmd) + + if got := m.PaletteRows(); len(got) != 1 { + t.Errorf("rows = %q, want the one Meeting", got) + } +} + +func TestAFailingCalendarFailsAlone(t *testing.T) { + ok := feed(t, 200, vcalendar(vevent("a@example.test", "Standup", 9, 30, 15))) + m := meetingsApp(t, calendarsConfig("secret", feed(t, 401, ""), "work", ok)) + + m, cmd := pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + m = drive(t, m, cmd) + + if got := m.PaletteRows(); len(got) != 1 { + t.Errorf("rows = %q, want the working calendar's Meeting", got) + } + viewHas(t, m, "secret: HTTP 401") +} + +func TestAnEmptyDaySaysNoMeetings(t *testing.T) { + m := meetingsApp(t, calendarsConfig("work", feed(t, 200, vcalendar()))) + + m, cmd := pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + m = drive(t, m, cmd) + + viewHas(t, m, "no Meetings") +} + +func TestDayKeysMoveThePickerBetweenDays(t *testing.T) { + m := meetingsApp(t, calendarsConfig("work", feed(t, 200, vcalendar( + veventOn(11, "sun@example.test", "Brunch", 11, 0, 60), + veventOn(12, "mon@example.test", "Standup", 9, 30, 15), + veventOn(13, "tue@example.test", "Retro", 15, 0, 60), + veventOn(14, "wed@example.test", "Lunch", 12, 0, 60), + )))) + m = openMeetings(t, m) + + steps := []struct { + key tea.KeyPressMsg + title string + rows []string + }{ + {tea.KeyPressMsg{Code: 'l', Text: "l"}, "Meetings · Tue 13 Oct (tomorrow)", []string{" | 15:00–16:00 Retro | work"}}, + {tea.KeyPressMsg{Code: tea.KeyRight}, "Meetings · Wed 14 Oct ─", []string{" | 12:00–13:00 Lunch | work"}}, + {tea.KeyPressMsg{Code: 't', Text: "t"}, "Meetings · Mon 12 Oct (today)", []string{" | 09:30–09:45 Standup | work"}}, + {tea.KeyPressMsg{Code: 'h', Text: "h"}, "Meetings · Sun 11 Oct (yesterday)", []string{" | 11:00–12:00 Brunch | work"}}, + {tea.KeyPressMsg{Code: tea.KeyLeft}, "Meetings · Sat 10 Oct ─", nil}, + } + for _, s := range steps { + m = press(m, s.key) + viewHas(t, m, s.title) + if got := m.PaletteRows(); !reflect.DeepEqual(got, s.rows) { + t.Errorf("after %s: rows = %q, want %q", s.key, got, s.rows) + } + } + viewHas(t, m, "no Meetings") +} + +func TestEndedMeetingsAreDimmed(t *testing.T) { + // meetingDay is 08:00. + m := meetingsApp(t, "[[calendars]]\nname = \"work\"\ncolor = \"lightcoral\"\nurl = \""+feed(t, 200, vcalendar( + vevent("early@example.test", "Early call", 7, 0, 30), + vevent("now@example.test", "Running late", 7, 30, 60), + vevent("later@example.test", "Standup", 9, 30, 15), + ))+"\"\n") + m = openMeetings(t, m) + + if got, want := m.PaletteSlots(), []string{"overlay.hint", "", ""}; !reflect.DeepEqual(got, want) { + t.Errorf("slots = %q, want %q", got, want) + } + if got, want := m.PaletteDetailStyles(), []string{"overlay.hint", "#f08080", "#f08080"}; !reflect.DeepEqual(got, want) { + t.Errorf("Detail styles = %q, want %q", got, want) + } +} + +func TestCalendarColourComesFromConfigThenTheFeed(t *testing.T) { + colored := func(color, uid string, hh int) string { + return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//pholio//test//EN\r\n" + color + + vevent(uid, uid, hh, 0, 30) + "END:VCALENDAR\r\n" + } + cfg := "[[calendars]]\nname = \"a\"\ncolor = \"#1e90ff\"\nurl = \"" + feed(t, 200, colored("COLOR:steelblue\r\n", "a", 9)) + "\"\n" + + "[[calendars]]\nname = \"b\"\nurl = \"" + feed(t, 200, colored("COLOR:steelblue\r\n", "b", 10)) + "\"\n" + + "[[calendars]]\nname = \"c\"\nurl = \"" + feed(t, 200, colored("COLOR:notacolour\r\n", "c", 11)) + "\"\n" + + "[[calendars]]\nname = \"d\"\nurl = \"" + feed(t, 200, colored("X-APPLE-CALENDAR-COLOR:#ff0000\r\n", "d", 12)) + "\"\n" + m := openMeetings(t, meetingsApp(t, cfg)) + + want := []string{"#1e90ff", "#4682b4", "overlay.hint", "overlay.hint"} + if got := m.PaletteDetailStyles(); !reflect.DeepEqual(got, want) { + t.Errorf("Detail styles = %q, want %q", got, want) + } +} + +func TestLongTitlesTruncateBeforeTheCalendar(t *testing.T) { + long := strings.Repeat("Quarterly planning ", 8) + m := openMeetings(t, meetingsApp(t, calendarsConfig("work", feed(t, 200, vcalendar( + vevent("a@example.test", "Standup", 9, 0, 15), + vevent("b@example.test", long, 10, 0, 60), + ))))) + + viewHas(t, m, "10:00–11:00 Quarterly planning") + viewHas(t, m, "… work") +} + +func TestThePickerHintListsItsKeys(t *testing.T) { + m := openMeetings(t, meetingsApp(t, calendarsConfig("work", feed(t, 200, vcalendar())))) + + viewHas(t, m, "h/l day · t today · r refresh · enter open/create · esc close") +} + +func TestNoCalendarsSaysWhereToAddThem(t *testing.T) { + m := meetingsApp(t, "") + + m = typeKeys(press(m, space), "m") + + if m.PaletteRows() != nil { + t.Error("a picker opened with no calendars") + } + if got, want := messageLine(m), "no calendars: add [[calendars]] to "+userConfig; got != want { + t.Errorf("message = %q, want %q", got, want) + } +} + +func TestStartupFetchesSoThePickerOpensWithMeetings(t *testing.T) { + work := newLiveFeed(t, vcalendar(vevent("a@example.test", "Standup", 9, 30, 15))) + m := meetingsApp(t, calendarsConfig("work", work.url)) + + m = drive(t, m, m.Init()) + m, cmd := pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + + if got := m.PaletteRows(); len(got) != 1 { + t.Errorf("rows = %q, want the Meeting fetched at startup", got) + } + drive(t, m, cmd) + if n := work.hits.Load(); n != 1 { + t.Errorf("fetched %d times, want once at startup only", n) + } +} + +func TestThePickerShowsTheCacheAndSaysWhenOffline(t *testing.T) { + cache := t.TempDir() + work := newLiveFeed(t, vcalendar(vevent("a@example.test", "Standup", 9, 30, 15))) + cfg := calendarsConfig("work", work.url) + m := meetingsAppAt(t, cache, seamtest.NewClock(meetingDay), cfg) + drive(t, m, m.Init()) + setFetched(t, cache, meetingDay.Add(-2*time.Hour)) + work.set(401, "") + + m = meetingsAppAt(t, cache, seamtest.NewClock(meetingDay), cfg) + m = drive(t, m, m.Init()) + m, cmd := pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + m = drive(t, m, cmd) + if got := m.PaletteRows(); len(got) != 1 { + t.Errorf("rows = %q, want the cached Meeting kept after a failed fetch", got) + } + viewHas(t, m, "work: offline, showing data from 2h ago") +} + +func TestOpeningRefreshesStaleMeetingsInPlace(t *testing.T) { + work := newLiveFeed(t, vcalendar(vevent("a@example.test", "Standup", 9, 30, 15))) + clock := seamtest.NewClock(meetingDay) + m := meetingsAppAt(t, t.TempDir(), clock, calendarsConfig("work", work.url)) + m = drive(t, m, m.Init()) + work.set(200, vcalendar( + vevent("a@example.test", "Standup", 9, 30, 15), + vevent("b@example.test", "Review", 14, 0, 60), + )) + clock.Advance(16 * time.Minute) + + m, cmd := pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + if got := m.PaletteRows(); len(got) != 1 { + t.Errorf("rows = %q, want the old list at once", got) + } + m = drive(t, m, cmd) + + if got := m.PaletteRows(); len(got) != 2 { + t.Errorf("rows = %q, want the refreshed list", got) + } +} + +func TestRRefreshesEvenWhenFresh(t *testing.T) { + work := newLiveFeed(t, vcalendar(vevent("a@example.test", "Standup", 9, 30, 15))) + m := meetingsApp(t, calendarsConfig("work", work.url)) + m = drive(t, m, m.Init()) + m, cmd := pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + m = drive(t, m, cmd) + work.set(200, vcalendar()) + + m, cmd = pressing(m, tea.KeyPressMsg{Code: 'r', Text: "r"}) + m = drive(t, m, cmd) + + viewHas(t, m, "no Meetings") +} + +func TestStartupFailuresWaitForThePicker(t *testing.T) { + m := meetingsApp(t, calendarsConfig("work", feed(t, 401, ""))) + + m = drive(t, m, m.Init()) + + if got := messageLine(m); got != "" { + t.Errorf("message = %q, want nothing until the picker opens", got) + } + m, _ = pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + viewHas(t, m, "work: HTTP 401") +} + +func TestStartupFetchesEvenAFreshCache(t *testing.T) { + cache := t.TempDir() + work := newLiveFeed(t, vcalendar(vevent("a@example.test", "Standup", 9, 30, 15))) + cfg := calendarsConfig("work", work.url) + m := meetingsAppAt(t, cache, seamtest.NewClock(meetingDay), cfg) + drive(t, m, m.Init()) + setFetched(t, cache, meetingDay.Add(-time.Minute)) + + m = meetingsAppAt(t, cache, seamtest.NewClock(meetingDay), cfg) + drive(t, m, m.Init()) + + if n := work.hits.Load(); n != 2 { + t.Errorf("fetched %d times, want once per start", n) + } +} + +func TestOpeningRetriesAFailedFetch(t *testing.T) { + work := newLiveFeed(t, "") + work.set(503, "") + m := meetingsApp(t, calendarsConfig("work", work.url)) + m = drive(t, m, m.Init()) + work.set(200, vcalendar(vevent("a@example.test", "Standup", 9, 30, 15))) + + m, cmd := pressing(press(m, space), tea.KeyPressMsg{Code: 'm', Text: "m"}) + m = drive(t, m, cmd) + + if got := m.PaletteRows(); len(got) != 1 { + t.Errorf("rows = %q, want the Meeting from the retried fetch", got) + } +} diff --git a/internal/app/shell.go b/internal/app/shell.go index 19ff398..7c135b9 100644 --- a/internal/app/shell.go +++ b/internal/app/shell.go @@ -100,9 +100,9 @@ func (m Model) openAt(path string, at func(Model) Model) (Model, tea.Cmd) { } // openThen is openAt with before, which runs once the dirty buffer has been -// dealt with and before the switch (creating a Daily Note). An error from -// before is shown and nothing is opened. -func (m Model) openThen(path string, before func(Model) error, at func(Model) Model) (Model, tea.Cmd) { +// dealt with and before the switch (creating a Daily Note), and gives the +// path to open. An error from before is shown and nothing is opened. +func (m Model) openThen(path string, before func(Model) (string, error), at func(Model) Model) (Model, tea.Cmd) { from := m.here() if path == m.path() { m.focus = focusEditor @@ -114,7 +114,8 @@ func (m Model) openThen(path string, before func(Model) error, at func(Model) Mo } return m.unlessDirty(saveBeforeSwitch, func(m Model) (Model, tea.Cmd) { if before != nil { - if err := before(m); err != nil { + var err error + if path, err = before(m); err != nil { return m.say(err.Error(), true), nil } } diff --git a/internal/app/testdata/TestLeaderHintListsHelp.golden b/internal/app/testdata/TestLeaderHintListsHelp.golden index aa82105..e1b62c3 100644 --- a/internal/app/testdata/TestLeaderHintListsHelp.golden +++ b/internal/app/testdata/TestLeaderHintListsHelp.golden @@ -1 +1 @@ - spc e sidebar d today D date b backlinks / search z zettel f find n new t tasks T edit Task q quit ? help \ No newline at end of file + spc e sidebar d today D date b backlinks / search z zettel f find n new t tasks T edit Task m meetings q quit ? help \ No newline at end of file diff --git a/internal/calendar/calendar.go b/internal/calendar/calendar.go new file mode 100644 index 0000000..0ad2f97 --- /dev/null +++ b/internal/calendar/calendar.go @@ -0,0 +1,479 @@ +// Package calendar fetches ICS calendar feeds and reads their Meetings. +// See docs/adr/0002-calendar-source-is-ics-feeds.md. +package calendar + +import ( + "bytes" + "cmp" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "time" + + ics "github.com/arran4/golang-ical" + "github.com/teambition/rrule-go" +) + +// Meeting is one timed Meeting from a feed. A recurring Meeting from Parse +// stands for its whole series until On expands it into occurrences. +type Meeting struct { + UID string + Title string + Start time.Time + End time.Time + // CalendarColor is the feed's calendar-level COLOR (RFC 7986, a CSS + // colour name) as written, "" if none. + CalendarColor string + + Attendees []string // see details.go + Location string + Link string + Description string + // Original is the occurrence's original start in UTC: its + // RECURRENCE-ID when it was moved, else its start. UID and Original + // together are the Meeting's identity. + Original time.Time + + series *series // set on a recurring Meeting until On expands it +} + +// series is a recurring Meeting's occurrences, kept as wall-clock times +// (in UTC, ignoring zones) in its DTSTART zone, so they keep their clock +// time across DST changes. +type series struct { + set *rrule.Set + zone zone +} + +// Parse reads the Meetings of an ICS body. All-day Meetings +// (DTSTART;VALUE=DATE) and Meetings whose times can't be read are left +// out. A TZID that can't be resolved is read as local time. +func Parse(body []byte) ([]Meeting, error) { + cal, err := ics.ParseCalendar(bytes.NewReader(body)) + if err != nil { + return nil, err + } + color := "" + for _, p := range cal.CalendarProperties { + if p.IANAToken == string(ics.PropertyColor) { + color = strings.TrimSpace(p.Value) + } + } + zones := map[string]vtimezone{} + for _, tz := range cal.Timezones() { + if p := tz.GetProperty(ics.ComponentPropertyTzid); p != nil { + zones[p.Value] = readVTimezone(tz) + } + } + var ms []Meeting + moved := map[string][]time.Time{} // UID -> RECURRENCE-ID instants + for _, ev := range cal.Events() { + sp := ev.GetProperty(ics.ComponentPropertyDtStart) + if sp == nil || slices.Contains(sp.ICalParameters["VALUE"], "DATE") { + continue + } + walls, z := readTimes(sp, zones) + if len(walls) != 1 { + continue + } + start := z.at(walls[0]) + end := start + if p := ev.GetProperty(ics.ComponentPropertyDtEnd); p != nil { + if ws, ez := readTimes(p, zones); len(ws) == 1 { + end = ez.at(ws[0]) + } + } else if p := ev.GetProperty(ics.ComponentPropertyDuration); p != nil { + if d, ok := duration(p.Value); ok { + end = start.Add(d) + } + } + m := Meeting{UID: ev.Id(), Start: start, End: end, Original: start.UTC(), CalendarColor: color} + if p := ev.GetProperty(ics.ComponentPropertySummary); p != nil { + m.Title = p.Value + } + m.details(ev) + if p := ev.GetProperty(ics.ComponentPropertyRecurrenceId); p != nil { + if ws, rz := readTimes(p, zones); len(ws) == 1 { + m.Original = rz.at(ws[0]).UTC() + moved[m.UID] = append(moved[m.UID], m.Original) + } + if p := ev.GetProperty(ics.ComponentPropertyStatus); p != nil && p.Value == "CANCELLED" { + continue + } + } else { + m.series = readSeries(ev, walls[0], z, zones) + } + ms = append(ms, m) + } + for _, m := range ms { + if m.series != nil { + for _, t := range moved[m.UID] { + m.series.set.ExDate(m.series.zone.wall(t)) + } + } + } + return ms, nil +} + +// DateTime is the layout of an ICS DATE-TIME value, less any trailing Z. +const DateTime = "20060102T150405" + +var untilUTC = regexp.MustCompile(`UNTIL=\d{8}T\d{6}Z`) + +// readSeries is ev's recurrence starting at wall in z, or nil when ev +// doesn't recur. +func readSeries(ev *ics.VEvent, wall time.Time, z zone, zones map[string]vtimezone) *series { + rp := ev.GetProperty(ics.ComponentPropertyRrule) + rdates := ev.GetProperties(ics.ComponentPropertyRdate) + if rp == nil && len(rdates) == 0 { + return nil + } + s := &series{set: &rrule.Set{}, zone: z} + s.set.DTStart(wall) + if rp == nil { + s.set.RDate(wall) + } else if r := readRRule(rp.Value, wall, z); r != nil { + s.set.RRule(r) + } + for _, p := range rdates { + ws, pz := readTimes(p, zones) + for _, w := range ws { + s.set.RDate(z.wall(pz.at(w))) + } + } + for _, p := range ev.GetProperties(ics.ComponentPropertyExdate) { + ws, pz := readTimes(p, zones) + for _, w := range ws { + s.set.ExDate(z.wall(pz.at(w))) + } + } + return s +} + +// readRRule is the RRULE v starting at wall-clock time start in z, or nil +// when it can't be read. +func readRRule(v string, start time.Time, z zone) *rrule.RRule { + opt, err := rrule.StrToROptionInLocation(v, time.UTC) + if err != nil { + return nil + } + if untilUTC.MatchString(v) { + opt.Until = z.wall(opt.Until) + } + opt.Dtstart = start + r, err := rrule.NewRRule(*opt) + if err != nil { + return nil + } + return r +} + +// between is the series' starts in [from, to). +func (s *series) between(from, to time.Time) []time.Time { + // A day either side covers any gap between the zone's wall clock and + // the window's. + var out []time.Time + for _, w := range s.set.Between(s.zone.wall(from).AddDate(0, 0, -1), s.zone.wall(to).AddDate(0, 0, 1), true) { + if t := s.zone.at(w); !t.Before(from) && t.Before(to) { + out = append(out, t) + } + } + return out +} + +// readTimes is a DATE-TIME property's values as wall-clock times (in UTC, +// ignoring zones), and the zone they're in. Unreadable values are +// skipped. +func readTimes(p *ics.IANAProperty, zones map[string]vtimezone) ([]time.Time, zone) { + z := zone{loc: time.Local} + if tzid := p.ICalParameters["TZID"]; len(tzid) == 1 { + z = resolve(tzid[0], zones) + } + var out []time.Time + for v := range strings.SplitSeq(p.Value, ",") { + utc := strings.HasSuffix(v, "Z") + w, err := time.Parse(DateTime, strings.TrimSuffix(v, "Z")) + if err != nil { + continue + } + if utc { + // A UTC value is converted into the property's zone so that + // every value shares it. + w = z.wall(w) + } + out = append(out, w) + } + return out, z +} + +// resolve finds a TZID: Go's tz database, then the Windows names, then the +// feed's own VTIMEZONE, else local time. +func resolve(tzid string, zones map[string]vtimezone) zone { + if loc, err := time.LoadLocation(tzid); err == nil { + return zone{loc: loc} + } + if loc := ics.WindowsTimezoneToIANA(tzid); loc != nil { + return zone{loc: loc} + } + if vt, ok := zones[tzid]; ok && len(vt) > 0 { + return zone{vt: vt} + } + return zone{loc: time.Local} +} + +// zone is a Go location or, when loc is nil, a feed's VTIMEZONE. +type zone struct { + loc *time.Location + vt vtimezone +} + +// at is the instant of wall-clock time w in z. +func (z zone) at(w time.Time) time.Time { + if z.loc != nil { + return time.Date(w.Year(), w.Month(), w.Day(), w.Hour(), w.Minute(), w.Second(), 0, z.loc) + } + return w.Add(-z.vt.offset(w)) +} + +// wall is t's wall-clock time in z (in UTC, ignoring zones). +func (z zone) wall(t time.Time) time.Time { + if z.loc != nil { + t = t.In(z.loc) + return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.UTC) + } + // ponytail: the offset is looked up at t's UTC clock, so wall times + // within a few hours of a transition can be an hour out. + return t.UTC().Add(z.vt.offset(t.UTC())) +} + +// vtimezone is a VTIMEZONE's STANDARD and DAYLIGHT parts. +type vtimezone []tzPart + +// tzPart is one STANDARD or DAYLIGHT part: when it begins (wall-clock +// times) and the UTC offsets before and after. +type tzPart struct { + onsets *rrule.Set + from, to time.Duration +} + +func readVTimezone(tz *ics.VTimezone) vtimezone { + var vt vtimezone + for _, c := range tz.SubComponents() { + var cb *ics.ComponentBase + switch c := c.(type) { + case *ics.Standard: + cb = &c.ComponentBase + case *ics.Daylight: + cb = &c.ComponentBase + default: + continue + } + from, ok1 := offset(cb.GetProperty(ics.ComponentProperty(ics.PropertyTzoffsetfrom))) + to, ok2 := offset(cb.GetProperty(ics.ComponentProperty(ics.PropertyTzoffsetto))) + sp := cb.GetProperty(ics.ComponentPropertyDtStart) + if !ok1 || !ok2 || sp == nil { + continue + } + start, err := time.Parse(DateTime, sp.Value) + if err != nil { + continue + } + // rrule-go stops about 290 years after DTSTART, and Outlook starts + // its parts in 1601; transitions before 1970 don't matter here. + if start.Year() < 1970 { + start = start.AddDate(1970-start.Year(), 0, 0) + } + set := &rrule.Set{} + set.DTStart(start) + set.RDate(start) + if rp := cb.GetProperty(ics.ComponentPropertyRrule); rp != nil { + if r := readRRule(rp.Value, start, zone{loc: time.UTC}); r != nil { + set.RRule(r) + } + } + for _, p := range cb.GetProperties(ics.ComponentPropertyRdate) { + for v := range strings.SplitSeq(p.Value, ",") { + if t, err := time.Parse(DateTime, v); err == nil { + set.RDate(t) + } + } + } + vt = append(vt, tzPart{set, from, to}) + } + return vt +} + +// offset is the UTC offset in force at wall-clock time w: the TZOFFSETTO +// of the part that began last, else the first part's TZOFFSETFROM. +func (vt vtimezone) offset(w time.Time) time.Duration { + var last time.Time + off := vt[0].from + for _, p := range vt { + if t := p.onsets.Before(w, true); !t.IsZero() && t.After(last) { + last, off = t, p.to + } + } + return off +} + +var offsetRE = regexp.MustCompile(`^([+-])(\d\d)(\d\d)(\d\d)?$`) + +// offset reads a TZOFFSETFROM/TZOFFSETTO value such as -0500. +func offset(p *ics.IANAProperty) (time.Duration, bool) { + if p == nil { + return 0, false + } + m := offsetRE.FindStringSubmatch(p.Value) + if m == nil { + return 0, false + } + h, _ := strconv.Atoi(m[2]) + mi, _ := strconv.Atoi(m[3]) + s, _ := strconv.Atoi(m[4] + "0") + d := time.Duration(h)*time.Hour + time.Duration(mi)*time.Minute + time.Duration(s/10)*time.Second + if m[1] == "-" { + d = -d + } + return d, true +} + +var durationRE = regexp.MustCompile(`^([+-])?P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$`) + +// duration reads a DURATION value such as PT45M or P1DT2H. +func duration(v string) (time.Duration, bool) { + m := durationRE.FindStringSubmatch(v) + if m == nil { + return 0, false + } + var d time.Duration + for i, unit := range []time.Duration{7 * 24 * time.Hour, 24 * time.Hour, time.Hour, time.Minute, time.Second} { + n, _ := strconv.Atoi(m[i+2]) + d += time.Duration(n) * unit + } + if m[1] == "-" { + d = -d + } + return d, true +} + +// Timeout is how long one feed's fetch may take. +const Timeout = 15 * time.Second + +// Fetch downloads the feed at url and parses its Meetings. Its errors are +// short enough for the picker: "HTTP 401", "timed out", "not a calendar", +// "offline". They never hold the URL, which is a secret. +// With a cache dir, a body that parses replaces url's cache file there; a +// bad one leaves it alone. +func Fetch(client *http.Client, url, dir string) ([]Meeting, error) { + resp, err := client.Get(url) + if err == nil { + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode/100 != 2 { + return nil, fmt.Errorf("HTTP %d", resp.StatusCode) + } + var body []byte + if body, err = io.ReadAll(resp.Body); err == nil { + ms, err := parseFeed(body) + if err == nil && dir != "" { + // The cache only speeds up the next start; failing to + // write it doesn't fail the fetch. + _ = writeCache(cachePath(dir, url), body) + } + return ms, err + } + } + if ne, ok := errors.AsType[net.Error](err); ok && ne.Timeout() { + return nil, errors.New("timed out") + } + return nil, errors.New("offline") +} + +// parseFeed is Parse for a body that must be a calendar. +func parseFeed(body []byte) ([]Meeting, error) { + body = bytes.TrimSpace(bytes.TrimPrefix(body, []byte("\xef\xbb\xbf"))) + ms, err := Parse(body) + if err != nil || !bytes.HasPrefix(body, []byte("BEGIN:VCALENDAR")) { + return nil, errors.New("not a calendar") + } + return ms, nil +} + +// Cached is url's Meetings from the cache in dir, and when they were +// fetched. +func Cached(dir, url string) ([]Meeting, time.Time, error) { + path := cachePath(dir, url) + fi, err := os.Stat(path) + if err != nil { + return nil, time.Time{}, err + } + body, err := os.ReadFile(path) + if err != nil { + return nil, time.Time{}, err + } + ms, err := parseFeed(body) + return ms, fi.ModTime(), err +} + +// cachePath is url's cache file in dir. Feed URLs are secrets, so the +// name is a hash. +func cachePath(dir, url string) string { + sum := sha256.Sum256([]byte(url)) + return filepath.Join(dir, hex.EncodeToString(sum[:8])+".ics") +} + +// writeCache replaces path with body, readable by the user only. The +// file's mtime is the fetch time. +func writeCache(path string, body []byte) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + f, err := os.CreateTemp(filepath.Dir(path), ".fetch-*") // mode 0600 + if err != nil { + return err + } + _, err = f.Write(body) + if cerr := f.Close(); err == nil { + err = cerr + } + if err == nil { + err = os.Rename(f.Name(), path) + } + if err != nil { + _ = os.Remove(f.Name()) + } + return err +} + +// On is the Meetings that start on day (midnight to midnight in day's +// location), sorted by start. +func On(ms []Meeting, day time.Time) []Meeting { + from := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, day.Location()) + to := from.AddDate(0, 0, 1) + var out []Meeting + for _, m := range ms { + if m.series == nil { + if !m.Start.Before(from) && m.Start.Before(to) { + out = append(out, m) + } + continue + } + for _, start := range m.series.between(from, to) { + o := m + o.series = nil + o.Start, o.End, o.Original = start, start.Add(m.End.Sub(m.Start)), start.UTC() + out = append(out, o) + } + } + slices.SortStableFunc(out, func(a, b Meeting) int { return cmp.Compare(a.Start.UnixNano(), b.Start.UnixNano()) }) + return out +} diff --git a/internal/calendar/calendar_test.go b/internal/calendar/calendar_test.go new file mode 100644 index 0000000..66f66e3 --- /dev/null +++ b/internal/calendar/calendar_test.go @@ -0,0 +1,267 @@ +package calendar_test + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "sync/atomic" + "testing" + "time" + + "github.com/tedkulp/pholio/internal/calendar" +) + +func newYork(t *testing.T) *time.Location { + t.Helper() + loc, err := time.LoadLocation("America/New_York") + if err != nil { + t.Fatal(err) + } + return loc +} + +// clock is a Meeting as "HH:mm–HH:mm title" in loc. +func clock(ms []calendar.Meeting, loc *time.Location) []string { + var out []string + for _, m := range ms { + out = append(out, m.Start.In(loc).Format("15:04")+"–"+m.End.In(loc).Format("15:04")+" "+m.Title) + } + return out +} + +func TestOnListsTheDaysTimedMeetingsByStart(t *testing.T) { + body, err := os.ReadFile("testdata/day.ics") + if err != nil { + t.Fatal(err) + } + ms, err := calendar.Parse(body) + if err != nil { + t.Fatal(err) + } + ny := newYork(t) + + got := clock(calendar.On(ms, time.Date(2026, 10, 12, 0, 0, 0, 0, ny)), ny) + + want := []string{"09:30–09:45 Standup", "14:00–15:00 Design review"} + if !reflect.DeepEqual(got, want) { + t.Errorf("Meetings = %q, want %q", got, want) + } +} + +func serve(t *testing.T, h http.HandlerFunc) string { + t.Helper() + s := httptest.NewServer(h) + t.Cleanup(s.Close) + return s.URL +} + +func TestParseGivesEachMeetingTheCalendarLevelColor(t *testing.T) { + body := "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//pholio//test//EN\r\nCOLOR:lightcoral\r\n" + + "X-APPLE-CALENDAR-COLOR:#0000ff\r\n" + + "BEGIN:VEVENT\r\nUID:a@example.test\r\nDTSTAMP:20261001T000000Z\r\nDTSTART:20261012T130000Z\r\nSUMMARY:Standup\r\nEND:VEVENT\r\n" + + "END:VCALENDAR\r\n" + + ms, err := calendar.Parse([]byte(body)) + + if err != nil || len(ms) != 1 || ms[0].CalendarColor != "lightcoral" { + t.Errorf("Parse = %+v, %v; want one Meeting with CalendarColor lightcoral", ms, err) + } +} + +func TestFetchReadsTheFeedsMeetings(t *testing.T) { + body, err := os.ReadFile("testdata/day.ics") + if err != nil { + t.Fatal(err) + } + url := serve(t, func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(body) }) + + ms, err := calendar.Fetch(http.DefaultClient, url, "") + + if err != nil || len(ms) != 3 { + t.Errorf("Fetch = %d Meetings, %v; want 3, nil", len(ms), err) + } +} + +func TestFetchFailures(t *testing.T) { + tests := []struct { + name string + handler http.HandlerFunc + want string + }{ + {"401", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) }, "HTTP 401"}, + {"not ICS", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("<html><body>Sign in</body></html>\n")) + }, "not a calendar"}, + {"empty", func(http.ResponseWriter, *http.Request) {}, "not a calendar"}, + {"timeout", func(_ http.ResponseWriter, r *http.Request) { <-r.Context().Done() }, "timed out"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + url := serve(t, tt.handler) + + _, err := calendar.Fetch(&http.Client{Timeout: 50 * time.Millisecond}, url, "") + + if err == nil || err.Error() != tt.want { + t.Errorf("Fetch error = %v, want %q", err, tt.want) + } + }) + } +} + +func TestFetchNeverReportsTheSecretURL(t *testing.T) { + s := httptest.NewServer(http.NotFoundHandler()) + url := s.URL + "/private/s3cret-token/basic.ics" + s.Close() // nothing listens there now + + _, err := calendar.Fetch(http.DefaultClient, url, "") + + if err == nil || err.Error() != "offline" { + t.Errorf("Fetch error = %v, want %q", err, "offline") + } +} + +func TestFetchCachesTheBodyPrivatelyKeyedByURL(t *testing.T) { + body, err := os.ReadFile("testdata/day.ics") + if err != nil { + t.Fatal(err) + } + dir := filepath.Join(t.TempDir(), "calendars") + h := func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(body) } + a, b := serve(t, h), serve(t, h) + + for _, url := range []string{a, b} { + if _, err := calendar.Fetch(http.DefaultClient, url, dir); err != nil { + t.Fatal(err) + } + } + + files, _ := filepath.Glob(filepath.Join(dir, "*.ics")) + if len(files) != 2 { + t.Fatalf("cache files = %q, want one per URL", files) + } + for _, f := range files { + if fi, err := os.Stat(f); err != nil || fi.Mode().Perm() != 0o600 { + t.Errorf("%s: mode %v, %v; want 0600", f, fi.Mode().Perm(), err) + } + } + ms, at, err := calendar.Cached(dir, a) + if err != nil || len(ms) != 3 || time.Since(at) > time.Minute { + t.Errorf("Cached = %d Meetings at %v, %v; want 3 just now", len(ms), at, err) + } +} + +func TestABadFetchKeepsTheCache(t *testing.T) { + body, err := os.ReadFile("testdata/day.ics") + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + var bad atomic.Bool + url := serve(t, func(w http.ResponseWriter, _ *http.Request) { + if !bad.Load() { + _, _ = w.Write(body) + return + } + _, _ = w.Write([]byte("<html>Sign in</html>")) + }) + if _, err := calendar.Fetch(http.DefaultClient, url, dir); err != nil { + t.Fatal(err) + } + bad.Store(true) + + if _, err := calendar.Fetch(http.DefaultClient, url, dir); err == nil { + t.Fatal("a bad body fetched without error") + } + + if ms, _, err := calendar.Cached(dir, url); err != nil || len(ms) != 3 { + t.Errorf("Cached = %d Meetings, %v; want the 3 from the good fetch", len(ms), err) + } +} + +func TestNothingCached(t *testing.T) { + if _, _, err := calendar.Cached(t.TempDir(), "https://example.test/x.ics"); err == nil { + t.Error("Cached found a feed never fetched") + } +} + +func recurring(t *testing.T) []calendar.Meeting { + t.Helper() + body, err := os.ReadFile("testdata/recurring.ics") + if err != nil { + t.Fatal(err) + } + ms, err := calendar.Parse(body) + if err != nil { + t.Fatal(err) + } + return ms +} + +func TestMovedOccurrenceKeepsItsOriginalStart(t *testing.T) { + var got []time.Time + for _, m := range onDay(t, time.November, 10) { + if m.UID == "standup@example.test" { + got = append(got, m.Original) + } + } + + want := []time.Time{time.Date(2026, 11, 10, 14, 30, 0, 0, time.UTC)} + if !reflect.DeepEqual(got, want) { + t.Errorf("Original = %v, want %v", got, want) + } +} + +func TestOccurrenceIdentityIsItsStartInUTC(t *testing.T) { + ms := onDay(t, time.November, 3) + if len(ms) != 2 || !ms[1].Original.Equal(ms[1].Start) || ms[1].Original.Location() != time.UTC { + t.Errorf("Meetings = %+v, want the Standup's Original to be its start in UTC", ms) + } +} + +func TestUnresolvableTZIDIsLocalTime(t *testing.T) { + ms := calendar.On(recurring(t), time.Date(2026, 11, 20, 0, 0, 0, 0, time.Local)) + + if got := clock(ms, time.Local); !reflect.DeepEqual(got, []string{"16:00–17:00 Floating chat"}) { + t.Errorf("Meetings = %q, want the floating chat at 16:00 local", got) + } +} + +// onDay is testdata/recurring.ics's Meetings on a New York day. +func onDay(t *testing.T, mo time.Month, d int) []calendar.Meeting { + t.Helper() + return calendar.On(recurring(t), time.Date(2026, mo, d, 0, 0, 0, 0, newYork(t))) +} + +func TestRecurringMeetingsShowOnEachDayTheyOccur(t *testing.T) { + tests := []struct { + name string + month time.Month + day int + want []string + }{ + {"BYDAY ordinal", time.December, 8, []string{ + "08:00–08:30 Early sync", "09:30–09:45 Standup", "11:00–12:00 Monthly review", + }}, + {"BYSETPOS: last weekday of the month", time.November, 30, []string{"16:00–16:30 Month-end wrap-up"}}, + {"BYSETPOS: not the last weekday", time.November, 27, nil}, + {"comma EXDATE, first value", time.October, 20, nil}, + {"comma EXDATE, second value; VTIMEZONE in daylight time", time.October, 27, []string{"08:00–08:30 Early sync"}}, + {"across DST: VTIMEZONE in standard time", time.November, 3, []string{ + "08:00–08:30 Early sync", "09:30–09:45 Standup", + }}, + {"moved occurrence, Windows TZID, DURATION", time.November, 10, []string{ + "08:00–08:30 Early sync", "11:00–12:00 Monthly review", "12:00–12:30 Outlook lunch", + "14:00–14:15 Standup (moved)", "17:00–17:45 Retro", + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := clock(onDay(t, tt.month, tt.day), newYork(t)) + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Meetings = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/internal/calendar/details.go b/internal/calendar/details.go new file mode 100644 index 0000000..35197e6 --- /dev/null +++ b/internal/calendar/details.go @@ -0,0 +1,109 @@ +package calendar + +import ( + "net/url" + "regexp" + "strings" + + ics "github.com/arran4/golang-ical" +) + +// details fills m's Attendees, Location, Link and Description from ev. +// golang-ical has already ICS-unescaped the text values. +func (m *Meeting) details(ev *ics.VEvent) { + m.Location = text(ev, "LOCATION") + if m.Location == "" { + m.Location = text(ev, "X-MICROSOFT-LOCATIONDISPLAYNAME") + } + m.Description = text(ev, "DESCRIPTION") + m.Attendees = attendees(ev) + m.Link = link(ev, m.Location, m.Description) +} + +func text(ev *ics.VEvent, name string) string { + if p := ev.GetProperty(ics.ComponentProperty(name)); p != nil { + return strings.TrimSpace(p.Value) + } + return "" +} + +// attendees is the ATTENDEEs in feed order, CN else email, deduped by +// email, without rooms, resources and those who declined. +func attendees(ev *ics.VEvent) []string { + var out []string + seen := map[string]bool{} + for _, a := range ev.Attendees() { + cutype := strings.ToUpper(first(a.ICalParameters["CUTYPE"])) + if cutype == "ROOM" || cutype == "RESOURCE" || strings.EqualFold(string(a.ParticipationStatus()), "DECLINED") { + continue + } + email := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(a.Value, "mailto:"), "MAILTO:")) + key := strings.ToLower(email) + if seen[key] { + continue + } + seen[key] = true + if name := strings.TrimSpace(first(a.ICalParameters["CN"])); name != "" { + out = append(out, name) + } else if email != "" { + out = append(out, email) + } + } + return out +} + +func first(vs []string) string { + if len(vs) == 0 { + return "" + } + return vs[0] +} + +// linkProps are read in order; the first http(s) value is the link. +var linkProps = []string{ + "X-GOOGLE-CONFERENCE", + "X-MICROSOFT-SKYPETEAMSMEETINGURL", + "X-MICROSOFT-ONLINEMEETINGEXTERNALLINK", + "X-MICROSOFT-ONLINEMEETINGCONFLINK", + "URL", +} + +// callHosts are the hosts (and their subdomains) whose URLs count as a +// call link when found in LOCATION or DESCRIPTION. +var callHosts = []string{"zoom.us", "meet.google.com", "teams.microsoft.com", "teams.live.com", "webex.com"} + +var urlRE = regexp.MustCompile(`(?i)https?://[^\s<>"']+`) + +// link is the Meeting's call link: the first http(s) linkProps value, else +// the first call-host URL in location, then description. +func link(ev *ics.VEvent, location, description string) string { + for _, name := range linkProps { + if v := text(ev, name); isHTTP(v) { + return v + } + } + for _, s := range []string{location, description} { + for _, raw := range urlRE.FindAllString(s, -1) { + raw = strings.TrimRight(raw, ".,;:!?)]") + if u, err := url.Parse(raw); err == nil && callHost(u.Hostname()) { + return raw + } + } + } + return "" +} + +func isHTTP(v string) bool { + u, err := url.Parse(v) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" +} + +func callHost(host string) bool { + host = strings.ToLower(host) + for _, h := range callHosts { + if host == h || strings.HasSuffix(host, "."+h) { + return true + } + } + return false +} diff --git a/internal/calendar/details_test.go b/internal/calendar/details_test.go new file mode 100644 index 0000000..5807c47 --- /dev/null +++ b/internal/calendar/details_test.go @@ -0,0 +1,146 @@ +package calendar_test + +import ( + "reflect" + "strings" + "testing" + + "github.com/tedkulp/pholio/internal/calendar" +) + +// meeting parses one VEVENT made of the given extra lines. +func meeting(t *testing.T, lines ...string) calendar.Meeting { + t.Helper() + body := strings.Join(append(append([]string{ + "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//pholio//synthetic//EN", + "BEGIN:VEVENT", "UID:m@example.test", "DTSTAMP:20261001T000000Z", + "DTSTART:20261012T140000Z", "DTEND:20261012T150000Z", "SUMMARY:Sync", + }, lines...), "END:VEVENT", "END:VCALENDAR"), "\r\n") + ms, err := calendar.Parse([]byte(body)) + if err != nil || len(ms) != 1 { + t.Fatalf("Parse = %d Meetings, %v", len(ms), err) + } + return ms[0] +} + +func TestLink(t *testing.T) { + tests := []struct { + name string + lines []string + want string + }{ + {"none", nil, ""}, + {"Google conference first", []string{ + "URL:https://example.test/event", + "X-MICROSOFT-SKYPETEAMSMEETINGURL:https://teams.microsoft.com/l/b", + "X-GOOGLE-CONFERENCE:https://meet.google.com/abc-defg-hij", + }, "https://meet.google.com/abc-defg-hij"}, + {"Teams URL before external link", []string{ + "X-MICROSOFT-ONLINEMEETINGEXTERNALLINK:https://example.test/ext", + "X-MICROSOFT-SKYPETEAMSMEETINGURL:https://teams.microsoft.com/l/b", + }, "https://teams.microsoft.com/l/b"}, + {"external link before conf link", []string{ + "X-MICROSOFT-ONLINEMEETINGCONFLINK:https://example.test/conf", + "X-MICROSOFT-ONLINEMEETINGEXTERNALLINK:https://example.test/ext", + }, "https://example.test/ext"}, + {"conf link before URL", []string{ + "URL:https://example.test/event", + "X-MICROSOFT-ONLINEMEETINGCONFLINK:https://example.test/conf", + }, "https://example.test/conf"}, + {"URL before location", []string{ + "LOCATION:https://zoom.us/j/1", + "URL:https://example.test/event", + }, "https://example.test/event"}, + {"non-http skipped", []string{ + "X-GOOGLE-CONFERENCE:tel:+1-555-0100", + "X-MICROSOFT-ONLINEMEETINGCONFLINK:conf:sip:someone@example.test", + "URL:https://example.test/event", + }, "https://example.test/event"}, + {"location before description", []string{ + "DESCRIPTION:Join https://meet.google.com/zzz-zzzz-zzz", + "LOCATION:Room 4 / https://zoom.us/j/123?pwd=x", + }, "https://zoom.us/j/123?pwd=x"}, + {"description when location has none", []string{ + "LOCATION:Room 4", + `DESCRIPTION:Agenda\nJoin: https://teams.microsoft.com/l/meetup-join/1 now`, + }, "https://teams.microsoft.com/l/meetup-join/1"}, + {"subdomain matches", []string{ + "DESCRIPTION:https://example.test/doc then https://acme.zoom.us/j/9", + }, "https://acme.zoom.us/j/9"}, + {"lookalike host skipped", []string{ + "DESCRIPTION:https://notzoom.us/j/1 https://zoom.us.example.test/j/2 http://acme.webex.com/m", + }, "http://acme.webex.com/m"}, + {"teams.live.com", []string{"LOCATION:https://teams.live.com/meet/1"}, "https://teams.live.com/meet/1"}, + {"unknown host in description skipped", []string{"DESCRIPTION:see https://example.test/doc"}, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := meeting(t, tt.lines...).Link; got != tt.want { + t.Errorf("Link = %q, want %q", got, tt.want) + } + }) + } +} + +func TestAttendees(t *testing.T) { + tests := []struct { + name string + lines []string + want []string + }{ + {"none", nil, nil}, + {"CN else email, feed order", []string{ + "ATTENDEE;CN=Ada Example:mailto:ada@example.test", + "ATTENDEE:mailto:bob@example.test", + `ATTENDEE;CN="Cole, C.":mailto:cole@example.test`, + }, []string{"Ada Example", "bob@example.test", "Cole, C."}}, + {"deduped by email", []string{ + "ATTENDEE;CN=Ada Example:mailto:ada@example.test", + "ATTENDEE;CN=Ada Again:mailto:ADA@example.test", + }, []string{"Ada Example"}}, + {"rooms, resources and declined dropped", []string{ + "ATTENDEE;CUTYPE=ROOM;CN=Room 4:mailto:room4@example.test", + "ATTENDEE;CUTYPE=RESOURCE;CN=Projector:mailto:proj@example.test", + "ATTENDEE;PARTSTAT=DECLINED;CN=Dee:mailto:dee@example.test", + "ATTENDEE;PARTSTAT=ACCEPTED;CUTYPE=INDIVIDUAL;CN=Eve:mailto:eve@example.test", + }, []string{"Eve"}}, + {"organizer not added", []string{ + "ORGANIZER;CN=Olga:mailto:olga@example.test", + "ATTENDEE;CN=Ada Example:mailto:ada@example.test", + }, []string{"Ada Example"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := meeting(t, tt.lines...).Attendees; !reflect.DeepEqual(got, tt.want) { + t.Errorf("Attendees = %q, want %q", got, tt.want) + } + }) + } +} + +func TestLocationAndDescription(t *testing.T) { + tests := []struct { + name string + lines []string + location, description string + }{ + {"none", nil, "", ""}, + {"unescaped and trimmed", []string{ + `LOCATION: Room 4\, Floor 2 `, + `DESCRIPTION:Agenda\n- one\; two `, + "X-ALT-DESC;FMTTYPE=text/html:<b>ignored</b>", + }, "Room 4, Floor 2", "Agenda\n- one; two"}, + {"Microsoft display name when location empty", []string{ + "LOCATION:", + "X-MICROSOFT-LOCATIONDISPLAYNAME:Room 9", + }, "Room 9", ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := meeting(t, tt.lines...) + if m.Location != tt.location || m.Description != tt.description { + t.Errorf("Location, Description = %q, %q; want %q, %q", m.Location, m.Description, tt.location, tt.description) + } + }) + } +} diff --git a/internal/calendar/testdata/day.ics b/internal/calendar/testdata/day.ics new file mode 100644 index 0000000..86f8600 --- /dev/null +++ b/internal/calendar/testdata/day.ics @@ -0,0 +1,32 @@ +BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//pholio//synthetic test fixture//EN +BEGIN:VEVENT +UID:review@example.test +DTSTAMP:20261001T000000Z +DTSTART;TZID=America/New_York:20261012T140000 +DTEND;TZID=America/New_York:20261012T150000 +SUMMARY:Design review +END:VEVENT +BEGIN:VEVENT +UID:standup@example.test +DTSTAMP:20261001T000000Z +DTSTART:20261012T133000Z +DTEND:20261012T134500Z +SUMMARY:Standup +END:VEVENT +BEGIN:VEVENT +UID:holiday@example.test +DTSTAMP:20261001T000000Z +DTSTART;VALUE=DATE:20261012 +DTEND;VALUE=DATE:20261013 +SUMMARY:Holiday +END:VEVENT +BEGIN:VEVENT +UID:tomorrow@example.test +DTSTAMP:20261001T000000Z +DTSTART:20261013T150000Z +DTEND:20261013T160000Z +SUMMARY:Tomorrow's sync +END:VEVENT +END:VCALENDAR diff --git a/internal/calendar/testdata/recurring.ics b/internal/calendar/testdata/recurring.ics new file mode 100644 index 0000000..2a285cb --- /dev/null +++ b/internal/calendar/testdata/recurring.ics @@ -0,0 +1,81 @@ +BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//pholio//synthetic test fixture//EN +BEGIN:VTIMEZONE +TZID:Customized Time Zone +BEGIN:STANDARD +DTSTART:16010101T020000 +TZOFFSETFROM:-0400 +TZOFFSETTO:-0500 +RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:16010101T020000 +TZOFFSETFROM:-0500 +TZOFFSETTO:-0400 +RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU +END:DAYLIGHT +END:VTIMEZONE +BEGIN:VEVENT +UID:review@example.test +DTSTAMP:20261001T000000Z +DTSTART;TZID=America/New_York:20261013T110000 +DTEND;TZID=America/New_York:20261013T120000 +RRULE:FREQ=MONTHLY;BYDAY=2TU +SUMMARY:Monthly review +END:VEVENT +BEGIN:VEVENT +UID:wrapup@example.test +DTSTAMP:20261001T000000Z +DTSTART;TZID=America/New_York:20261030T160000 +DTEND;TZID=America/New_York:20261030T163000 +RRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1 +SUMMARY:Month-end wrap-up +END:VEVENT +BEGIN:VEVENT +UID:standup@example.test +DTSTAMP:20261001T000000Z +DTSTART;TZID=America/New_York:20261013T093000 +DTEND;TZID=America/New_York:20261013T094500 +RRULE:FREQ=WEEKLY;BYDAY=TU +EXDATE;TZID=America/New_York:20261020T093000,20261027T093000 +SUMMARY:Standup +END:VEVENT +BEGIN:VEVENT +UID:standup@example.test +DTSTAMP:20261001T000000Z +RECURRENCE-ID;TZID=America/New_York:20261110T093000 +DTSTART;TZID=America/New_York:20261110T140000 +DTEND;TZID=America/New_York:20261110T141500 +SUMMARY:Standup (moved) +END:VEVENT +BEGIN:VEVENT +UID:outlook@example.test +DTSTAMP:20261001T000000Z +DTSTART;TZID=Eastern Standard Time:20261110T120000 +DTEND;TZID=Eastern Standard Time:20261110T123000 +SUMMARY:Outlook lunch +END:VEVENT +BEGIN:VEVENT +UID:custom@example.test +DTSTAMP:20261001T000000Z +DTSTART;TZID=Customized Time Zone:20261027T080000 +DTEND;TZID=Customized Time Zone:20261027T083000 +RRULE:FREQ=WEEKLY;BYDAY=TU +SUMMARY:Early sync +END:VEVENT +BEGIN:VEVENT +UID:nowhere@example.test +DTSTAMP:20261001T000000Z +DTSTART;TZID=Nowhere Standard Time:20261120T160000 +DTEND;TZID=Nowhere Standard Time:20261120T170000 +SUMMARY:Floating chat +END:VEVENT +BEGIN:VEVENT +UID:duration@example.test +DTSTAMP:20261001T000000Z +DTSTART:20261110T220000Z +DURATION:PT45M +SUMMARY:Retro +END:VEVENT +END:VCALENDAR diff --git a/internal/config/config.go b/internal/config/config.go index 8318dd9..d159ec3 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -24,6 +24,7 @@ import ( "github.com/tedkulp/pholio/internal/dates" "github.com/tedkulp/pholio/internal/index" "github.com/tedkulp/pholio/internal/seam" + "github.com/tedkulp/pholio/internal/theme" ) // Config is the merged result of the user and Vault config files. @@ -38,6 +39,9 @@ type Config struct { Wrap bool Conceal bool OpenDailyOnStartup bool + // Calendars are the [[calendars]] feeds Meetings come from. User + // config only: feed URLs are secrets. + Calendars []Calendar // Vault keys. They may be set in either file; the Vault file wins. @@ -52,10 +56,27 @@ type Config struct { // NewNoteFolder is Vault-relative; "" is the Vault root. NewNoteFolder string TasksHeading string + // MeetingsFolder is where Meeting Notes are created. + MeetingsFolder string + // MeetingTemplate is the meeting Template; a built-in one is used when + // the file is missing. + MeetingTemplate string + // MeetingsHeading is the Daily Note heading Meeting Note back-links go + // under. + MeetingsHeading string // TaskFormat is the Task Format new Task Metadata is written in. TaskFormat index.Format } +// Calendar is one [[calendars]] entry: an ICS feed of Meetings. +type Calendar struct { + Name string + URL string + // Color is a CSS colour name or "#rrggbb" as written, "" if unset or + // invalid. + Color string +} + // Default returns the config used when no file sets anything. func Default() Config { return Config{ @@ -69,6 +90,9 @@ func Default() Config { ZettelFolder: "zettel", NewNoteFolder: "", TasksHeading: "## Tasks", + MeetingsFolder: "meetings", + MeetingTemplate: "templates/meeting.md", + MeetingsHeading: "## Meetings", TaskFormat: index.Dataview, } } @@ -89,9 +113,9 @@ func VaultConfigPath(vault string) string { func Load(fsys seam.FS, d Dirs, vault string) (Config, []string) { cfg := Default() var problems []string - problems = append(problems, apply(fsys, UserConfigPath(d), &cfg, userKeys, vaultKeys)...) + problems = append(problems, apply(fsys, UserConfigPath(d), &cfg, true, userKeys, vaultKeys)...) if vault != "" { - problems = append(problems, apply(fsys, VaultConfigPath(vault), &cfg, vaultKeys)...) + problems = append(problems, apply(fsys, VaultConfigPath(vault), &cfg, false, vaultKeys)...) } return cfg, problems } @@ -127,17 +151,20 @@ var userKeys = map[string]setter{ } var vaultKeys = map[string]setter{ - "day_starts_at": dayStart, - "daily_folder": str(func(c *Config) *string { return &c.DailyFolder }, inVault), - "daily_template": str(func(c *Config) *string { return &c.DailyTemplate }, inVaultFile), - "daily_subfolder": str(func(c *Config) *string { return &c.DailySubfolder }, inVaultLayout), - "zettel_folder": str(func(c *Config) *string { return &c.ZettelFolder }, inVault), - "new_note_folder": str(func(c *Config) *string { return &c.NewNoteFolder }, inVault), - "tasks_heading": str(func(c *Config) *string { return &c.TasksHeading }, heading), - "task_format": taskFormat, + "day_starts_at": dayStart, + "daily_folder": str(func(c *Config) *string { return &c.DailyFolder }, inVault), + "daily_template": str(func(c *Config) *string { return &c.DailyTemplate }, inVaultFile), + "daily_subfolder": str(func(c *Config) *string { return &c.DailySubfolder }, inVaultLayout), + "zettel_folder": str(func(c *Config) *string { return &c.ZettelFolder }, inVault), + "new_note_folder": str(func(c *Config) *string { return &c.NewNoteFolder }, inVault), + "tasks_heading": str(func(c *Config) *string { return &c.TasksHeading }, heading), + "task_format": taskFormat, + "meetings_folder": str(func(c *Config) *string { return &c.MeetingsFolder }, inVault), + "meeting_template": str(func(c *Config) *string { return &c.MeetingTemplate }, inVaultFile), + "meetings_heading": str(func(c *Config) *string { return &c.MeetingsHeading }, heading), } -func apply(fsys seam.FS, file string, cfg *Config, tables ...map[string]setter) []string { +func apply(fsys seam.FS, file string, cfg *Config, user bool, tables ...map[string]setter) []string { data, err := fsys.ReadFile(file) if errors.Is(err, fs.ErrNotExist) { return nil @@ -156,6 +183,16 @@ func apply(fsys seam.FS, file string, cfg *Config, tables ...map[string]setter) sort.Strings(keys) var problems []string for _, k := range keys { + if k == "calendars" { // an array of tables: one problem per bad entry + if !user { + problems = append(problems, file+": calendars: only allowed in the user config, since feed URLs are secrets") + continue + } + for _, p := range calendars(cfg, raw[k]) { + problems = append(problems, fmt.Sprintf("%s: %s", file, p)) + } + continue + } set := lookup(k, tables) if set == nil { problems = append(problems, fmt.Sprintf("%s: unknown key %q", file, k)) @@ -168,6 +205,51 @@ func apply(fsys seam.FS, file string, cfg *Config, tables ...map[string]setter) return problems } +// calendars stores the [[calendars]] entries that have a name and url, +// and describes the rest. +func calendars(c *Config, v any) []string { + entries, ok := v.([]map[string]any) + if !ok { + return []string{"calendars: want [[calendars]] tables, got " + show(v)} + } + var problems []string + for i, e := range entries { + at := fmt.Sprintf("calendars[%d]: ", i+1) + var cal Calendar + fields := map[string]*string{"name": &cal.Name, "url": &cal.URL, "color": &cal.Color} + keys := make([]string, 0, len(e)) + for k := range e { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + f, known := fields[k] + s, isStr := e[k].(string) + switch { + case !known: + problems = append(problems, fmt.Sprintf("%sunknown key %q", at, k)) + case !isStr: + problems = append(problems, fmt.Sprintf("%s%s: want a string, got %s", at, k, show(e[k]))) + default: + *f = s + } + } + if _, err := theme.ParseCSSColor(cal.Color); cal.Color != "" && err != nil { + problems = append(problems, fmt.Sprintf("%scolor: want a CSS colour name or \"#rrggbb\", got %q", at, cal.Color)) + cal.Color = "" + } + switch { + case cal.Name == "": + problems = append(problems, at+"name: want a non-empty string, got none") + case cal.URL == "": + problems = append(problems, at+"url: want a non-empty string, got none") + default: + c.Calendars = append(c.Calendars, cal) + } + } + return problems +} + func lookup(k string, tables []map[string]setter) setter { for _, t := range tables { if s, ok := t[k]; ok { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index ef18272..a966f57 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -1,6 +1,7 @@ package config_test import ( + "reflect" "testing" "time" @@ -28,6 +29,9 @@ func defaults() config.Config { DailyTemplate: "templates/daily.md", ZettelFolder: "zettel", NewNoteFolder: "", + MeetingsFolder: "meetings", + MeetingTemplate: "templates/meeting.md", + MeetingsHeading: "## Meetings", TasksHeading: "## Tasks", TaskFormat: index.Dataview, } @@ -39,7 +43,7 @@ func TestLoadWithNoFilesGivesDefaults(t *testing.T) { if len(problems) != 0 { t.Fatalf("problems = %v, want none", problems) } - if cfg != defaults() { + if !reflect.DeepEqual(cfg, defaults()) { t.Fatalf("cfg = %+v\nwant %+v", cfg, defaults()) } } @@ -69,8 +73,12 @@ zettel_folder = "z" new_note_folder = "inbox" tasks_heading = "### Todo" task_format = "emoji" +meetings_folder = "work/meetings" +meeting_template = "tpl/meeting.md" +meetings_heading = "### Calls" `, want: func(c *config.Config) { + c.MeetingsFolder, c.MeetingTemplate, c.MeetingsHeading = "work/meetings", "tpl/meeting.md", "### Calls" c.DayStartsAt = 4*time.Hour + 30*time.Minute c.DailyFolder, c.DailyTemplate, c.ZettelFolder, c.NewNoteFolder, c.TasksHeading = "journal", "tpl/day.md", "z", "inbox", "### Todo" c.DailySubfolder, c.TaskFormat = "YYYY/MM", index.Emoji @@ -110,6 +118,7 @@ task_format = "emoji" daily_folder = "/abs" zettel_folder = "../out" tasks_heading = "Tasks" +meetings_heading = "Meetings" task_format = "bogus" `, want: func(c *config.Config) { c.Conceal = false }, @@ -118,6 +127,7 @@ task_format = "bogus" userPath + `: theme: want a string, got 3`, vaultPath + `: daily_folder: want a folder inside the Vault, got "/abs"`, vaultPath + `: day_starts_at: want "HH:MM", got "25:00"`, + vaultPath + `: meetings_heading: want a markdown heading like "## Tasks", got "Meetings"`, vaultPath + `: task_format: want "dataview" or "emoji", got "bogus"`, vaultPath + `: tasks_heading: want a markdown heading like "## Tasks", got "Tasks"`, vaultPath + `: zettel_folder: want a folder inside the Vault, got "../out"`, @@ -139,6 +149,49 @@ task_format = "bogus" want: func(c *config.Config) { c.DailyFolder = "journal" }, problems: []string{userPath + ": toml: line 1 (last key \"wrap\"): expected value but found '\\n' instead"}, }, + { + name: "calendars", + user: "[[calendars]]\nname = \"work\"\nurl = \"https://example.test/work.ics\"\ncolor = \"lightcoral\"\n" + + "[[calendars]]\nname = \"home\"\nurl = \"https://example.test/home.ics\"\n", + want: func(c *config.Config) { + c.Calendars = []config.Calendar{ + {Name: "work", URL: "https://example.test/work.ics", Color: "lightcoral"}, + {Name: "home", URL: "https://example.test/home.ics"}, + } + }, + }, + { + name: "a calendar missing name or url is skipped", + user: "[[calendars]]\nurl = \"https://example.test/a.ics\"\n" + + "[[calendars]]\nname = \"b\"\n" + + "[[calendars]]\nname = \"c\"\nurl = \"https://example.test/c.ics\"\ncolour = \"red\"\n", + want: func(c *config.Config) { + c.Calendars = []config.Calendar{{Name: "c", URL: "https://example.test/c.ics"}} + }, + problems: []string{ + userPath + `: calendars[1]: name: want a non-empty string, got none`, + userPath + `: calendars[2]: url: want a non-empty string, got none`, + userPath + `: calendars[3]: unknown key "colour"`, + }, + }, + { + name: "a bad calendar color is dropped, keeping the calendar", + user: "[[calendars]]\nname = \"work\"\nurl = \"https://example.test/work.ics\"\ncolor = \"blurple\"\n", + want: func(c *config.Config) { + c.Calendars = []config.Calendar{{Name: "work", URL: "https://example.test/work.ics"}} + }, + problems: []string{userPath + `: calendars[1]: color: want a CSS colour name or "#rrggbb", got "blurple"`}, + }, + { + name: "calendars must be tables", + user: "calendars = \"work\"\n", + problems: []string{userPath + `: calendars: want [[calendars]] tables, got "work"`}, + }, + { + name: "calendars are refused in the Vault config", + vault: "[[calendars]]\nname = \"work\"\nurl = \"https://example.test/work.ics\"\n", + problems: []string{vaultPath + `: calendars: only allowed in the user config, since feed URLs are secrets`}, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -154,7 +207,7 @@ task_format = "bogus" if tt.want != nil { tt.want(&want) } - if cfg != want { + if !reflect.DeepEqual(cfg, want) { t.Errorf("cfg = %+v\nwant %+v", cfg, want) } if !equal(problems, tt.problems) { diff --git a/internal/config/dirs.go b/internal/config/dirs.go index c7cbb5d..4919914 100644 --- a/internal/config/dirs.go +++ b/internal/config/dirs.go @@ -8,6 +8,8 @@ type Dirs struct { ConfigHome string // StateHome is $XDG_STATE_HOME, or ~/.local/state. StateHome string + // CacheHome is $XDG_CACHE_HOME, or ~/.cache. + CacheHome string } // DirsFromEnv resolves Dirs from the XDG variables, falling back to home. @@ -23,5 +25,6 @@ func DirsFromEnv(getenv func(string) string, home string) Dirs { return Dirs{ ConfigHome: pick("XDG_CONFIG_HOME", ".config"), StateHome: pick("XDG_STATE_HOME", ".local", "state"), + CacheHome: pick("XDG_CACHE_HOME", ".cache"), } } diff --git a/internal/config/dirs_test.go b/internal/config/dirs_test.go index 0bb1d2c..9ba3df3 100644 --- a/internal/config/dirs_test.go +++ b/internal/config/dirs_test.go @@ -14,17 +14,17 @@ func TestDirsFromEnv(t *testing.T) { }{ { name: "unset falls back to home, on macOS too", - want: config.Dirs{ConfigHome: "/home/u/.config", StateHome: "/home/u/.local/state"}, + want: config.Dirs{ConfigHome: "/home/u/.config", StateHome: "/home/u/.local/state", CacheHome: "/home/u/.cache"}, }, { name: "XDG vars win", - env: map[string]string{"XDG_CONFIG_HOME": "/xdg/config", "XDG_STATE_HOME": "/xdg/state"}, - want: config.Dirs{ConfigHome: "/xdg/config", StateHome: "/xdg/state"}, + env: map[string]string{"XDG_CONFIG_HOME": "/xdg/config", "XDG_STATE_HOME": "/xdg/state", "XDG_CACHE_HOME": "/xdg/cache"}, + want: config.Dirs{ConfigHome: "/xdg/config", StateHome: "/xdg/state", CacheHome: "/xdg/cache"}, }, { name: "relative XDG vars are ignored, per the XDG spec", - env: map[string]string{"XDG_CONFIG_HOME": "rel/config", "XDG_STATE_HOME": "rel"}, - want: config.Dirs{ConfigHome: "/home/u/.config", StateHome: "/home/u/.local/state"}, + env: map[string]string{"XDG_CONFIG_HOME": "rel/config", "XDG_STATE_HOME": "rel", "XDG_CACHE_HOME": "rel"}, + want: config.Dirs{ConfigHome: "/home/u/.config", StateHome: "/home/u/.local/state", CacheHome: "/home/u/.cache"}, }, } for _, tt := range tests { diff --git a/internal/config/init.go b/internal/config/init.go index b7b3ecf..82871a4 100644 --- a/internal/config/init.go +++ b/internal/config/init.go @@ -32,6 +32,9 @@ var vaultKeyDocs = []struct { {"zettel_folder", "Folder that holds Zettels.", func(c Config) string { return strconv.Quote(c.ZettelFolder) }}, {"new_note_folder", "Folder for new Notes; \"\" is the Vault root.", func(c Config) string { return strconv.Quote(c.NewNoteFolder) }}, {"tasks_heading", "Heading the Task List adds new Tasks under.", func(c Config) string { return strconv.Quote(c.TasksHeading) }}, + {"meetings_folder", "Folder that holds Meeting Notes.", func(c Config) string { return strconv.Quote(c.MeetingsFolder) }}, + {"meeting_template", "Template for new Meeting Notes; a built-in one is used when the file is missing.", func(c Config) string { return strconv.Quote(c.MeetingTemplate) }}, + {"meetings_heading", "Daily Note heading that new Meeting Notes are linked under.", func(c Config) string { return strconv.Quote(c.MeetingsHeading) }}, {"task_format", "Task Format for new Task Metadata: \"dataview\" ([due:: 2026-10-10]) or \"emoji\" (📅 2026-10-10).", func(c Config) string { return strconv.Quote(string(c.TaskFormat)) }}, } diff --git a/internal/config/init_test.go b/internal/config/init_test.go index faff6ad..e435673 100644 --- a/internal/config/init_test.go +++ b/internal/config/init_test.go @@ -77,7 +77,7 @@ func TestInitConfigListsEveryVaultKeyAtItsDefault(t *testing.T) { for _, v := range variants { fsys := seamtest.NewMemFS(map[string]string{"/vault/.pholio/config.toml": v}) cfg, problems := config.Load(fsys, dirs, "/vault") - if len(problems) != 0 || cfg != defaults() { + if len(problems) != 0 || !reflect.DeepEqual(cfg, defaults()) { t.Errorf("loading:\n%s\ngot %+v, problems %v", v, cfg, problems) } } diff --git a/internal/config/startup_test.go b/internal/config/startup_test.go index 234d978..4f998c8 100644 --- a/internal/config/startup_test.go +++ b/internal/config/startup_test.go @@ -1,6 +1,7 @@ package config_test import ( + "reflect" "testing" "github.com/tedkulp/pholio/internal/config" @@ -13,7 +14,7 @@ func TestStartupWithNoConfigFilesUsesDefaults(t *testing.T) { if err != nil { t.Fatal(err) } - if got.Target != (config.Target{Vault: "/vault"}) || got.Config != defaults() || got.Message != "" { + if got.Target != (config.Target{Vault: "/vault"}) || !reflect.DeepEqual(got.Config, defaults()) || got.Message != "" { t.Fatalf("got %+v", got) } } diff --git a/internal/daily/daily.go b/internal/daily/daily.go index bef7247..24618fd 100644 --- a/internal/daily/daily.go +++ b/internal/daily/daily.go @@ -15,13 +15,19 @@ type Vars struct { Day time.Time // the Note's own day: {{date}}, {{yesterday}}, {{tomorrow}} Now time.Time // the wall clock: {{time}} Title string // the Note's name without .md: {{title}} + // Times are more time placeholders, such as a Meeting's {{start}}, with + // :FMT and HH:mm as the default. + Times map[string]time.Time + // Text are more plain placeholders, such as a Meeting's {{daily}}. + Text map[string]string } var placeholder = regexp.MustCompile(`\{\{\s*(\w+)(?::([^}]*))?\s*\}\}`) // Render expands the placeholders in a Template: {{date}}, {{date:FMT}}, // {{time}}, {{time:FMT}}, {{title}}, {{yesterday}} and {{tomorrow}}. -// Formats use moment.js tokens. Unknown placeholders are left as they are. +// Formats use moment.js tokens. v.Times and v.Text add more. Unknown +// placeholders are left as they are. func Render(tmpl string, v Vars) string { return placeholder.ReplaceAllStringFunc(tmpl, func(s string) string { m := placeholder.FindStringSubmatch(s) @@ -44,6 +50,12 @@ func Render(tmpl string, v Vars) string { case "tomorrow": return dates.Format(v.Day.AddDate(0, 0, 1), withDefault("YYYY-MM-DD")) } + if t, ok := v.Times[name]; ok { + return dates.Format(t, withDefault("HH:mm")) + } + if text, ok := v.Text[name]; ok { + return text + } return s }) } diff --git a/internal/daily/daily_test.go b/internal/daily/daily_test.go index 12d611a..38441bc 100644 --- a/internal/daily/daily_test.go +++ b/internal/daily/daily_test.go @@ -32,3 +32,23 @@ func TestRenderPlaceholders(t *testing.T) { } } } + +func TestRenderExtraPlaceholders(t *testing.T) { + vars := daily.Vars{ + Day: time.Date(2026, 10, 12, 0, 0, 0, 0, time.Local), + Title: "Standup", + Times: map[string]time.Time{"start": time.Date(2026, 10, 12, 9, 30, 0, 0, time.Local)}, + Text: map[string]string{"daily": "[[2026-10-12]]", "link": ""}, + } + for tmpl, want := range map[string]string{ + "{{start}}": "09:30", + "{{start:h:mm A}}": "9:30 AM", + "{{daily}}": "[[2026-10-12]]", + "Link: {{link}}": "Link: ", + "{{end}} {{title}}": "{{end}} Standup", + } { + if got := daily.Render(tmpl, vars); got != want { + t.Errorf("Render(%q) = %q, want %q", tmpl, got, want) + } + } +} diff --git a/internal/palette/palette.go b/internal/palette/palette.go index 8d68baa..25f9a08 100644 --- a/internal/palette/palette.go +++ b/internal/palette/palette.go @@ -7,6 +7,7 @@ package palette import ( + "image/color" "strings" tea "charm.land/bubbletea/v2" @@ -35,7 +36,10 @@ type Item struct { // DetailSlot styles Detail when the row is not selected. Zero means // overlay.hint. DetailSlot theme.Slot - Group string // a header row is drawn whenever this changes + // DetailColor, when set, is the unselected Detail's foreground, used + // as-is on every theme (a calendar's colour). + DetailColor color.Color + Group string // a header row is drawn whenever this changes // Slot styles Text when the row is not selected. Zero means overlay.box. Slot theme.Slot // Marks are [start, end) byte ranges of Text drawn with @@ -96,6 +100,9 @@ func New(title string, mode Mode) Model { return m.refilter() } +// WithTitle replaces the title. +func (m Model) WithTitle(s string) Model { m.title = s; return m } + // WithPlaceholder sets the text shown in an empty input. func (m Model) WithPlaceholder(s string) Model { m.placeholder = s; return m } @@ -431,7 +438,11 @@ func row(th theme.Theme, it Item, w int, selected bool) string { if dslot == "" { dslot = theme.OverlayHint } - return styled + strings.Repeat(" ", gap) + th.Style(dslot).Render(detail) + ds := th.Style(dslot) + if it.DetailColor != nil { + ds = ds.Foreground(it.DetailColor) + } + return styled + strings.Repeat(" ", gap) + ds.Render(detail) } // marked draws it.Text in slot with its Marks in markdown.search, fitted diff --git a/internal/palette/palette_test.go b/internal/palette/palette_test.go index f9b4308..a6d96b9 100644 --- a/internal/palette/palette_test.go +++ b/internal/palette/palette_test.go @@ -6,6 +6,7 @@ import ( "testing" tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" "github.com/tedkulp/pholio/internal/palette" @@ -265,6 +266,31 @@ func TestGeometryIsTopAnchoredAndCentred(t *testing.T) { } } +func TestDetailColorDrawsAnUnselectedDetailInThatColour(t *testing.T) { + th := theme.Default() + coral := lipgloss.Color("#f08080") + want := th.Style(theme.OverlayHint).Foreground(coral).Render("home") + p := palette.New("Meetings", palette.List).SetItems([]palette.Item{ + {Text: "Standup", Detail: "work"}, + {Text: "Dentist", Detail: "home", DetailColor: coral}, + }) + + if box, _, _, _ := p.View(th, 60, 24); !strings.Contains(box, want) { + t.Errorf("view lacks the coloured Detail %q:\n%q", want, box) + } + if box, _, _, _ := p.Select(1).View(th, 60, 24); strings.Contains(box, want) { + t.Errorf("the selected row kept its Detail colour:\n%q", box) + } +} + +func TestWithTitleRenamesThePalette(t *testing.T) { + p := palette.New("Old", palette.List).WithTitle("New") + + if got := view(p, 38, 24); !strings.HasPrefix(got, "╭─ New ─") { + t.Errorf("view =\n%s", got) + } +} + func TestMarksHighlightPartsOfAnUnselectedRow(t *testing.T) { th := theme.Default() p := palette.New("Search", palette.Type).SetItems([]palette.Item{ diff --git a/internal/seam/seam.go b/internal/seam/seam.go index 232ca64..e7b687a 100644 --- a/internal/seam/seam.go +++ b/internal/seam/seam.go @@ -20,6 +20,9 @@ type Clock interface { type FS interface { ReadFile(name string) ([]byte, error) WriteFile(name string, data []byte) error + // Create writes data to a new file, failing with fs.ErrExist when + // name is already there. + Create(name string, data []byte) error Stat(name string) (fs.FileInfo, error) ReadDir(name string) ([]fs.DirEntry, error) MkdirAll(name string) error @@ -81,6 +84,20 @@ func (OSFS) WriteFile(name string, data []byte) error { return os.WriteFile(name, data, 0o644) } +// Create writes data to a new file, failing with fs.ErrExist when name +// is already there. +func (OSFS) Create(name string, data []byte) error { + f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) //nolint:gosec // Notes get ordinary 0644 permissions, as WriteFile + if err != nil { + return err + } + _, err = f.Write(data) + if cerr := f.Close(); err == nil { + err = cerr + } + return err +} + // Stat describes the named file. func (OSFS) Stat(name string) (fs.FileInfo, error) { return os.Stat(name) } diff --git a/internal/seam/seamtest/seamtest.go b/internal/seam/seamtest/seamtest.go index 6eea66d..d4d91aa 100644 --- a/internal/seam/seamtest/seamtest.go +++ b/internal/seam/seamtest/seamtest.go @@ -98,6 +98,18 @@ func (m *MemFS) WriteFile(name string, data []byte) error { return nil } +// Create stores data at name, failing with fs.ErrExist when name is +// already there. +func (m *MemFS) Create(name string, data []byte) error { + m.mu.Lock() + defer m.mu.Unlock() + if _, err := m.files.Stat(key(name)); err == nil { + return pathErr("create", name, fs.ErrExist) + } + m.files[key(name)] = &fstest.MapFile{Data: append([]byte(nil), data...), Mode: 0o644, ModTime: time.Now()} + return nil +} + // Stat describes the named file or directory. func (m *MemFS) Stat(name string) (fs.FileInfo, error) { m.mu.Lock() diff --git a/internal/tasks/add.go b/internal/tasks/add.go index 68b643d..d49e9d2 100644 --- a/internal/tasks/add.go +++ b/internal/tasks/add.go @@ -9,9 +9,20 @@ import ( // AddAt is where the Task List's `a` puts a new Task in a Note's lines // (without their newlines): after the last Task in the section under // heading, right under heading when the section has no Task, or at the end -// when there is no such heading. The section runs to the next heading of -// the same or a higher level. Fenced code is skipped. +// when there is no such heading. func AddAt(lines []string, heading string) int { + at := SectionAt(lines, heading, func(l string) bool { _, ok := index.ParseTask(l); return ok }) + if at < 0 { + return len(lines) + } + return at +} + +// SectionAt is where a new item goes in the section under heading: after +// its last line that is an item, else right under heading. It is -1 when +// there is no such heading. The section runs to the next heading of the +// same or a higher level. Fenced code is skipped. +func SectionAt(lines []string, heading string, item func(string) bool) int { heading = strings.TrimSpace(heading) level := headingLevel(heading) var f index.Fences @@ -30,15 +41,10 @@ func AddAt(lines []string, heading string) int { continue } } - if in { - if _, ok := index.ParseTask(l); ok { - at = i + 1 - } + if in && item(l) { + at = i + 1 } } - if at < 0 { - return len(lines) - } return at } @@ -54,6 +60,15 @@ func headingLevel(s string) int { // AddFile puts line into the file at path where AddAt says, keeping the // file's line endings, and writes it back. func AddFile(fsys FS, path, heading, line string) error { + return EditFile(fsys, path, func(lines []string) []string { + at := AddAt(lines, heading) + return append(lines[:at], append([]string{line}, lines[at:]...)...) + }) +} + +// EditFile rewrites the lines (without their newlines) of the file at path +// with edit, keeping the file's line endings. +func EditFile(fsys FS, path string, edit func([]string) []string) error { data, err := fsys.ReadFile(path) if err != nil { return err @@ -67,7 +82,5 @@ func AddFile(fsys FS, path, heading, line string) error { if body := strings.TrimSuffix(strings.ReplaceAll(text, "\r\n", "\n"), "\n"); text != "" { lines = strings.Split(body, "\n") } - at := AddAt(lines, heading) - lines = append(lines[:at], append([]string{line}, lines[at:]...)...) - return fsys.WriteFile(path, []byte(strings.Join(lines, eol)+eol)) + return fsys.WriteFile(path, []byte(strings.Join(edit(lines), eol)+eol)) } diff --git a/internal/theme/color.go b/internal/theme/color.go index 7d3c7b9..3ccb105 100644 --- a/internal/theme/color.go +++ b/internal/theme/color.go @@ -4,8 +4,10 @@ import ( "fmt" "image/color" "strconv" + "strings" "charm.land/lipgloss/v2" + "golang.org/x/image/colornames" ) // ParseColor parses a literal colour: "#rrggbb", "#rgb" or an ANSI number @@ -24,6 +26,22 @@ func ParseColor(s string) (color.Color, error) { return lipgloss.Color(s), nil } +// ParseCSSColor parses a CSS colour: a name such as "lightcoral" (any +// case) or "#rrggbb". Calendar colours are written this way. +func ParseCSSColor(s string) (color.Color, error) { + name := strings.ToLower(s) + if c, ok := colornames.Map[name]; ok { + return c, nil + } + if name == "rebeccapurple" { // CSS 4; colornames stops at SVG 1.1 + return color.RGBA{0x66, 0x33, 0x99, 0xff}, nil + } + if len(s) == 7 && s[0] == '#' && isHex(s[1:]) { + return lipgloss.Color(s), nil + } + return nil, fmt.Errorf("bad colour %q: want a CSS colour name or #rrggbb", s) +} + func isHex(s string) bool { for _, r := range s { if (r < '0' || r > '9') && (r < 'a' || r > 'f') && (r < 'A' || r > 'F') { diff --git a/internal/theme/color_test.go b/internal/theme/color_test.go index f48b8d2..5f3fa7e 100644 --- a/internal/theme/color_test.go +++ b/internal/theme/color_test.go @@ -41,3 +41,35 @@ func TestParseColorRejects(t *testing.T) { } } } + +// rgb is c as 8-bit red, green and blue. +func rgb(c color.Color) [3]uint32 { + r, g, b, _ := c.RGBA() + return [3]uint32{r >> 8, g >> 8, b >> 8} +} + +func TestParseCSSColor(t *testing.T) { + tests := []struct { + in string + want [3]uint32 + }{ + {"lightcoral", [3]uint32{0xf0, 0x80, 0x80}}, + {"RebeccaPurple", [3]uint32{0x66, 0x33, 0x99}}, + {"#1e90ff", [3]uint32{0x1e, 0x90, 0xff}}, + } + for _, tt := range tests { + got, err := theme.ParseCSSColor(tt.in) + if err != nil { + t.Errorf("ParseCSSColor(%q): %v", tt.in, err) + continue + } + if rgb(got) != tt.want { + t.Errorf("ParseCSSColor(%q) = %x, want %x", tt.in, rgb(got), tt.want) + } + } + for _, in := range []string{"", "notacolour", "12", "#f80", "#gg0000"} { + if c, err := theme.ParseCSSColor(in); err == nil { + t.Errorf("ParseCSSColor(%q) = %v, want an error", in, c) + } + } +}