diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..df563f4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,50 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool +*.out + +# Go workspace file +go.work +go.work.sum + +# Dependency directories +vendor/ + +# Build output +bin +/bin +*.o +*.a + +# IDE and editor files +.vscode/ +.idea/ +*.swp +*.swo +*~ +.DS_Store + +# Configuration files (keep example) +config.ini +!config.example.ini + +# Log files +*.log + +# Temporary files +tmp/ +temp/ +*.tmp + +# OS generated files +Thumbs.db +.Spotlight-V100 +.Trashes diff --git a/README.md b/README.md index 6b60bbd..3485faa 100644 --- a/README.md +++ b/README.md @@ -35,4 +35,20 @@ From either the calendar grid or the timeline view, the user can click on a spec - The application is compiled into a single binary (plus a config file) for easy deployment. - Configuration is done via a config file that is read at startup. - The application can be run as a standalone server on a specified port. -- Static files (CSS, JS, images) are inculeded in the binary using Go's embed package. \ No newline at end of file +- Static files (CSS, JS, images) are inculeded in the binary using Go's embed package. + +## Building + +To compile the application and create a runnable binary in the `bin` folder: + +```bash +go build -o bin/chronological ./cmd/chronological +``` + +This will create the `chronological` executable in the `bin` directory. You can then run it with: + +```bash +./bin/chronological -config config.ini +``` + +If no config file is specified, the application will look for `config.ini` in the current directory and use default settings if not found. \ No newline at end of file diff --git a/cmd/chronological/main.go b/cmd/chronological/main.go new file mode 100644 index 0000000..472cf68 --- /dev/null +++ b/cmd/chronological/main.go @@ -0,0 +1,49 @@ +// Package main is the entry point for the Chronological application. +package main + +import ( + "flag" + "log" + "os" + + "github.com/luxick/chronological/internal/config" + "github.com/luxick/chronological/internal/server" + "github.com/luxick/chronological/web" +) + +func main() { + configPath := flag.String("config", "config.ini", "Path to configuration file") + flag.Parse() + + // Load configuration + cfg, err := config.Load(*configPath) + if err != nil { + log.Printf("Warning: Could not load config file: %v", err) + log.Println("Using default configuration") + cfg = &config.Config{ + Server: config.ServerConfig{ + Port: 8080, + }, + } + } + + // Validate configuration + if err := cfg.Validate(); err != nil { + log.Printf("Warning: Configuration validation: %v", err) + } + + // Set embedded filesystems from web package + server.TemplatesFS = web.TemplatesFS + server.StaticFS = web.StaticFS + + // Create and run server + srv, err := server.New(cfg) + if err != nil { + log.Fatalf("Failed to create server: %v", err) + } + + if err := srv.Run(); err != nil { + log.Printf("Server error: %v", err) + os.Exit(1) + } +} diff --git a/config.example.ini b/config.example.ini new file mode 100644 index 0000000..c3ce1cb --- /dev/null +++ b/config.example.ini @@ -0,0 +1,22 @@ +[server] +port = 8080 + +[calendar] +# Path to local .ics file for calendar events +local_ics = /path/to/calendar.ics + +[diary] +# Path to .ics file for diary/journal entries +ics_file = /path/to/diary.ics + +[caldav] +# Enable CalDAV sync for remote calendars +enabled = false +url = https://caldav.example.com/calendars/user/ +username = user +password = password + +[photos] +# Root folder containing year subfolders with photos +# Photos should be named: YYYY-MM-DD_description.ext +root_folder = /path/to/photos diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..80be87e --- /dev/null +++ b/go.mod @@ -0,0 +1,14 @@ +module github.com/luxick/chronological + +go 1.25.4 + +require ( + github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608 + github.com/emersion/go-webdav v0.7.0 + gopkg.in/ini.v1 v1.67.0 +) + +require ( + github.com/stretchr/testify v1.11.1 // indirect + github.com/teambition/rrule-go v1.8.2 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e55d131 --- /dev/null +++ b/go.sum @@ -0,0 +1,18 @@ +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/emersion/go-ical v0.0.0-20240127095438-fc1c9d8fb2b6/go.mod h1:BEksegNspIkjCQfmzWgsgbu6KdeJ/4LwUZs7DMBzjzw= +github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608 h1:5XWaET4YAcppq3l1/Yh2ay5VmQjUdq6qhJuucdGbmOY= +github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608/go.mod h1:BEksegNspIkjCQfmzWgsgbu6KdeJ/4LwUZs7DMBzjzw= +github.com/emersion/go-vcard v0.0.0-20230815062825-8fda7d206ec9/go.mod h1:HMJKR5wlh/ziNp+sHEDV2ltblO4JD2+IdDOWtGcQBTM= +github.com/emersion/go-webdav v0.7.0 h1:cp6aBWXBf8Sjzguka9VJarr4XTkGc2IHxXI1Gq3TKpA= +github.com/emersion/go-webdav v0.7.0/go.mod h1:mI8iBx3RAODwX7PJJ7qzsKAKs/vY429YfS2/9wKnDbQ= +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/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +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= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +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/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..67dd1bb --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,144 @@ +// Package config handles loading and validation of application configuration. +package config + +import ( + "fmt" + "os" + "path/filepath" + + "gopkg.in/ini.v1" +) + +// Config holds all application configuration. +type Config struct { + Server ServerConfig + Calendar CalendarConfig + Diary DiaryConfig + CalDAV CalDAVConfig + Photos PhotosConfig +} + +// ServerConfig holds HTTP server settings. +type ServerConfig struct { + Port int +} + +// CalendarConfig holds calendar ICS file settings. +type CalendarConfig struct { + LocalICS string +} + +// DiaryConfig holds diary ICS file settings. +type DiaryConfig struct { + ICSFile string +} + +// CalDAVConfig holds CalDAV remote calendar settings. +type CalDAVConfig struct { + Enabled bool + URL string + Username string + Password string +} + +// PhotosConfig holds photo storage settings. +type PhotosConfig struct { + RootFolder string +} + +// Load reads configuration from the specified INI file. +func Load(path string) (*Config, error) { + cfg, err := ini.Load(path) + if err != nil { + return nil, fmt.Errorf("failed to load config file: %w", err) + } + + config := &Config{ + Server: ServerConfig{ + Port: cfg.Section("server").Key("port").MustInt(8080), + }, + Calendar: CalendarConfig{ + LocalICS: cfg.Section("calendar").Key("local_ics").String(), + }, + Diary: DiaryConfig{ + ICSFile: cfg.Section("diary").Key("ics_file").String(), + }, + CalDAV: CalDAVConfig{ + Enabled: cfg.Section("caldav").Key("enabled").MustBool(false), + URL: cfg.Section("caldav").Key("url").String(), + Username: cfg.Section("caldav").Key("username").String(), + Password: cfg.Section("caldav").Key("password").String(), + }, + Photos: PhotosConfig{ + RootFolder: cfg.Section("photos").Key("root_folder").String(), + }, + } + + return config, nil +} + +// Validate checks that all required configuration values are set and valid. +func (c *Config) Validate() error { + if c.Server.Port <= 0 || c.Server.Port > 65535 { + return fmt.Errorf("invalid server port: %d", c.Server.Port) + } + + // Validate calendar ICS path if specified + if c.Calendar.LocalICS != "" { + if err := validateFileReadable(c.Calendar.LocalICS); err != nil { + return fmt.Errorf("calendar ICS file: %w", err) + } + } + + // Validate diary ICS path if specified + if c.Diary.ICSFile != "" { + dir := filepath.Dir(c.Diary.ICSFile) + if err := validateDirExists(dir); err != nil { + return fmt.Errorf("diary ICS directory: %w", err) + } + } + + // Validate CalDAV settings if enabled + if c.CalDAV.Enabled { + if c.CalDAV.URL == "" { + return fmt.Errorf("caldav URL is required when caldav is enabled") + } + } + + // Validate photos folder if specified + if c.Photos.RootFolder != "" { + if err := validateDirExists(c.Photos.RootFolder); err != nil { + return fmt.Errorf("photos root folder: %w", err) + } + } + + return nil +} + +func validateFileReadable(path string) error { + info, err := os.Stat(path) + if err != nil { + if os.IsNotExist(err) { + return fmt.Errorf("file does not exist: %s", path) + } + return fmt.Errorf("cannot access file: %w", err) + } + if info.IsDir() { + return fmt.Errorf("path is a directory, not a file: %s", path) + } + return nil +} + +func validateDirExists(path string) error { + info, err := os.Stat(path) + if err != nil { + if os.IsNotExist(err) { + return fmt.Errorf("directory does not exist: %s", path) + } + return fmt.Errorf("cannot access directory: %w", err) + } + if !info.IsDir() { + return fmt.Errorf("path is not a directory: %s", path) + } + return nil +} diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go new file mode 100644 index 0000000..ea3f391 --- /dev/null +++ b/internal/handlers/handlers.go @@ -0,0 +1,357 @@ +// Package handlers contains HTTP handlers for all routes. +package handlers + +import ( + "context" + "html/template" + "net/http" + "strconv" + "time" + + "github.com/luxick/chronological/internal/models" + "github.com/luxick/chronological/internal/storage" +) + +// Handlers holds all HTTP handlers and their dependencies. +type Handlers struct { + templates *template.Template + icsStore *storage.ICSStore + photoStore *storage.PhotoStore + caldavStore *storage.CalDAVStore +} + +// New creates a new Handlers instance. +func New(tmpl *template.Template, ics *storage.ICSStore, photos *storage.PhotoStore, caldav *storage.CalDAVStore) *Handlers { + return &Handlers{ + templates: tmpl, + icsStore: ics, + photoStore: photos, + caldavStore: caldav, + } +} + +// HandleIndex serves the main timeline page. +func (h *Handlers) HandleIndex(w http.ResponseWriter, r *http.Request) { + now := time.Now() + data := h.buildPageData(now.Year(), now.Month()) + h.render(w, "index.html", data) +} + +// HandleCalendar serves the calendar grid partial for HTMX. +func (h *Handlers) HandleCalendar(w http.ResponseWriter, r *http.Request) { + year, month, err := parseYearMonth(r) + if err != nil { + http.Error(w, "Invalid date", http.StatusBadRequest) + return + } + + data := h.buildCalendarData(year, month) + h.render(w, "calendar.html", data) +} + +// HandleTimeline serves the timeline partial for HTMX. +func (h *Handlers) HandleTimeline(w http.ResponseWriter, r *http.Request) { + year, month, err := parseYearMonth(r) + if err != nil { + http.Error(w, "Invalid date", http.StatusBadRequest) + return + } + + data := h.buildTimelineData(year, month) + h.render(w, "timeline.html", data) +} + +// HandleDay serves the day detail view. +func (h *Handlers) HandleDay(w http.ResponseWriter, r *http.Request) { + year, month, err := parseYearMonth(r) + if err != nil { + http.Error(w, "Invalid date", http.StatusBadRequest) + return + } + + dayStr := r.PathValue("day") + day, err := strconv.Atoi(dayStr) + if err != nil || day < 1 || day > 31 { + http.Error(w, "Invalid day", http.StatusBadRequest) + return + } + + date := time.Date(year, month, day, 0, 0, 0, 0, time.Local) + data := h.buildDayData(date) + h.render(w, "day.html", data) +} + +// HandleGetDiary serves a diary entry for a specific date. +func (h *Handlers) HandleGetDiary(w http.ResponseWriter, r *http.Request) { + date, err := parseDate(r.PathValue("date")) + if err != nil { + http.Error(w, "Invalid date", http.StatusBadRequest) + return + } + + entry, err := h.icsStore.LoadDiaryEntry(date) + if err != nil { + http.Error(w, "Failed to load diary", http.StatusInternalServerError) + return + } + + data := map[string]any{ + "Date": date, + "Entry": entry, + } + h.render(w, "diary_form.html", data) +} + +// HandleSaveDiary saves or updates a diary entry. +func (h *Handlers) HandleSaveDiary(w http.ResponseWriter, r *http.Request) { + date, err := parseDate(r.PathValue("date")) + if err != nil { + http.Error(w, "Invalid date", http.StatusBadRequest) + return + } + + if err := r.ParseForm(); err != nil { + http.Error(w, "Failed to parse form", http.StatusBadRequest) + return + } + + text := r.FormValue("text") + entry := &models.DiaryEntry{ + Date: date, + Text: text, + } + + if err := h.icsStore.SaveDiaryEntry(entry); err != nil { + http.Error(w, "Failed to save diary", http.StatusInternalServerError) + return + } + + // Return updated day content + data := h.buildDayData(date) + h.render(w, "day_content.html", data) +} + +// HandleDeleteDiary deletes a diary entry. +func (h *Handlers) HandleDeleteDiary(w http.ResponseWriter, r *http.Request) { + date, err := parseDate(r.PathValue("date")) + if err != nil { + http.Error(w, "Invalid date", http.StatusBadRequest) + return + } + + if err := h.icsStore.DeleteDiaryEntry(date); err != nil { + http.Error(w, "Failed to delete diary", http.StatusInternalServerError) + return + } + + // Return updated day content + data := h.buildDayData(date) + h.render(w, "day_content.html", data) +} + +func (h *Handlers) render(w http.ResponseWriter, name string, data any) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := h.templates.ExecuteTemplate(w, name, data); err != nil { + http.Error(w, "Template error", http.StatusInternalServerError) + } +} + +func (h *Handlers) buildPageData(year int, month time.Month) map[string]any { + return map[string]any{ + "Year": year, + "Month": month, + "Calendar": h.buildCalendarData(year, month), + "Timeline": h.buildTimelineData(year, month), + } +} + +func (h *Handlers) buildCalendarData(year int, month time.Month) map[string]any { + // Load content indicators for each day + events, _ := h.icsStore.LoadEventsForMonth(year, month) + diaries, _ := h.icsStore.LoadDiaryEntries() + photos, _ := h.photoStore.LoadPhotosForMonth(year, month) + + // Load CalDAV events if available + if h.caldavStore != nil { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + caldavEvents, err := h.caldavStore.LoadEventsForMonth(ctx, year, month) + if err == nil { + events = append(events, caldavEvents...) + } + } + + // Build day content map + days := make(map[int]*models.DayContent) + daysInMonth := time.Date(year, month+1, 0, 0, 0, 0, 0, time.Local).Day() + + for day := 1; day <= daysInMonth; day++ { + date := time.Date(year, month, day, 0, 0, 0, 0, time.Local) + content := &models.DayContent{Date: date} + + // Add events for this day + for _, event := range events { + if event.IsOnDate(date) { + content.Events = append(content.Events, event) + } + } + + // Add diary entry for this day + for _, diary := range diaries { + if diary.Date.Truncate(24 * time.Hour).Equal(date.Truncate(24 * time.Hour)) { + content.Diary = diary + break + } + } + + // Add photos for this day + for _, photo := range photos { + if photo.Date.Truncate(24 * time.Hour).Equal(date.Truncate(24 * time.Hour)) { + content.Photos = append(content.Photos, photo) + } + } + + days[day] = content + } + + // Calculate first day offset (0 = Sunday) + firstDay := time.Date(year, month, 1, 0, 0, 0, 0, time.Local) + firstDayWeekday := int(firstDay.Weekday()) + + // Previous/next month + prevMonth := time.Date(year, month-1, 1, 0, 0, 0, 0, time.Local) + nextMonth := time.Date(year, month+1, 1, 0, 0, 0, 0, time.Local) + + return map[string]any{ + "Year": year, + "Month": month, + "MonthName": month.String(), + "DaysInMonth": daysInMonth, + "FirstDayWeekday": firstDayWeekday, + "Days": days, + "PrevYear": prevMonth.Year(), + "PrevMonth": int(prevMonth.Month()), + "NextYear": nextMonth.Year(), + "NextMonth": int(nextMonth.Month()), + } +} + +func (h *Handlers) buildTimelineData(year int, month time.Month) map[string]any { + events, _ := h.icsStore.LoadEventsForMonth(year, month) + diaries, _ := h.icsStore.LoadDiaryEntries() + photos, _ := h.photoStore.LoadPhotosForMonth(year, month) + + // Load CalDAV events if available + if h.caldavStore != nil { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + caldavEvents, err := h.caldavStore.LoadEventsForMonth(ctx, year, month) + if err == nil { + events = append(events, caldavEvents...) + } + } + + // Build entries grouped by day + daysInMonth := time.Date(year, month+1, 0, 0, 0, 0, 0, time.Local).Day() + var daysWithContent []*models.DayContent + + for day := 1; day <= daysInMonth; day++ { + date := time.Date(year, month, day, 0, 0, 0, 0, time.Local) + content := &models.DayContent{Date: date} + + for _, event := range events { + if event.IsOnDate(date) { + content.Events = append(content.Events, event) + } + } + + for _, diary := range diaries { + if diary.Date.Truncate(24 * time.Hour).Equal(date.Truncate(24 * time.Hour)) { + content.Diary = diary + break + } + } + + for _, photo := range photos { + if photo.Date.Truncate(24 * time.Hour).Equal(date.Truncate(24 * time.Hour)) { + content.Photos = append(content.Photos, photo) + } + } + + if content.HasContent() { + daysWithContent = append(daysWithContent, content) + } + } + + // Previous/next month + prevMonth := time.Date(year, month-1, 1, 0, 0, 0, 0, time.Local) + nextMonth := time.Date(year, month+1, 1, 0, 0, 0, 0, time.Local) + + return map[string]any{ + "Year": year, + "Month": month, + "MonthName": month.String(), + "Days": daysWithContent, + "PrevYear": prevMonth.Year(), + "PrevMonth": int(prevMonth.Month()), + "NextYear": nextMonth.Year(), + "NextMonth": int(nextMonth.Month()), + } +} + +func (h *Handlers) buildDayData(date time.Time) map[string]any { + content := &models.DayContent{Date: date} + + events, _ := h.icsStore.LoadEventsForMonth(date.Year(), date.Month()) + for _, event := range events { + if event.IsOnDate(date) { + content.Events = append(content.Events, event) + } + } + + // Load CalDAV events if available + if h.caldavStore != nil { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + caldavEvents, err := h.caldavStore.LoadEventsForMonth(ctx, date.Year(), date.Month()) + if err == nil { + for _, event := range caldavEvents { + if event.IsOnDate(date) { + content.Events = append(content.Events, event) + } + } + } + } + + entry, _ := h.icsStore.LoadDiaryEntry(date) + content.Diary = entry + + photos, _ := h.photoStore.LoadPhotosForDate(date) + content.Photos = photos + + return map[string]any{ + "Date": date, + "Content": content, + } +} + +func parseYearMonth(r *http.Request) (int, time.Month, error) { + yearStr := r.PathValue("year") + monthStr := r.PathValue("month") + + year, err := strconv.Atoi(yearStr) + if err != nil { + return 0, 0, err + } + + monthInt, err := strconv.Atoi(monthStr) + if err != nil || monthInt < 1 || monthInt > 12 { + return 0, 0, err + } + + return year, time.Month(monthInt), nil +} + +func parseDate(dateStr string) (time.Time, error) { + return time.Parse("2006-01-02", dateStr) +} diff --git a/internal/models/diary.go b/internal/models/diary.go new file mode 100644 index 0000000..fb3a738 --- /dev/null +++ b/internal/models/diary.go @@ -0,0 +1,14 @@ +package models + +import "time" + +// DiaryEntry represents a journal entry for a specific day. +type DiaryEntry struct { + Date time.Time + Text string +} + +// DateString returns the date formatted as YYYY-MM-DD. +func (d *DiaryEntry) DateString() string { + return d.Date.Format("2006-01-02") +} diff --git a/internal/models/event.go b/internal/models/event.go new file mode 100644 index 0000000..0477d4e --- /dev/null +++ b/internal/models/event.go @@ -0,0 +1,37 @@ +// Package models defines the core data structures for the application. +package models + +import "time" + +// Event represents a calendar event. +type Event struct { + ID string + Title string + Description string + Start time.Time + End time.Time + AllDay bool + Location string + Source EventSource +} + +// EventSource indicates where an event originated from. +type EventSource string + +const ( + SourceLocal EventSource = "local" + SourceCalDAV EventSource = "caldav" +) + +// IsOnDate checks if the event occurs on the given date. +func (e *Event) IsOnDate(date time.Time) bool { + eventDate := e.Start.Truncate(24 * time.Hour) + checkDate := date.Truncate(24 * time.Hour) + + if e.AllDay { + endDate := e.End.Truncate(24 * time.Hour) + return !checkDate.Before(eventDate) && checkDate.Before(endDate) + } + + return eventDate.Equal(checkDate) +} diff --git a/internal/models/photo.go b/internal/models/photo.go new file mode 100644 index 0000000..f797459 --- /dev/null +++ b/internal/models/photo.go @@ -0,0 +1,30 @@ +package models + +import ( + "path/filepath" + "time" +) + +// Photo represents a photo with its metadata. +type Photo struct { + Date time.Time + Year string + Filename string + Description string + FullPath string +} + +// DateString returns the date formatted as YYYY-MM-DD. +func (p *Photo) DateString() string { + return p.Date.Format("2006-01-02") +} + +// URLPath returns the URL path to access this photo. +func (p *Photo) URLPath() string { + return filepath.Join("/photos", p.Year, p.Filename) +} + +// ThumbURLPath returns the URL path to access this photo's thumbnail. +func (p *Photo) ThumbURLPath() string { + return filepath.Join("/photos/thumb", p.Year, p.Filename) +} diff --git a/internal/models/timeline.go b/internal/models/timeline.go new file mode 100644 index 0000000..6c7977a --- /dev/null +++ b/internal/models/timeline.go @@ -0,0 +1,104 @@ +package models + +import ( + "sort" + "time" +) + +// TimelineEntry represents any item that can appear in the timeline. +type TimelineEntry struct { + Date time.Time + Type EntryType + Event *Event + Diary *DiaryEntry + Photo *Photo +} + +// EntryType indicates what kind of entry this is. +type EntryType string + +const ( + EntryTypeEvent EntryType = "event" + EntryTypeDiary EntryType = "diary" + EntryTypePhoto EntryType = "photo" +) + +// DayContent aggregates all content for a specific day. +type DayContent struct { + Date time.Time + Events []*Event + Diary *DiaryEntry + Photos []*Photo +} + +// HasContent returns true if there is any content for this day. +func (d *DayContent) HasContent() bool { + return len(d.Events) > 0 || d.Diary != nil || len(d.Photos) > 0 +} + +// HasEvents returns true if there are events on this day. +func (d *DayContent) HasEvents() bool { + return len(d.Events) > 0 +} + +// HasDiary returns true if there is a diary entry for this day. +func (d *DayContent) HasDiary() bool { + return d.Diary != nil +} + +// HasPhotos returns true if there are photos for this day. +func (d *DayContent) HasPhotos() bool { + return len(d.Photos) > 0 +} + +// ToTimelineEntries converts day content to a sorted slice of timeline entries. +func (d *DayContent) ToTimelineEntries() []TimelineEntry { + var entries []TimelineEntry + + for _, event := range d.Events { + entries = append(entries, TimelineEntry{ + Date: event.Start, + Type: EntryTypeEvent, + Event: event, + }) + } + + if d.Diary != nil { + entries = append(entries, TimelineEntry{ + Date: d.Diary.Date, + Type: EntryTypeDiary, + Diary: d.Diary, + }) + } + + for _, photo := range d.Photos { + entries = append(entries, TimelineEntry{ + Date: photo.Date, + Type: EntryTypePhoto, + Photo: photo, + }) + } + + sort.Slice(entries, func(i, j int) bool { + return entries[i].Date.Before(entries[j].Date) + }) + + return entries +} + +// MonthData holds all data for a specific month. +type MonthData struct { + Year int + Month time.Month + Days map[int]*DayContent +} + +// GetDay returns the day content for a specific day number. +func (m *MonthData) GetDay(day int) *DayContent { + if content, ok := m.Days[day]; ok { + return content + } + return &DayContent{ + Date: time.Date(m.Year, m.Month, day, 0, 0, 0, 0, time.Local), + } +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..f31fdf9 --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,217 @@ +// Package server sets up and runs the HTTP server. +package server + +import ( + "context" + "embed" + "fmt" + "html/template" + "io/fs" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "github.com/luxick/chronological/internal/config" + "github.com/luxick/chronological/internal/handlers" + "github.com/luxick/chronological/internal/storage" +) + +// TemplatesFS and StaticFS are set from main package where embed works +var TemplatesFS embed.FS +var StaticFS embed.FS + +// Server represents the HTTP server and its dependencies. +type Server struct { + config *config.Config + httpServer *http.Server + templates *template.Template + icsStore *storage.ICSStore + photoStore *storage.PhotoStore + caldavStore *storage.CalDAVStore +} + +// New creates a new server with the given configuration. +func New(cfg *config.Config) (*Server, error) { + s := &Server{ + config: cfg, + icsStore: storage.NewICSStore(cfg.Calendar.LocalICS, cfg.Diary.ICSFile), + photoStore: storage.NewPhotoStore(cfg.Photos.RootFolder), + } + + // Initialize CalDAV store if enabled + if cfg.CalDAV.Enabled { + s.caldavStore = storage.NewCalDAVStore(cfg.CalDAV.URL, cfg.CalDAV.Username, cfg.CalDAV.Password) + } + + // Parse templates + if err := s.parseTemplates(); err != nil { + return nil, fmt.Errorf("failed to parse templates: %w", err) + } + + return s, nil +} + +func (s *Server) parseTemplates() error { + funcMap := template.FuncMap{ + "formatDate": formatDate, + "formatTime": formatTime, + "formatDateTime": formatDateTime, + "formatMonth": formatMonth, + "daysInMonth": daysInMonth, + "weekday": weekday, + "add": add, + "sub": sub, + "seq": seq, + "isToday": isToday, + "isSameMonth": isSameMonth, + } + + // Get the templates subdirectory + templatesDir, err := fs.Sub(TemplatesFS, "templates") + if err != nil { + return fmt.Errorf("failed to get templates subdirectory: %w", err) + } + + tmpl, err := template.New("").Funcs(funcMap).ParseFS(templatesDir, + "layouts/*.html", + "partials/*.html", + "pages/*.html", + ) + if err != nil { + return fmt.Errorf("failed to parse templates: %w", err) + } + + s.templates = tmpl + return nil +} + +// Run starts the HTTP server and blocks until shutdown. +func (s *Server) Run() error { + // Connect to CalDAV if enabled + if s.caldavStore != nil { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if err := s.caldavStore.Connect(ctx); err != nil { + log.Printf("Warning: failed to connect to CalDAV server: %v", err) + } + } + + // Create handlers + h := handlers.New(s.templates, s.icsStore, s.photoStore, s.caldavStore) + + // Set up routes + mux := http.NewServeMux() + + // Static files + staticDir, err := fs.Sub(StaticFS, "static") + if err != nil { + return fmt.Errorf("failed to get static subdirectory: %w", err) + } + mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticDir)))) + + // Photo files (served from configured directory) + if s.config.Photos.RootFolder != "" { + mux.Handle("GET /photos/", http.StripPrefix("/photos/", http.FileServer(http.Dir(s.config.Photos.RootFolder)))) + } + + // Page routes + mux.HandleFunc("GET /", h.HandleIndex) + mux.HandleFunc("GET /calendar/{year}/{month}", h.HandleCalendar) + mux.HandleFunc("GET /timeline/{year}/{month}", h.HandleTimeline) + mux.HandleFunc("GET /day/{year}/{month}/{day}", h.HandleDay) + + // Diary routes + mux.HandleFunc("GET /diary/{date}", h.HandleGetDiary) + mux.HandleFunc("POST /diary/{date}", h.HandleSaveDiary) + mux.HandleFunc("DELETE /diary/{date}", h.HandleDeleteDiary) + + // Create HTTP server + s.httpServer = &http.Server{ + Addr: fmt.Sprintf(":%d", s.config.Server.Port), + Handler: mux, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + } + + // Start server in goroutine + go func() { + log.Printf("Starting server on http://localhost:%d", s.config.Server.Port) + if err := s.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("Server error: %v", err) + } + }() + + // Wait for shutdown signal + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + <-quit + + log.Println("Shutting down server...") + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + if err := s.httpServer.Shutdown(ctx); err != nil { + return fmt.Errorf("server shutdown error: %w", err) + } + + log.Println("Server stopped") + return nil +} + +// Template helper functions + +func formatDate(t time.Time) string { + return t.Format("2006-01-02") +} + +func formatTime(t time.Time) string { + return t.Format("15:04") +} + +func formatDateTime(t time.Time) string { + return t.Format("2006-01-02 15:04") +} + +func formatMonth(t time.Time) string { + return t.Format("January 2006") +} + +func daysInMonth(year int, month time.Month) int { + return time.Date(year, month+1, 0, 0, 0, 0, 0, time.Local).Day() +} + +func weekday(year int, month time.Month, day int) int { + return int(time.Date(year, month, day, 0, 0, 0, 0, time.Local).Weekday()) +} + +func add(a, b int) int { + return a + b +} + +func sub(a, b int) int { + return a - b +} + +func seq(start, end int) []int { + s := make([]int, end-start+1) + for i := range s { + s[i] = start + i + } + return s +} + +func isToday(year int, month time.Month, day int) bool { + now := time.Now() + return now.Year() == year && now.Month() == month && now.Day() == day +} + +func isSameMonth(year int, month time.Month) bool { + now := time.Now() + return now.Year() == year && now.Month() == month +} diff --git a/internal/storage/caldav.go b/internal/storage/caldav.go new file mode 100644 index 0000000..9a0d638 --- /dev/null +++ b/internal/storage/caldav.go @@ -0,0 +1,185 @@ +package storage + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/emersion/go-ical" + "github.com/emersion/go-webdav/caldav" + "github.com/luxick/chronological/internal/models" +) + +// CalDAVStore handles fetching events from a CalDAV server. +type CalDAVStore struct { + url string + username string + password string + client *caldav.Client +} + +// NewCalDAVStore creates a new CalDAV store with the given credentials. +func NewCalDAVStore(url, username, password string) *CalDAVStore { + return &CalDAVStore{ + url: url, + username: username, + password: password, + } +} + +// Connect establishes a connection to the CalDAV server. +func (s *CalDAVStore) Connect(ctx context.Context) error { + httpClient := &http.Client{ + Transport: &basicAuthTransport{ + username: s.username, + password: s.password, + }, + } + + client, err := caldav.NewClient(httpClient, s.url) + if err != nil { + return fmt.Errorf("failed to create caldav client: %w", err) + } + + s.client = client + return nil +} + +// LoadEvents fetches events from the CalDAV server for a date range. +func (s *CalDAVStore) LoadEvents(ctx context.Context, start, end time.Time) ([]*models.Event, error) { + if s.client == nil { + return nil, fmt.Errorf("caldav client not connected") + } + + principal, err := s.client.FindCurrentUserPrincipal(ctx) + if err != nil { + return nil, fmt.Errorf("failed to find user principal: %w", err) + } + + homeSet, err := s.client.FindCalendarHomeSet(ctx, principal) + if err != nil { + return nil, fmt.Errorf("failed to find calendar home set: %w", err) + } + + calendars, err := s.client.FindCalendars(ctx, homeSet) + if err != nil { + return nil, fmt.Errorf("failed to find calendars: %w", err) + } + + var allEvents []*models.Event + + for _, cal := range calendars { + query := &caldav.CalendarQuery{ + CompRequest: caldav.CalendarCompRequest{ + Name: "VCALENDAR", + Comps: []caldav.CalendarCompRequest{{ + Name: "VEVENT", + Props: []string{ + "SUMMARY", + "DESCRIPTION", + "DTSTART", + "DTEND", + "LOCATION", + "UID", + }, + }}, + }, + CompFilter: caldav.CompFilter{ + Name: "VCALENDAR", + Comps: []caldav.CompFilter{{ + Name: "VEVENT", + Start: start, + End: end, + }}, + }, + } + + objects, err := s.client.QueryCalendar(ctx, cal.Path, query) + if err != nil { + continue // Skip calendars that fail + } + + events, err := parseCalDAVObjects(objects) + if err != nil { + continue + } + + allEvents = append(allEvents, events...) + } + + return allEvents, nil +} + +// LoadEventsForMonth fetches events for a specific month. +func (s *CalDAVStore) LoadEventsForMonth(ctx context.Context, year int, month time.Month) ([]*models.Event, error) { + start := time.Date(year, month, 1, 0, 0, 0, 0, time.Local) + end := start.AddDate(0, 1, 0) + return s.LoadEvents(ctx, start, end) +} + +func parseCalDAVObjects(objects []caldav.CalendarObject) ([]*models.Event, error) { + var events []*models.Event + + for _, obj := range objects { + cal := obj.Data + if cal == nil { + continue + } + + for _, child := range cal.Children { + if child.Name != ical.CompEvent { + continue + } + + event := ical.Event{Component: child} + + uid, _ := event.Props.Text(ical.PropUID) + summary, _ := event.Props.Text(ical.PropSummary) + description, _ := event.Props.Text(ical.PropDescription) + location, _ := event.Props.Text(ical.PropLocation) + + dtstart, err := event.Props.DateTime(ical.PropDateTimeStart, time.Local) + if err != nil { + continue + } + + dtend, err := event.Props.DateTime(ical.PropDateTimeEnd, time.Local) + if err != nil { + dtend = dtstart.Add(time.Hour) + } + + // Check if all-day event + prop := event.Props.Get(ical.PropDateTimeStart) + allDay := false + if prop != nil { + valueParam := prop.Params.Get(ical.ParamValue) + allDay = valueParam == "DATE" + } + + events = append(events, &models.Event{ + ID: uid, + Title: summary, + Description: description, + Start: dtstart, + End: dtend, + AllDay: allDay, + Location: location, + Source: models.SourceCalDAV, + }) + } + } + + return events, nil +} + +// basicAuthTransport adds basic auth to HTTP requests. +type basicAuthTransport struct { + username string + password string +} + +func (t *basicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req.SetBasicAuth(t.username, t.password) + return http.DefaultTransport.RoundTrip(req) +} diff --git a/internal/storage/ics.go b/internal/storage/ics.go new file mode 100644 index 0000000..79b1c98 --- /dev/null +++ b/internal/storage/ics.go @@ -0,0 +1,341 @@ +// Package storage handles reading and writing data from various sources. +package storage + +import ( + "fmt" + "os" + "time" + + "github.com/emersion/go-ical" + "github.com/luxick/chronological/internal/models" +) + +// ICSStore handles reading and writing ICS calendar files. +type ICSStore struct { + calendarPath string + diaryPath string +} + +// NewICSStore creates a new ICS store with the given file paths. +func NewICSStore(calendarPath, diaryPath string) *ICSStore { + return &ICSStore{ + calendarPath: calendarPath, + diaryPath: diaryPath, + } +} + +// LoadEvents loads all events from the calendar ICS file. +func (s *ICSStore) LoadEvents() ([]*models.Event, error) { + if s.calendarPath == "" { + return nil, nil + } + + file, err := os.Open(s.calendarPath) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, fmt.Errorf("failed to open calendar file: %w", err) + } + defer file.Close() + + dec := ical.NewDecoder(file) + cal, err := dec.Decode() + if err != nil { + return nil, fmt.Errorf("failed to decode calendar: %w", err) + } + + return parseEventsFromCalendar(cal, models.SourceLocal) +} + +// LoadEventsForMonth loads events that occur within the specified month. +func (s *ICSStore) LoadEventsForMonth(year int, month time.Month) ([]*models.Event, error) { + allEvents, err := s.LoadEvents() + if err != nil { + return nil, err + } + + start := time.Date(year, month, 1, 0, 0, 0, 0, time.Local) + end := start.AddDate(0, 1, 0) + + var monthEvents []*models.Event + for _, event := range allEvents { + if eventInRange(event, start, end) { + monthEvents = append(monthEvents, event) + } + } + + return monthEvents, nil +} + +// LoadDiaryEntries loads all diary entries from the diary ICS file. +func (s *ICSStore) LoadDiaryEntries() ([]*models.DiaryEntry, error) { + if s.diaryPath == "" { + return nil, nil + } + + file, err := os.Open(s.diaryPath) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, fmt.Errorf("failed to open diary file: %w", err) + } + defer file.Close() + + dec := ical.NewDecoder(file) + cal, err := dec.Decode() + if err != nil { + return nil, fmt.Errorf("failed to decode diary calendar: %w", err) + } + + return parseDiaryFromCalendar(cal) +} + +// LoadDiaryEntry loads a single diary entry for a specific date. +func (s *ICSStore) LoadDiaryEntry(date time.Time) (*models.DiaryEntry, error) { + entries, err := s.LoadDiaryEntries() + if err != nil { + return nil, err + } + + targetDate := date.Truncate(24 * time.Hour) + for _, entry := range entries { + if entry.Date.Truncate(24 * time.Hour).Equal(targetDate) { + return entry, nil + } + } + + return nil, nil +} + +// SaveDiaryEntry saves or updates a diary entry for a specific date. +func (s *ICSStore) SaveDiaryEntry(entry *models.DiaryEntry) error { + if s.diaryPath == "" { + return fmt.Errorf("diary path not configured") + } + + var cal *ical.Calendar + + // Try to load existing calendar + file, err := os.Open(s.diaryPath) + if err == nil { + dec := ical.NewDecoder(file) + cal, err = dec.Decode() + file.Close() + if err != nil { + cal = nil + } + } + + // Create new calendar if none exists + if cal == nil { + cal = ical.NewCalendar() + cal.Props.SetText(ical.PropVersion, "2.0") + cal.Props.SetText(ical.PropProductID, "-//Chronological//Diary//EN") + } + + targetDate := entry.Date.Truncate(24 * time.Hour) + found := false + + // Update existing entry if found + for _, child := range cal.Children { + if child.Name != ical.CompEvent { + continue + } + event := ical.Event{Component: child} + summary, _ := event.Props.Text(ical.PropSummary) + if summary != "Chronolog" { + continue + } + + dtstart, err := event.Props.DateTime(ical.PropDateTimeStart, time.Local) + if err != nil { + continue + } + + if dtstart.Truncate(24 * time.Hour).Equal(targetDate) { + event.Props.SetText(ical.PropDescription, entry.Text) + found = true + break + } + } + + // Create new entry if not found + if !found { + event := ical.NewEvent() + event.Props.SetText(ical.PropUID, fmt.Sprintf("chronolog-%s@chronological", entry.DateString())) + event.Props.SetDateTime(ical.PropDateTimeStamp, time.Now()) + event.Props.SetDate(ical.PropDateTimeStart, targetDate) + event.Props.SetDate(ical.PropDateTimeEnd, targetDate.AddDate(0, 0, 1)) + event.Props.SetText(ical.PropSummary, "Chronolog") + event.Props.SetText(ical.PropDescription, entry.Text) + cal.Children = append(cal.Children, event.Component) + } + + // Write calendar back to file + outFile, err := os.Create(s.diaryPath) + if err != nil { + return fmt.Errorf("failed to create diary file: %w", err) + } + defer outFile.Close() + + enc := ical.NewEncoder(outFile) + if err := enc.Encode(cal); err != nil { + return fmt.Errorf("failed to encode diary calendar: %w", err) + } + + return nil +} + +// DeleteDiaryEntry removes a diary entry for a specific date. +func (s *ICSStore) DeleteDiaryEntry(date time.Time) error { + if s.diaryPath == "" { + return fmt.Errorf("diary path not configured") + } + + file, err := os.Open(s.diaryPath) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return fmt.Errorf("failed to open diary file: %w", err) + } + + dec := ical.NewDecoder(file) + cal, err := dec.Decode() + file.Close() + if err != nil { + return fmt.Errorf("failed to decode diary calendar: %w", err) + } + + targetDate := date.Truncate(24 * time.Hour) + var newChildren []*ical.Component + + for _, child := range cal.Children { + keep := true + + if child.Name == ical.CompEvent { + event := ical.Event{Component: child} + summary, _ := event.Props.Text(ical.PropSummary) + if summary == "Chronolog" { + dtstart, err := event.Props.DateTime(ical.PropDateTimeStart, time.Local) + if err == nil && dtstart.Truncate(24*time.Hour).Equal(targetDate) { + keep = false + } + } + } + + if keep { + newChildren = append(newChildren, child) + } + } + + cal.Children = newChildren + + outFile, err := os.Create(s.diaryPath) + if err != nil { + return fmt.Errorf("failed to create diary file: %w", err) + } + defer outFile.Close() + + enc := ical.NewEncoder(outFile) + if err := enc.Encode(cal); err != nil { + return fmt.Errorf("failed to encode diary calendar: %w", err) + } + + return nil +} + +func parseEventsFromCalendar(cal *ical.Calendar, source models.EventSource) ([]*models.Event, error) { + var events []*models.Event + + for _, child := range cal.Children { + if child.Name != ical.CompEvent { + continue + } + + event := ical.Event{Component: child} + + uid, _ := event.Props.Text(ical.PropUID) + summary, _ := event.Props.Text(ical.PropSummary) + description, _ := event.Props.Text(ical.PropDescription) + location, _ := event.Props.Text(ical.PropLocation) + + dtstart, err := event.Props.DateTime(ical.PropDateTimeStart, time.Local) + if err != nil { + // Try date-only format for all-day events + dtstart, err = event.Props.DateTime(ical.PropDateTimeStart, time.Local) + if err != nil { + continue + } + } + + dtend, err := event.Props.DateTime(ical.PropDateTimeEnd, time.Local) + if err != nil { + dtend = dtstart.Add(time.Hour) + } + + // Check if all-day event (date-only, no time component) + allDay := isAllDayEvent(&event) + + events = append(events, &models.Event{ + ID: uid, + Title: summary, + Description: description, + Start: dtstart, + End: dtend, + AllDay: allDay, + Location: location, + Source: source, + }) + } + + return events, nil +} + +func parseDiaryFromCalendar(cal *ical.Calendar) ([]*models.DiaryEntry, error) { + var entries []*models.DiaryEntry + + for _, child := range cal.Children { + if child.Name != ical.CompEvent { + continue + } + + event := ical.Event{Component: child} + + summary, _ := event.Props.Text(ical.PropSummary) + if summary != "Chronolog" { + continue + } + + dtstart, err := event.Props.DateTime(ical.PropDateTimeStart, time.Local) + if err != nil { + continue + } + + description, _ := event.Props.Text(ical.PropDescription) + + entries = append(entries, &models.DiaryEntry{ + Date: dtstart.Truncate(24 * time.Hour), + Text: description, + }) + } + + return entries, nil +} + +func isAllDayEvent(event *ical.Event) bool { + prop := event.Props.Get(ical.PropDateTimeStart) + if prop == nil { + return false + } + + // All-day events have VALUE=DATE parameter + valueParam := prop.Params.Get(ical.ParamValue) + return valueParam == "DATE" +} + +func eventInRange(event *models.Event, start, end time.Time) bool { + return event.Start.Before(end) && event.End.After(start) +} diff --git a/internal/storage/photos.go b/internal/storage/photos.go new file mode 100644 index 0000000..a801715 --- /dev/null +++ b/internal/storage/photos.go @@ -0,0 +1,167 @@ +package storage + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/luxick/chronological/internal/models" +) + +// PhotoStore handles scanning and serving photos from the filesystem. +type PhotoStore struct { + rootFolder string +} + +// NewPhotoStore creates a new photo store with the given root folder. +func NewPhotoStore(rootFolder string) *PhotoStore { + return &PhotoStore{ + rootFolder: rootFolder, + } +} + +// Supported image extensions +var supportedExtensions = map[string]bool{ + ".jpg": true, + ".jpeg": true, + ".png": true, + ".gif": true, + ".webp": true, +} + +// Filename pattern: YYYY-MM-DD_description.ext +var filenamePattern = regexp.MustCompile(`^(\d{4})-(\d{2})-(\d{2})_(.+)\.(\w+)$`) + +// LoadAllPhotos scans and loads all photos from the configured directory. +func (s *PhotoStore) LoadAllPhotos() ([]*models.Photo, error) { + if s.rootFolder == "" { + return nil, nil + } + + var photos []*models.Photo + + // Walk through year folders + entries, err := os.ReadDir(s.rootFolder) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, fmt.Errorf("failed to read photo root folder: %w", err) + } + + for _, entry := range entries { + if !entry.IsDir() { + continue + } + + yearFolder := entry.Name() + yearPath := filepath.Join(s.rootFolder, yearFolder) + + yearPhotos, err := s.loadPhotosFromYear(yearFolder, yearPath) + if err != nil { + continue // Skip problematic folders + } + + photos = append(photos, yearPhotos...) + } + + return photos, nil +} + +// LoadPhotosForMonth loads photos for a specific month. +func (s *PhotoStore) LoadPhotosForMonth(year int, month time.Month) ([]*models.Photo, error) { + allPhotos, err := s.LoadAllPhotos() + if err != nil { + return nil, err + } + + var monthPhotos []*models.Photo + for _, photo := range allPhotos { + if photo.Date.Year() == year && photo.Date.Month() == month { + monthPhotos = append(monthPhotos, photo) + } + } + + return monthPhotos, nil +} + +// LoadPhotosForDate loads photos for a specific date. +func (s *PhotoStore) LoadPhotosForDate(date time.Time) ([]*models.Photo, error) { + allPhotos, err := s.LoadAllPhotos() + if err != nil { + return nil, err + } + + targetDate := date.Truncate(24 * time.Hour) + var datePhotos []*models.Photo + + for _, photo := range allPhotos { + if photo.Date.Truncate(24 * time.Hour).Equal(targetDate) { + datePhotos = append(datePhotos, photo) + } + } + + return datePhotos, nil +} + +// GetPhotoPath returns the full filesystem path for a photo. +func (s *PhotoStore) GetPhotoPath(year, filename string) string { + return filepath.Join(s.rootFolder, year, filename) +} + +func (s *PhotoStore) loadPhotosFromYear(yearFolder, yearPath string) ([]*models.Photo, error) { + var photos []*models.Photo + + entries, err := os.ReadDir(yearPath) + if err != nil { + return nil, err + } + + for _, entry := range entries { + if entry.IsDir() { + continue + } + + filename := entry.Name() + ext := strings.ToLower(filepath.Ext(filename)) + + if !supportedExtensions[ext] { + continue + } + + photo := parsePhotoFilename(yearFolder, filename, filepath.Join(yearPath, filename)) + if photo != nil { + photos = append(photos, photo) + } + } + + return photos, nil +} + +func parsePhotoFilename(yearFolder, filename, fullPath string) *models.Photo { + matches := filenamePattern.FindStringSubmatch(filename) + if matches == nil { + return nil + } + + dateStr := fmt.Sprintf("%s-%s-%s", matches[1], matches[2], matches[3]) + date, err := time.Parse("2006-01-02", dateStr) + if err != nil { + return nil + } + + description := matches[4] + // Convert underscores and camelCase to spaces for display + description = strings.ReplaceAll(description, "_", " ") + + return &models.Photo{ + Date: date, + Year: yearFolder, + Filename: filename, + Description: description, + FullPath: fullPath, + } +} diff --git a/web/embed.go b/web/embed.go new file mode 100644 index 0000000..7a8c01f --- /dev/null +++ b/web/embed.go @@ -0,0 +1,10 @@ +// Package web provides embedded static assets and templates. +package web + +import "embed" + +//go:embed all:templates +var TemplatesFS embed.FS + +//go:embed all:static +var StaticFS embed.FS diff --git a/web/static/css/style.css b/web/static/css/style.css new file mode 100644 index 0000000..c9c381e --- /dev/null +++ b/web/static/css/style.css @@ -0,0 +1,517 @@ +/* Chronological - Main Stylesheet */ + +/* CSS Reset and Base Styles */ +*, *::before, *::after { + box-sizing: border-box; +} + +:root { + --color-primary: #3b82f6; + --color-primary-dark: #2563eb; + --color-secondary: #64748b; + --color-success: #22c55e; + --color-danger: #ef4444; + --color-warning: #f59e0b; + + --color-bg: #f8fafc; + --color-surface: #ffffff; + --color-border: #e2e8f0; + --color-text: #1e293b; + --color-text-muted: #64748b; + + --spacing-xs: 0.25rem; + --spacing-sm: 0.5rem; + --spacing-md: 1rem; + --spacing-lg: 1.5rem; + --spacing-xl: 2rem; + + --radius-sm: 0.25rem; + --radius-md: 0.5rem; + --radius-lg: 1rem; + + --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05); + --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1); + --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1); + + --font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + --font-size-sm: 0.875rem; + --font-size-md: 1rem; + --font-size-lg: 1.25rem; + --font-size-xl: 1.5rem; +} + +html, body { + margin: 0; + padding: 0; + font-family: var(--font-family); + font-size: var(--font-size-md); + line-height: 1.5; + color: var(--color-text); + background-color: var(--color-bg); + min-height: 100vh; +} + +/* App Layout */ +.app-header { + background-color: var(--color-primary); + color: white; + padding: var(--spacing-md) var(--spacing-lg); + box-shadow: var(--shadow-md); +} + +.app-header h1 { + margin: 0; + font-size: var(--font-size-xl); + font-weight: 600; +} + +.app-main { + height: calc(100vh - 60px); + overflow: hidden; +} + +/* Timeline Container - Split Layout */ +.timeline-container { + display: grid; + grid-template-columns: 350px 1fr; + height: 100%; +} + +/* Calendar Panel */ +.calendar-panel { + background-color: var(--color-surface); + border-right: 1px solid var(--color-border); + padding: var(--spacing-lg); + overflow-y: auto; +} + +.calendar { + max-width: 320px; + margin: 0 auto; +} + +.calendar-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: var(--spacing-md); +} + +.calendar-header h2 { + margin: 0; + font-size: var(--font-size-lg); + font-weight: 600; +} + +.nav-btn { + background: none; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + padding: var(--spacing-xs) var(--spacing-sm); + cursor: pointer; + font-size: var(--font-size-lg); + color: var(--color-text); + transition: background-color 0.2s, border-color 0.2s; +} + +.nav-btn:hover { + background-color: var(--color-bg); + border-color: var(--color-primary); +} + +.calendar-weekdays { + display: grid; + grid-template-columns: repeat(7, 1fr); + text-align: center; + font-size: var(--font-size-sm); + font-weight: 600; + color: var(--color-text-muted); + margin-bottom: var(--spacing-sm); +} + +.calendar-grid { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 2px; +} + +.calendar-day { + aspect-ratio: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: var(--color-bg); + border-radius: var(--radius-sm); + cursor: pointer; + transition: background-color 0.2s; + position: relative; + padding: 2px; +} + +.calendar-day:hover { + background-color: var(--color-border); +} + +.calendar-day.empty { + background: none; + cursor: default; +} + +.calendar-day.today { + background-color: var(--color-primary); + color: white; +} + +.calendar-day.today:hover { + background-color: var(--color-primary-dark); +} + +.calendar-day.has-content { + font-weight: 600; +} + +.day-number { + font-size: var(--font-size-sm); +} + +.day-indicators { + display: flex; + gap: 1px; + font-size: 0.6rem; + position: absolute; + bottom: 2px; +} + +.indicator { + line-height: 1; +} + +.calendar-actions { + margin-top: var(--spacing-lg); + text-align: center; +} + +/* Timeline Panel */ +.timeline-panel { + padding: var(--spacing-lg); + overflow-y: auto; +} + +.timeline { + max-width: 800px; + margin: 0 auto; +} + +.timeline-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: var(--spacing-lg); + padding-bottom: var(--spacing-md); + border-bottom: 2px solid var(--color-border); +} + +.timeline-header h2 { + margin: 0; + font-size: var(--font-size-xl); +} + +.timeline-content { + display: flex; + flex-direction: column; + gap: var(--spacing-lg); +} + +.timeline-day { + background-color: var(--color-surface); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); + overflow: hidden; +} + +.timeline-day-header { + background-color: var(--color-bg); + padding: var(--spacing-md) var(--spacing-lg); + border-bottom: 1px solid var(--color-border); +} + +.timeline-day-header time { + font-weight: 600; + color: var(--color-primary); +} + +.timeline-entries { + padding: var(--spacing-md) var(--spacing-lg); + display: flex; + flex-direction: column; + gap: var(--spacing-md); +} + +.timeline-entry { + display: flex; + gap: var(--spacing-md); + padding: var(--spacing-md); + background-color: var(--color-bg); + border-radius: var(--radius-md); +} + +.entry-icon { + font-size: 1.5rem; + flex-shrink: 0; +} + +.entry-content { + flex-grow: 1; + min-width: 0; +} + +.entry-content h4 { + margin: 0 0 var(--spacing-xs); + font-size: var(--font-size-md); +} + +.entry-time { + font-size: var(--font-size-sm); + color: var(--color-text-muted); + margin-right: var(--spacing-sm); +} + +.entry-location { + font-size: var(--font-size-sm); + color: var(--color-text-muted); +} + +.entry-description { + margin: var(--spacing-sm) 0 0; + color: var(--color-text-muted); + font-size: var(--font-size-sm); +} + +.diary-text { + white-space: pre-wrap; +} + +.timeline-empty { + text-align: center; + padding: var(--spacing-xl); + color: var(--color-text-muted); +} + +/* Photo Grid */ +.photo-grid, .photo-gallery { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); + gap: var(--spacing-md); + margin-top: var(--spacing-sm); +} + +.photo-item { + margin: 0; +} + +.photo-item img { + width: 100%; + height: 150px; + object-fit: cover; + border-radius: var(--radius-md); + cursor: pointer; + transition: transform 0.2s; +} + +.photo-item img:hover { + transform: scale(1.02); +} + +.photo-item figcaption { + font-size: var(--font-size-sm); + color: var(--color-text-muted); + margin-top: var(--spacing-xs); + text-align: center; +} + +/* Day Modal */ +.day-modal { + border: none; + border-radius: var(--radius-lg); + box-shadow: var(--shadow-lg); + max-width: 600px; + width: 90%; + padding: 0; +} + +.day-modal::backdrop { + background-color: rgba(0, 0, 0, 0.5); +} + +.day-detail { + padding: var(--spacing-lg); +} + +.day-header { + margin-bottom: var(--spacing-lg); + padding-bottom: var(--spacing-md); + border-bottom: 2px solid var(--color-border); +} + +.day-header h2 { + margin: 0; + font-size: var(--font-size-lg); +} + +.day-section { + margin-bottom: var(--spacing-lg); +} + +.day-section h3 { + margin: 0 0 var(--spacing-md); + font-size: var(--font-size-md); + color: var(--color-text-muted); +} + +.event-list { + list-style: none; + padding: 0; + margin: 0; +} + +.event-item { + padding: var(--spacing-sm); + background-color: var(--color-bg); + border-radius: var(--radius-sm); + margin-bottom: var(--spacing-sm); +} + +.event-item strong { + display: block; + margin-bottom: var(--spacing-xs); +} + +.empty-message { + color: var(--color-text-muted); + font-style: italic; +} + +/* Form Elements */ +textarea { + width: 100%; + padding: var(--spacing-md); + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + font-family: inherit; + font-size: var(--font-size-md); + resize: vertical; + min-height: 100px; +} + +textarea:focus { + outline: none; + border-color: var(--color-primary); + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); +} + +.form-actions { + display: flex; + gap: var(--spacing-sm); + margin-top: var(--spacing-md); +} + +/* Buttons */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + padding: var(--spacing-sm) var(--spacing-md); + border: none; + border-radius: var(--radius-md); + font-family: inherit; + font-size: var(--font-size-sm); + font-weight: 500; + cursor: pointer; + transition: background-color 0.2s, transform 0.1s; +} + +.btn:hover { + transform: translateY(-1px); +} + +.btn:active { + transform: translateY(0); +} + +.btn-primary { + background-color: var(--color-primary); + color: white; +} + +.btn-primary:hover { + background-color: var(--color-primary-dark); +} + +.btn-secondary { + background-color: var(--color-border); + color: var(--color-text); +} + +.btn-secondary:hover { + background-color: var(--color-secondary); + color: white; +} + +.btn-danger { + background-color: var(--color-danger); + color: white; +} + +.btn-danger:hover { + background-color: #dc2626; +} + +.btn-small { + padding: var(--spacing-xs) var(--spacing-sm); + font-size: var(--font-size-sm); +} + +/* Responsive Design */ +@media (max-width: 768px) { + .timeline-container { + grid-template-columns: 1fr; + grid-template-rows: auto 1fr; + } + + .calendar-panel { + border-right: none; + border-bottom: 1px solid var(--color-border); + max-height: 50vh; + } + + .calendar { + max-width: none; + } +} + +/* HTMX Loading Indicator */ +.htmx-request { + opacity: 0.7; + pointer-events: none; +} + +.htmx-request::after { + content: ''; + position: absolute; + top: 50%; + left: 50%; + width: 20px; + height: 20px; + margin: -10px 0 0 -10px; + border: 2px solid var(--color-border); + border-top-color: var(--color-primary); + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} diff --git a/web/static/js/app.js b/web/static/js/app.js new file mode 100644 index 0000000..0887ce9 --- /dev/null +++ b/web/static/js/app.js @@ -0,0 +1,74 @@ +// Chronological - Minimal JavaScript +// Most interactivity is handled by HTMX + +document.addEventListener('DOMContentLoaded', function() { + // Close modal when clicking backdrop + document.querySelectorAll('dialog').forEach(function(dialog) { + dialog.addEventListener('click', function(event) { + if (event.target === dialog) { + dialog.close(); + } + }); + }); + + // Event delegation for dynamic content + document.body.addEventListener('click', function(event) { + var target = event.target; + + // Handle modal opening via data attribute + var modalOpener = target.closest('[data-opens-modal]'); + if (modalOpener) { + var modalId = modalOpener.getAttribute('data-opens-modal'); + var modal = document.getElementById(modalId); + if (modal && modal.showModal) { + modal.showModal(); + } + } + + // Handle diary edit toggle + if (target.matches('[data-action="toggle-diary-edit"]')) { + var display = target.closest('.diary-display'); + if (display) { + display.style.display = 'none'; + var editForm = display.nextElementSibling; + if (editForm) { + editForm.style.display = 'block'; + } + } + } + + // Handle diary edit cancel + if (target.matches('[data-action="cancel-diary-edit"]')) { + var editDiv = target.closest('.diary-edit'); + if (editDiv) { + editDiv.style.display = 'none'; + var displayDiv = editDiv.previousElementSibling; + if (displayDiv) { + displayDiv.style.display = 'block'; + } + } + } + }); +}); + +// Handle keyboard shortcuts +document.addEventListener('keydown', function(event) { + // Close modal on Escape + if (event.key === 'Escape') { + document.querySelectorAll('dialog[open]').forEach(function(dialog) { + dialog.close(); + }); + } +}); + +// HTMX event handlers +document.body.addEventListener('htmx:afterSwap', function(event) { + // Re-initialize any dynamic elements after HTMX swaps + if (event.detail.target.id === 'day-modal-content') { + // Focus textarea when opening day modal with diary form + var textarea = event.detail.target.querySelector('textarea'); + if (textarea) { + textarea.focus(); + } + } +}); diff --git a/web/static/js/htmx.min.js b/web/static/js/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/web/static/js/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/web/templates/layouts/base.html b/web/templates/layouts/base.html new file mode 100644 index 0000000..21d944f --- /dev/null +++ b/web/templates/layouts/base.html @@ -0,0 +1,21 @@ +{{define "base"}} + + + + + + Chronological + + + + +
+

