Files
projax/web/timeline_test.go
mAi 13923aadb6 feat(views): Phase 5i slice A — project filter dim + descendants toggle
m's Q5 pick (2026-05-26): project scope on every Views-supporting page,
with descendants exposed as an explicit on/off chip toggle rather than
always-on. Slice A ships the smallest standalone piece of the Views
system; slices B–E (view_type URL param, kanban, saved-views schema,
defaults) follow on the same branch.

TreeFilter grows two fields:
- ProjectPath: scoped item's primary path; "" = no filter.
- IncludeDescendants: default true; flipped via ?project_descendants=0.

Matching extends to path-prefix across `it.Paths` when ProjectPath is
set; equality-only when IncludeDescendants is off. Multi-parent items
pass when ANY of their paths qualifies.

Picker is a shared partial (templates/project_chip.tmpl) that every
Views-supporting filter strip includes (tree, dashboard, timeline,
calendar). Two states: <select> picker when no project is set; active
chip with × clear + descendants on/off chip when scoped. Hidden
inputs added to each form so non-picker chip clicks preserve the
project state. Graph and admin tools are NOT Views consumers (per
design.md / docs/plans/views-system.md §5) and stay untouched.

Test-source edits (per the 5c sharpened rule):
- dashboard_test.go, public_listing_test.go, timeline_test.go: row
  membership assertions tightened from `Contains(body, slug)` to
  `Contains(body, href="/i/path")`. The picker now renders every
  item's primary path inside a <select>, so coarse slug substring
  matches falsely passed across filtered-out picker options. Behaviour
  preserved (filtered rows still don't render); the impl-detail
  assertion moved to the row link.

New tests: TestProjectFilterIncludesDescendants,
TestProjectFilterDescendantsOff, TestParseTreeFilterProjectFields,
TestTreeFilterProjectRoundTrip, TestSetProjectAndToggleHelpers,
TestProjectFilterScopesTreeToDescendants (end-to-end via /).
2026-05-26 13:27:37 +02:00

353 lines
13 KiB
Go

package web_test
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/m/projax/caldav"
"github.com/m/projax/web"
)
// TestTimelineRendersEmpty checks GET /timeline renders cleanly without any
// linked DAV / Gitea integration and surfaces the "Nothing on this timeline
// yet" copy when no dated content exists in the default window.
func TestTimelineRendersEmpty(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
code, body := get(t, h, "/timeline")
if code != 200 {
t.Fatalf("GET /timeline → %d body=%s", code, body)
}
for _, want := range []string{
`id="timeline-section"`,
`<h1>Timeline</h1>`,
} {
if !strings.Contains(body, want) {
t.Errorf("timeline missing %q", want)
}
}
}
// TestTimelineSurfacesDatedDocs seeds a dated item_link inside the default
// window and asserts the timeline page renders the corresponding PER.
func TestTimelineSurfacesDatedDocs(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stamp := strings.ReplaceAll(time.Now().UTC().Format("150405.000000"), ".", "")
slug := "tl-doc-" + stamp
var dev, id string
if err := pool.QueryRow(ctx, `select id from projax.items where slug='dev' and cardinality(parent_ids)=0`).Scan(&dev); err != nil {
t.Fatalf("dev: %v", err)
}
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids)
values (array['project']::text[], 'TL doc', $1, ARRAY[$2]::uuid[])
returning id`,
slug, dev,
).Scan(&id); err != nil {
t.Fatalf("seed item: %v", err)
}
defer pool.Exec(context.Background(), `delete from projax.items where id=$1`, id)
if _, err := pool.Exec(ctx,
`insert into projax.item_links (item_id, ref_type, ref_id, rel, note, event_date)
values ($1, 'document', $2, 'contains', $3, current_date)`,
id, "https://example.com/tl-doc-"+stamp, "tl test "+stamp,
); err != nil {
t.Fatalf("seed link: %v", err)
}
code, body := get(t, h, "/timeline")
if code != 200 {
t.Fatalf("GET /timeline → %d", code)
}
wantPER := "dev." + slug + "." + time.Now().UTC().Format("060102")
if !strings.Contains(body, wantPER) {
t.Errorf("timeline body missing PER %q", wantPER)
}
// Today header should fire on the seeded date.
if !strings.Contains(body, "Today") {
t.Errorf("timeline body missing 'Today' header for today's row")
}
}
// TestTimelineFilterByKindNarrowsRows seeds an item-creation marker (item just
// created in the seed step) and a dated doc; ?kind=doc should hide the
// creation marker but keep the doc row.
func TestTimelineFilterByKindNarrowsRows(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stamp := strings.ReplaceAll(time.Now().UTC().Format("150405.000000"), ".", "")
slug := "tl-k-" + stamp
var dev, id string
if err := pool.QueryRow(ctx, `select id from projax.items where slug='dev' and cardinality(parent_ids)=0`).Scan(&dev); err != nil {
t.Fatalf("dev: %v", err)
}
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids)
values (array['project']::text[], 'TL kind', $1, ARRAY[$2]::uuid[])
returning id`,
slug, dev,
).Scan(&id); err != nil {
t.Fatalf("seed item: %v", err)
}
defer pool.Exec(context.Background(), `delete from projax.items where id=$1`, id)
if _, err := pool.Exec(ctx,
`insert into projax.item_links (item_id, ref_type, ref_id, rel, event_date)
values ($1, 'document', $2, 'contains', current_date)`,
id, "https://example.com/tl-k-"+stamp,
); err != nil {
t.Fatalf("seed link: %v", err)
}
// Unfiltered: both the creation marker and the dated doc should be present.
_, allBody := get(t, h, "/timeline")
if !strings.Contains(allBody, "added <a class=\"proj\" href=\"/i/dev."+slug) {
t.Errorf("expected creation marker in unfiltered timeline body")
}
if !strings.Contains(allBody, "dev."+slug+"."+time.Now().UTC().Format("060102")) {
t.Errorf("expected doc PER in unfiltered timeline body")
}
// kind=doc only: the doc row stays; the creation marker drops.
_, docOnly := get(t, h, "/timeline?kind=doc")
if strings.Contains(docOnly, "added <a class=\"proj\" href=\"/i/dev."+slug) {
t.Errorf("kind=doc should hide creation marker")
}
if !strings.Contains(docOnly, "dev."+slug+"."+time.Now().UTC().Format("060102")) {
t.Errorf("kind=doc should still surface doc row")
}
}
// TestTimelineOrderToggleReversesDays seeds dated docs across two distinct
// dates and asserts the rendered order swaps between ?order=asc and the
// (default) ?order=desc.
func TestTimelineOrderToggleReversesDays(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stamp := strings.ReplaceAll(time.Now().UTC().Format("150405.000000"), ".", "")
slug := "tl-ord-" + stamp
var dev, id string
if err := pool.QueryRow(ctx, `select id from projax.items where slug='dev' and cardinality(parent_ids)=0`).Scan(&dev); err != nil {
t.Fatalf("dev: %v", err)
}
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids)
values (array['project']::text[], 'TL ord', $1, ARRAY[$2]::uuid[])
returning id`,
slug, dev,
).Scan(&id); err != nil {
t.Fatalf("seed item: %v", err)
}
defer pool.Exec(context.Background(), `delete from projax.items where id=$1`, id)
// Two distinct dates: today (older marker) and today+5 (newer marker)
if _, err := pool.Exec(ctx,
`insert into projax.item_links (item_id, ref_type, ref_id, rel, event_date)
values ($1, 'document', $2, 'contains', current_date - interval '3 days'),
($1, 'document', $3, 'contains', current_date + interval '5 days')`,
id, "https://example.com/tl-ord-a-"+stamp, "https://example.com/tl-ord-b-"+stamp,
); err != nil {
t.Fatalf("seed links: %v", err)
}
older := "dev." + slug + "." + time.Now().UTC().AddDate(0, 0, -3).Format("060102")
newer := "dev." + slug + "." + time.Now().UTC().AddDate(0, 0, 5).Format("060102")
_, desc := get(t, h, "/timeline")
idxNewerDesc := strings.Index(desc, newer)
idxOlderDesc := strings.Index(desc, older)
if idxNewerDesc < 0 || idxOlderDesc < 0 {
t.Fatalf("default timeline missing one of the PERs (newer=%d, older=%d)", idxNewerDesc, idxOlderDesc)
}
if !(idxNewerDesc < idxOlderDesc) {
t.Errorf("default order should be desc (newest first); newer at %d, older at %d", idxNewerDesc, idxOlderDesc)
}
_, asc := get(t, h, "/timeline?order=asc")
idxNewerAsc := strings.Index(asc, newer)
idxOlderAsc := strings.Index(asc, older)
if !(idxOlderAsc < idxNewerAsc) {
t.Errorf("?order=asc should put older first; newer at %d, older at %d", idxNewerAsc, idxOlderAsc)
}
}
// TestTimelineSurfacesCalDAVTodosAndAllDayEvents wires a fake CalDAV server
// that returns one open VTODO with DUE=today and one all-day VEVENT
// starting today + spanning two days. Asserts both surface and that the
// all-day event renders without a HH:MM prefix while the multi-day duration
// hint appears.
func TestTimelineSurfacesCalDAVTodosAndAllDayEvents(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
now := time.Now().UTC()
today := now
dueDate := today.Format("20060102")
endDate := today.AddDate(0, 0, 2).Format("20060102")
startDate := today.Format("20060102")
icsTodo := `BEGIN:VCALENDAR
BEGIN:VTODO
UID:tl-todo-1@fake
SUMMARY:Timeline todo today
STATUS:NEEDS-ACTION
DUE;VALUE=DATE:` + dueDate + `
END:VTODO
END:VCALENDAR`
icsEvent := `BEGIN:VCALENDAR
BEGIN:VEVENT
UID:tl-evt-1@fake
SUMMARY:Two-day offsite
DTSTART;VALUE=DATE:` + startDate + `
DTEND;VALUE=DATE:` + endDate + `
END:VEVENT
END:VCALENDAR`
multi := func(href, etag, ics string) string {
return `<d:response><d:href>` + href + `</d:href><d:propstat><d:prop>` +
`<d:getetag>"` + etag + `"</d:getetag>` +
`<cal:calendar-data>` + ics + `</cal:calendar-data>` +
`</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>`
}
mux := http.NewServeMux()
mux.HandleFunc("/dav/calendars/m/TL/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "REPORT" {
http.Error(w, "method", http.StatusMethodNotAllowed)
return
}
body, _ := io.ReadAll(r.Body)
w.WriteHeader(207)
if strings.Contains(string(body), "VTODO") {
_, _ = io.WriteString(w, `<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" xmlns:cal="urn:ietf:params:xml:ns:caldav">`+
multi("/dav/calendars/m/TL/td-1.ics", "t1", icsTodo)+
`</d:multistatus>`)
return
}
_, _ = io.WriteString(w, `<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" xmlns:cal="urn:ietf:params:xml:ns:caldav">`+
multi("/dav/calendars/m/TL/ev-1.ics", "e1", icsEvent)+
`</d:multistatus>`)
})
fake := httptest.NewServer(mux)
defer fake.Close()
srv.CalDAV = &web.CalDAVDeps{Client: caldav.New(fake.URL+"/dav/calendars/m/", "u", "p")}
stamp := strings.ReplaceAll(time.Now().UTC().Format("150405.000000"), ".", "")
slug := "tl-mix-" + stamp
calURL := fake.URL + "/dav/calendars/m/TL/"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var dev, id string
if err := pool.QueryRow(ctx, `select id from projax.items where slug='dev' and cardinality(parent_ids)=0`).Scan(&dev); err != nil {
t.Fatalf("dev: %v", err)
}
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids)
values (array['project']::text[], 'TL mix', $1, ARRAY[$2]::uuid[])
returning id`,
slug, dev,
).Scan(&id); err != nil {
t.Fatalf("seed item: %v", err)
}
defer pool.Exec(context.Background(), `delete from projax.items where id=$1`, id)
if _, err := pool.Exec(ctx,
`insert into projax.item_links (item_id, ref_type, ref_id, rel)
values ($1, 'caldav-list', $2, 'tracks')`,
id, calURL,
); err != nil {
t.Fatalf("seed link: %v", err)
}
h := srv.Routes()
code, body := get(t, h, "/timeline")
if code != 200 {
t.Fatalf("GET /timeline → %d", code)
}
for _, want := range []string{
"Timeline todo today",
"Two-day offsite",
"(2 days)", // duration hint
`hx-post="/dashboard/task/edit"`, // edit affordance on timeline VTODO row
`hx-post="/dashboard/task/delete"`, // delete affordance
`hx-post="/dashboard/task/done"`, // complete affordance
} {
if !strings.Contains(body, want) {
t.Errorf("timeline body missing %q", want)
}
}
}
// TestTimelineFilterByTagAppliesAcrossKinds seeds two items in different areas,
// each with a dated link; ?tag=work should narrow the timeline to the work-
// tagged item only.
func TestTimelineFilterByTagAppliesAcrossKinds(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stamp := strings.ReplaceAll(time.Now().UTC().Format("150405.000000"), ".", "")
var dev, home string
if err := pool.QueryRow(ctx, `select id from projax.items where slug='dev' and cardinality(parent_ids)=0`).Scan(&dev); err != nil {
t.Fatalf("dev: %v", err)
}
if err := pool.QueryRow(ctx, `select id from projax.items where slug='home' and cardinality(parent_ids)=0`).Scan(&home); err != nil {
t.Fatalf("home: %v", err)
}
mkItem := func(parent, slug, tag string) string {
var id string
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids, tags)
values (array['project']::text[], $1, $2, ARRAY[$3]::uuid[], ARRAY[$4]::text[])
returning id`,
"X "+slug, slug, parent, tag,
).Scan(&id); err != nil {
t.Fatalf("seed %s: %v", slug, err)
}
if _, err := pool.Exec(ctx,
`insert into projax.item_links (item_id, ref_type, ref_id, rel, event_date)
values ($1, 'document', $2, 'contains', current_date)`,
id, "https://example.com/"+slug,
); err != nil {
t.Fatalf("link %s: %v", slug, err)
}
return id
}
devID := mkItem(dev, "tl-tag-d-"+stamp, "tl-tag-work-"+stamp)
homeID := mkItem(home, "tl-tag-h-"+stamp, "tl-tag-life-"+stamp)
defer pool.Exec(context.Background(), `delete from projax.items where id in ($1, $2)`, devID, homeID)
tag := "tl-tag-work-" + stamp
_, body := get(t, h, "/timeline?tag="+tag)
// Phase 5i Slice A: the project picker renders every item path as a
// <select> option, so a naive substring match also sees filtered-out
// items inside the dropdown. Anchor on the timeline-row link instead.
devLink := `href="/i/dev.tl-tag-d-` + stamp + `"`
homeLink := `href="/i/home.tl-tag-h-` + stamp + `"`
if !strings.Contains(body, devLink) {
t.Errorf("?tag=%s should surface dev-tagged item", tag)
}
if strings.Contains(body, homeLink) {
t.Errorf("?tag=%s should hide home-tagged item", tag)
}
}