Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0964fdc5b7 | ||
|
|
c7aa4fd7dd | ||
|
|
1a451023f0 | ||
|
|
543814cbd6 | ||
|
|
3262f88005 | ||
|
|
0b6343aff0 |
No files matched your search
@@ -35,8 +35,8 @@ jobs:
|
||||
[worker.oci]
|
||||
max-parallelism = 2
|
||||
|
||||
- name: Test release tooling
|
||||
run: node --test tools/ci/release-images.test.mjs
|
||||
- name: Test release tooling and wallpaper palette
|
||||
run: node --test tools/ci/release-images.test.mjs static/js/home-palette-core.test.cjs
|
||||
|
||||
- name: Test
|
||||
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
|
||||
@@ -24,9 +24,15 @@ Webの新規作成・クイック追加・サブタスク追加でも既定値
|
||||
|
||||
### メール本文のWiki保存
|
||||
|
||||
v0.9.0は任意の `wiki_suffix` をcaptureに追加する。CLI v0.4.0はML連番なら `リスト名/連番`、それ以外は `YYYY/MM/UUID`(Message-IDあり)または `YYYY/MM/原文SHA-256`(なし)を送る。Dateの記載タイムゾーンの年月を採用し、不正・欠落時のみ初回取り込みUTC年月を用いる。判定はCLIで確定してoutboxに保持する。リスト名はASCII英数字で始まる100文字以内の英数字・`._-`、連番は先頭ゼロ除去後最大20桁。複数表記は先頭を採用する。不正な表記は年月方式へフォールバックする。
|
||||
|
||||
サーバーはMLの2階層または年月の3階層だけを受理し、絶対Path・`.`・`..`・予約セグメント・query/fragment・不正年月・不正識別子を拒否する。解決した親Pathの下へ結合し、その完全Pathのread/create/write権限を検証する。衝突は409で、別Message-IDのタスクも部分作成しない。wiki_suffixはwiki_body指定時のみ許可する。省略時は従来の `mail-request_id` とし、旧receiptのhash・保存先を維持する。新CLIは旧サーバーに暗黙フォールバックしない。既存ページの自動移動、同じ件名・同じ連番の上書きは行わない。設定変更や月替わりで保留要求を書き換えず、異なるオプションでの上書きを拒否する。
|
||||
|
||||
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エスケープして格納し、波括弧も実体参照にしてマクロを実行しない。Pathは `親Path/安全化した件名--request_id`。既存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を使う。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へ移動できる。
|
||||
|
||||
|
||||
@@ -43,6 +43,42 @@ Principalで直下の子だけを認可し、最大250件、`private, no-store`
|
||||
modeをdata属性で指定する。これにより今後のストレージ、アダプタ、City設定でも
|
||||
任意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,30 @@
|
||||
# PagesWiki v0.8.0 本番反映
|
||||
|
||||
2026-11-06 08:48:35 JST、本番のapp・app2・adaptor-gateway・excalidraw-viewerをv0.8.0へ更新した。このホストの `/home/anya/.local/bin/pages` も公開ELFのpages-cli v0.3.0へ更新した。機能・配布物は[リリース記録](../releases/2026-11-06-mail-wiki.md)を参照する。
|
||||
|
||||
## 保全と切替
|
||||
|
||||
`.deployment-backups/release-v0.8.0-20261106/` に構成とデータを保全した。configには旧 `.env`、`.env.release`、Compose、旧CLIの `pages-before-v0.3.0` がある。親ディレクトリ0700、構成コピー0600。data・data2は内容を解釈しないファイルコピーで、外部取り込みカレンダー要素にはアクセスしていない。
|
||||
|
||||
最終 `cutover/data`・`cutover/data2` は対象サービス停止後にchecksum付きrsyncで確定し、差分ゼロ、DB・WAL・SHMのバイト一致と稼働元と異なるinodeを確認した。未変更ファイルは前回の不変バックアップとのみlink-destで共有する。稼働元へのハードリンクは作らない。既存バックアップは削除していない。
|
||||
|
||||
| 時刻 JST | 操作 |
|
||||
| --- | --- |
|
||||
| 08:47:23 | 対象4サービス停止開始 |
|
||||
| 08:48:29 | 最終バックアップ検証完了 |
|
||||
| 08:48:35 | v0.8.0起動完了 |
|
||||
|
||||
停止開始から起動完了まで72秒。リリースイメージとSHAイメージのID・source revision一致を確認してから、`.env.release` をv0.8.0へ変更し、registry overlayの `up --no-build --no-deps` で対象4サービスだけ更新した。旧v0.7.1イメージは `rollback-before-v0.8.0-20261106` を付けて保持し、ローカルlatestを新リリースへ揃えた。registry latest、code-server、Kroki等は変更しない。
|
||||
|
||||
DBスキーマ変更はない。新イメージをネットワークなし・読み取り専用で起動するschema checkを切替前に両データ系統へ実施した。切戻し時は書込みを停止して現状も保全し、新CLIのWiki保存を停止する。旧版で個人設定を保存するとwiki_prefixが失われ得る。バックアップの自動復元は行っていない。
|
||||
|
||||
## 検証
|
||||
|
||||
- 対象4コンテナのsource revisionは `80d297dab40871b42ff2afb2ab6212661c465248` と一致。起動正常、再起動0回。appとExcalidrawはhealthy、app2の内部healthも成功。
|
||||
- 両系統の管理対象12コンポーネントはcurrent。legacy領域を含む全データ完全性の検査ではない。
|
||||
- 公開HTTPSでhealth・ログインは200。匿名のタスク・個人設定は303、preferences API・CardDAVは401。
|
||||
- 公開tasks.js・task-productivity.js・tasks.cssのSHA-256がv0.8.0と一致。
|
||||
- 初期ログのpanic、fatal、DB lock、job failed、scheduler claim failed、errorレベルの一致件数は0。
|
||||
- ホストCLIは公開ELFとバイト一致し、versionは0.3.0、from-mailの新オプションも確認した。既存資格情報・セッション・NeoMutt設定は変更していない。
|
||||
|
||||
認証済みのメール取り込み・個人設定操作は一時DBと合成データで検証し、本番にテストメールやタスクを追加していない。利用者の既定Pathは自動設定せず、保存先のACLを確認したうえで本人が選択する。反映後の空き容量は約33 GiB。
|
||||
@@ -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。切戻し時もまず書込み停止と現状保全を行い、バックアップを自動復元しない。
|
||||
@@ -0,0 +1,40 @@
|
||||
# 日本語メール件名とWiki Pathの修正
|
||||
|
||||
PagesWiki v0.8.1とpages-cli v0.3.1はメールの表示名とPathの識別子を分離する。v0.8.0は件名全体をURLへ含め、CLIは300 UTF-8 bytesを超える件名を取り込み前に拒否していた。短い日本語Pathそのものは合成HTTP試験で取得可能だが、実メールの失敗入力は取得していないため、報告されたすべての失敗が同じ原因とは断定しない。
|
||||
|
||||
## 動作
|
||||
|
||||
- Wiki Pathの末尾は `mail-request_id`。接続先・本人・Message-IDから生成済みのUUIDを利用し、件名の文字コード・記号・長さに依存しない。Message-IDそのものをURLへ露出しない。Message-IDなしは原文SHA-256から識別する。
|
||||
- MIME Subjectを復号後、先頭の `[list 123]`・`[list:123]`・`[list#123]` を除去する。Re:/Fw:/Fwd:は維持し、その後の連番も除去する。連番を含まない `[重要]` や途中の括弧はそのまま。
|
||||
- 自動件名は300 UTF-8 bytes以内に文字境界で省略し「…」を付ける。元のSubjectはWiki本文へ保持する。明示的な `--title` は連番除去・省略をせず、上限を超えたら拒否する。
|
||||
- 既存ページのPath・タスク名を一括更新しない。既存receiptを使った同一要求の再送は元のページを返す。旧版で保存済みのメールを新しい本文・件名で再作成すると412となるため、通信失敗分は保持済み要求の `task retry` を使う。
|
||||
|
||||
個人設定の既定Wiki親Pathと保存先ACLは従来通り。APIフィールド・receipt hash形式・DBスキーマは変更しない。
|
||||
|
||||
## ソースと確認
|
||||
|
||||
サーバーの対象コミットは `3262f8800547e8ea343fe290153d4abc84ebd0d0`、CLIは `541c2bd069b5507281b0dde2810243447c098e71`。サーバーのCLI結合テスト用コピーも同じソースへ更新した。
|
||||
|
||||
CLI単体42件、全Goテスト、go vetを実施した。合成メールの日本語SubjectからWikiを作成し、関連メモAPIからPathを取得して本文をHTTP取得する結合テストが成功した。既存の日本語PathのHTTP取得・URLエンコードと再送時の非移動も検証した。
|
||||
|
||||
[CLI v0.3.1](https://git.anya.jp/anya/pages-cli/releases/tag/v0.3.1)はmain CI run 38、タグCI run 40で成功。公開添付5ファイルを匿名ダウンロードし、4生成物のSHA-256を照合した。公開ELFでUTF-8/ISO-2022-JPのSubject、ML連番除去、元件名保持、Message-IDによる同一識別子、通常のログイン・メール取り込み・連絡先スモークを確認した。
|
||||
|
||||
## リリースと本番反映
|
||||
|
||||
[サーバーCI run 39](https://git.anya.jp/anya/wikipages/actions/runs/39)の全工程が成功し、[run 41](https://git.anya.jp/anya/wikipages/actions/runs/41)で検証済みSHAイメージをv0.8.1へ昇格した。ソースrevisionとリリースイメージの一致を確認した。公開タグの付け替えは行っていない。
|
||||
|
||||
| イメージ | v0.8.1 manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:44aa267d010568e6dd83354839d976429dc979ed283888009457bffcc2d37119` |
|
||||
| pageswiki-adaptor-gateway | `sha256:5ccf30103cf4f01a49de0d80289736cbca9cde6f0e34661a39652b3468843533` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:33b44cc2c061c3b66ce8e1124b9e25c43584aec508669564c9f4a260e1c53454` |
|
||||
|
||||
2026-11-06 09:15:57 JSTに対象4サービスの停止を開始、09:17:03に最終バックアップ照合完了、09:17:09にv0.8.1起動完了。停止から起動まで72秒。`.env.release` を更新し、registry overlayの対象4サービスだけを `up --no-build --no-deps` した。code-serverやKroki等は変更していない。
|
||||
|
||||
`.deployment-backups/release-v0.8.1-20261106/` に構成と `cutover/data`・`cutover/data2` を保持する。停止後のchecksum付き同期と差分ゼロ、DB・WAL・SHMのバイト一致と稼働元と異なるinodeを確認した。変更のないファイルは前回の不変バックアップとのみlink-destで共有する。旧イメージは `rollback-before-v0.8.1-20261106` を付けて保持した。既存バックアップは削除しない。
|
||||
|
||||
このホストの `/home/anya/.local/bin/pages` を公開ELFのv0.3.1へ原子的に置換し、バイト一致・versionを確認した。旧CLIは保全先configの `pages-before-v0.3.1` に保持する。利用者の資格情報・セッション・個人設定は変更していない。独立CLIリポジトリも対象コミットとタグへ同期した。
|
||||
|
||||
両系統の管理対象12コンポーネントは切替前後ともcurrent。全コンテナの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一致。これはlegacy領域を含む全データ完全性検査ではない。
|
||||
|
||||
実メール本文・外部取り込みカレンダーは検証に使用していない。本番には合成メールやタスクを追加せず、認証済み操作は一時DBで確認した。保全は内容を解釈しないファイルコピー。完了時の空き容量は約26 GiB。切戻しは書込みを停止し現状も保全して実施し、バックアップを自動復元しない。
|
||||
@@ -1,6 +1,6 @@
|
||||
# メール本文のWiki保存
|
||||
|
||||
PagesWiki v0.8.0とpages-cli v0.3.0で、NeoMuttからのメール取り込みを関連Wikiページ付きタスク作成へ拡張する。サーバーを先に更新し、その後CLIを更新する。
|
||||
PagesWiki v0.8.0とpages-cli v0.3.0で、NeoMuttからのメール取り込みを関連Wikiページ付きタスク作成へ拡張した。2026-11-06に本番サーバーと、このホストのCLIへの反映を完了した。別の端末ではサーバーv0.8.0以降への接続を確認してからCLIを更新する。
|
||||
|
||||
## 利用方法と互換性
|
||||
|
||||
@@ -19,11 +19,24 @@ CLIの本文非送信は `--metadata-only`。旧 `--include-body` は既定動
|
||||
|
||||
## ソースと検証
|
||||
|
||||
独立CLIの対象コミットは `cde94ed`。サーバー内の `pages-cli/pages` と `test_productivity.py` はこのソースに明示更新した結合テスト用スナップショットで、配布元ではない。
|
||||
独立CLIの対象コミットは `cde94ed936ddfa1911809f3d1a824bd48a815223`、サーバーは `80d297dab40871b42ff2afb2ab6212661c465248`。サーバー内の `pages-cli/pages` と `test_productivity.py` はこのCLIソースに明示更新した結合テスト用スナップショットで、配布元ではない。
|
||||
|
||||
- CLI単体テスト41件、合成HTTP経由のログイン・メール取り込み・連絡先・ログアウト。
|
||||
- GoのメールWiki作成、既定Path・明示Path・プロジェクト配下、再送、権限拒否、衝突、本文上限、トランザクションのロールバック。
|
||||
- 独立CLIスナップショットとGo APIの結合テスト。作成したページがタスクのメモ操作から開けることを確認。
|
||||
- Chromiumのデスクトップ・スマホ幅で、現在のプロジェクト選択・フォームリセット・Wiki Path保存を確認。デスクトップでは候補の先頭ページにないプロジェクトも検証。
|
||||
- 全Goテスト、go vet、JS構文検査、リリースツール8件も成功。オーガナイザーの全ブラウザ回帰15ケース(小型スマホ・英語を含む)も成功。
|
||||
|
||||
配布・本番切替結果は確認後に追記する。外部取り込みカレンダーや実メール本文を検証のために読まない。
|
||||
## 公開結果
|
||||
|
||||
[CLIのmain CI run 34](https://git.anya.jp/anya/pages-cli/actions/runs/34)と[タグCI run 36](https://git.anya.jp/anya/pages-cli/actions/runs/36)が成功し、[pages-cli v0.3.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.3.0)を公開した。Linux/amd64 ELF、tar.gz、ソース、メタデータ、SHA256SUMSの5添付を匿名取得した。4生成物のチェックサムとsource_revision、同梱ガイド・設定例を照合し、配布ELFで合成HTTPスモークとTLS回帰6件を実施した。macOS/Windowsの配布状態は変更しない。
|
||||
|
||||
[サーバービルド run 35](https://git.anya.jp/anya/wikipages/actions/runs/35)は全工程成功。[リリース run 37](https://git.anya.jp/anya/wikipages/actions/runs/37)でSHAイメージを再ビルドせずv0.8.0へ昇格した。Gitタグは注釈付きで、公開済みタグを付け替えていない。
|
||||
|
||||
| イメージ | v0.8.0 manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:1817474559818898bd75c0bcc3e9ef7d0d02879604b46bd082668be557922482` |
|
||||
| pageswiki-adaptor-gateway | `sha256:264d545d8b8c8f9d1e48f79153f3a91d1d446f9e7cd3b067d8f3f7338d04053f` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:dbfcac6071db55f34ea52b7c00bdeb624ff2d71a9c8cdab5b5e522e8b745d38b` |
|
||||
|
||||
本番反映と切戻し用保全は[本番切替記録](../deployments/2026-11-06-v0.8.0.md)を参照。外部取り込みカレンダーや実メール本文は検証のために読んでいない。
|
||||
@@ -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)),
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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から選択",
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -15,6 +17,7 @@ import (
|
||||
|
||||
func TestTaskMailWikiCapture(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
||||
ctx := context.Background()
|
||||
p, err := s.store.TaskPreferences(ctx, domain, actor)
|
||||
if err != nil {
|
||||
@@ -51,6 +54,29 @@ func TestTaskMailWikiCapture(t *testing.T) {
|
||||
if err != nil || !strings.Contains(rev.Body, "<script>bad()</script>") || strings.Contains(rev.Body, "{{children}}") {
|
||||
t.Fatal(rev, err)
|
||||
}
|
||||
// Existing Japanese paths are not renamed or broken by receipt replay.
|
||||
legacy := "/private/mail/日本語の件名 [list 123]--" + id
|
||||
if _, err = s.store.DB.Exec(`UPDATE paths SET path=? WHERE domain_uuid=? AND object_uuid=?`, legacy, domain, response.Item.PageUUID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
note := taskRequest(s, token, "GET", "items/"+id+"/note", nil, "")
|
||||
var links struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
if err = json.Unmarshal(note.Body.Bytes(), &links); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(links.URL)
|
||||
if err != nil || u.Path != legacy || u.RawQuery != "" || u.Fragment != "" {
|
||||
t.Fatal("Japanese note URL", links.URL, err)
|
||||
}
|
||||
request := httptest.NewRequest("GET", "http://localhost/v/raw/path:"+links.URL, nil)
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
rawResult := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(rawResult, request)
|
||||
if rawResult.Code != 200 || rawResult.Body.String() != rev.Body {
|
||||
t.Fatal("Japanese path fetch", rawResult.Code)
|
||||
}
|
||||
// A committed retry remains stable even if the preference changes.
|
||||
p, err = s.store.TaskPreferences(ctx, domain, actor)
|
||||
if err != nil {
|
||||
@@ -63,6 +89,9 @@ func TestTaskMailWikiCapture(t *testing.T) {
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 || !strings.Contains(w.Body.String(), response.Item.PageUUID) {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), legacy) {
|
||||
t.Fatal("retry changed existing path", w.Body)
|
||||
}
|
||||
input["wiki_body"] = "different"
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 412 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
@@ -74,6 +103,18 @@ func TestTaskMailWikiCapture(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailWikiPathDoesNotContainSubject(t *testing.T) {
|
||||
id := uuid.NewString()
|
||||
for _, title := range []string{"日本語", "[hogehoge 123] 件名", strings.Repeat("長い", 100), "?#/\\% []"} {
|
||||
if got := store.TaskCaptureWikiPath("/mail", title, id); got != "/mail/mail-"+id {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
if store.TaskCaptureWikiPath("/mail", "日本語", uuid.NewString()) == store.TaskCaptureWikiPath("/mail", "日本語", id) {
|
||||
t.Fatal("different mails collided")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskMailWikiRollbackAndAccess(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -16,6 +16,7 @@ func TestTaskCLIHTTPIntegration(t *testing.T) {
|
||||
t.Skip("python3 not installed")
|
||||
}
|
||||
s, token, _, _ := taskFixture(t)
|
||||
s.mux.HandleFunc("/v/raw/", s.handleRawView)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestTaskMailLayouts(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
for _, suffix := range []string{"hogehoge/123", "v/0", "2026/01/" + uuid.NewString(), "2026/12/" + strings.Repeat("a", 64)} {
|
||||
id := uuid.NewString()
|
||||
input := map[string]any{"request_id": id, "title": "日本語の件名", "wiki_body": "Body", "wiki_prefix": "/mail", "wiki_suffix": suffix}
|
||||
w := taskRequest(s, token, "POST", "capture", input, "")
|
||||
if w.Code != 201 {
|
||||
t.Fatal(suffix, w.Code, w.Body)
|
||||
}
|
||||
var response struct {
|
||||
Path string `json:"page_path"`
|
||||
Item store.TaskRecord `json:"item"`
|
||||
}
|
||||
if e := json.Unmarshal(w.Body.Bytes(), &response); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if response.Path != "/mail/"+suffix {
|
||||
t.Fatal(response.Path)
|
||||
}
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||
t.Fatal("replay", w.Code, w.Body)
|
||||
}
|
||||
// A different Message-ID produces a different request UUID, never an overwrite.
|
||||
other := uuid.NewString()
|
||||
input["request_id"] = other
|
||||
input["wiki_body"] = "Different mail"
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 409 {
|
||||
t.Fatal("collision", w.Code, w.Body)
|
||||
}
|
||||
if _, e := s.store.GetTask(context.Background(), domain, actor, other); !errors.Is(e, sql.ErrNoRows) {
|
||||
t.Fatal("partial task", e)
|
||||
}
|
||||
rev, e := s.store.GetLatestRevision(response.Item.PageUUID)
|
||||
if e != nil || strings.Contains(rev.Body, "Different") {
|
||||
t.Fatal("page overwritten", e)
|
||||
}
|
||||
}
|
||||
for _, suffix := range []string{"", "../123", "/list/123", "a/../../123", "list/001", "list/-1", "list/1?x", "list%2f/1", "list/1/2", "_/123", "2026/13/" + uuid.NewString(), "0000/01/" + uuid.NewString(), "2026/01/not-an-id"} {
|
||||
input := map[string]any{"request_id": uuid.NewString(), "title": "Bad", "wiki_body": "Body", "wiki_prefix": "/mail", "wiki_suffix": suffix}
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 422 {
|
||||
t.Fatal(suffix, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
input := map[string]any{"request_id": uuid.NewString(), "title": "No body", "wiki_suffix": "list/123"}
|
||||
if w := taskRequest(s, token, "POST", "capture", input, ""); w.Code != 422 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
other, e := s.store.CreatePasswordAccount(domain, "mail-layout-other", "fixture password long", "Other", "")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
otherToken, e := s.store.CreateAuthSession(domain, other.UUID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
input = map[string]any{"request_id": uuid.NewString(), "title": "No Wiki permission", "wiki_body": "Body", "wiki_prefix": "/mail", "wiki_suffix": "private/123"}
|
||||
if w := taskRequest(s, otherToken, "POST", "capture", input, ""); w.Code != 403 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,7 @@ type taskCaptureInput struct {
|
||||
Complexity *int `json:"complexity"`
|
||||
WikiBody *string `json:"wiki_body,omitempty"`
|
||||
WikiPrefix *string `json:"wiki_prefix,omitempty"`
|
||||
WikiSuffix *string `json:"wiki_suffix,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
|
||||
@@ -260,6 +261,13 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
||||
return
|
||||
}
|
||||
target = store.TaskCaptureWikiPath(prefix, item.Title, input.RequestID)
|
||||
if input.WikiSuffix != nil {
|
||||
if !store.ValidTaskMailSuffix(*input.WikiSuffix) {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
target = strings.TrimRight(prefix, "/") + "/" + *input.WikiSuffix
|
||||
}
|
||||
for _, capability := range []string{"read", "create", "write"} {
|
||||
if s.authorizePathRequest(r, capability, target) != nil {
|
||||
taskError(w, store.ErrAccessDenied)
|
||||
@@ -267,7 +275,7 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
|
||||
}
|
||||
}
|
||||
body = *input.WikiBody
|
||||
} else if input.WikiPrefix != nil {
|
||||
} else if input.WikiPrefix != nil || input.WikiSuffix != nil {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
|
||||
+59
@@ -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); }
|
||||
})();
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"html"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
@@ -34,11 +35,18 @@ func ValidTaskWikiPrefix(p string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// A request UUID suffix separates equal subjects and makes the target stable.
|
||||
// The CLI derives the request UUID from origin, user and Message-ID (or a raw
|
||||
// mail hash). Keep subjects in the title, never in the URL's identity segment.
|
||||
func TaskCaptureWikiPath(prefix, title, request string) string {
|
||||
item := TaskRecord{Title: title, UUID: request}
|
||||
name := path.Base(TaskNotePath("", TaskRecord{}, item))
|
||||
return strings.TrimRight(prefix, "/") + "/" + name + "--" + request
|
||||
return strings.TrimRight(prefix, "/") + "/mail-" + request
|
||||
}
|
||||
|
||||
var mailListSuffix = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,99}/(0|[1-9][0-9]{0,19})$`)
|
||||
var mailMonthSuffix = regexp.MustCompile(`^[0-9]{4}/(0[1-9]|1[0-2])/([0-9a-f]{64}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$`)
|
||||
|
||||
// Only the two mail layouts are accepted; no arbitrary relative path traversal.
|
||||
func ValidTaskMailSuffix(s string) bool {
|
||||
return mailListSuffix.MatchString(s) || (mailMonthSuffix.MatchString(s) && !strings.HasPrefix(s, "0000/"))
|
||||
}
|
||||
|
||||
func (s *Store) createCapturedTaskWiki(ctx context.Context, tx *sql.Tx, domain, actor string, item *TaskRecord, target, body string) error {
|
||||
|
||||
+43
-5
@@ -3,6 +3,8 @@
|
||||
import argparse
|
||||
import email.policy
|
||||
import email.parser
|
||||
import email.utils
|
||||
import datetime
|
||||
import uuid
|
||||
import base64
|
||||
import contextlib
|
||||
@@ -30,7 +32,7 @@ import urllib.parse as url
|
||||
import urllib.request as http
|
||||
import webbrowser
|
||||
|
||||
VERSION = '0.3.0'
|
||||
VERSION = '0.4.0'
|
||||
|
||||
class Failure(Exception):
|
||||
def __init__(self, message, status=0, payload=None):
|
||||
@@ -496,11 +498,37 @@ class MailText(HTMLParser):
|
||||
if not self.hidden: self.parts.append(data)
|
||||
|
||||
|
||||
def mail_subject(value):
|
||||
# Remove only leading mailing-list sequence markers, preserving meaningful
|
||||
# tags such as [Important], and any Re:/Fwd: prefix before the marker.
|
||||
marker = re.compile(r'^(?P<reply>(?:(?:re|fw|fwd)\s*:\s*)*)\[[^\[\]\r\n]+[\s:#]\s*[0-9]+\]\s*', re.IGNORECASE)
|
||||
while True:
|
||||
match = marker.match(value)
|
||||
if not match: return value.strip()
|
||||
value = match.group('reply') + value[match.end():]
|
||||
|
||||
|
||||
def task_mail_suffix(raw, request_id, now=None):
|
||||
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||
subject = ' '.join(safe_text(str(message.get('Subject') or '')).split())
|
||||
marker = re.match(r'^(?:(?:re|fw|fwd)\s*:\s*)*\[([A-Za-z0-9][A-Za-z0-9._-]{0,99})[\s:#]+([0-9]{1,20})\]',subject,re.IGNORECASE)
|
||||
if marker:
|
||||
return marker[1]+'/'+str(int(marker[2]))
|
||||
try: date = email.utils.parsedate_to_datetime(str(message.get('Date') or ''))
|
||||
except (ValueError, TypeError, OverflowError): date = now or datetime.datetime.now(datetime.timezone.utc)
|
||||
# Preserve the month in the sender's Date timezone, not the receiving host's.
|
||||
ident = request_id if ' '.join(safe_text(str(message.get('Message-ID') or '')).split()) else hashlib.sha256(raw).hexdigest()
|
||||
return f'{date.year:04d}/{date.month:02d}/{ident}'
|
||||
|
||||
|
||||
def task_mail(raw, include_body=True, override_title=None):
|
||||
if len(raw) > 2 << 20: raise Failure('Mail input exceeds 2 MiB; pipe one message at a time.')
|
||||
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||
clean = lambda value: ' '.join(safe_text(str(value or '')).split())
|
||||
title = override_title or clean(message.get('Subject')) or '(No subject)'
|
||||
subject = clean(message.get('Subject'))
|
||||
title = override_title or mail_subject(subject) or '(No subject)'
|
||||
if not override_title and len(title.encode()) > 300:
|
||||
title = title.encode()[:297].decode('utf-8',errors='ignore').rstrip() + '…'
|
||||
if len(title.encode()) > 300: raise Failure('Mail subject exceeds 300 UTF-8 bytes; use --title.')
|
||||
notes = '\n'.join(key+': '+clean(message.get(key)) for key in ('From','Date','Message-ID') if message.get(key))
|
||||
wiki_body = None
|
||||
@@ -513,7 +541,8 @@ def task_mail(raw, include_body=True, override_title=None):
|
||||
if not isinstance(content,str): raise Failure('Mail body is not readable text.')
|
||||
if part.get_content_type() == 'text/html':
|
||||
parser = MailText();parser.feed(content);parser.close();content = ''.join(parser.parts).strip()
|
||||
wiki_body = notes + '\n\n' + content
|
||||
# Retain the original subject when its mailing-list marker was removed.
|
||||
wiki_body = (('Subject: '+subject+'\n') if title != subject else '') + notes + '\n\n' + content
|
||||
if '\0' in wiki_body or len(wiki_body.encode()) > 256 << 10: raise Failure('Mail Wiki body must be valid text of at most 256 KiB; nothing was uploaded.')
|
||||
if len(notes.encode()) > 16384: raise Failure('Mail metadata exceeds 16 KiB.')
|
||||
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest(), wiki_body
|
||||
@@ -549,6 +578,7 @@ def tasks(client, profile, words):
|
||||
def capture(payload):
|
||||
pending=profile.data.setdefault('task_outbox',{})
|
||||
if len(pending)>=20 and payload['request_id'] not in pending:raise Failure('20 pending captures retained. Retry them before adding more.')
|
||||
if payload['request_id'] in pending and pending[payload['request_id']] != payload:raise Failure('A different draft with this request ID is retained. Use pages task retry '+payload['request_id'])
|
||||
pending[payload['request_id']]=payload;profile.save()
|
||||
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
||||
except Failure as e:
|
||||
@@ -581,13 +611,21 @@ def tasks(client, profile, words):
|
||||
payload={'request_id':getattr(a,'request_id',None) or str(uuid.uuid4()),'title':a.title,'notes':a.notes or ''}
|
||||
if action=='from-mail':
|
||||
if a.metadata_only and a.wiki_prefix is not None: raise Failure('--wiki-prefix cannot be combined with --metadata-only.')
|
||||
title,notes,message_id,wiki_body=task_mail(sys.stdin.buffer.read((2<<20)+1),not a.metadata_only,a.title)
|
||||
raw=sys.stdin.buffer.read((2<<20)+1)
|
||||
title,notes,message_id,wiki_body=task_mail(raw,not a.metadata_only,a.title)
|
||||
payload.update(title=a.title or title,notes=a.notes if a.notes is not None else notes,request_id=str(uuid.uuid5(uuid.NAMESPACE_URL,client.base+'\n'+profile.data.get('username','')+'\n'+message_id)))
|
||||
if wiki_body is not None: payload['wiki_body']=wiki_body
|
||||
if wiki_body is not None:
|
||||
payload['wiki_body']=wiki_body
|
||||
payload['wiki_suffix']=task_mail_suffix(raw,payload['request_id'])
|
||||
if a.wiki_prefix is not None: payload['wiki_prefix']=a.wiki_prefix
|
||||
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due','due_on'),('start_on','start_on'),('planned','planned_on'),('review','review_on'),('estimate','estimate_minutes'),('complexity','complexity')]:
|
||||
value=getattr(a,attr)
|
||||
if value is not None:payload[key]=task_project(client,value) if attr=='project' else value
|
||||
# A retry of the same pending mail must not drift across a month boundary
|
||||
# when Date was missing. Other changed options still fail closed.
|
||||
old=profile.data.get('task_outbox',{}).get(payload['request_id'])
|
||||
if action=='from-mail' and old and {k:v for k,v in old.items() if k!='wiki_suffix'}=={k:v for k,v in payload.items() if k!='wiki_suffix'}:
|
||||
payload=old.copy()
|
||||
emit(capture(payload));return
|
||||
if action=='project-add':
|
||||
emit(client.json(TASK_API+'items',method='POST',data={'uuid':str(uuid.uuid4()),'kind':'project','title':a.title,'notes':a.notes,'status':'todo','bucket':'inbox','priority':1}));return
|
||||
|
||||
@@ -9,6 +9,39 @@ import unittest
|
||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||
|
||||
class ProductivityTests(unittest.TestCase):
|
||||
def test_mail_path_priority_and_dates(self):
|
||||
import datetime,hashlib
|
||||
ident='06cb3a24-61f8-4a9f-a0bf-89eea9632f25'
|
||||
suffix=m['task_mail_suffix'];now=datetime.datetime(2030,2,1,tzinfo=datetime.timezone.utc)
|
||||
for marker in ('[hogehoge 00123]','Re: [hogehoge:123]','Fwd: [hogehoge#123]'):
|
||||
raw=('Subject: '+marker+' Title\r\n\r\nbody').encode()
|
||||
self.assertEqual(suffix(raw,ident,now),'hogehoge/123')
|
||||
raw=b'Subject: Plain\r\nDate: Sat, 31 Jan 2026 23:30:00 -0800\r\nMessage-ID: <id@example.invalid>\r\n\r\nbody'
|
||||
self.assertEqual(suffix(raw,ident,now),'2026/01/'+ident)
|
||||
noid=raw.replace(b'Message-ID: <id@example.invalid>\r\n',b'')
|
||||
self.assertEqual(suffix(noid,ident,now),'2026/01/'+hashlib.sha256(noid).hexdigest())
|
||||
for date in (b'',b'Date: broken\r\n'):
|
||||
raw=b'Subject: [../unsafe 123] Title\r\n'+date+b'\r\nbody'
|
||||
self.assertEqual(suffix(raw,ident,now),'2030/02/'+hashlib.sha256(raw).hexdigest())
|
||||
|
||||
def test_pending_mail_month_and_options_are_preserved(self):
|
||||
from unittest.mock import patch
|
||||
raw=b'Subject: Test\r\nMessage-ID: <same@example.invalid>\r\n\r\nbody'
|
||||
calls=[]
|
||||
def send(route,**kw):
|
||||
calls.append(kw['data'].copy())
|
||||
raise m['Failure']('offline')
|
||||
client=SimpleNamespace(base='https://example.invalid',json=send)
|
||||
profile=SimpleNamespace(data={'username':'test'},save=lambda:None)
|
||||
for month in ('2030/01','2030/02'):
|
||||
with patch.dict(m['tasks'].__globals__,task_mail_suffix=lambda raw,ident:month+'/'+ident),patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||
m['tasks'](client,profile,['from-mail'])
|
||||
self.assertEqual(calls[0],calls[1])
|
||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),self.assertRaises(m['Failure']):
|
||||
m['tasks'](client,profile,['from-mail','--wiki-prefix','/changed'])
|
||||
self.assertEqual(len(calls),2)
|
||||
self.assertEqual(next(iter(profile.data['task_outbox'].values())),calls[0])
|
||||
|
||||
def test_mail_privacy_and_long_subject_override(self):
|
||||
raw=b'Subject: Test\r\nFrom: Person <person@example.invalid>\r\nMessage-ID: <id@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPRIVATE BODY'
|
||||
title,notes,ident,body=m['task_mail'](raw)
|
||||
@@ -16,9 +49,27 @@ class ProductivityTests(unittest.TestCase):
|
||||
self.assertIn('PRIVATE BODY',body)
|
||||
self.assertIsNone(m['task_mail'](raw,False)[3])
|
||||
raw=raw.replace(b'Subject: Test',b'Subject: '+b'a'*301)
|
||||
with self.assertRaises(m['Failure']):m['task_mail'](raw)
|
||||
self.assertLessEqual(len(m['task_mail'](raw)[0].encode()),300)
|
||||
with self.assertRaises(m['Failure']):m['task_mail'](raw,True,'x'*301)
|
||||
self.assertEqual(m['task_mail'](raw,False,'Override')[0],'Override')
|
||||
|
||||
def test_japanese_subject_and_mailing_list_markers(self):
|
||||
from email.message import EmailMessage
|
||||
from email.header import Header
|
||||
for encoding in ('utf-8','iso-2022-jp'):
|
||||
subject='Re: [hogehoge 00123] [team:456] 日本語の依頼 [重要]'
|
||||
raw=('Subject: '+Header(subject,encoding).encode()+'\r\nMessage-ID: <same@example.invalid>\r\n\r\nbody').encode('ascii')
|
||||
title,notes,ident,body=m['task_mail'](raw)
|
||||
self.assertEqual(title,'Re: 日本語の依頼 [重要]')
|
||||
self.assertEqual(ident,'<same@example.invalid>');self.assertIn('Subject: '+subject,body)
|
||||
for subject in ('[重要] 日本語','報告 [list 123]','[release 1.2] 更新'):
|
||||
self.assertEqual(m['mail_subject'](subject),subject)
|
||||
msg=EmailMessage();msg['Subject']='[list 123] '+('日本語'*100);msg.set_content('Body')
|
||||
title,_,_,body=m['task_mail'](msg.as_bytes())
|
||||
self.assertLessEqual(len(title.encode()),300);self.assertTrue(title.endswith('…'))
|
||||
self.assertIn('日本語'*100,body)
|
||||
self.assertEqual(m['task_mail'](msg.as_bytes(),True,'[list 123] 手動指定')[0],'[list 123] 手動指定')
|
||||
|
||||
def test_html_mail_and_limits(self):
|
||||
raw=b'Subject: HTML\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<head><style>secret</style></head><p>Hello</p><script>evil()</script><img src="https://example.invalid/image"><p>World & friends</p>'
|
||||
body=m['task_mail'](raw)[3]
|
||||
|
||||
@@ -7,6 +7,7 @@ import runpy
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
from email.message import EmailMessage
|
||||
|
||||
def run():
|
||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||
@@ -29,15 +30,27 @@ def run():
|
||||
report=task('report','--json');assert sum(d['points'] for d in report['days'])==7
|
||||
assert any(i['uuid']==ident for i in report['tasks'])
|
||||
task('preferences','--wiki-prefix','/private/mail')
|
||||
mail=b'Subject: CLI mail\r\nMessage-ID: <integration@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPrivate mail body {{children}}'
|
||||
message=EmailMessage();message['Subject']='[hogehoge 123] 日本語の件名と依頼';message['Message-ID']='<integration@example.invalid>';message.set_content('Private mail body {{children}}')
|
||||
mail=message.as_bytes()
|
||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))):
|
||||
captured=task('from-mail')
|
||||
assert captured['item']['page_uuid'] and captured['page_path'].startswith('/private/mail/CLI mail--')
|
||||
assert captured['item']['page_uuid'] and captured['page_path']=='/private/mail/hogehoge/123'
|
||||
assert captured['item']['title']=='日本語の件名と依頼'
|
||||
assert 'Private mail body' not in captured['item']['notes']
|
||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))):
|
||||
assert task('from-mail')['item']['page_uuid']==captured['item']['page_uuid']
|
||||
note=client.json(m['TASK_API']+'items/'+captured['item']['uuid']+'/note')
|
||||
assert note['linked'] and note['path']==captured['page_path']
|
||||
raw,_=client.raw('path:'+captured['page_path'])
|
||||
assert '日本語の件名と依頼' in raw.decode() and 'Private mail body' in raw.decode()
|
||||
message.replace_header('Subject','連番なしの日本語');message.replace_header('Message-ID','<other@example.invalid>');message['Date']='Sat, 31 Jan 2026 23:30:00 -0800'
|
||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(message.as_bytes()))):dated=task('from-mail')
|
||||
assert dated['page_path']=='/private/mail/2026/01/'+dated['item']['uuid']
|
||||
del message['Message-ID']
|
||||
import hashlib
|
||||
raw_mail=message.as_bytes()
|
||||
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw_mail))):hashed=task('from-mail')
|
||||
assert hashed['page_path']=='/private/mail/2026/01/'+hashlib.sha256(raw_mail).hexdigest()
|
||||
path=Path(fixture['root'])/'person.vcf'
|
||||
path.write_text('BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:cli\r\nFN:CLI Person\r\nEMAIL:cli@example.invalid\r\nEND:VCARD\r\n')
|
||||
output=io.StringIO()
|
||||
|
||||
@@ -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::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}
|
||||
.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)}
|
||||
.asset-dialog-close { position:absolute;right:.75rem;top:.75rem }
|
||||
.table-scroll { overflow-x: auto; }
|
||||
|
||||
+8
-1
@@ -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 header button { border:0; background:transparent; color:inherit; font-size:1.5rem; cursor:pointer; }
|
||||
.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 input { width:100%; accent-color:var(--accent); }
|
||||
.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-dragging] { transition:none; user-select:none; }
|
||||
.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-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; }
|
||||
|
||||
@@ -8,23 +8,35 @@
|
||||
if (!open || !dialog || !form || !input || !output || !status) return;
|
||||
|
||||
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 transparency = Math.max(0, Math.min(85, Number(value) || 0));
|
||||
document.body.style.setProperty('--home-glass-opacity', `${100 - transparency}%`);
|
||||
output.value = `${transparency}%`;
|
||||
output.textContent = `${transparency}%`;
|
||||
palettePreview();
|
||||
};
|
||||
const restore = () => {
|
||||
input.value = String(saved);
|
||||
paletteNames.forEach((name,i) => { if (form.elements[name]) form.elements[name].value=savedPalette[i]; });
|
||||
preview(saved);
|
||||
status.textContent = '';
|
||||
};
|
||||
const close = () => {
|
||||
if (form.querySelector('[type=submit]').disabled) return;
|
||||
restore();
|
||||
dialog.close();
|
||||
};
|
||||
|
||||
input.addEventListener('input', () => preview(input.value));
|
||||
paletteNames.forEach(name => form.elements[name]?.addEventListener('input',palettePreview));
|
||||
open.addEventListener('click', () => {
|
||||
restore();
|
||||
dialog.showModal();
|
||||
@@ -46,25 +58,29 @@
|
||||
event.preventDefault();
|
||||
const submit = form.querySelector('[type=submit]');
|
||||
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;
|
||||
status.textContent = '';
|
||||
try {
|
||||
const response = await fetch(form.action, {
|
||||
method: 'POST',
|
||||
body: new URLSearchParams(new FormData(form)),
|
||||
body: submitted,
|
||||
headers: {Accept: 'application/json'},
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!response.ok) throw new Error((await response.text()).trim());
|
||||
await response.json();
|
||||
saved = Number(input.value);
|
||||
saved = Number(submitted.get('home_glass_transparency'));
|
||||
savedPalette = paletteNames.map(name => submitted.get(name));
|
||||
preview(saved);
|
||||
status.textContent = form.dataset.saved;
|
||||
window.setTimeout(() => dialog.open && dialog.close(), 350);
|
||||
} catch (error) {
|
||||
status.textContent = error.message;
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
controls.forEach(node => { node.disabled=false; });
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -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);
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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,7 +1,7 @@
|
||||
{{ define "auth.gohtml" }}<!doctype html>
|
||||
<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>
|
||||
<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 }}%">
|
||||
{{ 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>
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
<link rel="stylesheet" href="/static/css/theme/base.css">
|
||||
<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>
|
||||
|
||||
<body class="mode-config">
|
||||
@@ -107,6 +107,7 @@
|
||||
<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>
|
||||
<p class="muted wide">{{ T "home.glass_help" }}</p>
|
||||
{{ template "home-palette-controls" . }}
|
||||
<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>
|
||||
<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>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
<link rel="stylesheet" href="/static/css/theme/base.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 }}">
|
||||
<script defer src="/static/js/content-viewer.js"></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>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
{{ template "home-appearance" . }}{{ template "home-palette" . }}</body>
|
||||
</html>
|
||||
{{ end }}
|
||||
@@ -13,7 +13,7 @@
|
||||
<link rel="stylesheet" href="/static/css/content-viewer.css">
|
||||
<link rel="stylesheet" href="/static/css/city-graph.css">
|
||||
<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/viewer-shortcuts.js"></script>
|
||||
{{ if eq .ContentView.Kind "code" }}
|
||||
@@ -990,6 +990,6 @@ window.addEventListener("DOMContentLoaded", () => {
|
||||
</script>
|
||||
{{ end }}
|
||||
|
||||
</body>
|
||||
{{ template "home-appearance" . }}{{ template "home-palette" . }}</body>
|
||||
</html>
|
||||
{{ end }}
|
||||
@@ -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>
|
||||
<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 }}
|
||||
{{ 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 .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 }}
|
||||
|
||||
<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>
|
||||
{{ 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-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 }}
|
||||
@@ -8,7 +8,7 @@
|
||||
{{ template "social-metadata" . }}
|
||||
<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/home.css?v=13">
|
||||
</head>
|
||||
<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 }}
|
||||
@@ -47,19 +47,8 @@
|
||||
{{ template "home-bookmarks" . }}
|
||||
{{ end }}
|
||||
</main>
|
||||
{{ 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>
|
||||
<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 }}
|
||||
{{ template "home-appearance" . }}
|
||||
{{ template "home-palette" . }}
|
||||
{{ if eq .HomeLayout "directory" }}
|
||||
<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>
|
||||
|
||||
@@ -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 }}
|
||||
Reference in new issue
Block a user