Chronological

+
+
+ {{template "content" .}} +
+ + + +{{end}} diff --git a/web/templates/pages/index.html b/web/templates/pages/index.html new file mode 100644 index 0000000..74a3305 --- /dev/null +++ b/web/templates/pages/index.html @@ -0,0 +1,14 @@ +{{define "index.html"}} +{{template "base" .}} +{{end}} + +{{define "content"}} +
+ +
+ {{template "timeline.html" .Timeline}} +
+
+{{end}} diff --git a/web/templates/partials/calendar.html b/web/templates/partials/calendar.html new file mode 100644 index 0000000..df74d71 --- /dev/null +++ b/web/templates/partials/calendar.html @@ -0,0 +1,80 @@ +{{define "calendar.html"}} +
+
+ +

{{.MonthName}} {{.Year}}

+ +
+ +
+ Sun + Mon + Tue + Wed + Thu + Fri + Sat +
+ +
+ {{/* Empty cells before first day */}} + {{range seq 0 (sub .FirstDayWeekday 1)}} +
+ {{end}} + + {{/* Day cells */}} + {{range $day := seq 1 .DaysInMonth}} + {{$content := index $.Days $day}} +
+ {{$day}} + {{if $content.HasContent}} +
+ {{if $content.HasEvents}}📅{{end}} + {{if $content.HasDiary}}📝{{end}} + {{if $content.HasPhotos}}📷{{end}} +
+ {{end}} +
+ {{end}} +
+ +
+ +
+
+ + +
+ +
+
+ +
+
+{{end}} diff --git a/web/templates/partials/day.html b/web/templates/partials/day.html new file mode 100644 index 0000000..9a6aa4a --- /dev/null +++ b/web/templates/partials/day.html @@ -0,0 +1,112 @@ +{{define "day.html"}} +
+
+

