Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
297efaa4a6 | ||
|
|
c08dd355c0 | ||
|
|
9ec2585030 | ||
|
|
72bc974aa6 | ||
|
|
c678c7aa45 | ||
|
|
763163c24e |
No files matched your search
@@ -17,9 +17,6 @@ RUN pnpm run build:css && pnpm run build:js
|
|||||||
FROM golang:1.26-alpine AS go-builder
|
FROM golang:1.26-alpine AS go-builder
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Install git for potential private modules (though not strictly needed here)
|
|
||||||
RUN apk add --no-cache git
|
|
||||||
|
|
||||||
# Download Go modules
|
# Download Go modules
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
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
|
FROM alpine:latest
|
||||||
WORKDIR /app
|
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 the compiled binary from the builder stage
|
||||||
COPY --from=go-builder /app/server .
|
COPY --from=go-builder /app/server .
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
.PHONY: run
|
||||||
|
run: docker
|
||||||
|
air
|
||||||
|
|
||||||
|
.PHONY: docker
|
||||||
|
docker:
|
||||||
|
docker compose up -d
|
||||||
@@ -91,4 +91,3 @@ To optimize images before uploading to Nextcloud:
|
|||||||
```bash
|
```bash
|
||||||
convert input.png -resize 3000 -quality 80 output.webp
|
convert input.png -resize 3000 -quality 80 output.webp
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -30,11 +30,7 @@ func main() {
|
|||||||
slog.Error("could not read configuaration", "err", err)
|
slog.Error("could not read configuaration", "err", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
slog.SetDefault(
|
setupLogger(&cfg)
|
||||||
slog.New(
|
|
||||||
slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
err = server.Start(ctx, cfg)
|
err = server.Start(ctx, cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -42,3 +38,22 @@ func main() {
|
|||||||
return
|
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:
|
services:
|
||||||
valkey:
|
valkey:
|
||||||
image: valkey/valkey:8
|
image: valkey/valkey:8
|
||||||
restart: always
|
|
||||||
ports:
|
ports:
|
||||||
- "6379:6379"
|
- "6379:6379"
|
||||||
command: valkey-server --requirepass "valkey"
|
command: valkey-server --requirepass "valkey"
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ require (
|
|||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/InfinityTools/go-binpack2d v1.0.0 // indirect
|
||||||
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e // indirect
|
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e // indirect
|
||||||
github.com/andybalholm/brotli v1.1.0 // indirect
|
github.com/andybalholm/brotli v1.1.0 // indirect
|
||||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
github.com/cenkalti/backoff/v4 v4.3.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 h1:HjVbSQHy+dnlS6C3XajZ69NYAb5jbGNfHanvm1+iYlo=
|
||||||
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e/go.mod h1:3mnrkvGpurZ4ZrTDbYU84xhwXW2TjTKShSwjRi2ihfQ=
|
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e/go.mod h1:3mnrkvGpurZ4ZrTDbYU84xhwXW2TjTKShSwjRi2ihfQ=
|
||||||
github.com/a-h/templ v0.3.977 h1:kiKAPXTZE2Iaf8JbtM21r54A8bCNsncrfnokZZSrSDg=
|
github.com/a-h/templ v0.3.977 h1:kiKAPXTZE2Iaf8JbtM21r54A8bCNsncrfnokZZSrSDg=
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package gallery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log/slog"
|
||||||
|
"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, math.MaxInt)
|
||||||
|
|
||||||
|
for len(imgs) > 0 {
|
||||||
|
unused := make([]Image, 0, len(imgs))
|
||||||
|
for _, img := range imgs {
|
||||||
|
adjustImageSizeStrictRatio(&img, 200)
|
||||||
|
if img.Height == 0 || img.Width == 0 {
|
||||||
|
slog.Warn("image has invalid size", "img", img)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// getCleanRatio returns the simplified aspect ratio as (numerator, denominator).
|
||||||
|
// It searches for the best fit within a denominator limit to account for rounding errors.
|
||||||
|
func getCleanRatio(width, height int) (int, int) {
|
||||||
|
targetRatio := float64(width) / float64(height)
|
||||||
|
const maxDenominator = 100
|
||||||
|
|
||||||
|
bestN, bestD := 0, 1
|
||||||
|
minDiff := math.MaxFloat64
|
||||||
|
|
||||||
|
for d := 1; d <= maxDenominator; d++ {
|
||||||
|
// Calculate the closest numerator for this denominator
|
||||||
|
n := int(math.Round(float64(d) * targetRatio))
|
||||||
|
|
||||||
|
// Calculate the difference
|
||||||
|
currentRatio := float64(n) / float64(d)
|
||||||
|
diff := math.Abs(currentRatio - targetRatio)
|
||||||
|
|
||||||
|
// Keep track of the one with the smallest error
|
||||||
|
if diff < minDiff {
|
||||||
|
minDiff = diff
|
||||||
|
bestN, bestD = n, d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return bestN, bestD
|
||||||
|
}
|
||||||
|
|
||||||
|
func adjustImageSizeStrictRatio(img *Image, targetArea int) {
|
||||||
|
baseW, baseH := getCleanRatio(img.Width, img.Height)
|
||||||
|
|
||||||
|
baseArea := baseW * baseH
|
||||||
|
|
||||||
|
idealK := math.Sqrt(float64(targetArea) / float64(baseArea))
|
||||||
|
|
||||||
|
k := int(math.Floor(idealK))
|
||||||
|
|
||||||
|
if math.Abs(float64(k*k*baseArea-targetArea)) >
|
||||||
|
math.Abs(float64(int(math.Ceil(idealK))*int(math.Ceil(idealK))*baseArea-targetArea)) {
|
||||||
|
k = int(math.Ceil(idealK))
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Debug("adslkfj", "k", k, "idealK", idealK, "baseH", baseH, "baseW", baseW, "imgW", img.Width, "imgH", img.Height)
|
||||||
|
|
||||||
|
// 5. Apply the scaled dimensions (guarantees perfect aspect ratio)
|
||||||
|
img.Width = baseW * k
|
||||||
|
img.Height = baseH * k
|
||||||
|
}
|
||||||
@@ -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,156 @@
|
|||||||
|
package gallery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"hash/fnv"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
|
||||||
|
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest"
|
||||||
|
"github.com/valkey-io/valkey-go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Image struct {
|
||||||
|
UID string
|
||||||
|
X int
|
||||||
|
Y int
|
||||||
|
Width int
|
||||||
|
Height int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i Image) URL() string {
|
||||||
|
return images.URLFromUID(i.UID)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
w := img.Bounds().Dx()
|
||||||
|
h := img.Bounds().Dy()
|
||||||
|
|
||||||
|
// FIX 2: Defensive check to guard against unreadable/corrupted image boundaries
|
||||||
|
if w <= 0 || h <= 0 {
|
||||||
|
slog.Warn("skipping image with zero or negative dimensions", "path", imagePath, "w", w, "h", h)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
imgs = append(imgs, Image{
|
||||||
|
UID: uid,
|
||||||
|
Width: w,
|
||||||
|
Height: h,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetPrevAndNext(ctx context.Context, uid string) (previous *Image, next *Image, err error) {
|
||||||
|
imgs, err := s.GetImages(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range imgs {
|
||||||
|
if imgs[i].UID != uid {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if i > 0 {
|
||||||
|
prevImg := imgs[i-1]
|
||||||
|
previous = &prevImg
|
||||||
|
}
|
||||||
|
if i+1 < len(imgs) {
|
||||||
|
nextImg := imgs[i+1]
|
||||||
|
next = &nextImg
|
||||||
|
}
|
||||||
|
|
||||||
|
return previous, next, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, nil, &rest.Error{
|
||||||
|
Type: rest.ErrorTypeNotFound,
|
||||||
|
Message: "could not find image with uid",
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ import (
|
|||||||
|
|
||||||
var ErrNotAnImage = errors.New("not an image")
|
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)
|
info, err := s.fs.Stat(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("image file info could not be fetched: %w", err)
|
err = fmt.Errorf("image file info could not be fetched: %w", err)
|
||||||
@@ -35,13 +35,12 @@ func (s *Service) getMime(path string) (mimeType string, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) getImage(uid string) (file []byte, mimeType string, err error) {
|
func (s *Service) getImage(path string) (file []byte, mimeType string, err error) {
|
||||||
path, err := PathFromUID(uid)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("could not get path: %w", err)
|
err = fmt.Errorf("could not get path: %w", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
mimeType, err = s.getMime(path)
|
mimeType, err = s.GetMime(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -59,7 +58,19 @@ func (s *Service) getImage(uid string) (file []byte, mimeType string, err error)
|
|||||||
return
|
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 {
|
if err = s.seph.Acquire(ctx, 1); err != nil {
|
||||||
err = fmt.Errorf("could not Acquire semaphore: %w", err)
|
err = fmt.Errorf("could not Acquire semaphore: %w", err)
|
||||||
return
|
return
|
||||||
@@ -67,7 +78,12 @@ func (s *Service) GetImage(ctx context.Context, uid string, options Options) (im
|
|||||||
}
|
}
|
||||||
defer s.seph.Release(1)
|
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 {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import (
|
|||||||
|
|
||||||
func Setup(ctx context.Context, ctrl *gomock.Controller) (*images.Service, *mock.Client) {
|
func Setup(ctx context.Context, ctrl *gomock.Controller) (*images.Service, *mock.Client) {
|
||||||
valkey := mock.NewClient(ctrl)
|
valkey := mock.NewClient(ctrl)
|
||||||
return images.New(testdata.FS(), &config.ImageConfig{Concurency: 1, Quality: 80}, valkey), valkey
|
return images.New(testdata.FS(), &config.Image{Concurency: 1, Quality: 80}, valkey), valkey
|
||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkService_GetImage(b *testing.B) {
|
func BenchmarkService_GetImage(b *testing.B) {
|
||||||
@@ -29,7 +29,7 @@ func BenchmarkService_GetImage(b *testing.B) {
|
|||||||
for b.Loop() {
|
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.ErrorResult(errors.New("adf")))
|
||||||
valkeyClient.EXPECT().Do(gomock.Any(), gomock.Any()).Return(mock.Result(valkey.ValkeyMessage{}))
|
valkeyClient.EXPECT().Do(gomock.Any(), gomock.Any()).Return(mock.Result(valkey.ValkeyMessage{}))
|
||||||
_, _, err = srv.GetImage(b.Context(), uid, images.Options{Width: 500, Quality: 80})
|
_, _, err = srv.GetScaledImage(b.Context(), uid, images.Options{Width: 500, Quality: 80})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Error(err)
|
b.Error(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ func UIDFromPath(path string) (uid string, err error) {
|
|||||||
|
|
||||||
func URLFromPath(path string) (url string, err error) {
|
func URLFromPath(path string) (url string, err error) {
|
||||||
uid, err := UIDFromPath(path)
|
uid, err := UIDFromPath(path)
|
||||||
|
url = URLFromUID(uid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func URLFromUID(uid string) (url string) {
|
||||||
url = "/images/" + uid
|
url = "/images/" + uid
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
fs fileSystem
|
||||||
cache valkey.Client
|
cache valkey.Client
|
||||||
seph *semaphore.Weighted
|
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{
|
return &Service{
|
||||||
fs: fs,
|
fs: fs,
|
||||||
cache: cache,
|
cache: cache,
|
||||||
|
|||||||
@@ -56,9 +56,14 @@ func (s *Service) getPageHeaders(ctx context.Context, uid string) (page PageHead
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
page.md, err = s.fs.Read(contentMD.Path())
|
if contentMD != nil {
|
||||||
if err != nil {
|
|
||||||
return
|
page.md, err = s.fs.Read(contentMD.Path())
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
page.md = []byte("# ...")
|
||||||
}
|
}
|
||||||
|
|
||||||
title := titleRGX.FindStringSubmatch(string(page.md))
|
title := titleRGX.FindStringSubmatch(string(page.md))
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ func SupportedLanguages(ctx context.Context) []string {
|
|||||||
s, ok := ctx.Value(serviceKey).(*Service)
|
s, ok := ctx.Value(serviceKey).(*Service)
|
||||||
if !ok {
|
if !ok {
|
||||||
slog.Error("could not extract translation service from context for getting supported languages")
|
slog.Error("could not extract translation service from context for getting supported languages")
|
||||||
|
return []string{}
|
||||||
}
|
}
|
||||||
return s.SupportedLanguages()
|
return s.SupportedLanguages()
|
||||||
}
|
}
|
||||||
@@ -52,13 +53,21 @@ func Path(ctx context.Context, pp ...string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func PathForLang(ctx context.Context, lang string, pp ...string) string {
|
func PathForLang(ctx context.Context, lang string, pp ...string) string {
|
||||||
|
slog.Debug("computing path for lang", "pp", pp, "lang", lang)
|
||||||
s, ok := ctx.Value(serviceKey).(*Service)
|
s, ok := ctx.Value(serviceKey).(*Service)
|
||||||
if !ok {
|
if !ok {
|
||||||
slog.Error("could not extract translation service from context for translating path", "ctx", ctx, "path", pp)
|
slog.Error("could not extract translation service from context for translating path", "ctx", ctx, "path", pp)
|
||||||
return path.Join(pp...)
|
return path.Join(pp...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// remove leading ""
|
||||||
|
for len(pp) > 0 && pp[0] == "" {
|
||||||
|
pp = pp[1:]
|
||||||
|
}
|
||||||
|
|
||||||
if len(pp) > 0 {
|
if len(pp) > 0 {
|
||||||
|
|
||||||
|
slog.Debug("computing path for lang", "pp", pp, "lang", lang, "pp[0]", pp[0], "translations", s.translations)
|
||||||
if _, ok := s.translations[pp[0]]; ok {
|
if _, ok := s.translations[pp[0]]; ok {
|
||||||
pp = pp[1:]
|
pp = pp[1:]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package restgallery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest"
|
||||||
|
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
|
||||||
|
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/pages"
|
||||||
|
)
|
||||||
|
|
||||||
|
const preloadCount = 6
|
||||||
|
|
||||||
|
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 gallery set", "err", err)
|
||||||
|
rest.SendErr(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx := r.Context()
|
||||||
|
for i, image := range imgs.LG.Images {
|
||||||
|
if i > preloadCount {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
ctx = templer.AppendHeader(ctx, fmt.Sprintf(`<link rel="preload" href="%s?w=800" as="image" />`, image.URL()))
|
||||||
|
}
|
||||||
|
|
||||||
|
h.r.Render(ctx, w, r, pages.GallerySet(imgs))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) image(w http.ResponseWriter, r *http.Request) {
|
||||||
|
uid := r.PathValue("image_uid")
|
||||||
|
|
||||||
|
slog.Debug("image from gallery", "uid", uid)
|
||||||
|
prev, next, err := h.srv.GetPrevAndNext(r.Context(), uid)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("could not get gallery", "err", err)
|
||||||
|
rest.SendErr(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.r.Render(r.Context(), w, r, pages.GalleryImage(uid, next, prev))
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
galleryPath := url.PathEscape(cfg.Path)
|
||||||
|
|
||||||
|
mux.HandleFunc(fmt.Sprintf("GET /%s/{image_uid}", galleryPath), h.image)
|
||||||
|
mux.HandleFunc(fmt.Sprintf("GET /%s", galleryPath), h.gallery)
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
type galleryService interface {
|
||||||
|
GetGallerySet(ctx context.Context) (gallerySet gallery.Set, err error)
|
||||||
|
GetPrevAndNext(ctx context.Context, uid string) (previous *gallery.Image, next *gallery.Image, err error)
|
||||||
|
}
|
||||||
|
type renderer interface {
|
||||||
|
Render(ctx context.Context, w io.Writer, r *http.Request, component templ.Component)
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package resthome
|
package resthome
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
@@ -24,6 +26,10 @@ func (h *Handler) page(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
page, err := h.src.GetPage(r.Context(), uid)
|
page, err := h.src.GetPage(r.Context(), uid)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, context.Canceled) {
|
||||||
|
w.WriteHeader(http.StatusRequestTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -31,7 +31,7 @@ func (h *Handler) getImage(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
img, mime, err := h.img.GetImage(r.Context(), uid, options)
|
img, mime, err := h.img.GetScaledImage(r.Context(), uid, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("error wile serving image", "err", err, "uid", uid)
|
slog.Error("error wile serving image", "err", err, "uid", uid)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
@@ -25,5 +25,5 @@ func New(srv imageService) *Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type imageService interface {
|
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)
|
||||||
}
|
}
|
||||||
@@ -4,14 +4,22 @@ import "time"
|
|||||||
|
|
||||||
func Default() Cfg {
|
func Default() Cfg {
|
||||||
return Cfg{
|
return Cfg{
|
||||||
Image: &ImageConfig{
|
Image: &Image{
|
||||||
Concurency: 10,
|
Concurency: 10,
|
||||||
Quality: 80,
|
Quality: 80,
|
||||||
CacheLifetime: time.Hour * 24 * 31,
|
CacheLifetime: time.Hour * 24 * 31,
|
||||||
},
|
},
|
||||||
Tracking: &UmamiConfig{
|
Tracking: &Umami{
|
||||||
ScriptSrc: "https://umami.schreifuchs.ch/script.js",
|
ScriptSrc: "https://umami.schreifuchs.ch/script.js",
|
||||||
WebsiteID: "54d8a379-77d5-4c20-b46d-5c9a6c9e39bd",
|
WebsiteID: "54d8a379-77d5-4c20-b46d-5c9a6c9e39bd",
|
||||||
},
|
},
|
||||||
|
Gallery: &Gallery{
|
||||||
|
Path: "photos",
|
||||||
|
},
|
||||||
|
Cache: &Valkey{
|
||||||
|
RefreshTime: time.Minute * 10,
|
||||||
|
LifeTime: time.Hour * 48,
|
||||||
|
},
|
||||||
|
LogJSON: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,11 +10,13 @@ import (
|
|||||||
|
|
||||||
type Cfg struct {
|
type Cfg struct {
|
||||||
FileSystem *WebdavConfig `env:", prefix=FILESYSTEM_"`
|
FileSystem *WebdavConfig `env:", prefix=FILESYSTEM_"`
|
||||||
Cache *ValkeyConfig `env:", prefix=CACHE_"`
|
Cache *Valkey `env:", prefix=CACHE_"`
|
||||||
Image *ImageConfig `env:", prefix=IMAGE_"`
|
Image *Image `env:", prefix=IMAGE_"`
|
||||||
Tracking *UmamiConfig `env:", prefix=TRACKING_"`
|
Tracking *Umami `env:", prefix=TRACKING_"`
|
||||||
|
Gallery *Gallery `env:", prefix=GALLERY_"`
|
||||||
|
|
||||||
LogLevel slog.Level `env:"LOG_LEVEL, default=DEBUG"`
|
LogLevel slog.Level `env:"LOG_LEVEL, default=DEBUG"`
|
||||||
|
LogJSON bool `env:"LOG_JSON"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type WebdavConfig struct {
|
type WebdavConfig struct {
|
||||||
@@ -23,11 +25,14 @@ type WebdavConfig struct {
|
|||||||
Password string `env:"PASSWORD"`
|
Password string `env:"PASSWORD"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ValkeyConfig struct {
|
type Valkey struct {
|
||||||
ClientName string `env:"CLIENTNAME"`
|
ClientName string `env:"CLIENTNAME"`
|
||||||
Username string `env:"USERNAME"`
|
Username string `env:"USERNAME"`
|
||||||
Password string `env:"PASSWORD"`
|
Password string `env:"PASSWORD"`
|
||||||
|
|
||||||
|
RefreshTime time.Duration `env:"REFRESH_TIME"`
|
||||||
|
LifeTime time.Duration `env:"LIFE_TIME"`
|
||||||
|
|
||||||
// InitAddress point to valkey nodes.
|
// 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.
|
// 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.
|
// If len(InitAddress) == 1 and the address is not running in cluster mode, valkey will fall back to the single client mode.
|
||||||
@@ -36,13 +41,17 @@ type ValkeyConfig struct {
|
|||||||
InitAddress []string `env:"ADDRESS"`
|
InitAddress []string `env:"ADDRESS"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ImageConfig struct {
|
type Image struct {
|
||||||
Concurency int64 `env:"CONCURENCY"`
|
Concurency int64 `env:"CONCURENCY"`
|
||||||
Quality int `env:"QUALITY"`
|
Quality int `env:"QUALITY"`
|
||||||
CacheLifetime time.Duration `env:"CACHE_LIFETIME"`
|
CacheLifetime time.Duration `env:"CACHE_LIFETIME"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UmamiConfig struct {
|
type Gallery struct {
|
||||||
|
Path string `env:"PATH"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Umami struct {
|
||||||
ScriptSrc string `env:"SCRIPT_SRC"`
|
ScriptSrc string `env:"SCRIPT_SRC"`
|
||||||
WebsiteID string `env:"WEBSITE_ID"`
|
WebsiteID string `env:"WEBSITE_ID"`
|
||||||
}
|
}
|
||||||
@@ -64,5 +73,7 @@ func Read(ctx context.Context) (cfg Cfg, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
slog.Info("rft", "rft", cfg.Cache.RefreshTime)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -23,11 +23,11 @@ type CachedClient struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewCachedClient creates a new CachedClient.
|
// 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{
|
c := &CachedClient{
|
||||||
impl: impl,
|
impl: impl,
|
||||||
cache: client,
|
cache: client,
|
||||||
ttl: refreshtime * 5,
|
ttl: lifetime,
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
@@ -42,6 +42,7 @@ func NewCachedClient(impl FS, client valkey.Client, refreshtime time.Duration) *
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *CachedClient) revalidate(ctx context.Context) {
|
func (c *CachedClient) revalidate(ctx context.Context) {
|
||||||
|
slog.Info("starting revalidation")
|
||||||
go c.revalidateReadDir(ctx)
|
go c.revalidateReadDir(ctx)
|
||||||
go c.revalidateRead(ctx)
|
go c.revalidateRead(ctx)
|
||||||
go c.revalidateStat(ctx)
|
go c.revalidateStat(ctx)
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ func (m *MockFS) ReadDir(path string) ([]os.FileInfo, error) {
|
|||||||
if len(prefix) > 0 && prefix[len(prefix)-1] != '/' {
|
if len(prefix) > 0 && prefix[len(prefix)-1] != '/' {
|
||||||
prefix += "/"
|
prefix += "/"
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(p) > len(prefix) && p[:len(prefix)] == prefix {
|
if len(p) > len(prefix) && p[:len(prefix)] == prefix {
|
||||||
// Ensure direct child (no more slashes)
|
// Ensure direct child (no more slashes)
|
||||||
rel := p[len(prefix):]
|
rel := p[len(prefix):]
|
||||||
@@ -150,7 +150,7 @@ func TestCachedClient_Stat(t *testing.T) {
|
|||||||
mockFS := NewMockFS()
|
mockFS := NewMockFS()
|
||||||
mockFS.AddFile("/test.txt", []byte("hello"))
|
mockFS.AddFile("/test.txt", []byte("hello"))
|
||||||
|
|
||||||
c := NewCachedClient(mockFS, client, time.Hour)
|
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
|
||||||
|
|
||||||
// First call: Cache miss
|
// First call: Cache miss
|
||||||
info, err := c.Stat("/test.txt")
|
info, err := c.Stat("/test.txt")
|
||||||
@@ -209,7 +209,7 @@ func TestCachedClient_Read(t *testing.T) {
|
|||||||
content := []byte("hello world")
|
content := []byte("hello world")
|
||||||
mockFS.AddFile("/read.txt", content)
|
mockFS.AddFile("/read.txt", content)
|
||||||
|
|
||||||
c := NewCachedClient(mockFS, client, time.Hour)
|
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
|
||||||
|
|
||||||
// First call: Miss
|
// First call: Miss
|
||||||
data, err := c.Read("/read.txt")
|
data, err := c.Read("/read.txt")
|
||||||
@@ -257,7 +257,7 @@ func TestCachedClient_ReadDir(t *testing.T) {
|
|||||||
mockFS.AddFile("/dir/f1.txt", []byte("1"))
|
mockFS.AddFile("/dir/f1.txt", []byte("1"))
|
||||||
mockFS.AddFile("/dir/f2.txt", []byte("2"))
|
mockFS.AddFile("/dir/f2.txt", []byte("2"))
|
||||||
|
|
||||||
c := NewCachedClient(mockFS, client, time.Hour)
|
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
|
||||||
|
|
||||||
// First call: Miss
|
// First call: Miss
|
||||||
infos, err := c.ReadDir("/dir")
|
infos, err := c.ReadDir("/dir")
|
||||||
@@ -303,7 +303,7 @@ func TestCachedClient_RevalidateStat(t *testing.T) {
|
|||||||
mockFS := NewMockFS()
|
mockFS := NewMockFS()
|
||||||
mockFS.AddFile("/reval.txt", []byte("initial"))
|
mockFS.AddFile("/reval.txt", []byte("initial"))
|
||||||
|
|
||||||
c := NewCachedClient(mockFS, client, time.Hour)
|
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
|
||||||
|
|
||||||
// Populate cache
|
// Populate cache
|
||||||
_, _ = c.Stat("/reval.txt")
|
_, _ = c.Stat("/reval.txt")
|
||||||
@@ -342,7 +342,7 @@ func TestCachedClient_RevalidateStat(t *testing.T) {
|
|||||||
// We can inspect redis directly or trust `Stat` returns cached value (which should be updated).
|
// We can inspect redis directly or trust `Stat` returns cached value (which should be updated).
|
||||||
// Let's inspect redis to be sure.
|
// Let's inspect redis to be sure.
|
||||||
// Or just call Stat again. It should be a cache HIT, but return NEW values.
|
// Or just call Stat again. It should be a cache HIT, but return NEW values.
|
||||||
|
|
||||||
// Reset stats to check hit
|
// Reset stats to check hit
|
||||||
c.hits.Store(0)
|
c.hits.Store(0)
|
||||||
c.misses.Store(0)
|
c.misses.Store(0)
|
||||||
@@ -351,11 +351,11 @@ func TestCachedClient_RevalidateStat(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Stat failed: %v", err)
|
t.Fatalf("Stat failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if info.Size() != int64(len("updated content")) {
|
if info.Size() != int64(len("updated content")) {
|
||||||
t.Errorf("expected size %d, got %d", len("updated content"), info.Size())
|
t.Errorf("expected size %d, got %d", len("updated content"), info.Size())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Should be a hit because revalidate updated the cache entry, so it exists and is valid.
|
// Should be a hit because revalidate updated the cache entry, so it exists and is valid.
|
||||||
if c.hits.Load() != 1 {
|
if c.hits.Load() != 1 {
|
||||||
t.Errorf("expected 1 hit, got %d", c.hits.Load())
|
t.Errorf("expected 1 hit, got %d", c.hits.Load())
|
||||||
@@ -381,7 +381,7 @@ func TestCachedClient_RevalidateRead(t *testing.T) {
|
|||||||
mockFS := NewMockFS()
|
mockFS := NewMockFS()
|
||||||
mockFS.AddFile("/read_reval.txt", []byte("initial"))
|
mockFS.AddFile("/read_reval.txt", []byte("initial"))
|
||||||
|
|
||||||
c := NewCachedClient(mockFS, client, time.Hour)
|
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
|
||||||
|
|
||||||
// Populate cache
|
// Populate cache
|
||||||
_, _ = c.Read("/read_reval.txt")
|
_, _ = c.Read("/read_reval.txt")
|
||||||
@@ -431,7 +431,7 @@ func TestCachedClient_RevalidateReadDir(t *testing.T) {
|
|||||||
mockFS.AddDir("/dir_reval")
|
mockFS.AddDir("/dir_reval")
|
||||||
mockFS.AddFile("/dir_reval/f1.txt", []byte("1"))
|
mockFS.AddFile("/dir_reval/f1.txt", []byte("1"))
|
||||||
|
|
||||||
c := NewCachedClient(mockFS, client, time.Hour)
|
c := NewCachedClient(mockFS, client, time.Hour, time.Hour*2)
|
||||||
|
|
||||||
// Populate cache
|
// Populate cache
|
||||||
_, err = c.ReadDir("/dir_reval")
|
_, err = c.ReadDir("/dir_reval")
|
||||||
@@ -461,4 +461,3 @@ func TestCachedClient_RevalidateReadDir(t *testing.T) {
|
|||||||
t.Errorf("expected 1 hit, got %d", c.hits.Load())
|
t.Errorf("expected 1 hit, got %d", c.hits.Load())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,7 +26,6 @@ func (c *CachedClient) Read(path string) ([]byte, error) {
|
|||||||
if err == nil && len(cached) > 0 {
|
if err == nil && len(cached) > 0 {
|
||||||
c.readHits.Add(1)
|
c.readHits.Add(1)
|
||||||
c.hits.Add(1)
|
c.hits.Add(1)
|
||||||
slog.Debug("cache hit", "key", key)
|
|
||||||
|
|
||||||
var file readFile
|
var file readFile
|
||||||
err := json.Unmarshal(cached, &file)
|
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 {
|
if err := json.Unmarshal([]byte(val), &cached); err == nil {
|
||||||
c.readDirHits.Add(1)
|
c.readDirHits.Add(1)
|
||||||
c.hits.Add(1)
|
c.hits.Add(1)
|
||||||
slog.Debug("cache hit", "key", key)
|
|
||||||
infos := make([]os.FileInfo, len(cached))
|
infos := make([]os.FileInfo, len(cached))
|
||||||
for i, f := range cached {
|
for i, f := range cached {
|
||||||
infos[i] = f
|
infos[i] = f
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ func (c *CachedClient) Stat(path string) (info os.FileInfo, err error) {
|
|||||||
var f File
|
var f File
|
||||||
if err := json.Unmarshal([]byte(val), &f); err == nil {
|
if err := json.Unmarshal([]byte(val), &f); err == nil {
|
||||||
c.hits.Add(1)
|
c.hits.Add(1)
|
||||||
slog.Debug("cache hit", "key", key)
|
|
||||||
|
|
||||||
return f, nil
|
return f, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package templer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,12 +27,38 @@ func Middleware(next http.Handler) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Path returns the current path without a leading slash
|
// Path returns the current path with a leading slash
|
||||||
func Path(ctx context.Context) string {
|
func Path(ctx context.Context) string {
|
||||||
path, ok := ctx.Value(pathKey).(string)
|
path, ok := ctx.Value(pathKey).(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
slog.Error("could not extract request path from context")
|
slog.Error("could not extract request path from context")
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
return strings.TrimPrefix(path, "/")
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func RelativePath(ctx context.Context, relPath string) (path string, err error) {
|
||||||
|
baseStr := Path(ctx)
|
||||||
|
|
||||||
|
if baseStr != "" && !strings.HasSuffix(baseStr, "/") {
|
||||||
|
baseStr += "/"
|
||||||
|
}
|
||||||
|
|
||||||
|
base, err := url.Parse(baseStr)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("could not parse base path: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rel, err := url.Parse(relPath)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("could not parse relative path: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve the relative path against the base
|
||||||
|
path = base.ResolveReference(rel).Path
|
||||||
|
if strings.HasSuffix(path, "/") {
|
||||||
|
path = path[:len(path)-1]
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package templer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRelativePath(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string // description of this test case
|
||||||
|
// Named input parameters for target function.
|
||||||
|
base string
|
||||||
|
relPath string
|
||||||
|
want string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
// TODO: Add test cases.
|
||||||
|
{
|
||||||
|
name: "with no relative path stays the same",
|
||||||
|
base: "/foo/bar",
|
||||||
|
relPath: "",
|
||||||
|
want: "/foo/bar",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "with . relative path stays the same",
|
||||||
|
base: "/foo/bar",
|
||||||
|
relPath: ".",
|
||||||
|
want: "/foo/bar",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "with ./ relative path stays the same",
|
||||||
|
base: "/foo/bar",
|
||||||
|
relPath: "./",
|
||||||
|
want: "/foo/bar",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
name: "with .. relative path goes one up",
|
||||||
|
base: "/foo/bar",
|
||||||
|
relPath: "..",
|
||||||
|
want: "/foo",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
name: "with ../baz relative path replaces last element with baz",
|
||||||
|
base: "/foo/bar",
|
||||||
|
relPath: "../baz",
|
||||||
|
want: "/foo/baz",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
ctx := context.WithValue(t.Context(), pathKey, tt.base)
|
||||||
|
got, gotErr := RelativePath(ctx, tt.relPath)
|
||||||
|
if gotErr != nil {
|
||||||
|
if !tt.wantErr {
|
||||||
|
t.Errorf("RelativePath() failed: %v", gotErr)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tt.wantErr {
|
||||||
|
t.Fatal("RelativePath() succeeded unexpectedly")
|
||||||
|
}
|
||||||
|
// TODO: update the condition below to compare got with tt.want.
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("RelativePath() = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,10 +5,12 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"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/images"
|
||||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/page"
|
"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/components/translate"
|
||||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest"
|
"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/resthome"
|
||||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/restimage"
|
"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/filesystem"
|
||||||
@@ -59,11 +61,12 @@ func (s *Server) dynamicRoutes() (h http.Handler, err error) {
|
|||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
} else {
|
} else {
|
||||||
fs = filesystem.NewCachedClient(webdavClient, valkeyClient, 5*time.Hour)
|
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(
|
mux.Handle("/images/", rest.Use(
|
||||||
restimage.New(images.New(fs, s.cfg.Image, valkeyClient)),
|
restimage.New(imageSrv),
|
||||||
middleware.Cache(time.Hour*24*5),
|
middleware.Cache(time.Hour*24*5),
|
||||||
))
|
))
|
||||||
|
|
||||||
@@ -71,7 +74,16 @@ func (s *Server) dynamicRoutes() (h http.Handler, err error) {
|
|||||||
renderer := layouts.New(s.cfg)
|
renderer := layouts.New(s.cfg)
|
||||||
|
|
||||||
mux.Handle("/", rest.Use(
|
mux.Handle("/", rest.Use(
|
||||||
resthome.New(renderer, page.New(fs)),
|
func() http.Handler {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
|
||||||
|
galleryMux := restgallery.New(renderer, gallery.New(fs, s.cfg.Gallery, imageSrv, valkeyClient), s.cfg.Gallery)
|
||||||
|
mux.Handle("/"+s.cfg.Gallery.Path, galleryMux)
|
||||||
|
mux.Handle("/"+s.cfg.Gallery.Path+"/", galleryMux)
|
||||||
|
mux.Handle("/", resthome.New(renderer, page.New(fs)))
|
||||||
|
|
||||||
|
return mux
|
||||||
|
}(),
|
||||||
translator.Middleware,
|
translator.Middleware,
|
||||||
middleware.Cache(time.Minute),
|
middleware.Cache(time.Minute),
|
||||||
))
|
))
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
package components
|
|
||||||
|
|
||||||
templ Hello() {
|
|
||||||
<h1>Hello World</h1>
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package components
|
||||||
|
|
||||||
|
// Modal renders a modal dialog.
|
||||||
|
//
|
||||||
|
// The <dialog> itself must never be an htmx swap target: swapping its
|
||||||
|
// innerHTML would replace the wrapper below (centering + close button) and
|
||||||
|
// break the layout. Content is swapped into the inner element with id
|
||||||
|
// "<id>-content" instead.
|
||||||
|
templ Modal(id string) {
|
||||||
|
<dialog
|
||||||
|
id={ id }
|
||||||
|
class="m-auto backdrop:bg-black/90 bg-transparent p-0 w-full h-full max-w-none max-h-none"
|
||||||
|
hx-on::after-swap="if (!this.open) this.showModal()"
|
||||||
|
>
|
||||||
|
<div class="relative w-full h-full flex items-center justify-center overflow-hidden">
|
||||||
|
<button
|
||||||
|
class="absolute right-5 top-5 z-10 p-2 text-white"
|
||||||
|
hx-on:click="this.closest('dialog').close()"
|
||||||
|
>
|
||||||
|
X
|
||||||
|
</button>
|
||||||
|
<div id={ id + "-content" } class="w-full h-full flex items-center justify-center overflow-hidden">
|
||||||
|
{ children... }
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</dialog>
|
||||||
|
}
|
||||||
+36
-23
@@ -7,7 +7,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
templ Head(cfg config.Cfg, title string) {
|
templ head(cfg config.Cfg, title string) {
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8"/>
|
<meta charset="UTF-8"/>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||||
@@ -29,29 +29,42 @@ templ Head(cfg config.Cfg, title string) {
|
|||||||
templ Base(cfg config.Cfg, title string) {
|
templ Base(cfg config.Cfg, title string) {
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang={ translate.Language(ctx) }>
|
<html lang={ translate.Language(ctx) }>
|
||||||
@Head(cfg, title)
|
@head(cfg, title)
|
||||||
<body class="bg-black dark" hx-boost="true" hx-target="main" hx-ext="head-support,preload,preload-links">
|
<body class="bg-black dark" hx-boost="true" hx-target="body" hx-ext="head-support,preload,preload-links">
|
||||||
<header
|
@body() {
|
||||||
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, "") } 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), "/")...) }
|
|
||||||
hreflang={ lang }
|
|
||||||
data-no-translate
|
|
||||||
preload="mouseover"
|
|
||||||
class="text-white hover:underline uppercase"
|
|
||||||
>
|
|
||||||
{ lang }
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
<main class="text-white">
|
|
||||||
{ children... }
|
{ children... }
|
||||||
</main>
|
}
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
templ Content(cfg config.Cfg, title string) {
|
||||||
|
@head(cfg, title)
|
||||||
|
@body() {
|
||||||
|
{ children... }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
templ body() {
|
||||||
|
<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, "") } 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), "/")...) }
|
||||||
|
hreflang={ lang }
|
||||||
|
data-no-translate
|
||||||
|
preload="mouseover"
|
||||||
|
class="text-white hover:underline uppercase"
|
||||||
|
>
|
||||||
|
{ lang }
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
<main class="text-white">
|
||||||
|
{ children... }
|
||||||
|
</main>
|
||||||
|
}
|
||||||
@@ -36,7 +36,7 @@ func (l *Layouts) Render(ctx context.Context, w io.Writer, r *http.Request, comp
|
|||||||
component = Base(l.cfg, title)
|
component = Base(l.cfg, title)
|
||||||
} else {
|
} else {
|
||||||
ctx = templ.WithChildren(ctx, component)
|
ctx = templ.WithChildren(ctx, component)
|
||||||
component = Head(l.cfg, title)
|
component = Content(l.cfg, title)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := component.Render(ctx, w); err != nil {
|
if err := component.Render(ctx, w); err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package pages
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/gallery"
|
||||||
|
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
|
||||||
|
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/components"
|
||||||
|
)
|
||||||
|
|
||||||
|
const detailsID = "imgs-details"
|
||||||
|
|
||||||
|
// detailsContentID is the inner element of the modal that htmx swaps into.
|
||||||
|
// It is defined by components.Modal and must not be the dialog itself.
|
||||||
|
const detailsContentID = detailsID + "-content"
|
||||||
|
|
||||||
|
templ GallerySet(g gallery.Set) {
|
||||||
|
<div class="p-5">
|
||||||
|
@components.Modal(detailsID) {
|
||||||
|
// Placeholder: only visible until the first image is swapped in.
|
||||||
|
// prev/next are nil because relative links would be resolved
|
||||||
|
// against the gallery index, not the image page.
|
||||||
|
if len(g.SM.Images) > 0 {
|
||||||
|
@GalleryImage(g.SM.Images[0].UID, nil, nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<div
|
||||||
|
class="grid gap-5 grid-cols-1 lg:hidden"
|
||||||
|
>
|
||||||
|
for _,img := range g.SM.Images {
|
||||||
|
<button
|
||||||
|
hx-get={ templer.RelativePath(ctx, "./"+img.UID) }
|
||||||
|
hx-target={ "#" + detailsContentID }
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
class="block w-full cursor-pointer"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={ "/images/" + img.UID + "?w=600" }
|
||||||
|
loading="lazy"
|
||||||
|
class="w-full"
|
||||||
|
alt="Gallery item"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="hidden lg:block 3xl:hidden">
|
||||||
|
@Gallery(g.SM)
|
||||||
|
</div>
|
||||||
|
<div class="hidden 3xl:block 6xl:hidden">
|
||||||
|
@Gallery(g.LG)
|
||||||
|
</div>
|
||||||
|
<div class="hidden 6xl:block">
|
||||||
|
@Gallery(g.XLG)
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define a templ script to hold complex post-load behavior
|
||||||
|
templ GalleryImage(image string, next *gallery.Image, prev *gallery.Image) {
|
||||||
|
<link rel="preload" href={ "/images/" + image + "?w=800" } as="image"/>
|
||||||
|
<div class="relative w-10/12 h-10/12 flex items-center justify-center overflow-hidden ">
|
||||||
|
<!-- 1. Preloaded Base Image (w=800) -->
|
||||||
|
<img
|
||||||
|
src={ "/images/" + image + "?w=800" }
|
||||||
|
alt=""
|
||||||
|
class="absolute inset-0 w-full h-full object-contain"
|
||||||
|
/>
|
||||||
|
<!-- 2. Responsive Image Layer (Overlaid on top) -->
|
||||||
|
<img
|
||||||
|
src={ "/images/" + image + "?w=800" }
|
||||||
|
srcset={ "/images/" + image + "?w=400 400w, /images/" + image + "?w=800 800w, /images/" + image + "?w=1200 1200w, /images/" + image + "?w=1600 1600w" }
|
||||||
|
sizes="(max-width: 600px) 400px, (max-width: 1200px) 800px, 1200px"
|
||||||
|
alt="Image description"
|
||||||
|
onload="this.decode().then(() => {this.classList.remove('opacity-0')}).catch(() => {})"
|
||||||
|
class="absolute inset-0 w-full h-full object-contain transition-opacity duration-900 opacity-0"
|
||||||
|
/>
|
||||||
|
<!-- 3. Navigation Controls -->
|
||||||
|
if prev != nil {
|
||||||
|
<button
|
||||||
|
hx-get={ templer.RelativePath(ctx, "../"+prev.UID) }
|
||||||
|
hx-target={ "#" + detailsContentID }
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
preload
|
||||||
|
class="absolute left-4 top-1/2 -translate-y-1/2 z-10 p-2 text-white"
|
||||||
|
>
|
||||||
|
<
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
if next != nil {
|
||||||
|
<button
|
||||||
|
hx-get={ templer.RelativePath(ctx, "../"+next.UID) }
|
||||||
|
hx-target={ "#" + detailsContentID }
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
preload="mouseover"
|
||||||
|
class="absolute right-4 top-1/2 -translate-y-1/2 z-10 p-2 text-white"
|
||||||
|
>
|
||||||
|
>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</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"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
hx-get={ templer.RelativePath(ctx, "./"+img.UID) }
|
||||||
|
hx-target={ "#" + detailsContentID }
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={ "/images/" + img.UID + "?w=800" }
|
||||||
|
loading="lazy"
|
||||||
|
class="w-full h-full object-cover"
|
||||||
|
alt="Gallery item"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@@ -1,2 +1,2 @@
|
|||||||
/*! tailwindcss v4.1.18 | MIT License | https://tailwindcss.com */
|
/*! tailwindcss v4.1.18 | MIT License | https://tailwindcss.com */
|
||||||
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-text-shadow-color:initial;--tw-text-shadow-alpha:100%}}}@layer theme{:root,:host{--font-sans:"Outfit","outfit",sans-serif;--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-6xl:72rem;--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25/1.875);--font-weight-bold:700;--text-shadow-lg:0px 0px 20px #000;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components{.prose img{max-height:90vh;margin-left:auto;margin-right:auto;display:block}}@layer utilities{.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{positLine truncated
|
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-duration:initial;--tw-text-shadow-color:initial;--tw-text-shadow-alpha:100%}}}@layer theme{:root,:host{--font-sans:"Outfit","outfit",sans-serif;--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-6xl:72rem;--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25/1.875);--font-weight-bold:700;--text-shadow-lg:0px 0px 20px #000;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components{.prose img{max-height:90vh;margin-left:auto;margin-right:auto;display:block}}@layer utilities{.pLine truncated
|
||||||
Reference in new issue
Block a user