feat: adapt home appearance to wallpaper colors
Build and publish container images / images (push) Successful in 10m56s
Release container images / release (push) Successful in 18s

This commit is contained in:
Anya Tokugawa committed 2026-11-07 22:51:56 +09:00
1 parent c7aa4fd7dd
commit 0964fdc5b7
23 files changed
+628 -32

No files matched your search

+19
View File
@@ -290,6 +290,11 @@ func (s *Server) handleConfig(
}
case "home":
palette, paletteErr := s.parseHomePalette(domainUUID, r.Form)
if paletteErr != nil {
http.Error(w, paletteErr.Error(), http.StatusBadRequest)
return
}
if controlled, e := s.store.DomainEntryControlled(domainUUID); e != nil || controlled {
http.Error(w, translate(s.getLocale(domainUUID), "periodical.controlled"), http.StatusConflict)
return
@@ -344,6 +349,10 @@ func (s *Server) handleConfig(
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = s.saveHomePalette(domainUUID, palette); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = s.store.SetConfigInDomain(domainUUID, "home_wallpaper_opacity", strconv.Itoa(wallpaperOpacity)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -463,6 +472,11 @@ func (s *Server) handleConfig(
}
case "home-appearance":
palette, paletteErr := s.parseHomePalette(domainUUID, r.Form)
if paletteErr != nil {
http.Error(w, paletteErr.Error(), http.StatusBadRequest)
return
}
if controlled, e := s.store.DomainEntryControlled(domainUUID); e != nil || controlled {
http.Error(w, translate(s.getLocale(domainUUID), "periodical.controlled"), http.StatusConflict)
return
@@ -472,6 +486,10 @@ func (s *Server) handleConfig(
http.Error(w, parseErr.Error(), http.StatusBadRequest)
return
}
if err = s.saveHomePalette(domainUUID, palette); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = s.store.SetConfigInDomain(domainUUID, "home_glass_transparency", strconv.Itoa(glassTransparency)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -1064,6 +1082,7 @@ func (s *Server) handleConfig(
"HomeWallpaperPath": homeWallpaperPath,
"HomeWallpaperOpacity": homeWallpaperOpacity,
"HomeGlassTransparency": s.homeGlassTransparency(domainUUID),
"HomePalette": s.homePalette(domainUUID),
"HomeLayout": s.homeLayout(s.domainUUIDForRequest(r)),
"HomeBookmarks": s.homeBookmarksText(s.domainUUIDForRequest(r)),
"VirtualFolderPages": s.getVirtualFolderPages(s.domainUUIDForRequest(r)),
+56
View File
@@ -0,0 +1,56 @@
package server
import (
"encoding/json"
"errors"
"net/url"
"strconv"
)
type homePaletteSettings struct {
Mode string `json:"mode"`
Strength int `json:"strength"`
Brightness string `json:"brightness"`
}
func validHomePalette(p homePaletteSettings) bool {
return (p.Mode == "off" || p.Mode == "accent" || p.Mode == "surface") && p.Strength >= 0 && p.Strength <= 100 && (p.Brightness == "preserve" || p.Brightness == "auto")
}
func (s *Server) homePalette(domain string) homePaletteSettings {
p := homePaletteSettings{Mode: "surface", Strength: 35, Brightness: "preserve"}
var saved homePaletteSettings
if json.Unmarshal([]byte(s.getDomainConfig("home_wallpaper_palette", domain)), &saved) == nil && validHomePalette(saved) {
return saved
}
return p
}
func (s *Server) parseHomePalette(domain string, form url.Values) (homePaletteSettings, error) {
p := s.homePalette(domain)
if form.Has("home_palette_mode") {
p.Mode = form.Get("home_palette_mode")
}
if form.Has("home_palette_brightness") {
p.Brightness = form.Get("home_palette_brightness")
}
if form.Has("home_palette_strength") {
n, err := strconv.Atoi(form.Get("home_palette_strength"))
if err != nil {
return p, errors.New("invalid wallpaper palette strength")
}
p.Strength = n
}
if !validHomePalette(p) {
return p, errors.New("invalid wallpaper palette settings")
}
return p, nil
}
func (s *Server) saveHomePalette(domain string, p homePaletteSettings) error {
b, err := json.Marshal(p)
if err != nil {
return err
}
return s.store.SetConfigInDomain(domain, "home_wallpaper_palette", string(b))
}
+165
View File
@@ -0,0 +1,165 @@
package server
import (
"bytes"
"context"
"image"
"image/color"
"image/png"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"strings"
"testing"
"time"
)
func TestHomePaletteSettingsAndScope(t *testing.T) {
s, token, domain := configFixture(t)
s.mux.HandleFunc("/", s.handleHome)
saveWallpaperFixture(t, s, domain, "/wallpapers/a.jpg", "image/jpeg")
if err := s.store.SetConfigInDomain(domain, "home_wallpaper_path", "/wallpapers/a.jpg"); err != nil {
t.Fatal(err)
}
initial := s.homePalette(domain)
if initial.Mode != "surface" || initial.Strength != 35 || initial.Brightness != "preserve" {
t.Fatal(initial)
}
for _, values := range []url.Values{{"home_palette_mode": {"bad"}}, {"home_palette_strength": {"101"}}, {"home_palette_strength": {"-1"}}, {"home_palette_strength": {"bad"}}, {"home_palette_brightness": {"bad"}}} {
values.Set("section", "home-appearance")
values.Set("home_glass_transparency", "47")
if w := configRequest(s, token, "POST", "/-/sys/config", values); w.Code != 400 {
t.Fatal(w.Code, w.Body)
}
if s.homePalette(domain) != initial || s.homeGlassTransparency(domain) != 42 {
t.Fatal("invalid request partially saved")
}
}
values := url.Values{"section": {"home-appearance"}, "home_glass_transparency": {"47"}, "home_palette_mode": {"accent"}, "home_palette_strength": {"70"}, "home_palette_brightness": {"auto"}}
if w := configRequest(s, token, "POST", "/-/sys/config", values); w.Code != http.StatusFound {
t.Fatal(w.Code, w.Body)
}
if p := s.homePalette(domain); p.Mode != "accent" || p.Strength != 70 || p.Brightness != "auto" {
t.Fatal(p)
}
member, err := s.store.CreatePasswordAccount(domain, "palette-reader", "a long test password", "Reader", "")
if err != nil {
t.Fatal(err)
}
memberToken, err := s.store.CreateAuthSession(domain, member.UUID)
if err != nil {
t.Fatal(err)
}
if w := configRequest(s, memberToken, "POST", "/-/sys/config", url.Values{"section": {"home-appearance"}, "home_palette_mode": {"off"}, "home_glass_transparency": {"47"}}); w.Code != http.StatusForbidden {
t.Fatalf("member changed domain appearance: %d", w.Code)
}
if s.homePalette(domain).Mode != "accent" {
t.Fatal("member overwrote settings")
}
for _, layout := range []string{"classic", "search", "directory"} {
if err := s.store.SetConfigInDomain(domain, "home_layout", layout); err != nil {
t.Fatal(err)
}
w := configRequest(s, token, "GET", "/", nil)
for _, want := range []string{`data-home-palette`, `data-mode="accent"`, `data-strength="70"`, `data-home-appearance-open`, `/static/js/home-palette.js?v=1`} {
if w.Code != 200 || !strings.Contains(w.Body.String(), want) {
t.Fatal(layout, w.Code, want)
}
}
}
for _, path := range []string{"/-/sys/config?panel=home", "/missing-page"} {
w := configRequest(s, token, http.MethodGet, path, nil)
if strings.Contains(w.Body.String(), `data-home-palette `) || strings.Contains(w.Body.String(), `src="/static/js/home-palette.js`) {
t.Fatal("theme leaked outside home", path)
}
}
settings := configRequest(s, token, http.MethodGet, "/-/sys/config?panel=home", nil)
if settings.Code != http.StatusOK || !strings.Contains(settings.Body.String(), `name="home_palette_mode"`) || !strings.Contains(settings.Body.String(), `value="accent" selected`) {
t.Fatal("settings panel did not load saved palette")
}
for _, section := range []string{"home", "home-appearance"} {
invalid := url.Values{"section": {section}, "home_palette_strength": {"NaN"}, "home_layout": {"search"}}
if w := configRequest(s, token, http.MethodPost, "/-/sys/config", invalid); w.Code != http.StatusBadRequest {
t.Fatal(section, w.Code)
}
}
// Old forms may omit the new fields without resetting their saved settings.
delete(values, "home_palette_mode")
delete(values, "home_palette_strength")
delete(values, "home_palette_brightness")
if w := configRequest(s, token, "POST", "/-/sys/config", values); w.Code != http.StatusFound {
t.Fatal(w.Code)
}
if s.homePalette(domain).Mode != "accent" {
t.Fatal("old form reset settings")
}
if err := s.store.SetConfigInDomain(domain, "home_wallpaper_path", ""); err != nil {
t.Fatal(err)
}
w := configRequest(s, token, "GET", "/", nil)
if strings.Contains(w.Body.String(), `src="/static/js/home-palette.js`) {
t.Fatal("loaded extractor without wallpaper")
}
}
func TestHomePaletteChromium(t *testing.T) {
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
t.Skip("opt-in Chromium")
}
s, token, domain := configFixture(t)
s.store.BackgroundJobsDisabled = true
s = New(s.store)
picture := image.NewRGBA(image.Rect(0, 0, 480, 320))
for y := 0; y < 320; y++ {
for x := 0; x < 480; x++ {
picture.SetRGBA(x, y, color.RGBA{uint8(30 + x/4), uint8(60 + y/3), uint8(180 + y/5), 255})
}
}
var content bytes.Buffer
if err := png.Encode(&content, picture); err != nil {
t.Fatal(err)
}
object, err := s.store.CreatePageAtPathInDomain(domain, "/wallpapers/test.png")
if err != nil {
t.Fatal(err)
}
if _, err = s.store.SaveRevisionContent(object, content.Bytes(), "test", "und", "image/png", "test.png"); err != nil {
t.Fatal(err)
}
for k, v := range map[string]string{"home_layout": "directory", "home_wallpaper_path": "/wallpapers/test.png", "home_wallpaper_opacity": "70", "theme": "nanoha-dark"} {
if err := s.store.SetConfigInDomain(domain, k, v); err != nil {
t.Fatal(err)
}
}
script, err := os.ReadFile("internal/server/testdata/home-palette.js")
if err != nil {
t.Fatal(err)
}
handler := s.handler()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Host = "localhost"
r.Header.Set("Authorization", "Bearer "+token)
if r.URL.Path == "/fixture" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte("<!doctype html><body style='margin:0'><script>" + string(script) + "</script></body>"))
return
}
handler.ServeHTTP(w, r)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 55*time.Second)
defer cancel()
width := os.Getenv("HOME_PALETTE_WIDTH")
if width == "" {
width = "1440"
}
args := []string{"internal/server/testdata/vim-browser-smoke.mjs", server.URL + "/fixture", t.TempDir(), os.Getenv("HOME_PALETTE_SCREENSHOT"), width, "850"}
if out, err := exec.CommandContext(ctx, "node", args...).CombinedOutput(); err != nil {
t.Fatalf("palette: %v\n%s", err, out)
}
if p := s.homePalette(domain); p.Mode != "accent" || p.Strength != 70 || p.Brightness != "auto" {
t.Fatalf("browser save not persisted: %+v", p)
}
}
+5 -2
View File
@@ -20,6 +20,7 @@ type homeWallpaperView struct {
Path string
URL string
Opacity string
Key string
}
// configuredLoginWallpaper returns only the image selected by the Domain
@@ -143,7 +144,8 @@ func (s *Server) homeWallpaperForRequest(r *http.Request) homeWallpaperView {
httpRequest := r
if objectUUID, err := s.store.ResolvePathInDomain(domainUUID, configured); err == nil && s.requestCanReadPath(httpRequest, configured) {
if revision, err := s.latestRevisionMetadataForRequest(httpRequest, objectUUID); err == nil && imageContentType(revision.ContentType) {
view.URL = rawProjectionURL("path:" + configured)
view.URL = rawProjectionURL("rev:" + revision.UUID)
view.Key = revision.DocumentHash
return view
}
}
@@ -165,6 +167,7 @@ func (s *Server) homeWallpaperForRequest(r *http.Request) homeWallpaperView {
if value, err := rand.Int(rand.Reader, big.NewInt(int64(len(candidates)))); err == nil {
index = int(value.Int64())
}
view.URL = rawProjectionURL("path:" + candidates[index].Path)
view.URL = rawProjectionURL("rev:" + candidates[index].RevisionUUID)
view.Key = candidates[index].DocumentHash
return view
}
+1 -1
View File
@@ -107,7 +107,7 @@ func TestHomeWallpaperFolderPickerAndTheme(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "http://localhost/", nil)
r.Header.Set("Authorization", "Bearer "+token)
view := s.homeWallpaperForRequest(r)
if view.Opacity != "0.41" || (view.URL != "/v/raw/path:/wallpapers/a.jpg" && view.URL != "/v/raw/path:/wallpapers/b.png") {
if view.Opacity != "0.41" || !strings.HasPrefix(view.URL, "/v/raw/rev:") || len(view.Key) != 64 {
t.Fatalf("view=%#v", view)
}
homeResponse := httptest.NewRecorder()
+18
View File
@@ -231,6 +231,15 @@ var translations = map[string]map[string]string{
"home.wallpaper_opacity": "Wallpaper opacity (%)",
"home.wallpaper_help": "Choose one image, or a folder whose direct image children are selected on each reload. Access permissions still apply.",
"home.appearance": "Home appearance",
"home.palette_mode": "Wallpaper color matching",
"home.palette_off": "Off — use the selected theme",
"home.palette_accent": "Accent only",
"home.palette_surface": "Accent and surfaces",
"home.palette_strength": "Color influence",
"home.palette_brightness": "Light and dark",
"home.palette_preserve": "Keep the current theme brightness",
"home.palette_auto": "Choose from the displayed wallpaper",
"home.palette_help": "Applies only to the home page and its dialogs. Warning colors are preserved. If extraction fails, the selected theme remains. Shared by this domain.",
"home.glass_transparency": "Glass transparency (%)",
"home.glass_help": "Controls the shared transparency of the home search, menus, suggestions, cards, and dialogs. Higher values are more transparent.",
"picker.open": "Browse PagesWiki",
@@ -1002,6 +1011,15 @@ var translations = map[string]map[string]string{
"home.wallpaper_opacity": "壁紙の透明度(%)",
"home.wallpaper_help": "画像を1つ選ぶか、直下の画像をリロードごとに選択するフォルダを指定します。閲覧権限はそのまま適用されます。",
"home.appearance": "トップ画面の外観",
"home.palette_mode": "壁紙との色連動",
"home.palette_off": "オフ — 選択中のテーマを使用",
"home.palette_accent": "アクセントのみ",
"home.palette_surface": "背景も連動",
"home.palette_strength": "色の反映量",
"home.palette_brightness": "明暗",
"home.palette_preserve": "現在のテーマの明暗を維持",
"home.palette_auto": "表示中の壁紙から自動判定",
"home.palette_help": "トップ画面とその上のダイアログにのみ適用します。警告色は変更しません。色を抽出できない場合は選択中のテーマを維持します。このドメインで共通の設定です。",
"home.glass_transparency": "グラスの透明度(%)",
"home.glass_help": "トップ画面の検索、メニュー、サジェスト、カード、ダイアログに共通の透明度です。数値を上げるほど背景が透けます。",
"picker.open": "PagesWikiから選択",
+3
View File
@@ -84,6 +84,9 @@ func (s *Server) renderWithContext(
wallpaper := s.homeWallpaperForRequest(r)
data["HomeWallpaperURL"] = wallpaper.URL
data["HomeWallpaperOpacity"] = wallpaper.Opacity
data["HomeWallpaperKey"] = wallpaper.Key
data["HomePalette"] = s.homePalette(domainUUID)
data["HomePaletteDomain"] = domainUUID
if wallpaper.URL != "" {
w.Header().Set("Cache-Control", "private, no-cache")
}
+59
View File
@@ -0,0 +1,59 @@
(async () => {
const assert = (ok, message) => { if (!ok) throw Error(message); };
const delay = ms => new Promise(r => setTimeout(r, ms));
const wait = async check => { for (let n=0;n<200;n++) { if(check()) return; await delay(25); } throw Error('Timed out: '+check); };
const frame=document.createElement('iframe');frame.style='display:block;width:100%;height:100vh;border:0';document.body.append(frame);
try {
const load=()=>new Promise(resolve=>{frame.onload=resolve;frame.src='/';});
await load();
let w=frame.contentWindow,d=frame.contentDocument;
await wait(()=>d.body.dataset.homePaletteActive==='surface');
assert(d.querySelector('[data-home-palette]').dataset.paletteSource==='image','First palette not extracted');
assert(w.performance.getEntriesByType('resource').filter(e=>e.name.includes('/v/raw/')).length===1,'Wallpaper fetched more than once');
const before=d.body.style.getPropertyValue('--bg');
const form=d.querySelector('[data-home-appearance-form]'),dialog=d.querySelector('[data-home-appearance-dialog]');
const change=(name,value)=>{form.elements[name].value=value;form.elements[name].dispatchEvent(new w.Event('input',{bubbles:true}));};
d.querySelector('[data-home-appearance-open]').click();
change('home_palette_mode','off');
assert(!d.body.dataset.homePaletteActive && !d.body.style.getPropertyValue('--bg'),'Off did not restore theme');
d.querySelector('[data-home-appearance-cancel]').click();
assert(d.body.style.getPropertyValue('--bg')===before,'Cancel did not restore palette');
assert(!dialog.open,'Cancel did not close dialog');
d.querySelector('[data-home-appearance-open]').click();
change('home_palette_mode','accent');change('home_palette_strength','70');change('home_palette_brightness','auto');
change('home_glass_transparency','47');
assert(!d.body.style.getPropertyValue('--bg') && d.body.style.getPropertyValue('--accent'),'Accent mode tinted surface');
form.requestSubmit();await wait(()=>!dialog.open);
await load();w=frame.contentWindow;d=frame.contentDocument;
await wait(()=>d.body.dataset.homePaletteActive==='accent');
assert(d.querySelector('[data-home-palette]').dataset.paletteSource==='cache','Reload did not reuse palette');
assert(d.querySelector('[name=home_palette_strength]').value==='70','Saved value not loaded');
assert(d.body.style.getPropertyValue('--home-glass-opacity')==='53%','Glass setting lost');
// A broken image must immediately remove derived colors, not retain a stale palette.
d.querySelector('.home-wallpaper').dispatchEvent(new w.Event('error'));
assert(!d.body.dataset.homePaletteActive && !d.body.style.getPropertyValue('--accent'),'Image error retained derived colors');
w.sessionStorage.setItem('pageswiki.wallpaper-palette.v1','invalid cache');
await load();w=frame.contentWindow;d=frame.contentDocument;
await wait(()=>d.body.dataset.homePaletteActive==='accent');
assert(d.querySelector('[data-home-palette]').dataset.paletteSource==='image','Invalid cache did not fall back to extraction');
assert(Array.isArray(JSON.parse(w.sessionStorage.getItem('pageswiki.wallpaper-palette.v1'))),'Invalid cache was not repaired');
const theme=d.querySelector('[data-theme-select]');
theme.value='light';theme.dispatchEvent(new w.Event('change',{bubbles:true}));
await wait(()=>!theme.disabled);await delay(100);
assert(d.body.dataset.homePaletteActive==='accent','Theme switch disabled palette');
d.querySelector('[data-home-appearance-open]').click();
const form2=d.querySelector('[data-home-appearance-form]');
form2.elements.home_palette_mode.value='off';form2.elements.home_palette_mode.dispatchEvent(new w.Event('input',{bubbles:true}));
assert(w.getComputedStyle(d.body).backgroundColor==='rgb(247, 247, 247)','Off did not restore newly selected theme');
d.querySelector('[data-home-appearance-cancel]').click();
theme.value='nanoha-dark';theme.dispatchEvent(new w.Event('change',{bubbles:true}));await wait(()=>!theme.disabled);await delay(100);
d.querySelector('[data-home-appearance-open]').click();
form2.elements.home_palette_mode.value='surface';form2.elements.home_palette_mode.dispatchEvent(new w.Event('input',{bubbles:true}));
const overflow=[...d.body.querySelectorAll('*')].filter(el=>{const r=el.getBoundingClientRect();return r.width>0 && r.right>w.innerWidth+1;}).slice(0,12).map(el=>el.tagName+'.'+el.className+':'+Math.round(el.getBoundingClientRect().right));
assert(d.documentElement.scrollWidth<=w.innerWidth,'Viewport overflows horizontally: '+d.documentElement.scrollWidth+'/'+w.innerWidth+' '+overflow.join(', '));
const rect=d.querySelector('[data-home-appearance-dialog]').getBoundingClientRect();
assert(rect.x>=0 && rect.right<=w.innerWidth && rect.top>=0 && rect.bottom<=w.innerHeight,'Dialog exceeds viewport');
// Deliberately leave an unsaved surface preview visible for screenshot review.
document.body.dataset.vimReady='1';
} catch(error) { const out=document.createElement('pre');out.id='error';out.textContent=error.stack;document.body.append(out); }
})();