Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
763163c24e | ||
|
|
ee3eba3cd9 | ||
|
|
b384c70c39 | ||
|
|
1c67eb0cff | ||
|
|
16e5107185 | ||
|
|
2b07701762 | ||
|
|
a27b4a66e6 | ||
|
|
bc900e1450 | ||
|
|
1310b7b243 | ||
|
|
01b24f830f |
@@ -17,9 +17,6 @@ RUN pnpm run build:css && pnpm run build:js
|
||||
FROM golang:1.26-alpine AS go-builder
|
||||
WORKDIR /app
|
||||
|
||||
# Install git for potential private modules (though not strictly needed here)
|
||||
RUN apk add --no-cache git
|
||||
|
||||
# Download Go modules
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
@@ -41,9 +38,6 @@ RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/server ./cmd/schr
|
||||
FROM alpine:latest
|
||||
WORKDIR /app
|
||||
|
||||
# Install root certificates and timezone data
|
||||
RUN apk --no-cache add ca-certificates tzdata
|
||||
|
||||
# Copy the compiled binary from the builder stage
|
||||
COPY --from=go-builder /app/server .
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
.PHONY: run
|
||||
run: docker
|
||||
air
|
||||
|
||||
.PHONY: docker
|
||||
docker:
|
||||
docker compose up -d
|
||||
@@ -2,35 +2,40 @@
|
||||
|
||||
Personal portfolio website for Schreifuchs, featuring photography, informatics, music, and video.
|
||||
|
||||
The site is built with **Svelte 5** and **SvelteKit**, and it is powered by a dynamic **Nextcloud** backend via WebDAV.
|
||||
The site is built with **Go**, **templ**, and **HTMX**, and it is powered by a dynamic **Nextcloud** backend via WebDAV.
|
||||
|
||||
## Features
|
||||
|
||||
- **Dynamic Content:** Pages are automatically discovered based on the folder structure in Nextcloud.
|
||||
- **Hidden Sites:** Folders starting with `_` are excluded from the navigation menu but remain accessible via direct links.
|
||||
- **Markdown Driven:** Content for each page is fetched from a corresponding Markdown file.
|
||||
- **Markdown Driven:** Content for each page is fetched from a corresponding Markdown file and rendered via `gomarkdown`.
|
||||
- **Image Optimization:** Automatic image resizing via Nextcloud's Preview API for optimized delivery and `srcset` support.
|
||||
- **Asset Proxying:** Images and attachments are securely streamed from Nextcloud through a server-side proxy.
|
||||
- **Performance:** In-memory caching for Nextcloud requests (15-minute TTL).
|
||||
- **Responsive Design:** Styled with Tailwind CSS, optimized for all screen sizes.
|
||||
- **Performance:** Multi-layer caching using **Valkey** (Redis-compatible) for WebDAV requests and image scaling.
|
||||
- **Responsive Design:** Styled with **Tailwind CSS**, optimized for all screen sizes.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Framework:** Svelte 5 (Runes) & SvelteKit
|
||||
- **Backend:** Go (Golang)
|
||||
- **UI Components:** [templ](https://templ.guide/)
|
||||
- **Frontend Interactivity:** [HTMX](https://htmx.org/)
|
||||
- **Styling:** Tailwind CSS
|
||||
- **Backend:** Node.js (via `@sveltejs/adapter-node`)
|
||||
- **Integration:** `webdav` library for Nextcloud communication
|
||||
- **Content:** `@ts-stack/markdown` for rendering
|
||||
- **Caching:** Valkey
|
||||
- **Integration:** `gowebdav` for Nextcloud communication
|
||||
- **Content:** `github.com/gomarkdown/markdown` for rendering
|
||||
|
||||
## Configuration
|
||||
|
||||
The application requires the following environment variables in a `.env` file:
|
||||
|
||||
```env
|
||||
NEXTCLOUD_URL=https://your-nextcloud-instance.com
|
||||
NEXTCLOUD_USER=your_username
|
||||
NEXTCLOUD_PASSWORD=your_app_password
|
||||
NEXTCLOUD_BASE_DIR=WebsiteContent # Optional: Root folder for site content
|
||||
FILESYSTEM_URL=https://your-nextcloud-instance.com/remote.php/dav/files/user/
|
||||
FILESYSTEM_USERNAME=your_username
|
||||
FILESYSTEM_PASSWORD=your_app_password
|
||||
CACHE_ADDRESS=localhost:6379
|
||||
CACHE_PASSWORD=your_valkey_password
|
||||
PORT=8080
|
||||
LOG_LEVEL=DEBUG
|
||||
```
|
||||
|
||||
## Content Management
|
||||
@@ -45,28 +50,40 @@ To add or update content, manage files in your configured Nextcloud directory:
|
||||
|
||||
## Development
|
||||
|
||||
Install dependencies:
|
||||
Install dependencies (Go, pnpm, and the `templ` binary):
|
||||
|
||||
```bash
|
||||
# Install Go dependencies
|
||||
go mod tidy
|
||||
# Install JS/CSS dependencies
|
||||
pnpm install
|
||||
```
|
||||
|
||||
Start the development server:
|
||||
Start the development server with hot reloading:
|
||||
|
||||
```bash
|
||||
pnpm run dev
|
||||
air
|
||||
```
|
||||
|
||||
For CSS changes, run in a separate terminal:
|
||||
|
||||
```bash
|
||||
pnpm run watch:css
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
Build for production (Node.js):
|
||||
Build the project for production:
|
||||
|
||||
```bash
|
||||
pnpm run build
|
||||
# Generate Go code from Templ files
|
||||
go generate ./...
|
||||
# Build CSS
|
||||
pnpm run build:css
|
||||
# Build Go binary
|
||||
go build -o ./tmp/main ./cmd/schreifuchs-ch/main.go
|
||||
```
|
||||
|
||||
The output will be in the `build/` directory, ready to be served by Node.
|
||||
|
||||
## Image Processing
|
||||
|
||||
To optimize images before uploading to Nextcloud:
|
||||
@@ -74,3 +91,4 @@ To optimize images before uploading to Nextcloud:
|
||||
```bash
|
||||
convert input.png -resize 3000 -quality 80 output.webp
|
||||
```
|
||||
|
||||
|
||||
@@ -3,20 +3,14 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
_ "net/http/pprof"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/server"
|
||||
)
|
||||
|
||||
func main() {
|
||||
go func() {
|
||||
http.ListenAndServe("localhost:6060", nil)
|
||||
}()
|
||||
ctx := context.Background()
|
||||
ctx, cancle := context.WithCancel(ctx)
|
||||
defer cancle()
|
||||
@@ -29,16 +23,37 @@ func main() {
|
||||
cancle()
|
||||
}()
|
||||
|
||||
slog.SetLogLoggerLevel(slog.LevelDebug)
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})))
|
||||
|
||||
cfg, err := config.Read(ctx)
|
||||
if err != nil {
|
||||
slog.Error("could not read configuaration", "err", err)
|
||||
}
|
||||
|
||||
setupLogger(&cfg)
|
||||
|
||||
err = server.Start(ctx, cfg)
|
||||
if err != nil {
|
||||
slog.Error("error while serving", "err", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func setupLogger(cfg *config.Cfg) {
|
||||
opts := slog.HandlerOptions{
|
||||
Level: cfg.LogLevel,
|
||||
}
|
||||
var handler slog.Handler
|
||||
|
||||
if cfg.LogJSON {
|
||||
handler = slog.NewJSONHandler(os.Stdout, &opts)
|
||||
} else {
|
||||
handler = slog.NewTextHandler(os.Stdout, &opts)
|
||||
}
|
||||
|
||||
slog.SetDefault(
|
||||
slog.New(
|
||||
handler,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
services:
|
||||
valkey:
|
||||
image: valkey/valkey:8
|
||||
restart: always
|
||||
ports:
|
||||
- "6379:6379"
|
||||
command: valkey-server --requirepass "valkey"
|
||||
|
||||
@@ -11,10 +11,14 @@ require (
|
||||
github.com/sethvargo/go-envconfig v1.3.0
|
||||
github.com/studio-b12/gowebdav v0.12.0
|
||||
github.com/valkey-io/valkey-go v1.0.72
|
||||
github.com/valkey-io/valkey-go/mock v1.0.72
|
||||
go.uber.org/mock v0.6.0
|
||||
golang.org/x/image v0.36.0
|
||||
golang.org/x/sync v0.16.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/InfinityTools/go-binpack2d v1.0.0 // indirect
|
||||
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e // indirect
|
||||
github.com/andybalholm/brotli v1.1.0 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
@@ -25,9 +29,8 @@ require (
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/natefinch/atomic v1.0.1 // indirect
|
||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
||||
golang.org/x/mod v0.26.0 // indirect
|
||||
golang.org/x/mod v0.27.0 // indirect
|
||||
golang.org/x/net v0.48.0 // indirect
|
||||
golang.org/x/sync v0.16.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/tools v0.35.0 // indirect
|
||||
golang.org/x/tools v0.36.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
github.com/InfinityTools/go-binpack2d v1.0.0 h1:l15wC3zDlR0FoffIcPze0qbszshmGCpMncDiAxpWnE8=
|
||||
github.com/InfinityTools/go-binpack2d v1.0.0/go.mod h1:3hwEmVO6ffChGwW55BVr9k4rzSYGow0OH2B8bjEdO6o=
|
||||
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e h1:HjVbSQHy+dnlS6C3XajZ69NYAb5jbGNfHanvm1+iYlo=
|
||||
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e/go.mod h1:3mnrkvGpurZ4ZrTDbYU84xhwXW2TjTKShSwjRi2ihfQ=
|
||||
github.com/a-h/templ v0.3.977 h1:kiKAPXTZE2Iaf8JbtM21r54A8bCNsncrfnokZZSrSDg=
|
||||
@@ -39,14 +41,18 @@ github.com/studio-b12/gowebdav v0.12.0 h1:kFRtQECt8jmVAvA6RHBz3geXUGJHUZA6/IKpOV
|
||||
github.com/studio-b12/gowebdav v0.12.0/go.mod h1:bHA7t77X/QFExdeAnDzK6vKM34kEZAcE1OX4MfiwjkE=
|
||||
github.com/valkey-io/valkey-go v1.0.72 h1:iRWt1hJyOchcEgbHSkRY3aKkcBudxvMaVMsmxuYxuxE=
|
||||
github.com/valkey-io/valkey-go v1.0.72/go.mod h1:VGhZ6fs68Qrn2+OhH+6waZH27bjpgQOiLyUQyXuYK5k=
|
||||
github.com/valkey-io/valkey-go/mock v1.0.72 h1:rE8K/sjlX0SRldI70Rt4/MCrYl224XD4A4vkYegP1Iw=
|
||||
github.com/valkey-io/valkey-go/mock v1.0.72/go.mod h1:A4B8L3Wg85yAOl/GwNgkO/6aeGNXydwBl+86e20NQQY=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/image v0.36.0 h1:Iknbfm1afbgtwPTmHnS2gTM/6PPZfH+z2EFuOkSbqwc=
|
||||
golang.org/x/image v0.36.0/go.mod h1:YsWD2TyyGKiIX1kZlu9QfKIsQ4nAAK9bdgdrIsE7xy4=
|
||||
golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
|
||||
golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
|
||||
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
|
||||
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
@@ -57,7 +63,7 @@ golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
|
||||
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
|
||||
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
|
||||
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package gallery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
|
||||
"github.com/InfinityTools/go-binpack2d"
|
||||
)
|
||||
|
||||
type Gallery struct {
|
||||
GridWith int
|
||||
GridHeight int
|
||||
Images []Image
|
||||
}
|
||||
type Set struct {
|
||||
SM Gallery
|
||||
LG Gallery
|
||||
XLG Gallery
|
||||
}
|
||||
|
||||
func (s *Service) GetGallerySet(ctx context.Context) (gallerySet Set, err error) {
|
||||
gallerySet.SM, err = s.GetGallery(ctx, 50)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
gallerySet.LG, err = s.GetGallery(ctx, 80)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
gallerySet.XLG, err = s.GetGallery(ctx, 120)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Service) GetGallery(ctx context.Context, width int) (gallery Gallery, err error) {
|
||||
imgs, err := s.GetImages(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
packer := binpack2d.Create(width, 999999)
|
||||
|
||||
for len(imgs) > 0 {
|
||||
unused := make([]Image, 0, len(imgs))
|
||||
for _, img := range imgs {
|
||||
adjustImageSize(&img, 200)
|
||||
rect, ok := packer.Insert(img.Width, img.Height, binpack2d.RULE_BEST_SHORT_SIDE_FIT)
|
||||
if !ok {
|
||||
unused = append(unused, img)
|
||||
continue
|
||||
}
|
||||
|
||||
img.X = rect.X
|
||||
img.Y = rect.Y
|
||||
|
||||
gallery.Images = append(gallery.Images, img)
|
||||
}
|
||||
imgs = unused
|
||||
}
|
||||
|
||||
packer.ShrinkBin(false)
|
||||
|
||||
gallery.GridHeight = packer.GetHeight()
|
||||
gallery.GridWith = packer.GetWidth()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// adjustImageSize adjusts the image size so that the aspect ratio stays the same
|
||||
// but the image area is the given parameter.
|
||||
func adjustImageSize(img *Image, area int) {
|
||||
// Calculate the original aspect ratio (W / H)
|
||||
aspectRatio := float64(img.Width) / float64(img.Height)
|
||||
|
||||
// Calculate new height and width using the derived formulas
|
||||
newHeight := math.Sqrt(float64(area) / aspectRatio)
|
||||
newWidth := newHeight * aspectRatio
|
||||
|
||||
// Round to the nearest integer to minimize precision loss
|
||||
img.Width = int(math.Round(newWidth))
|
||||
img.Height = int(math.Round(newHeight))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package gallery
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
)
|
||||
|
||||
type fileWithPath struct {
|
||||
os.FileInfo
|
||||
path string
|
||||
}
|
||||
|
||||
func (f fileWithPath) Name() string {
|
||||
return path.Join(f.path, f.FileInfo.Name())
|
||||
}
|
||||
|
||||
func (s *Service) readDirRecursive(path string) (files []os.FileInfo, err error) {
|
||||
return s.readDirRecursiveTo([]os.FileInfo{}, path)
|
||||
}
|
||||
|
||||
func (s *Service) readDirRecursiveTo(files []os.FileInfo, p ...string) ([]os.FileInfo, error) {
|
||||
localFiles, err := s.fs.ReadDir(path.Join(p...))
|
||||
if err != nil {
|
||||
return files, err
|
||||
}
|
||||
|
||||
for _, file := range localFiles {
|
||||
if file.IsDir() {
|
||||
newP := append(p, file.Name())
|
||||
files, err = s.readDirRecursiveTo(files, newP...)
|
||||
if err != nil {
|
||||
return files, err
|
||||
}
|
||||
} else {
|
||||
files = append(files, fileWithPath{file, path.Join(p[1:]...)})
|
||||
}
|
||||
}
|
||||
|
||||
return files, nil
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package gallery
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/valkey-io/valkey-go"
|
||||
)
|
||||
|
||||
type Image struct {
|
||||
UID string
|
||||
X int
|
||||
Y int
|
||||
Width int
|
||||
Height int
|
||||
}
|
||||
|
||||
const (
|
||||
imagesKey = "gallery:images:list"
|
||||
hashKey = "gallery:images:hash"
|
||||
)
|
||||
|
||||
func (s *Service) autoRefresh() {
|
||||
t := time.NewTicker(time.Minute)
|
||||
for {
|
||||
ctx, cancle := context.WithTimeout(context.Background(), time.Minute)
|
||||
|
||||
if err := s.assembleImageList(ctx); err != nil {
|
||||
slog.Error("error while refreshing gallery", "err", err)
|
||||
}
|
||||
cancle()
|
||||
<-t.C
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) assembleImageList(ctx context.Context) error {
|
||||
files, err := s.readDirRecursive(s.cfg.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not read contents of %s: %w", s.cfg.Path, err)
|
||||
}
|
||||
slog.Debug("loaded files", "files", files)
|
||||
|
||||
savedHash, _ := s.cache.Do(ctx, s.cache.B().Get().Key(hashKey).Build()).AsBytes()
|
||||
|
||||
newHash := hashImageList(files)
|
||||
|
||||
if bytes.Equal(savedHash, newHash) {
|
||||
slog.Debug("images up to date no refreshing of gallery", "savedHash", savedHash, "newHash", newHash)
|
||||
return nil
|
||||
}
|
||||
|
||||
slog.Info("starting gallery refresh")
|
||||
defer slog.Info("gallery refresh completed")
|
||||
|
||||
imgs := make([]Image, 0, len(files))
|
||||
for _, file := range files {
|
||||
if strings.HasSuffix(file.Name(), ".md") {
|
||||
continue
|
||||
}
|
||||
|
||||
imagePath := path.Join(s.cfg.Path, file.Name())
|
||||
img, err := s.img.GetImage(imagePath)
|
||||
if err != nil || img.Image == nil {
|
||||
slog.Warn("could not get image for gallery", "err", err, "img", img)
|
||||
continue
|
||||
}
|
||||
|
||||
uid, err := img.UID()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
imgs = append(imgs, Image{
|
||||
UID: uid,
|
||||
Width: img.Bounds().Dx(),
|
||||
Height: img.Bounds().Dy(),
|
||||
})
|
||||
}
|
||||
|
||||
if err = s.cache.Do(ctx, s.cache.B().Set().Key(hashKey).Value(valkey.BinaryString(newHash)).Build()).Error(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = s.cache.Do(ctx, s.cache.B().Set().Key(imagesKey).Value(valkey.JSON(imgs)).Build()).Error(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func hashImageList(files []os.FileInfo) []byte {
|
||||
h := fnv.New128()
|
||||
|
||||
for _, file := range files {
|
||||
fmt.Fprint(h, file.ModTime())
|
||||
fmt.Fprint(h, file.Size())
|
||||
fmt.Fprint(h, file.Name())
|
||||
}
|
||||
|
||||
return h.Sum([]byte{})
|
||||
}
|
||||
|
||||
func (s *Service) GetImages(ctx context.Context) (images []Image, err error) {
|
||||
err = s.cache.Do(ctx, s.cache.B().Get().Key(imagesKey).Build()).DecodeJSON(&images)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package gallery
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/filesystem"
|
||||
"github.com/valkey-io/valkey-go"
|
||||
)
|
||||
|
||||
type getImager interface {
|
||||
GetImage(path string) (img images.Image, err error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
fs filesystem.FS
|
||||
cfg *config.Gallery
|
||||
img getImager
|
||||
cache valkey.Client
|
||||
|
||||
refreshIntervall time.Duration
|
||||
}
|
||||
|
||||
func New(fs filesystem.FS, cfg *config.Gallery, img getImager, cache valkey.Client) *Service {
|
||||
s := &Service{
|
||||
fs: fs,
|
||||
cfg: cfg,
|
||||
img: img,
|
||||
cache: cache,
|
||||
}
|
||||
go s.autoRefresh()
|
||||
|
||||
return s
|
||||
}
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
_ "image/png"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "golang.org/x/image/webp"
|
||||
|
||||
@@ -22,7 +21,7 @@ import (
|
||||
|
||||
var ErrNotAnImage = errors.New("not an image")
|
||||
|
||||
func (s *Service) getMime(path string) (mimeType string, err error) {
|
||||
func (s *Service) GetMime(path string) (mimeType string, err error) {
|
||||
info, err := s.fs.Stat(path)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("image file info could not be fetched: %w", err)
|
||||
@@ -30,18 +29,18 @@ func (s *Service) getMime(path string) (mimeType string, err error) {
|
||||
|
||||
if mimer, ok := info.(interface{ ContentType() string }); ok {
|
||||
mimeType = mimer.ContentType()
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Service) getImage(uid string) (file []byte, mimeType string, err error) {
|
||||
path, err := PathFromUID(uid)
|
||||
func (s *Service) getImage(path string) (file []byte, mimeType string, err error) {
|
||||
if err != nil {
|
||||
err = fmt.Errorf("could not get path: %w", err)
|
||||
return
|
||||
}
|
||||
mimeType, err = s.getMime(path)
|
||||
mimeType, err = s.GetMime(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -59,7 +58,19 @@ func (s *Service) getImage(uid string) (file []byte, mimeType string, err error)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Service) GetImage(ctx context.Context, uid string, options Options) (img io.Reader, mimeType string, err error) {
|
||||
func (s *Service) GetImage(path string) (img Image, err error) {
|
||||
rawImage, _, err := s.getImage(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
img.Path = path
|
||||
img.Image, _, err = image.Decode(bytes.NewBuffer(rawImage))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Service) GetScaledImage(ctx context.Context, uid string, options Options) (img io.Reader, mimeType string, err error) {
|
||||
if err = s.seph.Acquire(ctx, 1); err != nil {
|
||||
err = fmt.Errorf("could not Acquire semaphore: %w", err)
|
||||
return
|
||||
@@ -67,7 +78,12 @@ func (s *Service) GetImage(ctx context.Context, uid string, options Options) (im
|
||||
}
|
||||
defer s.seph.Release(1)
|
||||
|
||||
rawImage, mimeType, err := s.getImage(uid)
|
||||
path, err := PathFromUID(uid)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
rawImage, mimeType, err := s.getImage(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -97,7 +113,7 @@ func (s *Service) GetImage(ctx context.Context, uid string, options Options) (im
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.cache.Do(ctx, s.cache.B().Set().Key("img:"+hash).Value(valkey.BinaryString(outBuff.Bytes())).Ex(time.Hour*48).Build()).Error(); err == nil {
|
||||
if err = s.cache.Do(ctx, s.cache.B().Set().Key("img:"+hash).Value(valkey.BinaryString(outBuff.Bytes())).Ex(s.cfg.CacheLifetime).Build()).Error(); err == nil {
|
||||
return outBuff, "image/jpeg", err
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package images_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/test/testdata"
|
||||
"github.com/valkey-io/valkey-go"
|
||||
"github.com/valkey-io/valkey-go/mock"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
func Setup(ctx context.Context, ctrl *gomock.Controller) (*images.Service, *mock.Client) {
|
||||
valkey := mock.NewClient(ctrl)
|
||||
return images.New(testdata.FS(), &config.Image{Concurency: 1, Quality: 80}, valkey), valkey
|
||||
}
|
||||
|
||||
func BenchmarkService_GetImage(b *testing.B) {
|
||||
srv, valkeyClient := Setup(b.Context(), gomock.NewController(b))
|
||||
uid, err := images.UIDFromPath("cover.jpg")
|
||||
if err != nil {
|
||||
b.Error("could not get uid", err)
|
||||
}
|
||||
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
valkeyClient.EXPECT().Do(gomock.Any(), gomock.Any()).Return(mock.ErrorResult(errors.New("adf")))
|
||||
valkeyClient.EXPECT().Do(gomock.Any(), gomock.Any()).Return(mock.Result(valkey.ValkeyMessage{}))
|
||||
_, _, err = srv.GetScaledImage(b.Context(), uid, images.Options{Width: 500, Quality: 80})
|
||||
if err != nil {
|
||||
b.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,11 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
sourceSetSteps = 300
|
||||
sourceSetMax = 1500
|
||||
)
|
||||
|
||||
func UIDFromPath(path string) (uid string, err error) {
|
||||
var b bytes.Buffer
|
||||
// NewWriter with NoDict (nil) creates a raw DEFLATE compressor
|
||||
@@ -57,12 +62,14 @@ func PathFromUID(uid string) (string, error) {
|
||||
func SourceSet(src string) string {
|
||||
sb := strings.Builder{}
|
||||
|
||||
for i := range 19 {
|
||||
sb.WriteString(fmt.Sprintf("%s?w=%d %dw, ", src, 100*(i+1), 100*(i+1)))
|
||||
}
|
||||
|
||||
i := 20
|
||||
sb.WriteString(fmt.Sprintf("%s?w=%d %dw", src, 100*(i+1), 100*(i+1)))
|
||||
|
||||
i := 1
|
||||
for {
|
||||
width := i * sourceSetSteps
|
||||
sb.WriteString(fmt.Sprintf("%s?w=%d %dw, ", src, width, width))
|
||||
if width >= sourceSetMax {
|
||||
return sb.String()
|
||||
}
|
||||
sb.WriteRune(',')
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package images
|
||||
|
||||
import "image"
|
||||
|
||||
type Image struct {
|
||||
image.Image
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
func (i Image) UID() (string, error) {
|
||||
return UIDFromPath(i.Path)
|
||||
}
|
||||
@@ -18,10 +18,10 @@ type Service struct {
|
||||
fs fileSystem
|
||||
cache valkey.Client
|
||||
seph *semaphore.Weighted
|
||||
cfg *config.ImageConfig
|
||||
cfg *config.Image
|
||||
}
|
||||
|
||||
func New(fs fileSystem, cfg *config.ImageConfig, cache valkey.Client) *Service {
|
||||
func New(fs fileSystem, cfg *config.Image, cache valkey.Client) *Service {
|
||||
return &Service{
|
||||
fs: fs,
|
||||
cache: cache,
|
||||
|
||||
@@ -14,7 +14,7 @@ func scale(src image.Image, options Options) image.Image {
|
||||
)
|
||||
|
||||
// Resize:
|
||||
draw.BiLinear.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
|
||||
draw.ApproxBiLinear.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
|
||||
|
||||
// Encode to `output`:
|
||||
return dst
|
||||
|
||||
@@ -16,6 +16,7 @@ type PageHeader struct {
|
||||
type Page struct {
|
||||
PageHeader
|
||||
Content string
|
||||
Images []Image
|
||||
}
|
||||
|
||||
func (s *Service) GetPages(ctx context.Context) (pages []PageHeader, err error) {
|
||||
@@ -46,7 +47,7 @@ func (s *Service) GetPage(ctx context.Context, uid string) (page Page, err error
|
||||
return
|
||||
}
|
||||
|
||||
html, err := s.getHTML(ctx, p)
|
||||
html, imgs, err := s.getHTML(ctx, p)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -54,6 +55,7 @@ func (s *Service) GetPage(ctx context.Context, uid string) (page Page, err error
|
||||
page = Page{
|
||||
PageHeader: p,
|
||||
Content: string(html),
|
||||
Images: imgs,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -14,7 +14,13 @@ import (
|
||||
"github.com/gomarkdown/markdown/parser"
|
||||
)
|
||||
|
||||
func (s *Service) getHTML(ctx context.Context, page PageHeader) (out []byte, err error) {
|
||||
// image can be used to preload
|
||||
type Image struct {
|
||||
SrcSet string
|
||||
Src string
|
||||
}
|
||||
|
||||
func (s *Service) getHTML(ctx context.Context, page PageHeader) (out []byte, imgs []Image, err error) {
|
||||
extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
|
||||
p := parser.NewWithExtensions(extensions)
|
||||
|
||||
@@ -24,7 +30,7 @@ func (s *Service) getHTML(ctx context.Context, page PageHeader) (out []byte, err
|
||||
htmlFlags := html.CommonFlags | html.HrefTargetBlank
|
||||
opts := html.RendererOptions{
|
||||
Flags: htmlFlags,
|
||||
RenderNodeHook: imageMiddleware(page),
|
||||
RenderNodeHook: imageMiddleware(page, &imgs),
|
||||
}
|
||||
renderer := html.NewRenderer(opts)
|
||||
|
||||
@@ -32,7 +38,7 @@ func (s *Service) getHTML(ctx context.Context, page PageHeader) (out []byte, err
|
||||
return
|
||||
}
|
||||
|
||||
func imageMiddleware(page PageHeader) func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
|
||||
func imageMiddleware(page PageHeader, imgs *[]Image) func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
|
||||
return func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
|
||||
if !entering {
|
||||
return ast.GoToNext, false
|
||||
@@ -53,11 +59,20 @@ func imageMiddleware(page PageHeader) func(w io.Writer, node ast.Node, entering
|
||||
slog.Error("could not get image url", "err", err)
|
||||
return ast.GoToNext, false
|
||||
}
|
||||
image := Image{
|
||||
SrcSet: images.SourceSet(src),
|
||||
Src: src + "?w=1024",
|
||||
}
|
||||
|
||||
img.Attribute = &ast.Attribute{Attrs: map[string][]byte{
|
||||
"srcset": []byte(images.SourceSet(src)),
|
||||
"src": []byte(src),
|
||||
// "srcset": []byte(image.SrcSet),
|
||||
"fetchpriority": []byte("low"),
|
||||
"loading": []byte("lazy"),
|
||||
"class": []byte("min-h-48"),
|
||||
"src": []byte(image.Src),
|
||||
}}
|
||||
|
||||
*imgs = append(*imgs, image)
|
||||
// // img.Attrs["srcset"] =
|
||||
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
@@ -57,12 +56,15 @@ func (s *Service) getPageHeaders(ctx context.Context, uid string) (page PageHead
|
||||
}
|
||||
}
|
||||
|
||||
slog.Debug("loaded page infos", "cover", coverImage, "content", contentMD)
|
||||
if contentMD != nil {
|
||||
|
||||
page.md, err = s.fs.Read(contentMD.Path())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
page.md = []byte("# ...")
|
||||
}
|
||||
|
||||
title := titleRGX.FindStringSubmatch(string(page.md))
|
||||
if len(title) < 2 {
|
||||
|
||||
@@ -25,6 +25,7 @@ func SupportedLanguages(ctx context.Context) []string {
|
||||
s, ok := ctx.Value(serviceKey).(*Service)
|
||||
if !ok {
|
||||
slog.Error("could not extract translation service from context for getting supported languages")
|
||||
return []string{}
|
||||
}
|
||||
return s.SupportedLanguages()
|
||||
}
|
||||
@@ -52,7 +53,6 @@ func Path(ctx context.Context, pp ...string) string {
|
||||
}
|
||||
|
||||
func PathForLang(ctx context.Context, lang string, pp ...string) string {
|
||||
slog.Info("path for lang", "path", pp)
|
||||
s, ok := ctx.Value(serviceKey).(*Service)
|
||||
if !ok {
|
||||
slog.Error("could not extract translation service from context for translating path", "ctx", ctx, "path", pp)
|
||||
@@ -65,7 +65,7 @@ func PathForLang(ctx context.Context, lang string, pp ...string) string {
|
||||
}
|
||||
}
|
||||
|
||||
return path.Join(append([]string{lang}, pp...)...)
|
||||
return "/" + path.Join(append([]string{lang}, pp...)...)
|
||||
}
|
||||
|
||||
func (s *Service) SupportedLanguages() (languages []string) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package restutil
|
||||
package rest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -1,4 +1,4 @@
|
||||
package restutil
|
||||
package rest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -0,0 +1,13 @@
|
||||
package rest
|
||||
|
||||
import "net/http"
|
||||
|
||||
type Middeware = func(next http.Handler) http.Handler
|
||||
|
||||
func Use(handler http.Handler, middlewares ...Middeware) http.Handler {
|
||||
for _, middleware := range middlewares {
|
||||
handler = middleware(handler)
|
||||
}
|
||||
|
||||
return handler
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package restgallery
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/pages"
|
||||
)
|
||||
|
||||
func (h *Handler) gallery(w http.ResponseWriter, r *http.Request) {
|
||||
imgs, err := h.srv.GetGallerySet(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("could not get images", "err", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.r.Render(r.Context(), w, r, pages.GallerySet(imgs))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package restgallery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/gallery"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
|
||||
"github.com/a-h/templ"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
http.Handler
|
||||
srv galleryService
|
||||
r renderer
|
||||
cfg *config.Gallery
|
||||
}
|
||||
|
||||
func New(renderer renderer, srv galleryService, cfg *config.Gallery) *Handler {
|
||||
mux := http.NewServeMux()
|
||||
h := &Handler{
|
||||
Handler: mux,
|
||||
srv: srv,
|
||||
r: renderer,
|
||||
cfg: cfg,
|
||||
}
|
||||
|
||||
mux.HandleFunc(fmt.Sprintf("GET /%s", url.PathEscape(cfg.Path)), h.gallery)
|
||||
return h
|
||||
}
|
||||
|
||||
type galleryService interface {
|
||||
GetGallerySet(ctx context.Context) (gallerySet gallery.Set, err error)
|
||||
}
|
||||
type renderer interface {
|
||||
Render(ctx context.Context, w io.Writer, r *http.Request, component templ.Component)
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package resthome
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/layouts"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/pages"
|
||||
)
|
||||
|
||||
@@ -14,17 +17,31 @@ func (h *Handler) home(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
layouts.Render(r.Context(), w, r, pages.Home(pageHeaders))
|
||||
h.r.Render(r.Context(), w, r, pages.Home(pageHeaders))
|
||||
}
|
||||
|
||||
func (h *Handler) page(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
uid := r.PathValue("uid")
|
||||
|
||||
page, err := h.src.GetPage(r.Context(), uid)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
w.WriteHeader(http.StatusRequestTimeout)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
layouts.Render(r.Context(), w, r, pages.ContentPage(page))
|
||||
for i, image := range page.Images {
|
||||
if i > 3 {
|
||||
break
|
||||
}
|
||||
ctx = templer.AppendHeader(ctx, fmt.Sprintf(`<link rel="preload" href="%s" as="image" />`, image.Src))
|
||||
}
|
||||
|
||||
ctx = templer.PageTitle(ctx, page.Title)
|
||||
|
||||
h.r.Render(ctx, w, r, pages.ContentPage(page))
|
||||
}
|
||||
|
||||
@@ -2,18 +2,25 @@ package resthome
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/page"
|
||||
"github.com/a-h/templ"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
http.Handler
|
||||
src pageService
|
||||
r renderer
|
||||
}
|
||||
|
||||
func New(mux *http.ServeMux, srv pageService) *Handler {
|
||||
func New(renderer renderer, srv pageService) *Handler {
|
||||
mux := http.NewServeMux()
|
||||
h := &Handler{
|
||||
Handler: mux,
|
||||
src: srv,
|
||||
r: renderer,
|
||||
}
|
||||
|
||||
mux.HandleFunc("GET /{$}", h.home)
|
||||
@@ -25,3 +32,6 @@ type pageService interface {
|
||||
GetPages(ctx context.Context) ([]page.PageHeader, error)
|
||||
GetPage(ctx context.Context, uid string) (page.Page, error)
|
||||
}
|
||||
type renderer interface {
|
||||
Render(ctx context.Context, w io.Writer, r *http.Request, component templ.Component)
|
||||
}
|
||||
|
||||
+8
-8
@@ -6,7 +6,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/restutil"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest"
|
||||
)
|
||||
|
||||
func (h *Handler) getImage(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -14,24 +14,24 @@ func (h *Handler) getImage(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var err error
|
||||
options := images.Options{}
|
||||
options.Height, err = restutil.IntParam(r, "h")
|
||||
options.Height, err = rest.IntParam(r, "h")
|
||||
if err != nil {
|
||||
restutil.SendErr(w, err)
|
||||
rest.SendErr(w, err)
|
||||
return
|
||||
}
|
||||
options.Width, err = restutil.IntParam(r, "w")
|
||||
options.Width, err = rest.IntParam(r, "w")
|
||||
if err != nil {
|
||||
restutil.SendErr(w, err)
|
||||
rest.SendErr(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
options.Quality, err = restutil.IntParam(r, "q")
|
||||
options.Quality, err = rest.IntParam(r, "q")
|
||||
if err != nil {
|
||||
restutil.SendErr(w, err)
|
||||
rest.SendErr(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
img, mime, err := h.img.GetImage(r.Context(), uid, options)
|
||||
img, mime, err := h.img.GetScaledImage(r.Context(), uid, options)
|
||||
if err != nil {
|
||||
slog.Error("error wile serving image", "err", err, "uid", uid)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
@@ -9,11 +9,14 @@ import (
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
http.Handler
|
||||
img imageService
|
||||
}
|
||||
|
||||
func New(mux *http.ServeMux, srv imageService) *Handler {
|
||||
func New(srv imageService) *Handler {
|
||||
mux := http.NewServeMux()
|
||||
h := &Handler{
|
||||
Handler: mux,
|
||||
img: srv,
|
||||
}
|
||||
|
||||
@@ -22,5 +25,5 @@ func New(mux *http.ServeMux, srv imageService) *Handler {
|
||||
}
|
||||
|
||||
type imageService interface {
|
||||
GetImage(ctx context.Context, uid string, options images.Options) (img io.Reader, mimeType string, err error)
|
||||
GetScaledImage(ctx context.Context, uid string, options images.Options) (img io.Reader, mimeType string, err error)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
package config
|
||||
|
||||
import "time"
|
||||
|
||||
func Default() Cfg {
|
||||
return Cfg{
|
||||
Image: &ImageConfig{
|
||||
Image: &Image{
|
||||
Concurency: 10,
|
||||
Quality: 80,
|
||||
CacheLifetime: time.Hour * 24 * 31,
|
||||
},
|
||||
Tracking: &Umami{
|
||||
ScriptSrc: "https://umami.schreifuchs.ch/script.js",
|
||||
WebsiteID: "54d8a379-77d5-4c20-b46d-5c9a6c9e39bd",
|
||||
},
|
||||
Gallery: &Gallery{
|
||||
Path: "photos",
|
||||
},
|
||||
Cache: &Valkey{
|
||||
RefreshTime: time.Minute * 10,
|
||||
LifeTime: time.Hour * 48,
|
||||
},
|
||||
LogJSON: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,21 @@ package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/sethvargo/go-envconfig"
|
||||
)
|
||||
|
||||
type Cfg struct {
|
||||
FileSystem *WebdavConfig `env:", prefix=FILESYSTEM_"`
|
||||
Cache *ValkeyConfig `env:", prefix=CACHE_"`
|
||||
Image *ImageConfig `env:", prefix=IMAGE_"`
|
||||
Cache *Valkey `env:", prefix=CACHE_"`
|
||||
Image *Image `env:", prefix=IMAGE_"`
|
||||
Tracking *Umami `env:", prefix=TRACKING_"`
|
||||
Gallery *Gallery `env:", prefix=GALLERY_"`
|
||||
|
||||
LogLevel slog.Level `env:"LOG_LEVEL, default=DEBUG"`
|
||||
LogJSON bool `env:"LOG_JSON"`
|
||||
}
|
||||
|
||||
type WebdavConfig struct {
|
||||
@@ -18,11 +25,14 @@ type WebdavConfig struct {
|
||||
Password string `env:"PASSWORD"`
|
||||
}
|
||||
|
||||
type ValkeyConfig struct {
|
||||
type Valkey struct {
|
||||
ClientName string `env:"CLIENTNAME"`
|
||||
Username string `env:"USERNAME"`
|
||||
Password string `env:"PASSWORD"`
|
||||
|
||||
RefreshTime time.Duration `env:"REFRESH_TIME"`
|
||||
LifeTime time.Duration `env:"LIFE_TIME"`
|
||||
|
||||
// InitAddress point to valkey nodes.
|
||||
// Valkey will connect to them one by one and issue a CLUSTER SLOT command to initialize the cluster client until success.
|
||||
// If len(InitAddress) == 1 and the address is not running in cluster mode, valkey will fall back to the single client mode.
|
||||
@@ -31,9 +41,19 @@ type ValkeyConfig struct {
|
||||
InitAddress []string `env:"ADDRESS"`
|
||||
}
|
||||
|
||||
type ImageConfig struct {
|
||||
type Image struct {
|
||||
Concurency int64 `env:"CONCURENCY"`
|
||||
Quality int `env:"QUALITY"`
|
||||
CacheLifetime time.Duration `env:"CACHE_LIFETIME"`
|
||||
}
|
||||
|
||||
type Gallery struct {
|
||||
Path string `env:"PATH"`
|
||||
}
|
||||
|
||||
type Umami struct {
|
||||
ScriptSrc string `env:"SCRIPT_SRC"`
|
||||
WebsiteID string `env:"WEBSITE_ID"`
|
||||
}
|
||||
|
||||
func Read(ctx context.Context) (cfg Cfg, err error) {
|
||||
@@ -45,6 +65,7 @@ func Read(ctx context.Context) (cfg Cfg, err error) {
|
||||
// overridden.
|
||||
DefaultDelimiter: ";",
|
||||
DefaultSeparator: "@",
|
||||
DefaultOverwrite: true,
|
||||
|
||||
Lookuper: envconfig.MultiLookuper(secretLookuper(), envconfig.OsLookuper()),
|
||||
})
|
||||
@@ -52,5 +73,7 @@ func Read(ctx context.Context) (cfg Cfg, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
slog.Info("rft", "rft", cfg.Cache.RefreshTime)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -23,11 +23,11 @@ type CachedClient struct {
|
||||
}
|
||||
|
||||
// NewCachedClient creates a new CachedClient.
|
||||
func NewCachedClient(impl FS, client valkey.Client, refreshtime time.Duration) *CachedClient {
|
||||
func NewCachedClient(impl FS, client valkey.Client, refreshtime time.Duration, lifetime time.Duration) *CachedClient {
|
||||
c := &CachedClient{
|
||||
impl: impl,
|
||||
cache: client,
|
||||
ttl: refreshtime * 5,
|
||||
ttl: lifetime,
|
||||
}
|
||||
|
||||
go func() {
|
||||
@@ -42,6 +42,7 @@ func NewCachedClient(impl FS, client valkey.Client, refreshtime time.Duration) *
|
||||
}
|
||||
|
||||
func (c *CachedClient) revalidate(ctx context.Context) {
|
||||
slog.Info("starting revalidation")
|
||||
go c.revalidateReadDir(ctx)
|
||||
go c.revalidateRead(ctx)
|
||||
go c.revalidateStat(ctx)
|
||||
|
||||
@@ -26,7 +26,6 @@ func (c *CachedClient) Read(path string) ([]byte, error) {
|
||||
if err == nil && len(cached) > 0 {
|
||||
c.readHits.Add(1)
|
||||
c.hits.Add(1)
|
||||
slog.Debug("cache hit", "key", key)
|
||||
|
||||
var file readFile
|
||||
err := json.Unmarshal(cached, &file)
|
||||
|
||||
@@ -22,7 +22,6 @@ func (c *CachedClient) ReadDir(path string) ([]os.FileInfo, error) {
|
||||
if err := json.Unmarshal([]byte(val), &cached); err == nil {
|
||||
c.readDirHits.Add(1)
|
||||
c.hits.Add(1)
|
||||
slog.Debug("cache hit", "key", key)
|
||||
infos := make([]os.FileInfo, len(cached))
|
||||
for i, f := range cached {
|
||||
infos[i] = f
|
||||
|
||||
@@ -19,7 +19,6 @@ func (c *CachedClient) Stat(path string) (info os.FileInfo, err error) {
|
||||
var f File
|
||||
if err := json.Unmarshal([]byte(val), &f); err == nil {
|
||||
c.hits.Add(1)
|
||||
slog.Debug("cache hit", "key", key)
|
||||
|
||||
return f, nil
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package server
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -17,7 +17,7 @@ func (c *captureWriter) WriteHeader(statusCode int) {
|
||||
c.ResponseWriter.WriteHeader(statusCode)
|
||||
}
|
||||
|
||||
func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
cw := &captureWriter{
|
||||
@@ -35,7 +35,7 @@ func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
// cacheMiddleware adds Cache-Control headers to the response.
|
||||
func cacheMiddleware(maxAge time.Duration) func(next http.Handler) http.Handler {
|
||||
func Cache(maxAge time.Duration) func(next http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%.0f", maxAge.Seconds()))
|
||||
@@ -0,0 +1,48 @@
|
||||
package templer
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// GetHeader returns a slice of strings that should be added to the html head.
|
||||
// Because strings are immutable a slice of strings is used.
|
||||
func GetHeader(ctx context.Context) []string {
|
||||
v := ctx.Value(headerKey)
|
||||
if v == nil {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
header, ok := v.([]string)
|
||||
if !ok {
|
||||
return []string{}
|
||||
}
|
||||
return header
|
||||
}
|
||||
|
||||
// AppendHeader lets you add lines to the header.
|
||||
func AppendHeader(ctx context.Context, v ...string) context.Context {
|
||||
header := GetHeader(ctx)
|
||||
|
||||
header = append(header, v...)
|
||||
|
||||
return context.WithValue(ctx, headerKey, header)
|
||||
}
|
||||
|
||||
// AppendHeader lets you add lines to the header.
|
||||
func PageTitle(ctx context.Context, title string) context.Context {
|
||||
return context.WithValue(ctx, titleKey, title)
|
||||
}
|
||||
|
||||
// AppendHeader lets you add lines to the header.
|
||||
func GetTitle(ctx context.Context, main string) string {
|
||||
v := ctx.Value(titleKey)
|
||||
if v == nil {
|
||||
return main
|
||||
}
|
||||
|
||||
title, ok := v.(string)
|
||||
if !ok {
|
||||
return main
|
||||
}
|
||||
return title + " | " + main
|
||||
}
|
||||
@@ -11,6 +11,8 @@ type ctxKey int
|
||||
|
||||
const (
|
||||
pathKey ctxKey = iota
|
||||
headerKey
|
||||
titleKey
|
||||
)
|
||||
|
||||
func Middleware(next http.Handler) http.HandlerFunc {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"time"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/gallery"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/page"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/translate"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/restgallery"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/resthome"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/restimage"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/filesystem"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/middleware"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/layouts"
|
||||
"github.com/studio-b12/gowebdav"
|
||||
"github.com/valkey-io/valkey-go"
|
||||
)
|
||||
|
||||
func (s *Server) allRoutes() (h http.Handler, err error) {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
registerStatic(mux)
|
||||
|
||||
other, err := s.dynamicRoutes()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
mux.Handle("/", other)
|
||||
|
||||
h = mux
|
||||
h = templer.Middleware(h)
|
||||
h = middleware.Logging(h)
|
||||
return h, nil
|
||||
}
|
||||
|
||||
func (s *Server) dynamicRoutes() (h http.Handler, err error) {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
webdavClient := gowebdav.NewClient(s.cfg.FileSystem.URL, s.cfg.FileSystem.User, s.cfg.FileSystem.Password)
|
||||
err = webdavClient.Connect()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("could not connect webdavClient: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
var fs filesystem.FS = webdavClient
|
||||
|
||||
valkeyClient, err := valkey.NewClient(valkey.ClientOption{
|
||||
InitAddress: s.cfg.Cache.InitAddress,
|
||||
Password: s.cfg.Cache.Password,
|
||||
})
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to create valkey client: %w", err)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
} else {
|
||||
fs = filesystem.NewCachedClient(webdavClient, valkeyClient, s.cfg.Cache.RefreshTime, s.cfg.Cache.LifeTime)
|
||||
}
|
||||
imageSrv := images.New(fs, s.cfg.Image, valkeyClient)
|
||||
|
||||
mux.Handle("/images/", rest.Use(
|
||||
restimage.New(imageSrv),
|
||||
middleware.Cache(time.Hour*24*5),
|
||||
))
|
||||
|
||||
translator := translate.New()
|
||||
renderer := layouts.New(s.cfg)
|
||||
|
||||
mux.Handle("/", rest.Use(
|
||||
func() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.Handle(path.Join("/"+s.cfg.Gallery.Path), restgallery.New(renderer, gallery.New(fs, s.cfg.Gallery, imageSrv, valkeyClient), s.cfg.Gallery))
|
||||
mux.Handle("/", resthome.New(renderer, page.New(fs)))
|
||||
|
||||
return mux
|
||||
}(),
|
||||
translator.Middleware,
|
||||
middleware.Cache(time.Minute),
|
||||
))
|
||||
|
||||
return mux, nil
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/page"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/translate"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/resthome"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/restimage"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/filesystem"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web"
|
||||
"github.com/studio-b12/gowebdav"
|
||||
"github.com/valkey-io/valkey-go"
|
||||
)
|
||||
|
||||
func (s *Server) RegisterRoutes() (h http.Handler) {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
registerStatic(mux)
|
||||
mux.Handle("/", s.registerOther())
|
||||
|
||||
h = mux
|
||||
h = templer.Middleware(h)
|
||||
h = s.loggingMiddleware(h)
|
||||
return h
|
||||
}
|
||||
|
||||
func (s *Server) registerOther() (h http.Handler) {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
webdavClient := gowebdav.NewClient(s.cfg.FileSystem.URL, s.cfg.FileSystem.User, s.cfg.FileSystem.Password)
|
||||
if err := webdavClient.Connect(); err != nil {
|
||||
slog.Error("could not connect webdavClient", "err", err)
|
||||
}
|
||||
|
||||
var fs filesystem.FS = webdavClient
|
||||
|
||||
valkeyClient, err := valkey.NewClient(valkey.ClientOption{
|
||||
InitAddress: s.cfg.Cache.InitAddress,
|
||||
Password: s.cfg.Cache.Password,
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("failed to create valkey client", "err", err)
|
||||
} else {
|
||||
fs = filesystem.NewCachedClient(webdavClient, valkeyClient, 5*time.Hour)
|
||||
}
|
||||
|
||||
_ = resthome.New(mux, page.New(fs))
|
||||
_ = restimage.New(mux, images.New(fs, s.cfg.Image, valkeyClient))
|
||||
|
||||
mux.Handle("/", http.FileServer(http.FS(web.GetStaticFS())))
|
||||
|
||||
translator := translate.New()
|
||||
|
||||
h = mux
|
||||
h = translator.Middleware(h)
|
||||
h = cacheMiddleware(time.Minute * 5)(h)
|
||||
return h
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
// Package server provides the http server for schreifuchs.ch.
|
||||
package server
|
||||
|
||||
import (
|
||||
@@ -17,6 +18,7 @@ type Server struct {
|
||||
cfg config.Cfg
|
||||
}
|
||||
|
||||
// Start starts a new http server. When the context gets canceled, the server stops gracefully.
|
||||
func Start(ctx context.Context, cfg config.Cfg) (err error) {
|
||||
port, _ := strconv.Atoi(os.Getenv("PORT"))
|
||||
if port == 0 {
|
||||
@@ -27,10 +29,16 @@ func Start(ctx context.Context, cfg config.Cfg) (err error) {
|
||||
cfg: cfg,
|
||||
}
|
||||
|
||||
hander, err := s.allRoutes()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("could not setup routes: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Declare Server config
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", s.port),
|
||||
Handler: s.RegisterRoutes(),
|
||||
Handler: hander,
|
||||
IdleTimeout: time.Minute,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
@@ -45,7 +53,7 @@ func Start(ctx context.Context, cfg config.Cfg) (err error) {
|
||||
// Shutdown server when ctx done
|
||||
if err = srv.Shutdown(context.Background()); err != nil {
|
||||
// Error from closing listeners, or context timeout:
|
||||
err = fmt.Errorf("error whilse shutting down server: %w", err)
|
||||
err = fmt.Errorf("error while shutting down server: %w", err)
|
||||
}
|
||||
|
||||
close(idleConnsClosed)
|
||||
@@ -53,7 +61,7 @@ func Start(ctx context.Context, cfg config.Cfg) (err error) {
|
||||
|
||||
slog.Info("starting server", "address", srv.Addr)
|
||||
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
|
||||
return fmt.Errorf("error while server ListenAndServe: %w", err)
|
||||
return fmt.Errorf("error while serving: %w", err)
|
||||
}
|
||||
|
||||
<-idleConnsClosed
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/middleware"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web"
|
||||
)
|
||||
|
||||
@@ -14,7 +15,7 @@ func registerStatic(mux *http.ServeMux) {
|
||||
fileSystem := web.GetStaticFS()
|
||||
|
||||
// we still use go's fileServer to avoid unnecessary implementation
|
||||
fileServer := cacheMiddleware(time.Hour * 24)(http.FileServer(http.FS(fileSystem)))
|
||||
fileServer := middleware.Cache(time.Hour * 24)(http.FileServer(http.FS(fileSystem)))
|
||||
|
||||
err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
@@ -26,7 +27,7 @@ func registerStatic(mux *http.ServeMux) {
|
||||
|
||||
path = "/" + path
|
||||
|
||||
slog.Debug("registering file", "path", path)
|
||||
slog.Debug("registered static file", "path", path)
|
||||
|
||||
mux.Handle(path, fileServer)
|
||||
|
||||
|
||||
+6
-3
@@ -4,9 +4,9 @@
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"build:css": "tailwindcss -i ./web/static/css/input.css -o ./web/static/css/output.css --minify",
|
||||
"watch:css": "tailwindcss -i ./web/static/css/input.css -o ./web/static/css/output.css --watch",
|
||||
"build:js": "cp node_modules/htmx.org/dist/htmx.min.js web/static/js/htmx.min.js"
|
||||
"build:css": "tailwindcss -i ./web/src/css/input.css -o ./web/static/css/output.css --minify",
|
||||
"watch:css": "tailwindcss -i ./web/src/css/input.css -o ./web/static/css/output.css --watch",
|
||||
"build:js": "node scripts/build.mjs"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
@@ -16,10 +16,13 @@
|
||||
"@tailwindcss/cli": "^4.1.18",
|
||||
"@tailwindcss/typography": "^0.5.19",
|
||||
"autoprefixer": "^10.4.24",
|
||||
"esbuild": "^0.27.4",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^4.1.18"
|
||||
},
|
||||
"dependencies": {
|
||||
"htmx-ext-head-support": "^2.0.5",
|
||||
"htmx-ext-preload": "^2.1.2",
|
||||
"htmx.org": "^2.0.8"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+291
@@ -8,6 +8,12 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
htmx-ext-head-support:
|
||||
specifier: ^2.0.5
|
||||
version: 2.0.5
|
||||
htmx-ext-preload:
|
||||
specifier: ^2.1.2
|
||||
version: 2.1.2
|
||||
htmx.org:
|
||||
specifier: ^2.0.8
|
||||
version: 2.0.8
|
||||
@@ -21,6 +27,9 @@ importers:
|
||||
autoprefixer:
|
||||
specifier: ^10.4.24
|
||||
version: 10.4.24(postcss@8.5.6)
|
||||
esbuild:
|
||||
specifier: ^0.27.4
|
||||
version: 0.27.4
|
||||
postcss:
|
||||
specifier: ^8.5.6
|
||||
version: 8.5.6
|
||||
@@ -30,6 +39,162 @@ importers:
|
||||
|
||||
packages:
|
||||
|
||||
'@esbuild/aix-ppc64@0.27.4':
|
||||
resolution: {integrity: sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ppc64]
|
||||
os: [aix]
|
||||
|
||||
'@esbuild/android-arm64@0.27.4':
|
||||
resolution: {integrity: sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/android-arm@0.27.4':
|
||||
resolution: {integrity: sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/android-x64@0.27.4':
|
||||
resolution: {integrity: sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/darwin-arm64@0.27.4':
|
||||
resolution: {integrity: sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@esbuild/darwin-x64@0.27.4':
|
||||
resolution: {integrity: sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@esbuild/freebsd-arm64@0.27.4':
|
||||
resolution: {integrity: sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [freebsd]
|
||||
|
||||
'@esbuild/freebsd-x64@0.27.4':
|
||||
resolution: {integrity: sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
|
||||
'@esbuild/linux-arm64@0.27.4':
|
||||
resolution: {integrity: sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-arm@0.27.4':
|
||||
resolution: {integrity: sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-ia32@0.27.4':
|
||||
resolution: {integrity: sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ia32]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-loong64@0.27.4':
|
||||
resolution: {integrity: sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-mips64el@0.27.4':
|
||||
resolution: {integrity: sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [mips64el]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-ppc64@0.27.4':
|
||||
resolution: {integrity: sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-riscv64@0.27.4':
|
||||
resolution: {integrity: sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-s390x@0.27.4':
|
||||
resolution: {integrity: sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-x64@0.27.4':
|
||||
resolution: {integrity: sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/netbsd-arm64@0.27.4':
|
||||
resolution: {integrity: sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [netbsd]
|
||||
|
||||
'@esbuild/netbsd-x64@0.27.4':
|
||||
resolution: {integrity: sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [netbsd]
|
||||
|
||||
'@esbuild/openbsd-arm64@0.27.4':
|
||||
resolution: {integrity: sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [openbsd]
|
||||
|
||||
'@esbuild/openbsd-x64@0.27.4':
|
||||
resolution: {integrity: sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [openbsd]
|
||||
|
||||
'@esbuild/openharmony-arm64@0.27.4':
|
||||
resolution: {integrity: sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [openharmony]
|
||||
|
||||
'@esbuild/sunos-x64@0.27.4':
|
||||
resolution: {integrity: sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [sunos]
|
||||
|
||||
'@esbuild/win32-arm64@0.27.4':
|
||||
resolution: {integrity: sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@esbuild/win32-ia32@0.27.4':
|
||||
resolution: {integrity: sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@esbuild/win32-x64@0.27.4':
|
||||
resolution: {integrity: sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@jridgewell/gen-mapping@0.3.13':
|
||||
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
|
||||
|
||||
@@ -267,6 +432,11 @@ packages:
|
||||
resolution: {integrity: sha512-phv3E1Xl4tQOShqSte26C7Fl84EwUdZsyOuSSk9qtAGyyQs2s3jJzComh+Abf4g187lUUAvH+H26omrqia2aGg==}
|
||||
engines: {node: '>=10.13.0'}
|
||||
|
||||
esbuild@0.27.4:
|
||||
resolution: {integrity: sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==}
|
||||
engines: {node: '>=18'}
|
||||
hasBin: true
|
||||
|
||||
escalade@3.2.0:
|
||||
resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
|
||||
engines: {node: '>=6'}
|
||||
@@ -277,6 +447,12 @@ packages:
|
||||
graceful-fs@4.2.11:
|
||||
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
|
||||
|
||||
htmx-ext-head-support@2.0.5:
|
||||
resolution: {integrity: sha512-fTzqnCw7OnMijiS48CCBFBHTuOMvycbX0nEFRL0lkRxyu5DFWX90IV1SwXpQ92fJf02IzkXcRNyjXn3j0QtYxA==}
|
||||
|
||||
htmx-ext-preload@2.1.2:
|
||||
resolution: {integrity: sha512-foD06XAITUUQApCUQnPexyJ6B7+4vFGMQ+t42unTVTGRu/CYHdAAt6oHg7eekPHT7NRnbM5hjnGVKtClryPabg==}
|
||||
|
||||
htmx.org@2.0.8:
|
||||
resolution: {integrity: sha512-fm297iru0iWsNJlBrjvtN7V9zjaxd+69Oqjh4F/Vq9Wwi2kFisLcrLCiv5oBX0KLfOX/zG8AUo9ROMU5XUB44Q==}
|
||||
|
||||
@@ -424,6 +600,84 @@ packages:
|
||||
|
||||
snapshots:
|
||||
|
||||
'@esbuild/aix-ppc64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/android-arm64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/android-arm@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/android-x64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/darwin-arm64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/darwin-x64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/freebsd-arm64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/freebsd-x64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-arm64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-arm@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-ia32@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-loong64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-mips64el@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-ppc64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-riscv64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-s390x@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-x64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/netbsd-arm64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/netbsd-x64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/openbsd-arm64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/openbsd-x64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/openharmony-arm64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/sunos-x64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/win32-arm64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/win32-ia32@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@esbuild/win32-x64@0.27.4':
|
||||
optional: true
|
||||
|
||||
'@jridgewell/gen-mapping@0.3.13':
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.5.5
|
||||
@@ -611,12 +865,49 @@ snapshots:
|
||||
graceful-fs: 4.2.11
|
||||
tapable: 2.3.0
|
||||
|
||||
esbuild@0.27.4:
|
||||
optionalDependencies:
|
||||
'@esbuild/aix-ppc64': 0.27.4
|
||||
'@esbuild/android-arm': 0.27.4
|
||||
'@esbuild/android-arm64': 0.27.4
|
||||
'@esbuild/android-x64': 0.27.4
|
||||
'@esbuild/darwin-arm64': 0.27.4
|
||||
'@esbuild/darwin-x64': 0.27.4
|
||||
'@esbuild/freebsd-arm64': 0.27.4
|
||||
'@esbuild/freebsd-x64': 0.27.4
|
||||
'@esbuild/linux-arm': 0.27.4
|
||||
'@esbuild/linux-arm64': 0.27.4
|
||||
'@esbuild/linux-ia32': 0.27.4
|
||||
'@esbuild/linux-loong64': 0.27.4
|
||||
'@esbuild/linux-mips64el': 0.27.4
|
||||
'@esbuild/linux-ppc64': 0.27.4
|
||||
'@esbuild/linux-riscv64': 0.27.4
|
||||
'@esbuild/linux-s390x': 0.27.4
|
||||
'@esbuild/linux-x64': 0.27.4
|
||||
'@esbuild/netbsd-arm64': 0.27.4
|
||||
'@esbuild/netbsd-x64': 0.27.4
|
||||
'@esbuild/openbsd-arm64': 0.27.4
|
||||
'@esbuild/openbsd-x64': 0.27.4
|
||||
'@esbuild/openharmony-arm64': 0.27.4
|
||||
'@esbuild/sunos-x64': 0.27.4
|
||||
'@esbuild/win32-arm64': 0.27.4
|
||||
'@esbuild/win32-ia32': 0.27.4
|
||||
'@esbuild/win32-x64': 0.27.4
|
||||
|
||||
escalade@3.2.0: {}
|
||||
|
||||
fraction.js@5.3.4: {}
|
||||
|
||||
graceful-fs@4.2.11: {}
|
||||
|
||||
htmx-ext-head-support@2.0.5:
|
||||
dependencies:
|
||||
htmx.org: 2.0.8
|
||||
|
||||
htmx-ext-preload@2.1.2:
|
||||
dependencies:
|
||||
htmx.org: 2.0.8
|
||||
|
||||
htmx.org@2.0.8: {}
|
||||
|
||||
is-extglob@2.1.1: {}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 439 KiB |
-1976
File diff suppressed because it is too large
Load Diff
|
Before Width: | Height: | Size: 112 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 439 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 439 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 439 KiB |
@@ -0,0 +1,69 @@
|
||||
import * as esbuild from "esbuild";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
const filesToCopy = [
|
||||
"node_modules/htmx.org/dist/htmx.min.js",
|
||||
"node_modules/htmx-ext-preload/dist/preload.min.js",
|
||||
"node_modules/htmx-ext-head-support/dist/head-support.min.js",
|
||||
];
|
||||
|
||||
const filesToMinifyRoot = "web/src/js";
|
||||
|
||||
const outputRoot = "web/static/js";
|
||||
|
||||
async function minifyFiles() {
|
||||
try {
|
||||
const files = (await fs.readdir(filesToMinifyRoot))
|
||||
.filter((p) => p.endsWith(".js"))
|
||||
.map((p) => {
|
||||
return {
|
||||
src: path.join(filesToMinifyRoot, p),
|
||||
dest: path.join(outputRoot, p.substring(0, p.length - 3) + ".min.js"),
|
||||
};
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
await esbuild.build({
|
||||
entryPoints: [file.src],
|
||||
bundle: false,
|
||||
minify: true,
|
||||
outfile: file.dest,
|
||||
});
|
||||
console.log(`Minified ${file.src} to ${file.dest}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("could not minify files", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function coppyFromNodemodules() {
|
||||
try {
|
||||
const fileMap = filesToCopy.map((file) => {
|
||||
return {
|
||||
src: file,
|
||||
dest: path.join(outputRoot, path.basename(file)),
|
||||
};
|
||||
});
|
||||
|
||||
for (const file of fileMap) {
|
||||
await fs.copyFile(file.src, file.dest);
|
||||
console.log(`Copied ${path.basename(file.dest)}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("JS build failed:", err);
|
||||
process.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
async function build() {
|
||||
console.log("Starting JS build...");
|
||||
|
||||
await minifyFiles();
|
||||
await coppyFromNodemodules();
|
||||
|
||||
console.log("JS build complete!");
|
||||
}
|
||||
|
||||
build();
|
||||
|
||||
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 4.2 MiB |
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
package testdata
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed *
|
||||
var fs embed.FS
|
||||
|
||||
func FS() mockFS {
|
||||
return mockFS{
|
||||
FS: fs,
|
||||
}
|
||||
}
|
||||
|
||||
type mockFS struct {
|
||||
embed.FS
|
||||
}
|
||||
|
||||
type mockMimer struct{ os.FileInfo }
|
||||
|
||||
func (m *mockMimer) ContentType() string {
|
||||
parts := strings.Split(m.Name(), ".")
|
||||
|
||||
suffix := parts[len(parts)-1]
|
||||
|
||||
switch suffix {
|
||||
case "jpg":
|
||||
return "image/jpeg"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (m mockFS) Read(path string) (b []byte, err error) {
|
||||
file, err := m.Open(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
buff := bytes.NewBuffer(make([]byte, 0, 1024))
|
||||
|
||||
_, err = io.Copy(buff, file)
|
||||
|
||||
return buff.Bytes(), err
|
||||
}
|
||||
|
||||
func (m mockFS) Stat(path string) (info os.FileInfo, err error) {
|
||||
file, err := m.Open(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
info, err = file.Stat()
|
||||
info = &mockMimer{info}
|
||||
return
|
||||
}
|
||||
@@ -8,6 +8,7 @@ templ ImageTile(src string) {
|
||||
src={ src }
|
||||
srcset={ images.SourceSet(src) }
|
||||
fetchpriority="high"
|
||||
loading="eager"
|
||||
class="row-start-1 col-start-1 pointer-events-none w-full h-96 object-cover"
|
||||
/>
|
||||
<div class="row-start-1 col-start-1">
|
||||
|
||||
+26
-11
@@ -1,32 +1,47 @@
|
||||
package layouts
|
||||
|
||||
import "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/translate"
|
||||
import "strings"
|
||||
import "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
|
||||
import (
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/translate"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
|
||||
"strings"
|
||||
)
|
||||
|
||||
templ Base(title string) {
|
||||
<!DOCTYPE html>
|
||||
<html lang={ translate.Language(ctx) }>
|
||||
templ Head(cfg config.Cfg, title string) {
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<title>{ title }</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.png"/>
|
||||
<link fetchpriority="high" href="/css/output.css" rel="stylesheet"/>
|
||||
<script fetchpriority="low" src="/js/htmx.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/htmx-ext-preload@2.1.2" integrity="sha384-PRIcY6hH1Y5784C76/Y8SqLyTanY9rnI3B8F3+hKZFNED55hsEqMJyqWhp95lgfk" crossorigin="anonymous"></script>
|
||||
<script src="/js/htmx.min.js"></script>
|
||||
<script src="/js/head-support.min.js"></script>
|
||||
<script src="/js/preload.min.js"></script>
|
||||
<script src="/js/preload-links.min.js"></script>
|
||||
<script src={ cfg.Tracking.ScriptSrc } data-website-id={ cfg.Tracking.WebsiteID }></script>
|
||||
for _, h := range templer.GetHeader(ctx) {
|
||||
@templ.Raw(h)
|
||||
}
|
||||
</head>
|
||||
<body class="bg-black dark" hx-boost="true" hx-target="main" hx-ext="preload">
|
||||
{ children... }
|
||||
}
|
||||
|
||||
templ Base(cfg config.Cfg, title string) {
|
||||
<!DOCTYPE html>
|
||||
<html lang={ translate.Language(ctx) }>
|
||||
@Head(cfg, title)
|
||||
<body class="bg-black dark" hx-boost="true" hx-target="main" hx-ext="head-support,preload,preload-links">
|
||||
<header
|
||||
class="fixed z-50 mix-blend-difference p-1 w-full flex justify-between items-start"
|
||||
>
|
||||
<a class="text-white text-2xl" href={ "/" + translate.Path(ctx, "") }>schreifuchs.ch</a>
|
||||
<a class="text-white text-2xl" href={ translate.Path(ctx, "") } preload="mouseover" preload-images="true">schreifuchs.ch</a>
|
||||
<nav class="flex gap-2 p-2">
|
||||
for _, lang := range translate.SupportedLanguages(ctx) {
|
||||
<a
|
||||
href={ "/" + translate.PathForLang(ctx, lang, strings.Split(templer.Path(ctx), "/")...) }
|
||||
href={ translate.PathForLang(ctx, lang, strings.Split(templer.Path(ctx), "/")...) }
|
||||
hreflang={ lang }
|
||||
data-no-translate
|
||||
preload="mouseover"
|
||||
class="text-white hover:underline uppercase"
|
||||
>
|
||||
{ lang }
|
||||
|
||||
+19
-2
@@ -7,19 +7,36 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
|
||||
"github.com/a-h/templ"
|
||||
)
|
||||
|
||||
type Layouts struct {
|
||||
cfg config.Cfg
|
||||
}
|
||||
|
||||
func New(cfg config.Cfg) *Layouts {
|
||||
return &Layouts{
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
// Render renders a page. If the query paramenter "c" is set
|
||||
// the component gets rendered without the layout
|
||||
func Render(ctx context.Context, w io.Writer, r *http.Request, component templ.Component) {
|
||||
func (l *Layouts) Render(ctx context.Context, w io.Writer, r *http.Request, component templ.Component) {
|
||||
withLayout := !r.URL.Query().Has("c")
|
||||
fmt.Println("layout: ", withLayout)
|
||||
|
||||
title := templer.GetTitle(ctx, "Schreifuchs")
|
||||
|
||||
slog.Debug("HX-Request", "value", r.Header.Get("HX-Request"))
|
||||
if r.Header.Get("HX-Request") != "true" {
|
||||
ctx = templ.WithChildren(ctx, component)
|
||||
component = Base("hello")
|
||||
component = Base(l.cfg, title)
|
||||
} else {
|
||||
ctx = templ.WithChildren(ctx, component)
|
||||
component = Head(l.cfg, title)
|
||||
}
|
||||
|
||||
if err := component.Render(ctx, w); err != nil {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/gallery"
|
||||
)
|
||||
|
||||
templ GallerySet(g gallery.Set) {
|
||||
<div
|
||||
class="grid gap-5 grid-cols-1 lg:hidden m-5"
|
||||
>
|
||||
for _,img := range g.SM.Images {
|
||||
<img
|
||||
src={ "/images/" + img.UID + "?w=600" }
|
||||
loading="lazy"
|
||||
class="w-full"
|
||||
alt="Gallery item"
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
<div class="hidden lg:block 3xl:hidden m-5">
|
||||
@Gallery(g.SM)
|
||||
</div>
|
||||
<div class="hidden 3xl:block 6xl:hidden m-5">
|
||||
@Gallery(g.LG)
|
||||
</div>
|
||||
<div class="hidden 6xl:block m-5">
|
||||
@Gallery(g.XLG)
|
||||
</div>
|
||||
}
|
||||
|
||||
templ Gallery(g gallery.Gallery) {
|
||||
<div
|
||||
class="grid gap-5"
|
||||
style={ fmt.Sprintf("grid-template-columns: repeat(%d, 1fr); grid-template-rows: repeat(%d, auto);", g.GridWith, g.GridHeight) }
|
||||
>
|
||||
for _, img := range g.Images {
|
||||
<div
|
||||
style={ fmt.Sprintf("grid-column: %d / span %d; grid-row: %d / span %d;aspect-ratio: %d / %d;", img.X+1, img.Width, img.Y+1, img.Height, img.Width, img.Height) }
|
||||
class="overflow-hidden shadow-sm"
|
||||
>
|
||||
<img
|
||||
src={ "/images/" + img.UID + "?w=800" }
|
||||
loading="lazy"
|
||||
class="w-full h-full object-cover"
|
||||
alt="Gallery item"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@@ -9,7 +9,12 @@ import (
|
||||
templ Home(pages []page.PageHeader) {
|
||||
for _, page := range pages {
|
||||
@components.ImageTile("/images/" + page.CoverImageUID) {
|
||||
<a class="flex items-center justify-center h-full " href={ translate.Path(ctx, page.UID) } preload="mouseover">
|
||||
<a
|
||||
class="flex items-center justify-center h-full "
|
||||
href={ translate.Path(ctx, "/"+page.UID) }
|
||||
preload="mouseover"
|
||||
hx-load-links="true"
|
||||
>
|
||||
<h2
|
||||
class="text-3xl font-bold text-white hover:underline text-shadow-lg"
|
||||
>
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @file preload-links.js
|
||||
* @description HTMX extension to extract <link rel="preload"> from preloaded HTML responses.
|
||||
* @generated By opencode (AI Agent)
|
||||
* @model gemini-3-flash-preview
|
||||
* @date Thu Mar 19 2026
|
||||
*/
|
||||
(function () {
|
||||
// Save the original XHR methods
|
||||
const originalOpen = XMLHttpRequest.prototype.open;
|
||||
const originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
|
||||
const originalSend = XMLHttpRequest.prototype.send;
|
||||
|
||||
// We need to track which XHRs are preloads
|
||||
XMLHttpRequest.prototype.open = function () {
|
||||
this._isHtmxPreload = false;
|
||||
return originalOpen.apply(this, arguments);
|
||||
};
|
||||
|
||||
XMLHttpRequest.prototype.setRequestHeader = function (header, value) {
|
||||
if (header.toLowerCase() === "hx-preloaded" && value === "true") {
|
||||
this._isHtmxPreload = true;
|
||||
}
|
||||
return originalSetRequestHeader.apply(this, arguments);
|
||||
};
|
||||
|
||||
XMLHttpRequest.prototype.send = function () {
|
||||
if (this._isHtmxPreload) {
|
||||
this.addEventListener("load", function () {
|
||||
// Parse the response text as HTML
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(this.responseText, "text/html");
|
||||
|
||||
// Find all preload links
|
||||
const links = doc.querySelectorAll('link[rel="preload"]');
|
||||
|
||||
links.forEach((link) => {
|
||||
const href = link.getAttribute("href");
|
||||
// Only inject if the current document doesn't already have it
|
||||
if (
|
||||
href &&
|
||||
!document.querySelector(`link[rel="preload"][href="${href}"]`)
|
||||
) {
|
||||
const newLink = document.createElement("link");
|
||||
newLink.rel = "preload";
|
||||
newLink.href = href;
|
||||
|
||||
// Copy relevant attributes
|
||||
["as", "type", "media", "fetchpriority", "crossorigin"].forEach(
|
||||
(attr) => {
|
||||
const val = link.getAttribute(attr);
|
||||
if (val) newLink.setAttribute(attr, val);
|
||||
},
|
||||
);
|
||||
|
||||
document.head.appendChild(newLink);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
return originalSend.apply(this, arguments);
|
||||
};
|
||||
})();
|
||||
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -0,0 +1 @@
|
||||
(function(){var H=null;function M(){}function a(e,t){if(e&&e.indexOf("<head")>-1){const g=document.createElement("html");var r=e.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");var a=r.match(/(<head(\s[^>]*>|>)([\s\S]*?)<\/head>)/im);if(a){var n=[];var d=[];var o=[];var i=[];g.innerHTML=a;var h=g.querySelector("head");var m=document.head;if(h==null){return}else{var s=new Map;for(const p of h.children){s.set(p.outerHTML,p)}}var u=H.getAttributeValue(h,"hx-head")||t;for(const x of m.children){var l=s.has(x.outerHTML);var f=x.getAttribute("hx-head")==="re-eval";var v=H.getAttributeValue(x,"hx-preserve")==="true";if(l||v){if(f){d.push(x)}else{s.delete(x.outerHTML);o.push(x)}}else{if(u==="append"){if(f){d.push(x);i.push(x)}}else{if(H.triggerEvent(document.body,"htmx:removingHeadElement",{headElement:x})!==false){d.push(x)}}}}i.push(...s.values());M("to append: ",i);for(const E of i){M("adding: ",E);var c=document.createRange().createContextualFragment(E.outerHTML);M(c);if(H.triggerEvent(document.body,"htmx:addingHeadElement",{headElement:c})!==false){m.appendChild(c);n.push(c)}}for(const b of d){if(H.triggerEvent(document.body,"htmx:removingHeadElement",{headElement:b})!==false){m.removeChild(b)}}H.triggerEvent(document.body,"htmx:afterHeadMerge",{added:n,kept:o,removed:d})}}}htmx.defineExtension("head-support",{init:function(e){H=e;htmx.on("htmx:afterSwap",function(e){let t=e.detail.xhr;if(t){var r=t.response;if(H.triggerEvent(document.body,"htmx:beforeHeadMerge",e.detail)){a(r,e.detail.boosted?"merge":"append")}}});htmx.on("htmx:historyRestore",function(e){if(H.triggerEvent(document.body,"htmx:beforeHeadMerge",e.detail)){if(e.detail.cacheMiss){a(e.detail.serverResponse,"merge")}else{a(e.detail.item.head,"merge")}}});htmx.on("htmx:historyItemCreated",function(e){var t=e.detail.item;t.head=document.head.outerHTML})}})})();
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
(function(){const p=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.setRequestHeader,l=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(){return this._isHtmxPreload=!1,p.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(r,o){return r.toLowerCase()==="hx-preloaded"&&o==="true"&&(this._isHtmxPreload=!0),a.apply(this,arguments)},XMLHttpRequest.prototype.send=function(){return this._isHtmxPreload&&this.addEventListener("load",function(){new DOMParser().parseFromString(this.responseText,"text/html").querySelectorAll('link[rel="preload"]').forEach(n=>{const t=n.getAttribute("href");if(t&&!document.querySelector(`link[rel="preload"][href="${t}"]`)){const e=document.createElement("link");e.rel="preload",e.href=t,["as","type","media","fetchpriority","crossorigin"].forEach(s=>{const i=n.getAttribute(s);i&&e.setAttribute(s,i)}),document.head.appendChild(e)}})}),l.apply(this,arguments)}})();
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
(function(){htmx.defineExtension("preload",{onEvent:function(e,t){if(e==="htmx:afterProcessNode"){const n=t.target||t.detail.elt;const r=[...n.hasAttribute("preload")?[n]:[],...n.querySelectorAll("[preload]")];r.forEach(function(e){i(e);e.querySelectorAll("[href],[hx-get],[data-hx-get]").forEach(i)});return}if(e==="htmx:beforeRequest"){const o=t.detail.requestConfig.headers;if(!("HX-Preloaded"in o&&o["HX-Preloaded"]==="true")){return}t.preventDefault();const a=t.detail.xhr;a.onload=function(){s(t.detail.elt,a.responseText)};a.onerror=null;a.onabort=null;a.ontimeout=null;a.send()}}});function i(t){if(t.preloadState!==undefined){return}if(!l(t)){return}if(t instanceof HTMLFormElement){const o=t;if(!(o.hasAttribute("method")&&o.method==="get"||o.hasAttribute("hx-get")||o.hasAttribute("hx-data-get"))){return}for(let e=0;e<o.elements.length;e++){const a=o.elements.item(e);i(a);if("labels"in a){a.labels.forEach(i)}}return}let e=p(t,"preload");t.preloadAlways=e&&e.includes("always");if(t.preloadAlways){e=e.replace("always","").trim()}let n=e||"mousedown";const r=n==="mouseover";t.addEventListener(n,u(t,r),{passive:true});if(n==="mousedown"||n==="mouseover"){t.addEventListener("touchstart",u(t),{passive:true})}if(n==="mouseover"){t.addEventListener("mouseout",function(e){if(e.target===t&&t.preloadState==="TIMEOUT"){t.preloadState="READY"}},{passive:true})}t.preloadState="READY";htmx.trigger(t,"preload:init")}function u(t,n=false){return function(){if(t.preloadState!=="READY"){return}if(n){t.preloadState="TIMEOUT";const e=100;window.setTimeout(function(){if(t.preloadState==="TIMEOUT"){t.preloadState="READY";r(t)}},e);return}r(t)}}function r(n){if(n.preloadState!=="READY"){return}n.preloadState="LOADING";const e=n.getAttribute("hx-get")||n.getAttribute("data-hx-get");if(e){m(e,n);return}const t=p(n,"hx-boost")==="true";if(n.hasAttribute("href")){const r=n.getAttribute("href");if(t){m(r,n)}else{h(r,n)}return}if(g(n)){const r=n.form.getAttribute("action")||n.form.getAttribute("hx-get")||n.form.getAttribute("data-hx-get");const o=htmx.values(n.form);const a=!(n.form.getAttribute("hx-get")||n.form.getAttribute("data-hx-get")||t);const i=a?h:m;if(n.type==="submit"){i(r,n.form,o);return}const u=n.name||n.control.name;if(n.tagName==="SELECT"){Array.from(n.options).forEach(e=>{if(e.selected)return;o.set(u,e.value);const t=d(n.form,o);i(r,n.form,t)});return}const s=n.getAttribute("type")||n.control.getAttribute("type");const l=n.value||n.control?.value;if(s==="radio"){o.set(u,l)}else if(s==="checkbox"){const c=o.getAll(u);if(c.includes(l)){o[u]=c.filter(e=>e!==l)}else{o.append(u,l)}}const f=d(n.form,o);i(r,n.form,f);return}}function d(e,t){const n=e.elements;const r=new FormData;for(let e=0;e<n.length;e++){const o=n.item(e);if(t.has(o.name)&&o.tagName==="SELECT"){r.append(o.name,t.get(o.name));continue}if(t.has(o.name)&&t.getAll(o.name).includes(o.value)){r.append(o.name,o.value)}}return r}function m(e,t,n=undefined){htmx.ajax("GET",e,{source:t,values:n,headers:{"HX-Preloaded":"true"}})}function h(e,t,n=undefined){const r=new XMLHttpRequest;if(n){e+="?"+new URLSearchParams(n.entries()).toString()}r.open("GET",e);r.setRequestHeader("HX-Preloaded","true");r.onload=function(){s(t,r.responseText)};r.send()}function s(e,t){e.preloadState=e.preloadAlways?"READY":"DONE";if(p(e,"preload-images")==="true"){document.createElement("div").innerHTML=t}}function p(e,t){if(e==undefined){return undefined}return e.getAttribute(t)||e.getAttribute("data-"+t)||p(e.parentElement,t)}function l(e){const n=["href","hx-get","data-hx-get"];const t=t=>n.some(e=>t.hasAttribute(e))||t.method==="get";const r=e.form instanceof HTMLFormElement&&t(e.form)&&g(e);if(!t(e)&&!r){return false}if(e instanceof HTMLInputElement&&e.closest("label")){return false}return true}function g(e){if(e instanceof HTMLInputElement||e instanceof HTMLButtonElement){const t=e.getAttribute("type");return["checkbox","radio","submit"].includes(t)}if(e instanceof HTMLLabelElement){return e.control&&g(e.control)}return e instanceof HTMLSelectElement}})();
|
||||
Reference in New Issue
Block a user