2 Commits
Author SHA1 Message Date
Anya Tokugawa 0964fdc5b7 feat: adapt home appearance to wallpaper colors
Release container images / release (push) Successful in 18s
Build and publish container images / images (push) Successful in 10m56s
2026-11-07 22:51:56 +09:00
Anya Tokugawa c7aa4fd7dd docs: record monthly mail layout release and deployment [skip ci] 2026-11-06 10:07:41 +09:00
25 changed files with 675 additions and 34 deletions

No files matched your search

+2 -2
View File
@@ -35,8 +35,8 @@ jobs:
[worker.oci] [worker.oci]
max-parallelism = 2 max-parallelism = 2
- name: Test release tooling - name: Test release tooling and wallpaper palette
run: node --test tools/ci/release-images.test.mjs run: node --test tools/ci/release-images.test.mjs static/js/home-palette-core.test.cjs
- name: Test - name: Test
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
+2 -2
View File
@@ -30,9 +30,9 @@ v0.9.0は任意の `wiki_suffix` をcaptureに追加する。CLI v0.4.0はML連
v0.8.0ではcaptureに省略可能な `wiki_body` と `wiki_prefix` を追加する。wiki_bodyを省略した従来クライアントの契約・receipt hashは変えない。本文を指定した場合、親Pathは要求のwiki_prefix、個人preferencesのwiki_prefix、選択プロジェクトの関連WikiとNotesSubpath(未設定はtasks)の順に解決する。いずれもなければ422 `wiki_prefix_required`。空の明示指定も拒否する。個人設定はDomain・本人単位で、既存preferences JSONに保存するため新規schema migrationは不要。 v0.8.0ではcaptureに省略可能な `wiki_body` と `wiki_prefix` を追加する。wiki_bodyを省略した従来クライアントの契約・receipt hashは変えない。本文を指定した場合、親Pathは要求のwiki_prefix、個人preferencesのwiki_prefix、選択プロジェクトの関連WikiとNotesSubpath(未設定はtasks)の順に解決する。いずれもなければ422 `wiki_prefix_required`。空の明示指定も拒否する。個人設定はDomain・本人単位で、既存preferences JSONに保存するため新規schema migrationは不要。
本文は256 KiBまでのUTF-8テキスト。H1に件名、preに本文をHTMLエスケープして格納し、波括弧も実体参照にしてマクロを実行しない。v0.8.1以降のPathは `親Path/mail-request_id`。CLIは接続先・本人・Message-ID(なければ原文SHA-256)からrequest_idを生成するため、Path末尾は件名・日本語の文字数・ML連番に依存しないASCIIになる。Message-ID自体はURLへ露出しない。既存Pathとの競合は409で、既存ページへ追記・上書きしない。新規Wikiのobject/path/revisionとactivity outbox、タスクのPageUUID、capture receiptは同一DBトランザクションで保存する。rollback時に未参照のcontent-addressed Documentファイルが残る可能性は既存DocumentStoreと同様だが、公開可能なページや片方だけのタスクは残さない。 本文は256 KiBまでのUTF-8テキスト。H1に件名、preに本文をHTMLエスケープして格納し、波括弧も実体参照にしてマクロを実行しない。v0.8.1、およびv0.9.0以降でwiki_suffixを省略した場合のPathは `親Path/mail-request_id`。CLIは接続先・本人・Message-ID(なければ原文SHA-256)からrequest_idを生成するため、Path末尾は件名・日本語の文字数・ML連番に依存しないASCIIになる。Message-ID自体はURLへ露出しない。既存Pathとの競合は409で、既存ページへ追記・上書きしない。新規Wikiのobject/path/revisionとactivity outbox、タスクのPageUUID、capture receiptは同一DBトランザクションで保存する。rollback時に未参照のcontent-addressed Documentファイルが残る可能性は既存DocumentStoreと同様だが、公開可能なページや片方だけのタスクは残さない。
v0.8.0の件名入りPathは自動移動しない。既存receiptの同一要求再送は元のページを返す。CLI v0.3.1は先頭のML連番を除去し、長い自動件名は300 UTF-8 bytes以内に文字境界で省略、変更前のSubjectをWiki本文へ保持する。旧版で保存済みの要求を新しい件名・本文で再作成すると412となるため、通信失敗した要求は保存済みoutboxのretryを使う。サーバーAPIの入力フィールド・receipt hash形式は変更しない。 v0.8.0の件名入りPathは自動移動しない。既存receiptの同一要求再送は元のページを返す。CLI v0.3.1は先頭のML連番を除去し、長い自動件名は300 UTF-8 bytes以内に文字境界で省略、変更前のSubjectをWiki本文へ保持する。旧版で保存済みの要求を新しい件名・本文で再作成すると412となるため、通信失敗した要求は保存済みoutboxのretryを使う。v0.8.1ではサーバーAPIの入力フィールド・receipt hash形式を変更していない。v0.9.0ではwiki_suffix未指定時のhashを維持し、指定時はsuffixもhashの対象に含める。
保存前に対象Pathへのread/create/write権限を検証する。個人タスクの所有権はWikiへの権限を付与しない。Wiki本文の公開範囲は保存先のACLに従うため、個人設定UIに注意を表示する。再送は既定値の再解決より前にreceiptを確認し、既定Pathの変更で重複作成しない。成功応答はitemとpage_pathを返し、タスクの既存メモ操作から関連Wikiへ移動できる。 保存前に対象Pathへのread/create/write権限を検証する。個人タスクの所有権はWikiへの権限を付与しない。Wiki本文の公開範囲は保存先のACLに従うため、個人設定UIに注意を表示する。再送は既定値の再解決より前にreceiptを確認し、既定Pathの変更で重複作成しない。成功応答はitemとpage_pathを返し、タスクの既存メモ操作から関連Wikiへ移動できる。
+36
View File
@@ -43,6 +43,42 @@ Principalで直下の子だけを認可し、最大250件、`private, no-store`
modeをdata属性で指定する。これにより今後のストレージ、アダプタ、City設定でも modeをdata属性で指定する。これにより今後のストレージ、アダプタ、City設定でも
任意HTMLや専用ファイルブラウザを増やさず同じPickerを再利用できる。 任意HTMLや専用ファイルブラウザを増やさず同じPickerを再利用できる。
## 実装済みの壁紙連動配色
壁紙の色調からアクセントとグラス面の配色を生成し、トップ画面 `/` とその上で開く
ダイアログにだけ適用する。通常のViewer、Editor、設定画面、ログイン画面の配色は
変更しない。iframe内に独立して表示されるビューにも配色は継承しない。
設定は `/-/sys/config?panel=home` またはトップ画面右下の歯車から行う。既存のトップ
画面設定と同じ管理権限を必要とし、ドメイン共通で保存する。歯車のダイアログでは
その場でプレビューし、キャンセル・ESCで保存前の状態に戻す。
| 項目 | 値と既定値 |
| --- | --- |
| 壁紙との色連動 | `off`、`accent`、`surface`。既定は `surface`(背景も連動) |
| 色の反映量 | 0–100。既定は35。0では元のテーマを維持 |
| 明暗 | `preserve`(既定、現在のテーマを維持)、`auto`(表示時の壁紙の明るさから判定) |
`home_wallpaper_palette` に `{"mode":"surface","strength":35,"brightness":"preserve"}`
の形式で保存する。明暗の自動判定は背景も連動する場合だけ有効。グラスの透明度は
既存の `home_glass_transparency` で独立して調整する。警告・エラー等の意味を持つ色は
上書きしない。壁紙がない場合、画像が壊れている場合、Canvasから色を読めない場合、
強制カラーモードの場合は元のテーマを維持する。
表示済みの画像を64×64へ縮小し、初回描画後のアイドル時間に平均色と彩度を重み付け
したアクセント候補を抽出する。追加の画像取得、サーバでの画像解析、定期ジョブは不要。
画像表示URLは選択したリビジョンに固定し、抽出結果をDomain UUIDと画像SHA256の組で
sessionStorageに最大24件保存する。キャッシュにはRGB値と透明部分の割合だけを保存し、
画像本体は保存しない。ストレージが使えない場合は表示中の画像から抽出する。
文字・リンクは推定したグラス背景とのコントラストを補正する。ただし画像の局所的な
明暗までは保証しないため、細かい柄で読みにくい場合は透明度を下げるか色連動をオフにする。
既存テーマを切り替えた際は新しいテーマを基準に再計算し、オフにするとそのテーマに戻る。
回帰テストは `node --test static/js/home-palette-core.test.cjs` と `TestHomePalette*`。
`PAGESWIKI_BROWSER_TEST=1` でブラウザテストを有効化すると、一時DBと合成画像を使い、
保存・キャンセル・再読み込み時のキャッシュ利用・テーマ切替・画面幅を通して検証する。
## サイドバー詳細設計(実装待ち) ## サイドバー詳細設計(実装待ち)
管理画面のグループ化されたサイドバーは 管理画面のグループ化されたサイドバーは
@@ -0,0 +1,45 @@
# ML連番・年月別メール保存先
PagesWiki v0.9.0とpages-cli v0.4.0は、メール本文を関連Wikiへ保存するとき、ML連番を優先してPathを決める。ML連番がないメールは年月で分割する。件名は表示に使い、日本語件名を識別用Pathには使わない。
| 優先順 | 判定 | 保存先 |
| --- | --- | --- |
| 1 | 先頭のML連番あり(例: `[hogehoge 00123]`) | `親Path/hogehoge/123` |
| 2 | ML連番なし、Message-IDあり | `親Path/YYYY/MM/UUID` |
| 3 | どちらもなし | `親Path/YYYY/MM/原文SHA-256` |
UUIDは接続先・本人・Message-IDから従来どおり生成する。Message-ID自体はURLへ露出しない。年月はメールのDateヘッダーに記載されたタイムゾーンを尊重する。Date欠落・不正時は初回取り込み時のUTC年月を採用し、再送用outboxへ保存する。月をまたいで同一の保留メールを再入力しても保存先は変えない。
MLリスト名はASCII英数字で始まる100文字以内の英数字・ピリオド・ハイフン・アンダースコア。連番は最大20桁で先頭ゼロを除く。安全なML表記として認識できないものは年月方式にする。同じML連番の別メールは409で拒否し、タスクの部分作成や既存Wikiの上書きを行わない。
APIの追加フィールドは省略可能なwiki_suffixのみ。省略時の旧Path・receipt hashは維持する。新CLIの本文取り込みには新サーバーが必要。既存メールの一括移動は行わず、旧版で保持済みの再送要求はそのまま扱う。DBスキーマ変更はない。
## ソースと検証
- サーバー: `1a451023f09f483f5efff450dc2c951c925eb999`
- CLI: `e22af6a0ecc2b001d6cc0d41901470f535fd8126`
- 手元のGo全体テスト・go vet、CLI単体44件が成功。
- サーバーCI run 43の全体テストが成功。合成メールを使うHTTP結合試験は手元で実行し、Wiki Pathと本文取得を検証した。
- CLI main CI run 42、タグCI run 44が成功。公開添付5ファイルを匿名取得し、4生成物のSHA-256を検証した。
- 公開ELFでUTF-8/ISO-2022-JP件名、ML連番Path、Dateのローカル年月、Message-ID由来UUID、Message-IDなし原文hashの各保存先を確認した。同梱ELF・ガイドと検証済みソースの一致も確認した。
- [CLI v0.4.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.4.0)と[NeoMuttガイド](https://git.anya.jp/anya/pages-cli/src/tag/v0.4.0/docs/neomutt.md)を公開。
## リリースと本番反映
[サーバーCI run 43](https://git.anya.jp/anya/wikipages/actions/runs/43)の全工程成功後、[run 45](https://git.anya.jp/anya/wikipages/actions/runs/45)で同じSHAイメージをv0.9.0へ昇格した。公開タグの付け替え・リリース時の再ビルドは行っていない。本番取得時にイメージIDとソースrevisionの一致を検証した。
| イメージ | v0.9.0 manifest digest |
| --- | --- |
| pageswiki-app | `sha256:4a9b0b85330dac915e73e1aa5155f4691e46b2de945c76f1e14ae9735533a99b` |
| pageswiki-adaptor-gateway | `sha256:4ff0dc5565537ae9d157df9515ac3b9df67090f1a69d8cc26f2bea5943885017` |
| pageswiki-excalidraw-viewer | `sha256:32a643778dff894f0ba679864e401d5605f80ad28bc4bd85bbcde453f2bc4127` |
2026-11-06 10:05:28 JSTに対象4サービスを停止開始、10:06:31に最終バックアップ照合完了、10:06:37に起動完了。停止から起動まで69秒。app・app2・adaptor gateway・Excalidraw viewerをregistry overlayでv0.9.0に更新し、他のサービスは変更していない。`.env.release`を更新し、ローカルlatestタグも稼働イメージへ揃えた。
保全先は `.deployment-backups/release-v0.9.0-20261106/`。旧構成と `cutover/data`・`cutover/data2` を保存し、停止後のchecksum付き同期・差分ゼロ・DB/WAL/SHMのバイト一致・稼働元と異なるinodeを確認した。変更のないファイルは前回の不変バックアップとだけlink-destで共有する。旧イメージは `rollback-before-v0.9.0-20261106` で保持し、既存バックアップは削除していない。
このホストの `/home/anya/.local/bin/pages` は公開ELF v0.4.0へ原子的に置換し、バイト一致とversionを検証した。旧CLIは保全先configの `pages-before-v0.4.0` に保持する。独立CLIの作業用リポジトリも公開コミット・タグへ同期した。資格情報・セッション・個人設定は変更していない。
対象4コンテナのrevision一致・起動・再起動0回、appとExcalidrawのhealthy、app2内部health、初期ログのエラーパターン0件を確認した。公開HTTPSのhealth・ログインは200、匿名のタスク画面・個人設定画面は303、preferences API・CardDAVは401。配信されたtasks.js・task-productivity.js・tasks.cssはリリースとSHA-256一致。両系統の管理対象12コンポーネントのschema checkは前後ともcurrent。ただしlegacy領域を含めた全データ完全性検査ではない。
実メール本文・外部取り込みカレンダーは検証に使用していない。本番には合成メールやタスクを追加せず、認証済み操作は一時DBで試験した。保全は内容を解釈しないファイルコピー。完了時の空き容量は約19 GiB。切戻し時もまず書込み停止と現状保全を行い、バックアップを自動復元しない。
+19
View File
@@ -290,6 +290,11 @@ func (s *Server) handleConfig(
} }
case "home": 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 { if controlled, e := s.store.DomainEntryControlled(domainUUID); e != nil || controlled {
http.Error(w, translate(s.getLocale(domainUUID), "periodical.controlled"), http.StatusConflict) http.Error(w, translate(s.getLocale(domainUUID), "periodical.controlled"), http.StatusConflict)
return return
@@ -344,6 +349,10 @@ func (s *Server) handleConfig(
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return 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 { if err = s.store.SetConfigInDomain(domainUUID, "home_wallpaper_opacity", strconv.Itoa(wallpaperOpacity)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
@@ -463,6 +472,11 @@ func (s *Server) handleConfig(
} }
case "home-appearance": 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 { if controlled, e := s.store.DomainEntryControlled(domainUUID); e != nil || controlled {
http.Error(w, translate(s.getLocale(domainUUID), "periodical.controlled"), http.StatusConflict) http.Error(w, translate(s.getLocale(domainUUID), "periodical.controlled"), http.StatusConflict)
return return
@@ -472,6 +486,10 @@ func (s *Server) handleConfig(
http.Error(w, parseErr.Error(), http.StatusBadRequest) http.Error(w, parseErr.Error(), http.StatusBadRequest)
return 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 { if err = s.store.SetConfigInDomain(domainUUID, "home_glass_transparency", strconv.Itoa(glassTransparency)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
@@ -1064,6 +1082,7 @@ func (s *Server) handleConfig(
"HomeWallpaperPath": homeWallpaperPath, "HomeWallpaperPath": homeWallpaperPath,
"HomeWallpaperOpacity": homeWallpaperOpacity, "HomeWallpaperOpacity": homeWallpaperOpacity,
"HomeGlassTransparency": s.homeGlassTransparency(domainUUID), "HomeGlassTransparency": s.homeGlassTransparency(domainUUID),
"HomePalette": s.homePalette(domainUUID),
"HomeLayout": s.homeLayout(s.domainUUIDForRequest(r)), "HomeLayout": s.homeLayout(s.domainUUIDForRequest(r)),
"HomeBookmarks": s.homeBookmarksText(s.domainUUIDForRequest(r)), "HomeBookmarks": s.homeBookmarksText(s.domainUUIDForRequest(r)),
"VirtualFolderPages": s.getVirtualFolderPages(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 Path string
URL string URL string
Opacity string Opacity string
Key string
} }
// configuredLoginWallpaper returns only the image selected by the Domain // configuredLoginWallpaper returns only the image selected by the Domain
@@ -143,7 +144,8 @@ func (s *Server) homeWallpaperForRequest(r *http.Request) homeWallpaperView {
httpRequest := r httpRequest := r
if objectUUID, err := s.store.ResolvePathInDomain(domainUUID, configured); err == nil && s.requestCanReadPath(httpRequest, configured) { 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) { 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 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 { if value, err := rand.Int(rand.Reader, big.NewInt(int64(len(candidates)))); err == nil {
index = int(value.Int64()) 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 return view
} }
+1 -1
View File
@@ -107,7 +107,7 @@ func TestHomeWallpaperFolderPickerAndTheme(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "http://localhost/", nil) r := httptest.NewRequest(http.MethodGet, "http://localhost/", nil)
r.Header.Set("Authorization", "Bearer "+token) r.Header.Set("Authorization", "Bearer "+token)
view := s.homeWallpaperForRequest(r) 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) t.Fatalf("view=%#v", view)
} }
homeResponse := httptest.NewRecorder() homeResponse := httptest.NewRecorder()
+18
View File
@@ -231,6 +231,15 @@ var translations = map[string]map[string]string{
"home.wallpaper_opacity": "Wallpaper opacity (%)", "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.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.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_transparency": "Glass transparency (%)",
"home.glass_help": "Controls the shared transparency of the home search, menus, suggestions, cards, and dialogs. Higher values are more transparent.", "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", "picker.open": "Browse PagesWiki",
@@ -1002,6 +1011,15 @@ var translations = map[string]map[string]string{
"home.wallpaper_opacity": "壁紙の透明度(%)", "home.wallpaper_opacity": "壁紙の透明度(%)",
"home.wallpaper_help": "画像を1つ選ぶか、直下の画像をリロードごとに選択するフォルダを指定します。閲覧権限はそのまま適用されます。", "home.wallpaper_help": "画像を1つ選ぶか、直下の画像をリロードごとに選択するフォルダを指定します。閲覧権限はそのまま適用されます。",
"home.appearance": "トップ画面の外観", "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_transparency": "グラスの透明度(%)",
"home.glass_help": "トップ画面の検索、メニュー、サジェスト、カード、ダイアログに共通の透明度です。数値を上げるほど背景が透けます。", "home.glass_help": "トップ画面の検索、メニュー、サジェスト、カード、ダイアログに共通の透明度です。数値を上げるほど背景が透けます。",
"picker.open": "PagesWikiから選択", "picker.open": "PagesWikiから選択",
+3
View File
@@ -84,6 +84,9 @@ func (s *Server) renderWithContext(
wallpaper := s.homeWallpaperForRequest(r) wallpaper := s.homeWallpaperForRequest(r)
data["HomeWallpaperURL"] = wallpaper.URL data["HomeWallpaperURL"] = wallpaper.URL
data["HomeWallpaperOpacity"] = wallpaper.Opacity data["HomeWallpaperOpacity"] = wallpaper.Opacity
data["HomeWallpaperKey"] = wallpaper.Key
data["HomePalette"] = s.homePalette(domainUUID)
data["HomePaletteDomain"] = domainUUID
if wallpaper.URL != "" { if wallpaper.URL != "" {
w.Header().Set("Cache-Control", "private, no-cache") 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); }
})();
+7
View File
@@ -107,6 +107,13 @@ body.mode-config .config-section {
.asset-detail-dialog { width:min(72rem,calc(100vw - 2rem));max-height:calc(100vh - 2rem);overflow:auto;background:var(--bg);color:var(--fg);border:1px solid var(--border-soft);border-radius:.5rem;padding:1.25rem } .asset-detail-dialog { width:min(72rem,calc(100vw - 2rem));max-height:calc(100vh - 2rem);overflow:auto;background:var(--bg);color:var(--fg);border:1px solid var(--border-soft);border-radius:.5rem;padding:1.25rem }
.asset-detail-dialog::backdrop { background:rgba(0,0,0,.55) } .asset-detail-dialog::backdrop { background:rgba(0,0,0,.55) }
.config-path-control,.config-range-control{display:flex;align-items:center;gap:.5rem;min-width:0}.config-path-control input{flex:1;min-width:0}.config-path-control button{flex:0 0 2.2rem;height:2.2rem;padding:0}.config-range-control input{flex:1;min-width:8rem}.config-range-control output{min-width:3.5rem;text-align:end;font-variant-numeric:tabular-nums} .config-path-control,.config-range-control{display:flex;align-items:center;gap:.5rem;min-width:0}.config-path-control input{flex:1;min-width:0}.config-path-control button{flex:0 0 2.2rem;height:2.2rem;padding:0}.config-range-control input{flex:1;min-width:8rem}.config-range-control output{min-width:3.5rem;text-align:end;font-variant-numeric:tabular-nums}
.mode-config .home-palette-controls{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,15rem),1fr));gap:.75rem;min-width:0}
.mode-config .home-palette-controls label{display:grid;gap:.35rem;min-width:0}
.mode-config .home-palette-controls select{width:100%;min-width:0}
.mode-config .home-palette-controls p{grid-column:1/-1;margin:0}
.mode-config .home-appearance-range{display:flex;gap:.5rem;align-items:center;min-width:0}
.mode-config .home-appearance-range input{flex:1;min-width:0;accent-color:var(--accent)}
.mode-config .home-appearance-range output{min-width:3.5rem;text-align:end;font-variant-numeric:tabular-nums}
.config-path-picker{box-sizing:border-box;width:min(46rem,95vw);height:min(42rem,90dvh);margin:auto;padding:0;overflow:hidden;border:1px solid var(--border);border-radius:.8rem;background:var(--input-bg,var(--bg));color:var(--fg);box-shadow:0 1.5rem 5rem #0009}.config-path-picker[open]{display:grid;grid-template-rows:auto auto auto minmax(0,1fr) auto}.config-path-picker::backdrop{background:#0009;backdrop-filter:blur(3px)}.config-path-picker>header,.config-path-picker>nav,.config-path-picker>footer{display:flex;align-items:center;gap:.6rem;padding:.75rem 1rem;background:var(--input-bg,var(--bg))}.config-path-picker>header{justify-content:space-between;border-bottom:1px solid var(--border)}.config-path-picker>header h2{margin:0;font-size:1.05rem}.config-path-picker>header button{border:0;background:transparent;color:inherit;font-size:1.4rem}.config-path-picker>nav{border-bottom:1px solid var(--border-soft)}.config-path-picker>nav code{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.config-path-picker>[data-path-picker-status]{min-height:1.2rem;margin:0;padding:.45rem 1rem}.config-path-picker-list{min-height:10rem;padding:.25rem .5rem;overflow:auto;overscroll-behavior:contain}.config-path-picker-item{display:grid;grid-template-columns:1.5rem minmax(0,1fr) auto;align-items:center;gap:.55rem;width:100%;padding:.5rem .65rem;border:0;border-radius:.35rem;background:transparent;color:inherit;text-align:start}.config-path-picker-item:hover,.config-path-picker-item[aria-selected=true]{background:var(--row-hover,var(--border-soft))}.config-path-picker-item[aria-selected=true]{outline:1px solid var(--accent)}.config-path-picker-item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.config-path-picker-item small{color:var(--muted)}.config-path-picker>footer{justify-content:flex-end;border-top:1px solid var(--border)} .config-path-picker{box-sizing:border-box;width:min(46rem,95vw);height:min(42rem,90dvh);margin:auto;padding:0;overflow:hidden;border:1px solid var(--border);border-radius:.8rem;background:var(--input-bg,var(--bg));color:var(--fg);box-shadow:0 1.5rem 5rem #0009}.config-path-picker[open]{display:grid;grid-template-rows:auto auto auto minmax(0,1fr) auto}.config-path-picker::backdrop{background:#0009;backdrop-filter:blur(3px)}.config-path-picker>header,.config-path-picker>nav,.config-path-picker>footer{display:flex;align-items:center;gap:.6rem;padding:.75rem 1rem;background:var(--input-bg,var(--bg))}.config-path-picker>header{justify-content:space-between;border-bottom:1px solid var(--border)}.config-path-picker>header h2{margin:0;font-size:1.05rem}.config-path-picker>header button{border:0;background:transparent;color:inherit;font-size:1.4rem}.config-path-picker>nav{border-bottom:1px solid var(--border-soft)}.config-path-picker>nav code{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.config-path-picker>[data-path-picker-status]{min-height:1.2rem;margin:0;padding:.45rem 1rem}.config-path-picker-list{min-height:10rem;padding:.25rem .5rem;overflow:auto;overscroll-behavior:contain}.config-path-picker-item{display:grid;grid-template-columns:1.5rem minmax(0,1fr) auto;align-items:center;gap:.55rem;width:100%;padding:.5rem .65rem;border:0;border-radius:.35rem;background:transparent;color:inherit;text-align:start}.config-path-picker-item:hover,.config-path-picker-item[aria-selected=true]{background:var(--row-hover,var(--border-soft))}.config-path-picker-item[aria-selected=true]{outline:1px solid var(--accent)}.config-path-picker-item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.config-path-picker-item small{color:var(--muted)}.config-path-picker>footer{justify-content:flex-end;border-top:1px solid var(--border)}
.asset-dialog-close { position:absolute;right:.75rem;top:.75rem } .asset-dialog-close { position:absolute;right:.75rem;top:.75rem }
.table-scroll { overflow-x: auto; } .table-scroll { overflow-x: auto; }
+8 -1
View File
@@ -72,6 +72,13 @@ body.periodical-top:has(> .home-wallpaper) .periodical-shell dialog header { bac
.home-appearance-dialog h2 { font-size:1.1rem; } .home-appearance-dialog h2 { font-size:1.1rem; }
.home-appearance-dialog header button { border:0; background:transparent; color:inherit; font-size:1.5rem; cursor:pointer; } .home-appearance-dialog header button { border:0; background:transparent; color:inherit; font-size:1.5rem; cursor:pointer; }
.home-appearance-dialog label { display:grid; gap:.55rem; } .home-appearance-dialog label { display:grid; gap:.55rem; }
.home-palette-controls { display:grid; gap:.85rem; min-width:0; }
.home-appearance-dialog { max-height:calc(100dvh - 2rem); overflow:auto; overscroll-behavior:contain; }
.home-palette-controls label { display:grid; gap:.4rem; }
.home-palette-controls select { width:100%; min-width:0; padding:.45rem .6rem; color:var(--input-fg,var(--fg)); background:var(--input-bg,var(--bg)); border:1px solid var(--input-border,var(--border)); border-radius:.4rem; }
body[data-home-palette-active] { background-color:var(--bg); color:var(--fg); accent-color:var(--accent); }
body[data-home-palette-active] .home-search :is(input,button) { color:var(--fg); }
body[data-home-palette-active] :is(.home-wiki-title,.home-shortcuts) { text-shadow:0 1px 4px color-mix(in srgb,var(--bg) 85%,transparent); }
.home-appearance-range { display:grid; grid-template-columns:minmax(0,1fr) 3.5rem; align-items:center; gap:.75rem; } .home-appearance-range { display:grid; grid-template-columns:minmax(0,1fr) 3.5rem; align-items:center; gap:.75rem; }
.home-appearance-range input { width:100%; accent-color:var(--accent); } .home-appearance-range input { width:100%; accent-color:var(--accent); }
.home-appearance-range output { color:var(--fg); font-variant-numeric:tabular-nums; text-align:right; } .home-appearance-range output { color:var(--fg); font-variant-numeric:tabular-nums; text-align:right; }
@@ -92,7 +99,7 @@ body.periodical-top:has(> .home-wallpaper) .periodical-shell dialog header { bac
.home-paged .home-main[data-home-page="bookmarks"] { transform:translate3d(0,calc(-100dvh + var(--home-pager-drag)),0); } .home-paged .home-main[data-home-page="bookmarks"] { transform:translate3d(0,calc(-100dvh + var(--home-pager-drag)),0); }
.home-paged .home-main[data-home-dragging] { transition:none; user-select:none; } .home-paged .home-main[data-home-dragging] { transition:none; user-select:none; }
.home-pager-page { position:relative; min-width:0; height:100vh; height:100dvh; } .home-pager-page { position:relative; min-width:0; height:100vh; height:100dvh; }
.home-search-page { display:grid; place-items:center; padding:5rem 0; touch-action:pan-x; } .home-search-page { display:grid; grid-template-columns:minmax(0,1fr); place-items:center; padding:5rem 0; touch-action:pan-x; }
.home-search-page .home-search { align-self:center; } .home-search-page .home-search { align-self:center; }
.home-bookmarks-page { padding:4.5rem 0 3rem; overflow:auto; overscroll-behavior:contain; scrollbar-gutter:stable; touch-action:pan-y; } .home-bookmarks-page { padding:4.5rem 0 3rem; overflow:auto; overscroll-behavior:contain; scrollbar-gutter:stable; touch-action:pan-y; }
.home-bookmarks-page-head { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin:0 0 1.25rem; padding-inline:.25rem; } .home-bookmarks-page-head { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin:0 0 1.25rem; padding-inline:.25rem; }
+19 -3
View File
@@ -8,23 +8,35 @@
if (!open || !dialog || !form || !input || !output || !status) return; if (!open || !dialog || !form || !input || !output || !status) return;
let saved = Number(input.value); let saved = Number(input.value);
const paletteNames = ['home_palette_mode','home_palette_strength','home_palette_brightness'];
let savedPalette = paletteNames.map(name => form.elements[name]?.value);
const palettePreview = () => {
const strength = Number(form.elements.home_palette_strength?.value ?? 35);
const label = form.querySelector('[data-palette-strength]');
if (label) label.textContent = `${strength}%`;
document.dispatchEvent(new CustomEvent('pageswiki:home-appearance', {detail:{mode:form.elements.home_palette_mode?.value || 'off', strength, brightness:form.elements.home_palette_brightness?.value || 'preserve'}}));
};
const preview = value => { const preview = value => {
const transparency = Math.max(0, Math.min(85, Number(value) || 0)); const transparency = Math.max(0, Math.min(85, Number(value) || 0));
document.body.style.setProperty('--home-glass-opacity', `${100 - transparency}%`); document.body.style.setProperty('--home-glass-opacity', `${100 - transparency}%`);
output.value = `${transparency}%`; output.value = `${transparency}%`;
output.textContent = `${transparency}%`; output.textContent = `${transparency}%`;
palettePreview();
}; };
const restore = () => { const restore = () => {
input.value = String(saved); input.value = String(saved);
paletteNames.forEach((name,i) => { if (form.elements[name]) form.elements[name].value=savedPalette[i]; });
preview(saved); preview(saved);
status.textContent = ''; status.textContent = '';
}; };
const close = () => { const close = () => {
if (form.querySelector('[type=submit]').disabled) return;
restore(); restore();
dialog.close(); dialog.close();
}; };
input.addEventListener('input', () => preview(input.value)); input.addEventListener('input', () => preview(input.value));
paletteNames.forEach(name => form.elements[name]?.addEventListener('input',palettePreview));
open.addEventListener('click', () => { open.addEventListener('click', () => {
restore(); restore();
dialog.showModal(); dialog.showModal();
@@ -46,25 +58,29 @@
event.preventDefault(); event.preventDefault();
const submit = form.querySelector('[type=submit]'); const submit = form.querySelector('[type=submit]');
if (submit.disabled) return; if (submit.disabled) return;
const submitted = new URLSearchParams(new FormData(form));
const controls = [...form.querySelectorAll('input,select,button')].filter(node => !node.disabled);
controls.forEach(node => { node.disabled=true; });
submit.disabled = true; submit.disabled = true;
status.textContent = ''; status.textContent = '';
try { try {
const response = await fetch(form.action, { const response = await fetch(form.action, {
method: 'POST', method: 'POST',
body: new URLSearchParams(new FormData(form)), body: submitted,
headers: {Accept: 'application/json'}, headers: {Accept: 'application/json'},
signal: AbortSignal.timeout(15000), signal: AbortSignal.timeout(15000),
}); });
if (!response.ok) throw new Error((await response.text()).trim()); if (!response.ok) throw new Error((await response.text()).trim());
await response.json(); await response.json();
saved = Number(input.value); saved = Number(submitted.get('home_glass_transparency'));
savedPalette = paletteNames.map(name => submitted.get(name));
preview(saved); preview(saved);
status.textContent = form.dataset.saved; status.textContent = form.dataset.saved;
window.setTimeout(() => dialog.open && dialog.close(), 350); window.setTimeout(() => dialog.open && dialog.close(), 350);
} catch (error) { } catch (error) {
status.textContent = error.message; status.textContent = error.message;
} finally { } finally {
submit.disabled = false; controls.forEach(node => { node.disabled=false; });
} }
}); });
})(); })();
+58
View File
@@ -0,0 +1,58 @@
/* Bounded, dependency-free palette math; also exercised by node --test. */
((root) => {
'use strict';
const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
const mix = (a, b, n) => a.map((x, i) => x * (1 - n) + b[i] * n);
const luminance = c => c.map(x => { x /= 255; return x <= .04045 ? x / 12.92 : ((x + .055) / 1.055) ** 2.4; }).reduce((a, x, i) => a + x * [.2126, .7152, .0722][i], 0);
const contrast = (a, b) => (Math.max(luminance(a), luminance(b)) + .05) / (Math.min(luminance(a), luminance(b)) + .05);
const ink = bg => contrast([255,255,255], bg) >= contrast([0,0,0], bg) ? [255,255,255] : [0,0,0];
const readable = (c, bg, ratio) => {
const end = ink(bg);
for (let n = 0; n <= 20; n++) { const v = mix(c, end, n / 20); if (contrast(v, bg) >= ratio) return v; }
return end;
};
const css = c => '#' + c.map(v => Math.round(clamp(v,0,255)).toString(16).padStart(2,'0')).join('');
function extract(pixels) {
if (!pixels || pixels.length > 64 * 64 * 4 || pixels.length % 4) return null;
const bins = new Map(), sum = [0,0,0]; let weight = 0;
for (let i = 0; i < pixels.length; i += 4) {
const a = pixels[i+3] / 255; if (a < .06) continue;
const c = [pixels[i], pixels[i+1], pixels[i+2]], key = c.map(x => x >> 5).join(',');
const bin = bins.get(key) || {sum:[0,0,0], weight:0};
c.forEach((v,j) => { sum[j] += v*a; bin.sum[j] += v*a; });
bin.weight += a; weight += a; bins.set(key, bin);
}
if (!weight) return null;
const average = sum.map(x => x / weight); let accent = average, best = 0;
for (const bin of bins.values()) {
const c = bin.sum.map(x => x / bin.weight), hi = Math.max(...c), lo = Math.min(...c);
const saturation = hi ? (hi-lo)/hi : 0, light = luminance(c);
const score = Math.sqrt(bin.weight) * saturation * (light > .025 && light < .85 ? 1 : .1);
if (score > best) { best = score; accent = c; }
}
return {average, accent, coverage:weight / (pixels.length / 4)};
}
function colors(p, base, opts) {
if (!p || opts.mode === 'off' || !opts.strength || opts.opacity <= 0) return {};
const strength = clamp(opts.strength / 100), opacity = clamp(opts.opacity * p.coverage);
const backdrop = mix(base.bg, p.average, opacity);
const dark = opts.brightness === 'auto' && opts.mode === 'surface' ? luminance(backdrop) < .36 : luminance(base.bg) < .36;
const neutral = dark ? [18,20,26] : [244,246,250];
const hue = mix(p.average, p.accent, .35);
const tinted = mix(neutral, hue, dark ? .23 : .12);
const bg = opts.mode === 'surface' ? mix(opts.brightness === 'auto' ? neutral : base.bg, tinted, strength) : base.bg;
const behind = mix(bg, p.average, opacity), glass = mix(behind, bg, clamp(opts.glass));
const accent = readable(mix(base.accent, p.accent, strength), glass, 3);
const result = {'--accent':css(accent), '--link':css(readable(accent, glass, 4.5)), '--link-hover':css(readable(accent,glass,7))};
if (opts.mode !== 'surface') return result;
const fg = readable(dark ? [238,242,248] : [22,25,32], glass, 7);
Object.assign(result, {'--bg':css(bg), '--panel':css(bg), '--fg':css(fg), '--muted':css(readable(mix(fg,glass,.3),glass,4.5)),
'--border':css(mix(bg,accent,.32)), '--border-soft':css(mix(bg,accent,.18)),
'--input-bg':css(bg), '--input-fg':css(fg), '--input-border':css(mix(bg,accent,.4)),
'--button-bg':css(bg), '--button-fg':css(fg), '--button-border':css(mix(bg,accent,.4)), '--button-hover-bg':css(mix(bg,accent,.12))});
return result;
}
const api = {extract, colors, luminance, contrast, mix};
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.HomePalette = api;
})(globalThis);
+48
View File
@@ -0,0 +1,48 @@
const test=require('node:test'), assert=require('node:assert/strict');
const p=require('./home-palette-core.js');
const pixels=(color,count=4096)=>new Uint8ClampedArray(Array.from({length:count},()=>color).flat());
const rgb=hex=>[1,3,5].map(i=>parseInt(hex.slice(i,i+2),16));
const base={bg:[17,17,17],fg:[240,240,240],accent:[176,119,255]};
const opts={mode:'surface',strength:35,brightness:'preserve',opacity:.4,glass:.58};
test('bounded transparent and invalid input',()=>{
assert.equal(p.extract(pixels([0,0,0,0])),null);
assert.equal(p.extract(new Uint8Array(64*64*4+4)),null);
assert.equal(p.extract(new Uint8Array(3)),null);
assert.equal(p.extract(new Uint8Array(0)),null);
});
test('solid colors and alpha coverage',()=>{
assert.deepEqual(p.extract(pixels([10,70,180,255])).average,[10,70,180]);
assert.ok(Math.abs(p.extract(pixels([10,70,180,128])).coverage-128/255)<1e-10);
});
test('colored minority is selected instead of a muddy average',()=>{
const data=pixels([180,180,180,255]);for(let i=0;i<400*4;i+=4)data.set([20,90,220,255],i);
assert.deepEqual(p.extract(data).accent,[20,90,220]);
});
test('off, invisible wallpaper and zero strength preserve all tokens',()=>{
const palette=p.extract(pixels([40,90,220,255]));
for(const change of [{mode:'off'},{strength:0},{opacity:0}])assert.deepEqual(p.colors(palette,base,{...opts,...change}),{});
});
test('accent only never changes surfaces, brightness or semantic colors',()=>{
const c=p.colors(p.extract(pixels([240,100,30,255])),base,{...opts,mode:'accent',brightness:'auto'});
assert.deepEqual(Object.keys(c).sort(),['--accent','--link','--link-hover']);
});
test('dark/light, black/white and colored wallpaper keep readable panel text',()=>{
for(const bg of [[17,17,17],[245,245,245]])for(const color of [[0,0,0],[255,255,255],[200,30,100],[20,90,220]])for(const strength of [5,35,100]) {
const palette=p.extract(pixels([...color,255]));
const c=p.colors(palette,{...base,bg},{...opts,strength});
const surface=rgb(c['--bg']),behind=p.mix(surface,palette.average,opts.opacity),glass=p.mix(behind,surface,opts.glass);
// Target enhanced contrast where possible; mid-tone glass can only provide
// normal contrast even with pure black/white. Allow for RGB rounding.
assert.ok(p.contrast(rgb(c['--fg']),glass)>4.4);
assert.ok(p.contrast(rgb(c['--muted']),glass)>4.4);
assert.ok(!('--danger' in c));
assert.ok(Object.values(c).every(v=>/^#[0-9a-f]{6}$/.test(v)));
}
});
test('auto brightness follows composited wallpaper, not invisible source pixels',()=>{
const palette=p.extract(pixels([255,255,255,255]));
const dark=p.colors(palette,base,{...opts,brightness:'auto',opacity:.1});
const light=p.colors(palette,base,{...opts,brightness:'auto',opacity:1});
assert.ok(p.luminance(rgb(dark['--bg']))<.1);
assert.ok(p.luminance(rgb(light['--bg']))>.5);
});
+78
View File
@@ -0,0 +1,78 @@
(() => {
'use strict';
const config = document.querySelector('[data-home-palette]'), img = document.querySelector('body > .home-wallpaper');
if (!config || !img || !window.HomePalette) return;
const body = document.body, core = window.HomePalette, forced = matchMedia('(forced-colors: active)');
let options = {mode:config.dataset.mode, strength:Number(config.dataset.strength), brightness:config.dataset.brightness};
let palette = null, pending = false, attempted = false;
const originals = new Map();
const restore = () => {
for (const [key, value] of originals) { if (value[0]) body.style.setProperty(key,...value); else body.style.removeProperty(key); }
originals.clear(); delete body.dataset.homePaletteActive;
};
const valid = p => p && ['average','accent'].every(k => Array.isArray(p[k]) && p[k].length === 3 && p[k].every(v => Number.isFinite(v) && v >= 0 && v <= 255)) && Number.isFinite(p.coverage) && p.coverage > 0 && p.coverage <= 1;
const cacheName = 'pageswiki.wallpaper-palette.v1';
const key = /^[a-f0-9]{64}$/.test(config.dataset.key || '') ? config.dataset.domain + ':' + config.dataset.key : '';
const cacheRead = () => { try { const rows = JSON.parse(sessionStorage.getItem(cacheName) || '[]'); if (!Array.isArray(rows) || rows.length > 24) return; const row = rows.find(x => x.key === key); if (row && valid(row.palette)) return row.palette; } catch {} };
const cacheWrite = p => {
if (!key) return;
let rows=[];
try { rows=JSON.parse(sessionStorage.getItem(cacheName) || '[]'); } catch {}
if (!Array.isArray(rows)) rows=[];
rows=rows.filter(x => x && x.key !== key && valid(x.palette)).slice(-23);
rows.push({key,palette:p});
try { sessionStorage.setItem(cacheName, JSON.stringify(rows)); } catch {}
};
// Resolve custom-theme CSS colors (including color-mix) through computed style.
function baseColors() {
const probe = document.createElement('span'), canvas = document.createElement('canvas');
canvas.width=canvas.height=1;
const ctx=canvas.getContext('2d',{willReadFrequently:true});
probe.hidden=true; body.append(probe);
try {
const read = name => { probe.style.color=`var(--${name})`; ctx.clearRect(0,0,1,1); ctx.fillStyle=getComputedStyle(probe).color; ctx.fillRect(0,0,1,1); return [...ctx.getImageData(0,0,1,1).data].slice(0,3); };
return {bg:read('bg'), fg:read('fg'), accent:read('accent')};
} finally { probe.remove(); }
}
function apply() {
restore();
if (!palette || options.mode === 'off' || !options.strength || forced.matches) return;
try {
const glass = parseFloat(getComputedStyle(body).getPropertyValue('--home-glass-opacity')) / 100;
const values=core.colors(palette,baseColors(),{...options,opacity:Number(getComputedStyle(img).opacity),glass:Number.isFinite(glass)?glass:.58});
if (!Object.keys(values).length) return;
for (const [name,value] of Object.entries(values)) { originals.set(name,[body.style.getPropertyValue(name),body.style.getPropertyPriority(name)]); body.style.setProperty(name,value); }
body.dataset.homePaletteActive=options.mode;
} catch { restore(); }
}
function schedule() {
if (options.mode === 'off' || !options.strength || forced.matches) { restore(); return; }
if (palette) { apply(); return; }
if (!img.complete || !img.naturalWidth || pending || attempted) return;
pending=true;
const work=() => {
pending=false;
if (options.mode === 'off' || !options.strength || forced.matches) return;
attempted=true;
try {
palette=key && cacheRead();
if (!palette) {
const canvas=document.createElement('canvas'); canvas.width=canvas.height=64;
const ctx=canvas.getContext('2d',{willReadFrequently:true});
// Reuse the already displayed/decoded image: no second fetch or random pick.
ctx.drawImage(img,0,0,64,64); palette=core.extract(ctx.getImageData(0,0,64,64).data);
if (valid(palette)) { cacheWrite(palette); config.dataset.paletteSource='image'; }
} else config.dataset.paletteSource='cache';
if (valid(palette)) apply();
} catch { palette=null; restore(); }
};
if ('requestIdleCallback' in window) requestIdleCallback(work,{timeout:1500}); else setTimeout(work,32);
}
document.addEventListener('pageswiki:home-appearance', event => { if (event.detail) options={...options,...event.detail}; schedule(); });
document.addEventListener('pageswiki:theme',schedule);
document.addEventListener('load', event => { if (event.target instanceof HTMLLinkElement && event.target.rel === 'stylesheet') schedule(); },true);
forced.addEventListener('change',schedule);
img.addEventListener('load',schedule);
img.addEventListener('error',() => { palette=null; restore(); });
schedule();
})();
+1 -1
View File
@@ -1,7 +1,7 @@
{{ define "auth.gohtml" }}<!doctype html> {{ define "auth.gohtml" }}<!doctype html>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> <html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{ if .CLIAuth }}{{ T "auth.cli_title" }}{{ else if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }} · {{ .WikiName }}</title> <title>{{ if .CLIAuth }}{{ T "auth.cli_title" }}{{ else if .Logout }}{{ T "auth.logout" }}{{ else if .MFA }}{{ T "auth.totp" }}{{ else if .Setup }}{{ T "auth.setup" }}{{ else }}{{ T "auth.login" }}{{ end }} · {{ .WikiName }}</title>
<link rel="stylesheet" href="/static/css/theme/base.css"><link rel="stylesheet" href="/static/css/main.css"><link rel="stylesheet" href="/static/css/home.css?v=12"><link rel="stylesheet" href="/static/css/auth.css?v=1"><link rel="stylesheet" href="{{ .ThemeCSS }}"></head> <link rel="stylesheet" href="/static/css/theme/base.css"><link rel="stylesheet" href="/static/css/main.css"><link rel="stylesheet" href="/static/css/home.css?v=13"><link rel="stylesheet" href="/static/css/auth.css?v=1"><link rel="stylesheet" href="{{ .ThemeCSS }}"></head>
<body class="auth-page" style="--home-glass-opacity:{{ .HomeGlassOpacity }}%"> <body class="auth-page" style="--home-glass-opacity:{{ .HomeGlassOpacity }}%">
{{ if .HomeWallpaperURL }}<img class="home-wallpaper" src="{{ .HomeWallpaperURL }}" alt="" aria-hidden="true" decoding="async" fetchpriority="high" style="opacity:{{ .HomeWallpaperOpacity }}">{{ end }} {{ if .HomeWallpaperURL }}<img class="home-wallpaper" src="{{ .HomeWallpaperURL }}" alt="" aria-hidden="true" decoding="async" fetchpriority="high" style="opacity:{{ .HomeWallpaperOpacity }}">{{ end }}
<a class="auth-brand" href="/">{{ .WikiName }}</a> <a class="auth-brand" href="/">{{ .WikiName }}</a>
+2 -1
View File
@@ -15,7 +15,7 @@
<link rel="stylesheet" href="/static/css/theme/base.css"> <link rel="stylesheet" href="/static/css/theme/base.css">
<link rel="stylesheet" href="{{ .ThemeCSS }}"> <link rel="stylesheet" href="{{ .ThemeCSS }}">
<link rel="stylesheet" href="/static/css/config.css?v=external-resources-1"> <link rel="stylesheet" href="/static/css/config.css?v=home-palette-1">
</head> </head>
<body class="mode-config"> <body class="mode-config">
@@ -107,6 +107,7 @@
<p class="muted wide">{{ T "home.wallpaper_help" }}</p> <p class="muted wide">{{ T "home.wallpaper_help" }}</p>
<label class="wide">{{ T "home.glass_transparency" }}<span class="config-range-control"><input name="home_glass_transparency" type="range" min="0" max="85" step="1" value="{{ .HomeGlassTransparency }}" data-range-output="home-glass-transparency-output"><output id="home-glass-transparency-output">{{ .HomeGlassTransparency }}%</output></span></label> <label class="wide">{{ T "home.glass_transparency" }}<span class="config-range-control"><input name="home_glass_transparency" type="range" min="0" max="85" step="1" value="{{ .HomeGlassTransparency }}" data-range-output="home-glass-transparency-output"><output id="home-glass-transparency-output">{{ .HomeGlassTransparency }}%</output></span></label>
<p class="muted wide">{{ T "home.glass_help" }}</p> <p class="muted wide">{{ T "home.glass_help" }}</p>
{{ template "home-palette-controls" . }}
<p class="muted wide">{{ T "home.layout_help" }}</p> <p class="muted wide">{{ T "home.layout_help" }}</p>
<a class="wide" href="/-/sys/config?panel=bookmarks" data-config-panel="bookmarks">{{ T "config.manage_bookmarks" }} →</a> <a class="wide" href="/-/sys/config?panel=bookmarks" data-config-panel="bookmarks">{{ T "config.manage_bookmarks" }} →</a>
<label class="config-toggle wide" data-label="{{ T "config.virtual_folder_pages" }}"><input name="virtual_folder_pages" value="1" type="checkbox" role="switch" aria-label="{{ T "config.virtual_folder_pages" }}" {{ if .VirtualFolderPages }}checked{{ end }}></label> <label class="config-toggle wide" data-label="{{ T "config.virtual_folder_pages" }}"><input name="virtual_folder_pages" value="1" type="checkbox" role="switch" aria-label="{{ T "config.virtual_folder_pages" }}" {{ if .VirtualFolderPages }}checked{{ end }}></label>
+2 -2
View File
@@ -10,7 +10,7 @@
<link rel="stylesheet" href="/static/css/theme/base.css"> <link rel="stylesheet" href="/static/css/theme/base.css">
<link rel="stylesheet" href="/static/css/content-viewer.css"> <link rel="stylesheet" href="/static/css/content-viewer.css">
<link rel="stylesheet" href="/static/css/home.css?v=12"> <link rel="stylesheet" href="/static/css/home.css?v=13">
<link rel="stylesheet" href="{{ .ThemeCSS }}"> <link rel="stylesheet" href="{{ .ThemeCSS }}">
<script defer src="/static/js/content-viewer.js"></script> <script defer src="/static/js/content-viewer.js"></script>
<script defer src="/static/js/home-type-search.js?v=1"></script> <script defer src="/static/js/home-type-search.js?v=1"></script>
@@ -83,6 +83,6 @@
<button type="button" data-children-delete>{{ T "children.delete_selected" }}</button> <button type="button" data-children-delete>{{ T "children.delete_selected" }}</button>
</div> </div>
</body> {{ template "home-appearance" . }}{{ template "home-palette" . }}</body>
</html> </html>
{{ end }} {{ end }}
+2 -2
View File
@@ -13,7 +13,7 @@
<link rel="stylesheet" href="/static/css/content-viewer.css"> <link rel="stylesheet" href="/static/css/content-viewer.css">
<link rel="stylesheet" href="/static/css/city-graph.css"> <link rel="stylesheet" href="/static/css/city-graph.css">
<link rel="stylesheet" href="{{ .ThemeCSS }}"> <link rel="stylesheet" href="{{ .ThemeCSS }}">
{{ if .IsHome }}<link rel="stylesheet" href="/static/css/home.css?v=12">{{ end }} {{ if .IsHome }}<link rel="stylesheet" href="/static/css/home.css?v=13">{{ end }}
<script defer src="/static/js/content-viewer.js"></script> <script defer src="/static/js/content-viewer.js"></script>
<script defer src="/static/js/viewer-shortcuts.js"></script> <script defer src="/static/js/viewer-shortcuts.js"></script>
{{ if eq .ContentView.Kind "code" }} {{ if eq .ContentView.Kind "code" }}
@@ -990,6 +990,6 @@ window.addEventListener("DOMContentLoaded", () => {
</script> </script>
{{ end }} {{ end }}
</body> {{ template "home-appearance" . }}{{ template "home-palette" . }}</body>
</html> </html>
{{ end }} {{ end }}
+3 -3
View File
@@ -1,9 +1,9 @@
{{ define "periodical.gohtml" }}<!doctype html><html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ .Title }} · {{ .WikiName }}</title><link rel="stylesheet" href="/static/css/main.css"><link rel="stylesheet" href="/static/css/theme/base.css"><link rel="stylesheet" href="{{ .ThemeCSS }}"><link rel="stylesheet" href="/static/css/home.css?v=12"><link rel="stylesheet" href="/static/css/periodicals.css?v=6"></head> {{ define "periodical.gohtml" }}<!doctype html><html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ .Title }} · {{ .WikiName }}</title><link rel="stylesheet" href="/static/css/main.css"><link rel="stylesheet" href="/static/css/theme/base.css"><link rel="stylesheet" href="{{ .ThemeCSS }}"><link rel="stylesheet" href="/static/css/home.css?v=13"><link rel="stylesheet" href="/static/css/periodicals.css?v=6"></head>
<body class="{{ .Theme }} periodical-top">{{ if .HomeWallpaperURL }}<img class="home-wallpaper" src="{{ .HomeWallpaperURL }}" alt="" aria-hidden="true" decoding="async" fetchpriority="high" style="opacity:{{ .HomeWallpaperOpacity }}">{{ end }}<main class="periodical-shell" data-periodical-kind="{{ .Kind }}"><header class="topbar"><a href="/">{{ .WikiName }}</a>{{ if not .Public }}<nav><a href="/v/diary">{{ T "periodical.diary" }}</a><a href="/v/blog">{{ T "periodical.blog" }}</a></nav>{{ template "auth-menu" . }}{{ end }}</header><div class="periodical-heading"><h1>{{ .Title }}</h1><nav>{{ if .CanConfigure }}<a href="/-/sys/config?panel={{ .Kind }}" title="{{ T "extension.settings" }}">⚙</a>{{ end }}{{ if and .Projection (not .Public) }}<a href="{{ .SourceViewer }}">{{ T "periodical.source_viewer" }}</a>{{ else if and .Enabled (not .Public) }}<button type="button" data-periodical-compose aria-haspopup="dialog">+ {{ T "periodical.compose" }}</button><a href="/v/{{ .Kind }}/-/new" aria-label="{{ T "periodical.new_page" }}" title="{{ T "periodical.new_page" }}">↗</a><button type="button" data-periodical-new aria-haspopup="dialog">{{ T "periodical.plan" }}</button><button type="button" data-periodical-add aria-haspopup="dialog">+ {{ T "periodical.register" }}</button>{{ end }}</nav></div>{{ if not .Public }}<p class="muted">{{ T "periodical.scope_help" }}</p>{{ end }} <body class="{{ .Theme }} periodical-top"{{ if .IsHome }} style="--home-glass-opacity:{{ .HomeGlassOpacity }}%"{{ end }}>{{ if .HomeWallpaperURL }}<img class="home-wallpaper" src="{{ .HomeWallpaperURL }}" alt="" aria-hidden="true" decoding="async" fetchpriority="high" style="opacity:{{ .HomeWallpaperOpacity }}">{{ end }}<main class="periodical-shell" data-periodical-kind="{{ .Kind }}"><header class="topbar"><a href="/">{{ .WikiName }}</a>{{ if not .Public }}<nav><a href="/v/diary">{{ T "periodical.diary" }}</a><a href="/v/blog">{{ T "periodical.blog" }}</a></nav>{{ template "auth-menu" . }}{{ end }}</header><div class="periodical-heading"><h1>{{ .Title }}</h1><nav>{{ if .CanConfigure }}<a href="/-/sys/config?panel={{ .Kind }}" title="{{ T "extension.settings" }}">⚙</a>{{ end }}{{ if and .Projection (not .Public) }}<a href="{{ .SourceViewer }}">{{ T "periodical.source_viewer" }}</a>{{ else if and .Enabled (not .Public) }}<button type="button" data-periodical-compose aria-haspopup="dialog">+ {{ T "periodical.compose" }}</button><a href="/v/{{ .Kind }}/-/new" aria-label="{{ T "periodical.new_page" }}" title="{{ T "periodical.new_page" }}">↗</a><button type="button" data-periodical-new aria-haspopup="dialog">{{ T "periodical.plan" }}</button><button type="button" data-periodical-add aria-haspopup="dialog">+ {{ T "periodical.register" }}</button>{{ end }}</nav></div>{{ if not .Public }}<p class="muted">{{ T "periodical.scope_help" }}</p>{{ end }}
{{ if not .Enabled }}<p role="status">{{ T "periodical.disabled" }}</p>{{ else }} {{ if not .Enabled }}<p role="status">{{ T "periodical.disabled" }}</p>{{ else }}
<div class="periodical-layout"><section class="periodical-entries" aria-label="{{ .Title }}"><table class="periodical-index"><thead><tr><th scope="col">{{ T "periodical.date" }}</th><th scope="col">{{ T "periodical.title" }}</th><th scope="col" class="periodical-index-actions">{{ T "config.actions" }}</th></tr></thead><tbody>{{ range .Entries }}<tr data-periodical-entry data-page="{{ .PageUUID }}" data-path="{{ .Path }}" data-title="{{ .Title }}" data-date="{{ .Date }}" data-category="{{ .Category }}" data-version="{{ .Version }}"><td class="periodical-index-date"><time datetime="{{ .Date }}">{{ .Date }}</time></td><td class="periodical-index-title"><h2><a href="{{ .Href }}" title="{{ .Title }}">{{ .Title }}</a></h2></td><td class="periodical-index-actions">{{ if .CanEdit }}<nav><a href="{{ .EditHref }}" title="{{ T "periodical.edit_body" }}" aria-label="{{ T "periodical.edit_body" }}">✎</a><button type="button" data-periodical-edit aria-label="{{ T "periodical.edit_metadata" }}" title="{{ T "periodical.edit_metadata" }}">⚙</button><button type="button" data-periodical-remove data-confirm="{{ T "periodical.remove_confirm" }}" title="{{ T "periodical.remove" }}" aria-label="{{ T "periodical.remove" }}">×</button></nav>{{ end }}</td></tr>{{ else }}<tr><td colspan="3">{{ T "periodical.empty" }}</td></tr>{{ end }}</tbody></table><nav class="periodical-pagination">{{ if .Previous }}<a href="{{ .Previous }}">← {{ T "periodical.previous" }}</a>{{ end }}{{ if .Next }}<a href="{{ .Next }}">{{ T "periodical.next" }} →</a>{{ end }}</nav></section> <div class="periodical-layout"><section class="periodical-entries" aria-label="{{ .Title }}"><table class="periodical-index"><thead><tr><th scope="col">{{ T "periodical.date" }}</th><th scope="col">{{ T "periodical.title" }}</th><th scope="col" class="periodical-index-actions">{{ T "config.actions" }}</th></tr></thead><tbody>{{ range .Entries }}<tr data-periodical-entry data-page="{{ .PageUUID }}" data-path="{{ .Path }}" data-title="{{ .Title }}" data-date="{{ .Date }}" data-category="{{ .Category }}" data-version="{{ .Version }}"><td class="periodical-index-date"><time datetime="{{ .Date }}">{{ .Date }}</time></td><td class="periodical-index-title"><h2><a href="{{ .Href }}" title="{{ .Title }}">{{ .Title }}</a></h2></td><td class="periodical-index-actions">{{ if .CanEdit }}<nav><a href="{{ .EditHref }}" title="{{ T "periodical.edit_body" }}" aria-label="{{ T "periodical.edit_body" }}">✎</a><button type="button" data-periodical-edit aria-label="{{ T "periodical.edit_metadata" }}" title="{{ T "periodical.edit_metadata" }}">⚙</button><button type="button" data-periodical-remove data-confirm="{{ T "periodical.remove_confirm" }}" title="{{ T "periodical.remove" }}" aria-label="{{ T "periodical.remove" }}">×</button></nav>{{ end }}</td></tr>{{ else }}<tr><td colspan="3">{{ T "periodical.empty" }}</td></tr>{{ end }}</tbody></table><nav class="periodical-pagination">{{ if .Previous }}<a href="{{ .Previous }}">← {{ T "periodical.previous" }}</a>{{ end }}{{ if .Next }}<a href="{{ .Next }}">{{ T "periodical.next" }} →</a>{{ end }}</nav></section>
<aside><div class="periodical-calendar-panel"><form method="get" action="{{ .FilterAction }}" class="periodical-filters" data-periodical-filters><div class="periodical-month-controls">{{ template "periodical-month-controls" . }}<a class="periodical-filter-icon" href="{{ .BasePath }}" title="{{ T "periodical.clear" }}" aria-label="{{ T "periodical.clear" }}">{{ template "periodical-reset-icon" . }}</a></div>{{ if not .Public }}<label>{{ T "periodical.category" }} <select name="category"><option value="">{{ T "periodical.all" }}</option>{{ range .Categories }}<option {{ if eq . $.Category }}selected{{ end }}>{{ . }}</option>{{ end }}</select></label><label><input type="checkbox" name="own" value="" {{ if .Mine }}checked{{ end }}> {{ T "periodical.mine" }}</label>{{ end }}</form><section class="periodical-calendar"><header><a href="{{ .PreviousMonth }}" aria-label="{{ T "periodical.previous_month" }}">‹</a><strong>{{ .Month }}</strong><a href="{{ .NextMonth }}" aria-label="{{ T "periodical.next_month" }}">›</a></header><div class="periodical-weekdays" aria-hidden="true">{{ if eq .Locale "ja" }}<span>日</span><span>月</span><span>火</span><span>水</span><span>木</span><span>金</span><span>土</span>{{ else }}<span>Su</span><span>Mo</span><span>Tu</span><span>We</span><span>Th</span><span>Fr</span><span>Sa</span>{{ end }}</div><div class="periodical-days">{{ range .Days }}{{ if .Number }}<a href="{{ .Href }}" class="{{ if .Count }}has-entries{{ end }}" {{ if .Selected }}aria-current="date"{{ end }}>{{ .Number }}{{ if .Count }}<small aria-label="{{ T "periodical.entries" }}">{{ .Count }}</small>{{ end }}</a>{{ else }}<span></span>{{ end }}{{ end }}</div></section></div><section class="periodical-recent"><h2>{{ T "periodical.recent" }}</h2>{{ range .Recent }}<a href="{{ .Href }}"><time>{{ .Date }}</time> {{ .Title }}</a>{{ else }}<p>{{ T "periodical.empty" }}</p>{{ end }}</section></aside></div> <aside><div class="periodical-calendar-panel"><form method="get" action="{{ .FilterAction }}" class="periodical-filters" data-periodical-filters><div class="periodical-month-controls">{{ template "periodical-month-controls" . }}<a class="periodical-filter-icon" href="{{ .BasePath }}" title="{{ T "periodical.clear" }}" aria-label="{{ T "periodical.clear" }}">{{ template "periodical-reset-icon" . }}</a></div>{{ if not .Public }}<label>{{ T "periodical.category" }} <select name="category"><option value="">{{ T "periodical.all" }}</option>{{ range .Categories }}<option {{ if eq . $.Category }}selected{{ end }}>{{ . }}</option>{{ end }}</select></label><label><input type="checkbox" name="own" value="" {{ if .Mine }}checked{{ end }}> {{ T "periodical.mine" }}</label>{{ end }}</form><section class="periodical-calendar"><header><a href="{{ .PreviousMonth }}" aria-label="{{ T "periodical.previous_month" }}">‹</a><strong>{{ .Month }}</strong><a href="{{ .NextMonth }}" aria-label="{{ T "periodical.next_month" }}">›</a></header><div class="periodical-weekdays" aria-hidden="true">{{ if eq .Locale "ja" }}<span>日</span><span>月</span><span>火</span><span>水</span><span>木</span><span>金</span><span>土</span>{{ else }}<span>Su</span><span>Mo</span><span>Tu</span><span>We</span><span>Th</span><span>Fr</span><span>Sa</span>{{ end }}</div><div class="periodical-days">{{ range .Days }}{{ if .Number }}<a href="{{ .Href }}" class="{{ if .Count }}has-entries{{ end }}" {{ if .Selected }}aria-current="date"{{ end }}>{{ .Number }}{{ if .Count }}<small aria-label="{{ T "periodical.entries" }}">{{ .Count }}</small>{{ end }}</a>{{ else }}<span></span>{{ end }}{{ end }}</div></section></div><section class="periodical-recent"><h2>{{ T "periodical.recent" }}</h2>{{ range .Recent }}<a href="{{ .Href }}"><time>{{ .Date }}</time> {{ .Title }}</a>{{ else }}<p>{{ T "periodical.empty" }}</p>{{ end }}</section></aside></div>
{{ if not .Public }}<dialog data-periodical-composer><form><header><h2>{{ T "periodical.compose" }}</h2><button type="button" data-composer-close aria-label="{{ T "city.close" }}">×</button></header><fieldset><label>{{ T "periodical.title" }}<input name="title" required maxlength="240"></label><label>{{ T "periodical.date" }}<input type="date" name="date" required value="{{ .Today }}"></label><label>{{ T "periodical.keyword" }}<input name="keyword" maxlength="240"></label><p>{{ T "periodical.prefix" }}: <code>{{ .Prefix }}</code></p><label>{{ T "periodical.category" }}<input name="category" maxlength="80"></label><label>{{ T "periodical.body" }}<textarea name="body" rows="12" required maxlength="131072"></textarea></label><p>{{ T "periodical.compose_help" }}</p><button type="submit">{{ T "periodical.save_article" }}</button></fieldset><p role="status" data-composer-status></p></form></dialog> {{ if not .Public }}<dialog data-periodical-composer><form><header><h2>{{ T "periodical.compose" }}</h2><button type="button" data-composer-close aria-label="{{ T "city.close" }}">×</button></header><fieldset><label>{{ T "periodical.title" }}<input name="title" required maxlength="240"></label><label>{{ T "periodical.date" }}<input type="date" name="date" required value="{{ .Today }}"></label><label>{{ T "periodical.keyword" }}<input name="keyword" maxlength="240"></label><p>{{ T "periodical.prefix" }}: <code>{{ .Prefix }}</code></p><label>{{ T "periodical.category" }}<input name="category" maxlength="80"></label><label>{{ T "periodical.body" }}<textarea name="body" rows="12" required maxlength="131072"></textarea></label><p>{{ T "periodical.compose_help" }}</p><button type="submit">{{ T "periodical.save_article" }}</button></fieldset><p role="status" data-composer-status></p></form></dialog>
<dialog data-periodical-planner><form><header><h2>{{ T "periodical.plan" }}</h2><button type="button" data-planner-close aria-label="{{ T "city.close" }}">×</button></header><p>{{ T "periodical.prefix" }}: <code>{{ .Prefix }}</code></p><label>{{ T "periodical.date" }}<input type="date" name="date" required value="{{ .Today }}"></label><label>{{ T "periodical.keyword" }}<input name="keyword" maxlength="240"></label><button type="submit">{{ T "periodical.plan" }}</button><p data-planner-status role="status"></p><div data-planner-result hidden><p><a data-planner-editor target="_blank" rel="noopener">{{ T "periodical.open_editor" }}</a></p><p>{{ T "periodical.registration_help" }}</p><button type="button" data-planner-register>{{ T "periodical.register" }}</button></div></form></dialog> <dialog data-periodical-planner><form><header><h2>{{ T "periodical.plan" }}</h2><button type="button" data-planner-close aria-label="{{ T "city.close" }}">×</button></header><p>{{ T "periodical.prefix" }}: <code>{{ .Prefix }}</code></p><label>{{ T "periodical.date" }}<input type="date" name="date" required value="{{ .Today }}"></label><label>{{ T "periodical.keyword" }}<input name="keyword" maxlength="240"></label><button type="submit">{{ T "periodical.plan" }}</button><p data-planner-status role="status"></p><div data-planner-result hidden><p><a data-planner-editor target="_blank" rel="noopener">{{ T "periodical.open_editor" }}</a></p><p>{{ T "periodical.registration_help" }}</p><button type="button" data-planner-register>{{ T "periodical.register" }}</button></div></form></dialog>
<dialog data-periodical-dialog><form data-periodical-entry-form><header><h2>{{ T "periodical.register" }}</h2><button type="button" data-periodical-close aria-label="{{ T "city.close" }}">×</button></header><input type="hidden" name="page_uuid"><input type="hidden" name="version" value="0"><label>Path<input name="path" required placeholder="/diary/2026/09/16" maxlength="4096"></label><label>{{ T "periodical.title" }}<input name="title" required maxlength="240"></label><label>{{ T "periodical.date" }}<input type="date" name="date" required value="{{ .Today }}"></label><label>{{ T "periodical.category" }}<input name="category" maxlength="80"></label><p>{{ T "periodical.registration_help" }}</p><button type="submit">{{ T "config.save" }}</button><p data-periodical-status role="status"></p></form></dialog>{{ end }}{{ end }}</main><script src="/static/js/periodicals.js?v=8" defer></script></body></html>{{ end }} <dialog data-periodical-dialog><form data-periodical-entry-form><header><h2>{{ T "periodical.register" }}</h2><button type="button" data-periodical-close aria-label="{{ T "city.close" }}">×</button></header><input type="hidden" name="page_uuid"><input type="hidden" name="version" value="0"><label>Path<input name="path" required placeholder="/diary/2026/09/16" maxlength="4096"></label><label>{{ T "periodical.title" }}<input name="title" required maxlength="240"></label><label>{{ T "periodical.date" }}<input type="date" name="date" required value="{{ .Today }}"></label><label>{{ T "periodical.category" }}<input name="category" maxlength="80"></label><p>{{ T "periodical.registration_help" }}</p><button type="submit">{{ T "config.save" }}</button><p data-periodical-status role="status"></p></form></dialog>{{ end }}{{ end }}</main><script src="/static/js/periodicals.js?v=8" defer></script>{{ template "home-appearance" . }}{{ template "home-palette" . }}</body></html>{{ end }}
+3 -14
View File
@@ -8,7 +8,7 @@
{{ template "social-metadata" . }} {{ template "social-metadata" . }}
<link rel="stylesheet" href="/static/css/theme/base.css"> <link rel="stylesheet" href="/static/css/theme/base.css">
<link rel="stylesheet" href="{{ .ThemeCSS }}"> <link rel="stylesheet" href="{{ .ThemeCSS }}">
<link rel="stylesheet" href="/static/css/home.css?v=12"> <link rel="stylesheet" href="/static/css/home.css?v=13">
</head> </head>
<body class="home-landing home-layout-{{ .HomeLayout }}{{ if eq .HomeLayout "directory" }} home-paged{{ end }}" style="--home-glass-opacity:{{ .HomeGlassOpacity }}%"> <body class="home-landing home-layout-{{ .HomeLayout }}{{ if eq .HomeLayout "directory" }} home-paged{{ end }}" style="--home-glass-opacity:{{ .HomeGlassOpacity }}%">
{{ if .HomeWallpaperURL }}<img class="home-wallpaper" src="{{ .HomeWallpaperURL }}" alt="" aria-hidden="true" decoding="async" fetchpriority="high" style="opacity:{{ .HomeWallpaperOpacity }}">{{ end }} {{ if .HomeWallpaperURL }}<img class="home-wallpaper" src="{{ .HomeWallpaperURL }}" alt="" aria-hidden="true" decoding="async" fetchpriority="high" style="opacity:{{ .HomeWallpaperOpacity }}">{{ end }}
@@ -47,19 +47,8 @@
{{ template "home-bookmarks" . }} {{ template "home-bookmarks" . }}
{{ end }} {{ end }}
</main> </main>
{{ if .CanConfigureHome }} {{ template "home-appearance" . }}
<button type="button" class="home-appearance-launch" data-home-appearance-open aria-label="{{ T "home.appearance" }}" title="{{ T "home.appearance" }}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m9 3-.5 3-2 .9L4 6l-2 4 2.5 1.8v2.4L2 16l2 4 2.5-.9 2 .9.5 3h6l.5-3 2-.9L20 20l2-4-2.5-1.8v-2.4L22 10l-2-4-2.5.9-2-.9-.5-3z"/><circle cx="12" cy="13" r="3"/></svg></button> {{ template "home-palette" . }}
<dialog class="home-appearance-dialog" data-home-appearance-dialog aria-labelledby="home-appearance-title">
<form method="post" action="/-/sys/config" data-home-appearance-form data-saved="{{ T "config.saved" }}">
<input type="hidden" name="section" value="home-appearance">
<header><h2 id="home-appearance-title">{{ T "home.appearance" }}</h2><button type="button" data-home-appearance-close aria-label="{{ T "picker.cancel" }}">×</button></header>
<label>{{ T "home.glass_transparency" }}<span class="home-appearance-range"><input name="home_glass_transparency" type="range" min="0" max="85" step="1" value="{{ .HomeGlassTransparency }}"><output>{{ .HomeGlassTransparency }}%</output></span></label>
<p class="muted">{{ T "home.glass_help" }}</p>
<footer><span data-home-appearance-status role="status"></span><button type="button" data-home-appearance-cancel>{{ T "picker.cancel" }}</button><button type="submit">{{ T "config.save" }}</button></footer>
</form>
</dialog>
<script defer src="/static/js/home-appearance.js?v=1"></script>
{{ end }}
{{ if eq .HomeLayout "directory" }} {{ if eq .HomeLayout "directory" }}
<nav class="home-page-indicator" data-home-page-indicator aria-label="{{ T "home.bookmarks" }}"> <nav class="home-page-indicator" data-home-page-indicator aria-label="{{ T "home.bookmarks" }}">
<button type="button" data-home-page-target="search" aria-current="page" aria-label="{{ T "home.search" }}"></button> <button type="button" data-home-page-target="search" aria-current="page" aria-label="{{ T "home.search" }}"></button>
+33
View File
@@ -0,0 +1,33 @@
{{ define "home-palette-controls" }}
<div class="home-palette-controls wide">
<label>{{ T "home.palette_mode" }}<select name="home_palette_mode"><option value="off" {{ if eq .HomePalette.Mode "off" }}selected{{ end }}>{{ T "home.palette_off" }}</option><option value="accent" {{ if eq .HomePalette.Mode "accent" }}selected{{ end }}>{{ T "home.palette_accent" }}</option><option value="surface" {{ if eq .HomePalette.Mode "surface" }}selected{{ end }}>{{ T "home.palette_surface" }}</option></select></label>
<label>{{ T "home.palette_strength" }}<span class="home-appearance-range"><input name="home_palette_strength" data-range-output="home-palette-strength-output" type="range" min="0" max="100" step="5" value="{{ .HomePalette.Strength }}"><output id="home-palette-strength-output" data-palette-strength>{{ .HomePalette.Strength }}%</output></span></label>
<label>{{ T "home.palette_brightness" }}<select name="home_palette_brightness"><option value="preserve" {{ if eq .HomePalette.Brightness "preserve" }}selected{{ end }}>{{ T "home.palette_preserve" }}</option><option value="auto" {{ if eq .HomePalette.Brightness "auto" }}selected{{ end }}>{{ T "home.palette_auto" }}</option></select></label>
<p class="muted">{{ T "home.palette_help" }}</p>
</div>
{{ end }}
{{ define "home-appearance" }}
{{ if .IsHome }}
{{ if .CanConfigureHome }}
<button type="button" class="home-appearance-launch" data-home-appearance-open aria-label="{{ T "home.appearance" }}" title="{{ T "home.appearance" }}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m9 3-.5 3-2 .9L4 6l-2 4 2.5 1.8v2.4L2 16l2 4 2.5-.9 2 .9.5 3h6l.5-3 2-.9L20 20l2-4-2.5-1.8v-2.4L22 10l-2-4-2.5.9-2-.9-.5-3z"/><circle cx="12" cy="13" r="3"/></svg></button>
<dialog class="home-appearance-dialog" data-home-appearance-dialog aria-labelledby="home-appearance-title">
<form method="post" action="/-/sys/config" data-home-appearance-form data-saved="{{ T "config.saved" }}">
<input type="hidden" name="section" value="home-appearance">
<header><h2 id="home-appearance-title">{{ T "home.appearance" }}</h2><button type="button" data-home-appearance-close aria-label="{{ T "picker.cancel" }}">×</button></header>
<label>{{ T "home.glass_transparency" }}<span class="home-appearance-range"><input name="home_glass_transparency" type="range" min="0" max="85" step="1" value="{{ .HomeGlassTransparency }}"><output>{{ .HomeGlassTransparency }}%</output></span></label>
<p class="muted">{{ T "home.glass_help" }}</p>
{{ template "home-palette-controls" . }}
<footer><span data-home-appearance-status role="status"></span><button type="button" data-home-appearance-cancel>{{ T "picker.cancel" }}</button><button type="submit">{{ T "config.save" }}</button></footer>
</form>
</dialog>
<script defer src="/static/js/home-appearance.js?v=2"></script>
{{ end }}
{{ end }}
{{ end }}
{{ define "home-palette" }}
{{ if and .IsHome .HomeWallpaperURL }}
<div hidden data-home-palette data-mode="{{ .HomePalette.Mode }}" data-strength="{{ .HomePalette.Strength }}" data-brightness="{{ .HomePalette.Brightness }}" data-key="{{ .HomeWallpaperKey }}" data-domain="{{ .HomePaletteDomain }}"></div>
<script defer src="/static/js/home-palette-core.js?v=1"></script>
<script defer src="/static/js/home-palette.js?v=1"></script>
{{ end }}
{{ end }}