diff options
| author | Martin Kagamino Lehoux <martin@lehoux.net> | 2026-08-05 11:21:55 +0200 |
|---|---|---|
| committer | Martin Kagamino Lehoux <martin@lehoux.net> | 2026-08-05 11:21:55 +0200 |
| commit | bef31e1d35fe88f2698cf0e3191f26a79623f66f (patch) | |
| tree | 8d8e10b2a58fc4ca557f0312cfda60adfc308c30 /web | |
| parent | 69f317d8cb51b911732712a9fcc8ac49563326c6 (diff) | |
feat: Add web ride library with Strava sync
Diffstat (limited to 'web')
| -rw-r--r-- | web/server.go | 356 | ||||
| -rw-r--r-- | web/server_test.go | 133 | ||||
| -rw-r--r-- | web/templates.templ | 106 | ||||
| -rw-r--r-- | web/templates_templ.go | 381 | ||||
| -rw-r--r-- | web/views.go | 52 |
5 files changed, 1028 insertions, 0 deletions
diff --git a/web/server.go b/web/server.go new file mode 100644 index 0000000..e394eec --- /dev/null +++ b/web/server.go @@ -0,0 +1,356 @@ +package web + +import ( + "crypto/rand" + "database/sql" + "encoding/hex" + "errors" + "fmt" + "log/slog" + "net/http" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/martinlehoux/biking_home/config" + "github.com/martinlehoux/biking_home/ride" + "github.com/martinlehoux/biking_home/rides" + "github.com/martinlehoux/biking_home/strava" + "github.com/martinlehoux/kagamigo/kcore" +) + +const dateFormat = "2006-01-02" + +type Server struct { + db *sql.DB + envPath string + gpxDir string + baseURL string + + oauthMu sync.Mutex + oauthState string + returnToURL string +} + +func NewServer(db *sql.DB, envPath, gpxDir, baseURL string) *Server { + return &Server{db: db, envPath: envPath, gpxDir: gpxDir, baseURL: strings.TrimRight(baseURL, "/")} +} + +func (s *Server) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /", s.handleRides) + mux.HandleFunc("GET /sync", s.handleSyncForm) + mux.HandleFunc("POST /sync", s.handleSync) + mux.HandleFunc("GET /strava/login", s.handleStravaLogin) + mux.HandleFunc("GET /strava/callback", s.handleStravaCallback) + return kcore.RecoverMiddleware(mux) +} + +func (s *Server) ListenAndServe(addr string) error { + return http.ListenAndServe(addr, s.Handler()) +} + +func (s *Server) handleRides(w http.ResponseWriter, r *http.Request) { + items, err := rides.List(s.db) + if err != nil { + http.Error(w, "failed to load rides", http.StatusInternalServerError) + return + } + kcore.RenderPage(r.Context(), RidesPage(buildRideViews(items)), w) +} + +const minimumDisplayedDistanceM = 10_000 + +func buildRideViews(items []rides.Ride) []RideView { + parser := ride.GPXRideParser{} + views := make([]RideView, 0, len(items)) + for _, item := range items { + if item.DistanceM < minimumDisplayedDistanceM { + continue + } + view := RideView{Ride: item, Cotacol: "-"} + parsed, err := ride.ParseFile(parser, item.GPXPath) + if err != nil { + slog.Warn("Failed to compute Cotacol", "ride", item.ExternalID, "file", item.GPXPath, "error", err) + } else { + score := parsed.DifficultyScore() + view.Cotacol = formatCotacol(score) + view.CotacolPer100Km = formatCotacolPer100Km(score, item.DistanceM) + } + views = append(views, view) + } + return views +} + +func (s *Server) handleSyncForm(w http.ResponseWriter, r *http.Request) { + data := SyncPageData{ + From: queryOrDefault(r, "from", time.Now().AddDate(0, 0, -30).Format(dateFormat)), + To: queryOrDefault(r, "to", time.Now().Format(dateFormat)), + Notice: syncNotice(r), + HasAuth: s.hasStravaToken(), + } + if _, _, err := s.stravaClient(); err != nil { + data.Error = err.Error() + } + kcore.RenderPage(r.Context(), SyncPage(data), w) +} + +func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", http.StatusBadRequest) + return + } + from, to, err := parseDateRange(r.FormValue("from"), r.FormValue("to")) + if err != nil { + s.renderSyncError(w, r, r.FormValue("from"), r.FormValue("to"), err) + return + } + client, authorized, err := s.stravaClient() + if err != nil { + s.renderSyncError(w, r, r.FormValue("from"), r.FormValue("to"), err) + return + } + if !authorized { + query := url.Values{} + query.Set("return_to", "/sync?from="+r.FormValue("from")+"&to="+r.FormValue("to")) + http.Redirect(w, r, "/strava/login?"+query.Encode(), http.StatusFound) + return + } + + if refreshed, err := client.RefreshIfNeeded(); err != nil { + s.renderSyncError(w, r, r.FormValue("from"), r.FormValue("to"), err) + return + } else if refreshed { + if err := s.saveStravaToken(client); err != nil { + s.renderSyncError(w, r, r.FormValue("from"), r.FormValue("to"), err) + return + } + } + imported, skipped, err := s.syncRides(client, from, to) + if err != nil { + s.renderSyncError(w, r, r.FormValue("from"), r.FormValue("to"), err) + return + } + query := url.Values{} + query.Set("from", r.FormValue("from")) + query.Set("to", r.FormValue("to")) + query.Set("imported", strconv.Itoa(imported)) + query.Set("skipped", strconv.Itoa(skipped)) + http.Redirect(w, r, "/sync?"+query.Encode(), http.StatusSeeOther) +} + +func (s *Server) handleStravaLogin(w http.ResponseWriter, r *http.Request) { + env, err := config.LoadEnv(s.envPath) + if err != nil { + http.Error(w, "failed to load configuration", http.StatusInternalServerError) + return + } + clientID := env["STRAVA_CLIENT_ID"] + clientSecret := env["STRAVA_CLIENT_SECRET"] + if clientID == "" || clientSecret == "" { + http.Error(w, "STRAVA_CLIENT_ID and STRAVA_CLIENT_SECRET are required", http.StatusInternalServerError) + return + } + state, err := newOAuthState() + if err != nil { + http.Error(w, "failed to start OAuth flow", http.StatusInternalServerError) + return + } + returnTo := safeReturnTo(r.URL.Query().Get("return_to")) + s.oauthMu.Lock() + s.oauthState = state + s.returnToURL = returnTo + s.oauthMu.Unlock() + redirectURI := s.baseURL + "/strava/callback" + http.Redirect(w, r, strava.AuthorizeURLWithState(clientID, redirectURI, state), http.StatusFound) +} + +func (s *Server) handleStravaCallback(w http.ResponseWriter, r *http.Request) { + if callbackError := r.URL.Query().Get("error"); callbackError != "" { + http.Error(w, "Strava authorization was denied: "+callbackError, http.StatusBadRequest) + return + } + returnTo, ok := s.consumeOAuthState(r.URL.Query().Get("state")) + if !ok { + http.Error(w, "invalid OAuth state", http.StatusBadRequest) + return + } + code := r.URL.Query().Get("code") + if code == "" { + http.Error(w, "missing authorization code", http.StatusBadRequest) + return + } + env, err := config.LoadEnv(s.envPath) + if err != nil { + http.Error(w, "failed to load configuration", http.StatusInternalServerError) + return + } + redirectURI := s.baseURL + "/strava/callback" + token, err := strava.ExchangeCode(env["STRAVA_CLIENT_ID"], env["STRAVA_CLIENT_SECRET"], code, redirectURI) + if err != nil { + http.Error(w, "failed to exchange Strava authorization code", http.StatusBadGateway) + return + } + if err := config.UpdateEnv(s.envPath, map[string]string{ + "STRAVA_ACCESS_TOKEN": token.AccessToken, + "STRAVA_REFRESH_TOKEN": token.RefreshToken, + "STRAVA_EXPIRES_AT": strconv.FormatInt(token.ExpiresAt.Unix(), 10), + }); err != nil { + http.Error(w, "failed to store Strava token", http.StatusInternalServerError) + return + } + slog.Info("Strava authorization completed") + http.Redirect(w, r, returnTo, http.StatusSeeOther) +} + +func (s *Server) syncRides(client *strava.Client, from, to time.Time) (imported, skipped int, err error) { + activities, err := client.List(from, to) + if err != nil { + return 0, 0, err + } + if err := os.MkdirAll(s.gpxDir, 0o755); err != nil { + return 0, 0, fmt.Errorf("create GPX directory: %w", err) + } + for _, summary := range activities { + externalID := fmt.Sprintf("strava:%d", summary.ID) + _, exists, err := rides.GetByExternalID(s.db, externalID) + if err != nil { + return imported, skipped, err + } + if exists { + skipped++ + continue + } + activity, gpxData, err := client.Get(summary.ID) + if err != nil { + return imported, skipped, err + } + gpxPath := filepath.Join(s.gpxDir, fmt.Sprintf("activity_%d.gpx", activity.ID)) + if err := os.WriteFile(gpxPath, gpxData, 0o644); err != nil { + return imported, skipped, fmt.Errorf("write GPX for activity %d: %w", activity.ID, err) + } + activityType := activity.SportType + if activityType == "" { + activityType = activity.Type + } + if err := rides.Save(s.db, rides.Ride{ + ExternalID: externalID, + GPXPath: gpxPath, + Name: activity.Name, + Type: activityType, + StartDate: activity.StartDate, + DistanceM: activity.DistanceM, + MovingTimeS: activity.MovingTimeS, + ElapsedTimeS: activity.ElapsedTimeS, + TotalElevationGainM: activity.TotalElevationGainM, + AverageSpeedMps: activity.AverageSpeedMps, + }); err != nil { + return imported, skipped, fmt.Errorf("save activity %d: %w", activity.ID, err) + } + imported++ + slog.Info("Imported Strava ride", "activity", activity.ID, "name", activity.Name) + } + return imported, skipped, nil +} + +func (s *Server) stravaClient() (*strava.Client, bool, error) { + env, err := config.LoadEnv(s.envPath) + if err != nil { + return nil, false, fmt.Errorf("load configuration: %w", err) + } + if env["STRAVA_CLIENT_ID"] == "" || env["STRAVA_CLIENT_SECRET"] == "" { + return nil, false, errors.New("STRAVA_CLIENT_ID and STRAVA_CLIENT_SECRET are required") + } + if env["STRAVA_ACCESS_TOKEN"] == "" || env["STRAVA_REFRESH_TOKEN"] == "" { + return nil, false, nil + } + var expiresAt time.Time + if unix, err := strconv.ParseInt(env["STRAVA_EXPIRES_AT"], 10, 64); err == nil && unix != 0 { + expiresAt = time.Unix(unix, 0) + } + return strava.NewClient(env["STRAVA_CLIENT_ID"], env["STRAVA_CLIENT_SECRET"], strava.Token{ + AccessToken: env["STRAVA_ACCESS_TOKEN"], + RefreshToken: env["STRAVA_REFRESH_TOKEN"], + ExpiresAt: expiresAt, + }), true, nil +} + +func (s *Server) saveStravaToken(client *strava.Client) error { + token := client.Tokens() + return config.UpdateEnv(s.envPath, map[string]string{ + "STRAVA_ACCESS_TOKEN": token.AccessToken, + "STRAVA_REFRESH_TOKEN": token.RefreshToken, + "STRAVA_EXPIRES_AT": strconv.FormatInt(token.ExpiresAt.Unix(), 10), + }) +} + +func (s *Server) hasStravaToken() bool { + _, authorized, err := s.stravaClient() + return err == nil && authorized +} + +func (s *Server) consumeOAuthState(state string) (string, bool) { + s.oauthMu.Lock() + defer s.oauthMu.Unlock() + if state == "" || state != s.oauthState { + return "", false + } + returnTo := s.returnToURL + s.oauthState = "" + s.returnToURL = "" + return returnTo, true +} + +func (s *Server) renderSyncError(w http.ResponseWriter, r *http.Request, from, to string, err error) { + w.WriteHeader(http.StatusBadRequest) + kcore.RenderPage(r.Context(), SyncPage(SyncPageData{From: from, To: to, Error: err.Error(), HasAuth: s.hasStravaToken()}), w) +} + +func newOAuthState() (string, error) { + data := make([]byte, 32) + if _, err := rand.Read(data); err != nil { + return "", err + } + return hex.EncodeToString(data), nil +} + +func parseDateRange(from, to string) (time.Time, time.Time, error) { + start, err := time.Parse(dateFormat, from) + if err != nil { + return time.Time{}, time.Time{}, errors.New("a valid start date is required") + } + end, err := time.Parse(dateFormat, to) + if err != nil { + return time.Time{}, time.Time{}, errors.New("a valid end date is required") + } + if end.Before(start) { + return time.Time{}, time.Time{}, errors.New("the end date must not be before the start date") + } + return start.UTC(), end.AddDate(0, 0, 1).UTC(), nil +} + +func queryOrDefault(r *http.Request, key, fallback string) string { + if value := r.URL.Query().Get(key); value != "" { + return value + } + return fallback +} + +func syncNotice(r *http.Request) string { + imported := r.URL.Query().Get("imported") + if imported == "" { + return "" + } + return fmt.Sprintf("Sync complete: %s imported, %s already stored.", imported, r.URL.Query().Get("skipped")) +} + +func safeReturnTo(value string) string { + if value == "" || !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") { + return "/sync" + } + return value +} diff --git a/web/server_test.go b/web/server_test.go new file mode 100644 index 0000000..8d3f653 --- /dev/null +++ b/web/server_test.go @@ -0,0 +1,133 @@ +package web + +import ( + "database/sql" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/martinlehoux/biking_home/rides" + _ "github.com/mattn/go-sqlite3" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func newWebTestServer(t *testing.T) (*Server, *sql.DB) { + t.Helper() + db, err := sql.Open("sqlite3", ":memory:") + require.NoError(t, err) + t.Cleanup(func() { db.Close() }) + _, err = db.Exec(` + create table rides ( + id integer primary key, + external_id text unique not null, + gpx_path text not null, + name text not null, + type text not null, + start_date text not null, + distance_m real not null, + moving_time_s integer not null, + elapsed_time_s integer not null, + total_elevation_gain_m real not null, + average_speed_mps real not null, + created_at text not null default (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + updated_at text not null default (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) + ) + `) + require.NoError(t, err) + envPath := filepath.Join(t.TempDir(), ".env") + require.NoError(t, os.WriteFile(envPath, []byte("STRAVA_CLIENT_ID=123\nSTRAVA_CLIENT_SECRET=secret\n"), 0o600)) + return NewServer(db, envPath, t.TempDir(), "http://localhost:8080"), db +} + +func TestHandlerRendersRidesPage(t *testing.T) { + server, db := newWebTestServer(t) + require.NoError(t, rides.Save(db, rides.Ride{ + ExternalID: "strava:1234", + GPXPath: "missing.gpx", + Name: "Long Ride", + Type: "Ride", + StartDate: time.Date(2026, 8, 1, 7, 0, 0, 0, time.UTC), + DistanceM: 20_000, + })) + require.NoError(t, rides.Save(db, rides.Ride{ + ExternalID: "strava:5678", + GPXPath: "short.gpx", + Name: "Short Ride", + Type: "Ride", + StartDate: time.Date(2026, 8, 2, 7, 0, 0, 0, time.UTC), + DistanceM: 9_999, + })) + req := httptest.NewRequest(http.MethodGet, "/", nil) + response := httptest.NewRecorder() + + server.Handler().ServeHTTP(response, req) + + assert.Equal(t, http.StatusOK, response.Code) + assert.Contains(t, response.Body.String(), "All rides") + assert.Contains(t, response.Body.String(), "Long Ride") + assert.NotContains(t, response.Body.String(), "Short Ride") + assert.Contains(t, response.Body.String(), "Cotacol") + assert.Contains(t, response.Body.String(), "Cotacol / 100 km") +} + +func TestSyncPageRequestsAuthorization(t *testing.T) { + server, _ := newWebTestServer(t) + req := httptest.NewRequest(http.MethodGet, "/sync", nil) + response := httptest.NewRecorder() + + server.Handler().ServeHTTP(response, req) + + assert.Equal(t, http.StatusOK, response.Code) + assert.Contains(t, response.Body.String(), "Authorize Strava") +} + +func TestSyncRedirectsToOAuthWhenUnauthenticated(t *testing.T) { + server, _ := newWebTestServer(t) + form := url.Values{"from": {"2026-08-01"}, "to": {"2026-08-04"}} + req := httptest.NewRequest(http.MethodPost, "/sync", strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + response := httptest.NewRecorder() + + server.Handler().ServeHTTP(response, req) + + assert.Equal(t, http.StatusFound, response.Code) + location, err := url.Parse(response.Header().Get("Location")) + require.NoError(t, err) + assert.Equal(t, "/strava/login", location.Path) + assert.Equal(t, "/sync?from=2026-08-01&to=2026-08-04", location.Query().Get("return_to")) +} + +func TestStravaLoginRedirectsToAuthorize(t *testing.T) { + server, _ := newWebTestServer(t) + req := httptest.NewRequest(http.MethodGet, "/strava/login?return_to=/sync", nil) + response := httptest.NewRecorder() + + server.Handler().ServeHTTP(response, req) + + assert.Equal(t, http.StatusFound, response.Code) + location, err := url.Parse(response.Header().Get("Location")) + require.NoError(t, err) + assert.Equal(t, "www.strava.com", location.Host) + assert.Equal(t, "/oauth/authorize", location.Path) + assert.Equal(t, "activity:read_all", location.Query().Get("scope")) + assert.Equal(t, "http://localhost:8080/strava/callback", location.Query().Get("redirect_uri")) + assert.NotEmpty(t, location.Query().Get("state")) +} + +func TestParseDateRangeMakesEndInclusive(t *testing.T) { + from, to, err := parseDateRange("2026-08-01", "2026-08-04") + require.NoError(t, err) + assert.Equal(t, "2026-08-01T00:00:00Z", from.Format("2006-01-02T15:04:05Z07:00")) + assert.Equal(t, "2026-08-05T00:00:00Z", to.Format("2006-01-02T15:04:05Z07:00")) +} + +func TestFormatCotacolPer100Km(t *testing.T) { + assert.Equal(t, "20.0", formatCotacolPer100Km(2, 10_000)) + assert.Equal(t, "-", formatCotacolPer100Km(2, 0)) +} diff --git a/web/templates.templ b/web/templates.templ new file mode 100644 index 0000000..d0b1c0c --- /dev/null +++ b/web/templates.templ @@ -0,0 +1,106 @@ +package web + +templ Layout(title string, content templ.Component) { + <!doctype html> + <html lang="en"> + <head> + <meta charset="utf-8"/> + <meta name="viewport" content="width=device-width, initial-scale=1"/> + <title>{ title } · biking_home</title> + <style> + :root { color-scheme: light; font-family: system-ui, sans-serif; background: #f5f3ee; color: #1d2a22; } + * { box-sizing: border-box; } + body { margin: 0; } + a { color: #18794e; } + .site-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 1rem max(1rem, calc((100vw - 70rem) / 2)); background: #173b2a; color: #fff; } + .site-header a { color: #fff; text-decoration: none; } + .brand { font-weight: 750; letter-spacing: .02em; } + .nav { display: flex; gap: 1rem; font-size: .95rem; } + .container { width: min(70rem, calc(100% - 2rem)); margin: 0 auto; padding: 2.5rem 0 4rem; } + .eyebrow { margin: 0 0 .4rem; color: #18794e; font-size: .78rem; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; } + h1 { margin: 0; font-size: clamp(2rem, 4vw, 3.2rem); line-height: 1; } + .lead { max-width: 42rem; color: #5b675f; } + .panel { margin-top: 2rem; padding: 1.25rem; border: 1px solid #d9ded8; border-radius: 1rem; background: #fff; box-shadow: 0 1rem 2.5rem #173b2a0d; } + .toolbar { display: flex; align-items: end; justify-content: space-between; gap: 1rem; flex-wrap: wrap; } + .button { display: inline-block; border: 0; border-radius: .65rem; padding: .7rem 1rem; background: #d96932; color: #fff; font: inherit; font-weight: 700; text-decoration: none; cursor: pointer; } + .button.secondary { background: #e8eee9; color: #173b2a; } + label { display: grid; gap: .35rem; color: #5b675f; font-size: .85rem; font-weight: 650; } + input { border: 1px solid #c8d0c9; border-radius: .55rem; padding: .65rem .7rem; font: inherit; color: inherit; background: #fff; } + .form-row { display: flex; align-items: end; gap: .75rem; flex-wrap: wrap; } + .notice { margin: 1rem 0 0; border-radius: .6rem; padding: .75rem 1rem; background: #e5f3e9; color: #17633f; } + .error { margin: 1rem 0 0; border-radius: .6rem; padding: .75rem 1rem; background: #fbe8df; color: #8c3517; } + table { width: 100%; border-collapse: collapse; } + th, td { padding: .85rem .5rem; border-bottom: 1px solid #e5e9e5; text-align: left; } + th { color: #68746c; font-size: .78rem; letter-spacing: .08em; text-transform: uppercase; } + .numeric { text-align: right; white-space: nowrap; } + .empty { padding: 2.5rem 1rem; text-align: center; color: #68746c; } + @media (max-width: 700px) { .container { width: min(100% - 1rem, 70rem); padding-top: 1.5rem; } .site-header { padding-inline: 1rem; } th:nth-child(n+4), td:nth-child(n+4) { display: none; } .panel { padding: .8rem; } } + </style> + </head> + <body> + <header class="site-header"> + <a class="brand" href="/">biking_home</a> + <nav class="nav"><a href="/">Rides</a><a href="/sync">Sync Strava</a></nav> + </header> + <main class="container"> + @content + </main> + </body> + </html> +} + +templ RidesPage(items []RideView) { + @Layout("Rides", RidesContent(items)) +} + +templ RidesContent(items []RideView) { + <p class="eyebrow">Ride library</p> + <div class="toolbar"> + <div><h1>All rides</h1><p class="lead">Your imported rides, ready for climb analysis.</p></div> + <a class="button" href="/sync">Sync Strava</a> + </div> + <section class="panel"> + if len(items) == 0 { + <div class="empty">No rides stored yet. <a href="/sync">Import your first Strava rides.</a></div> + } else { + <table> + <thead><tr><th>Ride</th><th>Started</th><th class="numeric">Distance</th><th class="numeric">Moving time</th><th class="numeric">Elevation</th><th class="numeric">Cotacol</th><th class="numeric">Cotacol / 100 km</th></tr></thead> + <tbody> + for _, item := range items { + <tr><td><strong>{ item.Name }</strong><br/><small>{ item.Type }</small></td><td>{ formatRideDate(item.StartDate) }</td><td class="numeric">{ formatDistance(item.DistanceM) }</td><td class="numeric">{ formatDuration(item.MovingTimeS) }</td><td class="numeric">{ formatElevation(item.TotalElevationGainM) }</td><td class="numeric">{ item.Cotacol }</td><td class="numeric">{ item.CotacolPer100Km }</td></tr> + } + </tbody> + </table> + } + </section> +} + +templ SyncPage(data SyncPageData) { + @Layout("Sync Strava", SyncContent(data)) +} + +templ SyncContent(data SyncPageData) { + <p class="eyebrow">Data import</p> + <h1>Sync Strava rides</h1> + <p class="lead">Choose a date range. New rides are downloaded as GPX files and recorded in the local library.</p> + if data.Notice != "" { + <div class="notice">{ data.Notice }</div> + } + if data.Error != "" { + <div class="error">{ data.Error }</div> + } + <section class="panel"> + if !data.HasAuth { + <p>Strava authorization is required before the first sync.</p> + <a class="button secondary" href={ templ.URL("/strava/login?return_to=/sync") }>Authorize Strava</a> + } else { + <form method="post" action="/sync"> + <div class="form-row"> + <label>From<input type="date" name="from" value={ data.From } required/></label> + <label>To<input type="date" name="to" value={ data.To } required/></label> + <button class="button" type="submit">Sync rides</button> + </div> + </form> + } + </section> +} diff --git a/web/templates_templ.go b/web/templates_templ.go new file mode 100644 index 0000000..8ab1d83 --- /dev/null +++ b/web/templates_templ.go @@ -0,0 +1,381 @@ +// Code generated by templ - DO NOT EDIT. + +// templ: version: v0.2.747 +package web + +//lint:file-ignore SA4006 This context is only used if a nested component is present. + +import "github.com/a-h/templ" +import templruntime "github.com/a-h/templ/runtime" + +func Layout(title string, content templ.Component) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Var1 := templ.GetChildren(ctx) + if templ_7745c5c3_Var1 == nil { + templ_7745c5c3_Var1 = templ.NopComponent + } + ctx = templ.ClearChildren(ctx) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var2 string + templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(title) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 9, Col: 17} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(" · biking_home</title><style>\n\t\t\t\t:root { color-scheme: light; font-family: system-ui, sans-serif; background: #f5f3ee; color: #1d2a22; }\n\t\t\t\t* { box-sizing: border-box; }\n\t\t\t\tbody { margin: 0; }\n\t\t\t\ta { color: #18794e; }\n\t\t\t\t.site-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 1rem max(1rem, calc((100vw - 70rem) / 2)); background: #173b2a; color: #fff; }\n\t\t\t\t.site-header a { color: #fff; text-decoration: none; }\n\t\t\t\t.brand { font-weight: 750; letter-spacing: .02em; }\n\t\t\t\t.nav { display: flex; gap: 1rem; font-size: .95rem; }\n\t\t\t\t.container { width: min(70rem, calc(100% - 2rem)); margin: 0 auto; padding: 2.5rem 0 4rem; }\n\t\t\t\t.eyebrow { margin: 0 0 .4rem; color: #18794e; font-size: .78rem; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }\n\t\t\t\th1 { margin: 0; font-size: clamp(2rem, 4vw, 3.2rem); line-height: 1; }\n\t\t\t\t.lead { max-width: 42rem; color: #5b675f; }\n\t\t\t\t.panel { margin-top: 2rem; padding: 1.25rem; border: 1px solid #d9ded8; border-radius: 1rem; background: #fff; box-shadow: 0 1rem 2.5rem #173b2a0d; }\n\t\t\t\t.toolbar { display: flex; align-items: end; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }\n\t\t\t\t.button { display: inline-block; border: 0; border-radius: .65rem; padding: .7rem 1rem; background: #d96932; color: #fff; font: inherit; font-weight: 700; text-decoration: none; cursor: pointer; }\n\t\t\t\t.button.secondary { background: #e8eee9; color: #173b2a; }\n\t\t\t\tlabel { display: grid; gap: .35rem; color: #5b675f; font-size: .85rem; font-weight: 650; }\n\t\t\t\tinput { border: 1px solid #c8d0c9; border-radius: .55rem; padding: .65rem .7rem; font: inherit; color: inherit; background: #fff; }\n\t\t\t\t.form-row { display: flex; align-items: end; gap: .75rem; flex-wrap: wrap; }\n\t\t\t\t.notice { margin: 1rem 0 0; border-radius: .6rem; padding: .75rem 1rem; background: #e5f3e9; color: #17633f; }\n\t\t\t\t.error { margin: 1rem 0 0; border-radius: .6rem; padding: .75rem 1rem; background: #fbe8df; color: #8c3517; }\n\t\t\t\ttable { width: 100%; border-collapse: collapse; }\n\t\t\t\tth, td { padding: .85rem .5rem; border-bottom: 1px solid #e5e9e5; text-align: left; }\n\t\t\t\tth { color: #68746c; font-size: .78rem; letter-spacing: .08em; text-transform: uppercase; }\n\t\t\t\t.numeric { text-align: right; white-space: nowrap; }\n\t\t\t\t.empty { padding: 2.5rem 1rem; text-align: center; color: #68746c; }\n\t\t\t\t@media (max-width: 700px) { .container { width: min(100% - 1rem, 70rem); padding-top: 1.5rem; } .site-header { padding-inline: 1rem; } th:nth-child(n+4), td:nth-child(n+4) { display: none; } .panel { padding: .8rem; } }\n\t\t\t</style></head><body><header class=\"site-header\"><a class=\"brand\" href=\"/\">biking_home</a><nav class=\"nav\"><a href=\"/\">Rides</a><a href=\"/sync\">Sync Strava</a></nav></header><main class=\"container\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = content.Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</main></body></html>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return templ_7745c5c3_Err + }) +} + +func RidesPage(items []RideView) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Var3 := templ.GetChildren(ctx) + if templ_7745c5c3_Var3 == nil { + templ_7745c5c3_Var3 = templ.NopComponent + } + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = Layout("Rides", RidesContent(items)).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return templ_7745c5c3_Err + }) +} + +func RidesContent(items []RideView) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Var4 := templ.GetChildren(ctx) + if templ_7745c5c3_Var4 == nil { + templ_7745c5c3_Var4 = templ.NopComponent + } + ctx = templ.ClearChildren(ctx) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<p class=\"eyebrow\">Ride library</p><div class=\"toolbar\"><div><h1>All rides</h1><p class=\"lead\">Your imported rides, ready for climb analysis.</p></div><a class=\"button\" href=\"/sync\">Sync Strava</a></div><section class=\"panel\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if len(items) == 0 { + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<div class=\"empty\">No rides stored yet. <a href=\"/sync\">Import your first Strava rides.</a></div>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<table><thead><tr><th>Ride</th><th>Started</th><th class=\"numeric\">Distance</th><th class=\"numeric\">Moving time</th><th class=\"numeric\">Elevation</th><th class=\"numeric\">Cotacol</th><th class=\"numeric\">Cotacol / 100 km</th></tr></thead> <tbody>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, item := range items { + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<tr><td><strong>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var5 string + templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(item.Name) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 70, Col: 33} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</strong><br><small>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var6 string + templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(item.Type) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 70, Col: 67} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</small></td><td>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var7 string + templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(formatRideDate(item.StartDate)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 70, Col: 118} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</td><td class=\"numeric\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(formatDistance(item.DistanceM)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 70, Col: 177} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</td><td class=\"numeric\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var9 string + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(formatDuration(item.MovingTimeS)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 70, Col: 238} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</td><td class=\"numeric\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var10 string + templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(formatElevation(item.TotalElevationGainM)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 70, Col: 308} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</td><td class=\"numeric\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var11 string + templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(item.Cotacol) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 70, Col: 349} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</td><td class=\"numeric\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var12 string + templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(item.CotacolPer100Km) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 70, Col: 398} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</td></tr>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</tbody></table>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</section>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return templ_7745c5c3_Err + }) +} + +func SyncPage(data SyncPageData) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Var13 := templ.GetChildren(ctx) + if templ_7745c5c3_Var13 == nil { + templ_7745c5c3_Var13 = templ.NopComponent + } + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = Layout("Sync Strava", SyncContent(data)).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return templ_7745c5c3_Err + }) +} + +func SyncContent(data SyncPageData) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Var14 := templ.GetChildren(ctx) + if templ_7745c5c3_Var14 == nil { + templ_7745c5c3_Var14 = templ.NopComponent + } + ctx = templ.ClearChildren(ctx) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<p class=\"eyebrow\">Data import</p><h1>Sync Strava rides</h1><p class=\"lead\">Choose a date range. New rides are downloaded as GPX files and recorded in the local library.</p>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if data.Notice != "" { + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<div class=\"notice\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var15 string + templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(data.Notice) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 87, Col: 35} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</div>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + if data.Error != "" { + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<div class=\"error\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var16 string + templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(data.Error) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 90, Col: 33} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</div>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<section class=\"panel\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if !data.HasAuth { + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<p>Strava authorization is required before the first sync.</p><a class=\"button secondary\" href=\"") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var17 templ.SafeURL = templ.URL("/strava/login?return_to=/sync") + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(string(templ_7745c5c3_Var17))) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("\">Authorize Strava</a>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<form method=\"post\" action=\"/sync\"><div class=\"form-row\"><label>From<input type=\"date\" name=\"from\" value=\"") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var18 string + templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(data.From) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 99, Col: 64} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("\" required></label> <label>To<input type=\"date\" name=\"to\" value=\"") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var19 string + templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(data.To) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/templates.templ`, Line: 100, Col: 58} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("\" required></label> <button class=\"button\" type=\"submit\">Sync rides</button></div></form>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</section>") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return templ_7745c5c3_Err + }) +} diff --git a/web/views.go b/web/views.go new file mode 100644 index 0000000..29f3c4f --- /dev/null +++ b/web/views.go @@ -0,0 +1,52 @@ +package web + +import ( + "fmt" + "time" + + "github.com/martinlehoux/biking_home/rides" +) + +type RideView struct { + rides.Ride + Cotacol string + CotacolPer100Km string +} + +type SyncPageData struct { + From string + To string + Error string + Notice string + HasAuth bool +} + +func formatRideDate(value time.Time) string { + return value.Local().Format("02 Jan 2006, 15:04") +} + +func formatDistance(meters float64) string { + return fmt.Sprintf("%.1f km", meters/1000) +} + +func formatDuration(seconds int64) string { + hours := seconds / 3600 + minutes := (seconds % 3600) / 60 + return fmt.Sprintf("%dh %02dm", hours, minutes) +} + +func formatElevation(meters float64) string { + return fmt.Sprintf("%.0f m", meters) +} + +func formatCotacol(score float64) string { + return fmt.Sprintf("%.1f", score) +} + +func formatCotacolPer100Km(score, distanceM float64) string { + distanceKm := distanceM / 1000 + if distanceKm <= 0 { + return "-" + } + return fmt.Sprintf("%.1f", score*100/distanceKm) +} |