{{.Date.Format "Monday, January 2, 2006"}}

+
+ +
+ {{template "day_content.html" .}} +
+
+{{end}} + +{{define "day_content.html"}} +
+ {{/* Events Section */}} +
+

📅 Events

+ {{if .Content.Events}} +
    + {{range .Content.Events}} +
  • + {{.Title}} + {{if not .AllDay}} + {{formatTime .Start}} - {{formatTime .End}} + {{else}} + All day + {{end}} + {{if .Location}} + 📍 {{.Location}} + {{end}} + {{if .Description}} +

    {{.Description}}

    + {{end}} +
  • + {{end}} +
+ {{else}} +

No events scheduled.

+ {{end}} +
+ + {{/* Diary Section */}} +
+

📝 Journal

+ {{if .Content.Diary}} +
+

{{.Content.Diary.Text}}

+ +
+ + {{else}} +
+ +
+ +
+
+ {{end}} +
+ + {{/* Photos Section */}} +
+

📷 Photos

+ {{if .Content.Photos}} + + {{else}} +

No photos for this day.

+ {{end}} +
+
+{{end}} diff --git a/web/templates/partials/diary_form.html b/web/templates/partials/diary_form.html new file mode 100644 index 0000000..47ababa --- /dev/null +++ b/web/templates/partials/diary_form.html @@ -0,0 +1,26 @@ +{{define "diary_form.html"}} +
+

Journal Entry - {{.Date.Format "January 2, 2006"}}

+
+ +
+ + {{if .Entry}} + + {{end}} +
+
+
+{{end}} diff --git a/web/templates/partials/timeline.html b/web/templates/partials/timeline.html new file mode 100644 index 0000000..e93e2b5 --- /dev/null +++ b/web/templates/partials/timeline.html @@ -0,0 +1,93 @@ +{{define "timeline.html"}} +
+
+ +

{{.MonthName}} {{.Year}}

+ +
+ +
+ {{if .Days}} + {{range .Days}} +
+
+ +
+ +
+ {{/* Events */}} + {{range .Events}} +
+
📅
+
+

{{.Title}}

+ {{if not .AllDay}} + {{formatTime .Start}} - {{formatTime .End}} + {{else}} + All day + {{end}} + {{if .Location}} + 📍 {{.Location}} + {{end}} + {{if .Description}} +

{{.Description}}

+ {{end}} +
+
+ {{end}} + + {{/* Diary entry */}} + {{if .Diary}} +
+
📝
+
+

Journal Entry

+

{{.Diary.Text}}

+
+
+ {{end}} + + {{/* Photos */}} + {{if .Photos}} +
+
📷
+
+

Photos

+
+ {{range .Photos}} +
+ {{.Description}} +
{{.Description}}
+
+ {{end}} +
+
+
+ {{end}} +
+
+ {{end}} + {{else}} +
+

No entries for this month.

+
+ {{end}} +
+
+{{end}}