7 Commits
Author SHA1 Message Date
Anya Tokugawa f4869c7c8b feat(feeds): add optional sandboxed in-tab article preview
Build and publish container images / images (push) Successful in 10m41s
Release container images / release (push) Successful in 24s
2026-11-08 13:55:22 +09:00
Anya Tokugawa ea1ca432c5 feat(feeds): share original articles through X extension
Build and publish container images / images (push) Successful in 11m18s
2026-11-08 13:50:24 +09:00
Anya Tokugawa c2bc637704 fix(feeds): use opaque themed capture dialog surface
Build and publish container images / images (push) Successful in 11m27s
2026-11-08 13:46:46 +09:00
Anya Tokugawa a5f90f933d feat(feeds): add templated capture paths and inline modal
Build and publish container images / images (push) Successful in 11m2s
2026-11-08 13:44:20 +09:00
Anya Tokugawa 78da33d549 feat(feeds): prefill Wiki capture path from personal defaults
Build and publish container images / images (push) Successful in 11m41s
2026-11-08 13:39:54 +09:00
Anya Tokugawa 50a90bcc14 fix(feeds): dismiss shortcut help without leaving article
Build and publish container images / images (push) Successful in 11m20s
2026-11-08 13:37:56 +09:00
Anya Tokugawa bf9a9c2847 feat(feeds): inherit FreshRSS folders in cached subscription tree
Build and publish container images / images (push) Successful in 10m33s
2026-11-08 13:34:22 +09:00
22 changed files with 662 additions and 78 deletions

No files matched your search

+61 -8
View File
@@ -72,7 +72,7 @@ API prefixは `/_/api/v1/extension/organizer.feeds/`。Domain内の本人専用
| `POST sources/{uuid}/refresh` | 次回背景取得を予約。画面から外部通信しない | | `POST sources/{uuid}/refresh` | 次回背景取得を予約。画面から外部通信しない |
| `POST sources/{uuid}/delete` | versionを照合してsource・cache・内蔵read/starを削除 | | `POST sources/{uuid}/delete` | versionを照合してsource・cache・内蔵read/starを削除 |
| `GET items` | source/unread/starred/件名・配信元で絞り込み、100件単位のkeysetページング | | `GET items` | source/unread/starred/件名・配信元で絞り込み、100件単位のkeysetページング |
| `GET catalog?source=…` | 本人のFreshRSS購読・カテゴリの取得済み一覧。外部通信なし | | `GET catalog?source=…` | 本人のFreshRSS購読・カテゴリの取得済み一覧。`subscriptions`と空フォルダも含む`folders`。外部通信なし |
| `GET item?source=…&id=…` | 本人の記事本文 | | `GET item?source=…&id=…` | 本人の記事本文 |
| `POST state` | 内蔵read/starの条件付き変更。FreshRSSは拒否 | | `POST state` | 内蔵read/starの条件付き変更。FreshRSSは拒否 |
| `POST remote-state` | FreshRSSの一記事・一項目の変更を予約。request_id、source、id、field、desired、source_versionを指定 | | `POST remote-state` | FreshRSSの一記事・一項目の変更を予約。request_id、source、id、field、desired、source_versionを指定 |
@@ -81,6 +81,7 @@ API prefixは `/_/api/v1/extension/organizer.feeds/`。Domain内の本人専用
| `GET action/export?request_id=…` | 本人の操作記録1件をJSON attachmentで保存。資格情報・本文・worker claimは含めない | | `GET action/export?request_id=…` | 本人の操作記録1件をJSON attachmentで保存。資格情報・本文・worker claimは含めない |
| `POST action/check` | request_idで結果不明操作の読取専用再確認を予約 | | `POST action/check` | request_idで結果不明操作の読取専用再確認を予約 |
| `POST note` | 公開範囲確認付きのWiki単独保存。request_idと入力hashで再送を識別 | | `POST note` | 公開範囲確認付きのWiki単独保存。request_idと入力hashで再送を識別 |
| `POST capture-preview` | Wiki親Pathのプレースホルダを展開。保存・外部通信なし |
| `GET opml/export` | 本人の内蔵購読をOPML 2.0としてダウンロード | | `GET opml/export` | 本人の内蔵購読をOPML 2.0としてダウンロード |
| `POST opml/preview` | ファイルを解析し、追加可能・登録済み・重複・未対応等を返す。保存・外部通信なし | | `POST opml/preview` | ファイルを解析し、追加可能・登録済み・重複・未対応等を返す。保存・外部通信なし |
| `POST opml/import` | 選択行を再解析・検査し、確認時の購読設定と一致する場合だけ原子的に追加 | | `POST opml/import` | 選択行を再解析・検査し、確認時の購読設定と一致する場合だけ原子的に追加 |
@@ -92,7 +93,10 @@ v3で`feed_import_receipts`を追加し、購読の一括追加と再送記録
v4でsourceに購読一覧、記事にremote feed ID・カテゴリIDを追加します。FreshRSSの旧workerを v4でsourceに購読一覧、記事にremote feed ID・カテゴリIDを追加します。FreshRSSの旧workerを
versionで無効化し、次の背景取得を予約します。内蔵sourceのversion・取得予約は変更しません。 versionで無効化し、次の背景取得を予約します。内蔵sourceのversion・取得予約は変更しません。
v5でsourceの`write_enabled`(既定OFF)と`feed_actions`を追加します。操作記録はsourceを削除しても保持し、 v5でsourceの`write_enabled`(既定OFF)と`feed_actions`を追加します。操作記録はsourceを削除しても保持し、
送信済みの可能性があるものはunknown、未送信はcancelledにします。DB更新前にバックアップを取得し、 送信済みの可能性があるものはunknown、未送信はcancelledにします。
v6でsourceに`remote_folders`を追加します。既存の購読・記事・設定version・取得予約・worker claim・
書戻しreceiptは変更しません。初回の背景取得までは既存の購読情報から分類を組み立て、
空フォルダは次の取得成功時に追加します。DB更新前にバックアップを取得し、
旧バイナリへの切戻しだけで追加schemaが巻き戻るとは扱いません。 旧バイナリへの切戻しだけで追加schemaが巻き戻るとは扱いません。
既存テーブルを破壊・再構成しません。SQLiteのforeign_keys設定に依存せず削除を完遂するtriggerを 既存テーブルを破壊・再構成しません。SQLiteのforeign_keys設定に依存せず削除を完遂するtriggerを
持ちます。内蔵read/starを本文cacheから分離し、記事を保持窓から落としても状態は黙って消しません。 持ちます。内蔵read/starを本文cacheから分離し、記事を保持窓から落としても状態は黙って消しません。
@@ -115,7 +119,7 @@ sourceのprovider・URL・資格情報の変更は別sourceを作る契約です
| 内蔵記事cache | 1 source最大500件、text本文32 KiB・HTML本文128 KiB。HTML上限超過はtextへフォールバックし、text切詰めを明示 | | 内蔵記事cache | 1 source最大500件、text本文32 KiB・HTML本文128 KiB。HTML上限超過はtextへフォールバックし、text切詰めを明示 |
| 内蔵read/star | 1 source最大10,000件。上限では新規状態保存を拒否し、既存状態を捨てない | | 内蔵read/star | 1 source最大10,000件。上限では新規状態保存を拒否し、既存状態を捨てない |
| FreshRSS | reading-list最新200件の窓を取得。更新成功時はその窓で置換し、全履歴同期とはしない | | FreshRSS | reading-list最新200件の窓を取得。更新成功時はその窓で置換し、全履歴同期とはしない |
| FreshRSS購読一覧 | 最大1,000購読、1購読64カテゴリ、保存JSON 1 MiB。記事と同じ取得予算で収集 | | FreshRSS購読・分類一覧 | 最大1,000購読・1,000フォルダ、1購読64カテゴリ、保存JSON合計1 MiB。記事と同じ取得予算で収集 |
| 再試行 | 次の設定間隔まで待機。手動予約にも最終成功から60秒の制限、取得中の重複claim拒否 | | 再試行 | 次の設定間隔まで待機。手動予約にも最終成功から60秒の制限、取得中の重複claim拒否 |
内蔵は条件付きGET、304ではcacheを保持します。どちらのproviderも通信・認証・構文失敗で 内蔵は条件付きGET、304ではcacheを保持します。どちらのproviderも通信・認証・構文失敗で
@@ -125,17 +129,48 @@ extension無効化は画面・API・取得・完了保存に適用します。
### FreshRSSの購読とカテゴリ ### FreshRSSの購読とカテゴリ
背景取得ではlogin後にreading-listと`subscription/list`を読み、両方に成功した場合だけ 背景取得ではlogin後にreading-list・`subscription/list`・`tag/list`を読み、すべてに成功した場合だけ
記事・購読一覧を同じtransactionで置換します。一方の取得失敗、上限超過、不正なsnapshotでは 記事・購読一覧・分類一覧を同じtransactionで置換します。一部の取得失敗、上限超過、不正なsnapshotでは
前回の両cacheを保持します。記事が取得窓内にない購読も一覧には残します。 前回のcache全体を保持します。記事が取得窓内にない購読も一覧には残します。
`tag/list`は`type=folder`だけを分類として取り込み、記事タグとシステムの状態タグは除外します。
購読一覧のカテゴリとIDで統合し、購読元のない空フォルダも保持します。
左ペインでFreshRSS sourceを選ぶと、接続先→分類フォルダ→購読元のツリーを表示します。
フォルダ名は記事の絞り込み、隣の矢印は開閉と役割を分けます。開閉状態は接続先UUID単位で
ブラウザのlocalStorageに保存し、利用できない場合もその画面内では保持します。
閉じたフォルダは購読元のDOMを作らず、展開時は50件ずつ描画します。購読名・分類名で検索すると
該当購読を重複なしで一覧化します。名前に含まれる`/`は文字として扱い、独自の階層には分割しません。
左ペインでFreshRSS sourceを選ぶとカテゴリ選択・購読名の検索・購読一覧を表示します。
カテゴリは表示名でなくremote category ID、購読は`origin.streamId`とsubscription IDを対応させます。 カテゴリは表示名でなくremote category ID、購読は`origin.streamId`とsubscription IDを対応させます。
同名でも混同せず、複数カテゴリに属する購読も扱います。`GET items`の`feed`/`category`は 同名でも混同せず、複数カテゴリに属する購読は各フォルダに表示します。記事の分類絞り込みは
記事タグではなく同期した購読元の所属を使い、FreshRSSでの分類移動に追従します。
分類のない購読は「未分類」に表示し、購読一覧にない記事を未分類へ混在させません。
`GET items`の`feed`/`category`/`category_mode=uncategorized`は
source指定と組み合わせ、既存の未読・star・検索・keysetページングと併用できます。 source指定と組み合わせ、既存の未読・star・検索・keysetページングと併用できます。
`category`と`category_mode`の同時指定は拒否します。
絞り込み対象は最新200記事のcache内に限られ、購読を選んでも履歴全件を外部取得しません。 絞り込み対象は最新200記事のcache内に限られ、購読を選んでも履歴全件を外部取得しません。
購読の追加・削除やカテゴリの編集はFreshRSS側で行います。 購読の追加・削除やカテゴリの編集はFreshRSS側で行います。
ショートカットヘルプは`?`で開閉し、`Esc`または閉じるボタンでも閉じます。
ヘルプだけを閉じる操作では閲覧中の記事や入力フォームを変更せず、エラー等のstatus表示も保持します。
`sharing.x`が有効なDomainでは、本文の操作列にX共有アイコンを表示します。
共有するのは記事の件名と原文URLで、RSS画面や非公開WikiのURLではありません。
URLはintentの`url`にだけ渡し、`text`へ重複させません。原文URLのない記事では表示しません。
通常の`target=_blank`リンクを一つだけ使い、JavaScriptによる二重openや自動投稿は行いません。
個人設定の「RSSの記事リンクの開き方」は`rss_link_mode`として保存します。既定は`tab`、
`embedded`を選ぶと原文リンクとHTML本文中の外部HTTP(S)リンクを同一タブ内の大きなdialogで開きます。
外部ページはクリック時だけiframeへ読み込み、閉じる際に破棄します。元の記事・一覧の状態は維持します。
Ctrl/Command/Shift付きのクリック等はブラウザ標準の別タブ操作を維持し、X共有アイコンも対象外です。
設定はRSS画面の再読込後に反映します。個人設定はタスク拡張のpreferencesに保存し、無効時は別タブを使います。
iframeは`allow-scripts`だけのsandboxと`no-referrer`を使い、親画面への操作・同一origin権限・
フォーム送信・popup等は許可しません。PagesWiki自身のoriginはiframe化しません。
リンク先のCSP/X-Frame-Options、ブラウザのmixed-content制限を回避するproxyは用意しません。
表示できないページやログイン・フォーム操作が必要な場合は、dialog内の別タブアイコンを使います。
表示可否をcross-origin DOMの読取で判定したり、失敗を装って自動で別タブへ遷移したりはしません。
## 既読とstarの書戻し ## 既読とstarの書戻し
server-authoritative stateと未送信の操作を分けます。操作ごとのrequest_idで重複を防ぎ、成功応答前に確定済みと表示しません。newsboat等で同時変更された場合、古いローカルcacheをまとめて送り返しません。接続解除・認可失効時は未送信変更を勝手に再送しません。 server-authoritative stateと未送信の操作を分けます。操作ごとのrequest_idで重複を防ぎ、成功応答前に確定済みと表示しません。newsboat等で同時変更された場合、古いローカルcacheをまとめて送り返しません。接続解除・認可失効時は未送信変更を勝手に再送しません。
@@ -260,6 +295,23 @@ previewはsource UUID・設定versionのsnapshotを返し、適用時に一致
既定はURL、出典、短いメモの保存です。全文保存は取得可能性・利用条件・個人用途等を確認する独立操作とし、feedが短いからといって有料記事を自動取得しません。保存先が自動公開範囲なら内容と添付の公開を明示確認します。 既定はURL、出典、短いメモの保存です。全文保存は取得可能性・利用条件・個人用途等を確認する独立操作とし、feedが短いからといって有料記事を自動取得しません。保存先が自動公開範囲なら内容と添付の公開を明示確認します。
タスク拡張が有効な場合、Wiki親Pathの初期値はDomain・本人単位の個人設定`wiki_prefix`を使います。
「個人設定 → メール・RSS取り込みの既定Wiki親Path」で設定し、メール取り込みと共通です。
RSS画面を読み込んだ時点の値を初期表示し、取り込みごとの上書き・空欄への変更を許します。
空欄でタスク作成を選んだ場合はWikiを作らず、個人設定の値を再適用しません。
未設定またはタスク拡張が無効な場合は空欄です。プロジェクトのWiki配下への暗黙の補完はRSSでは行いません。
保存時の公開範囲確認とACL検査は省略しません。既存preferencesを利用するため追加のschema変更はありません。
親Pathでは`{YYYY}`・`{MM}`・`{DD}`・`{Subject}`を使用できます。日付は取り込み時のドメインの
タイムゾーン、Subjectは編集可能な取り込み件名です。件名中の区切り文字・URI演算子・制御文字・
空白はハイフンに変換し、180バイト以内の単一Path要素へ整形します。空になる場合は`untitled`です。
未対応トークンや不正なPathは拒否します。メールcaptureでも同じ展開規則を適用します。
RSS取り込みは本文上のdialogで行い、本文を置き換えません。トークン挿入ボタンと実際の保存先を
表示し、件名・親Path・保存種別を変更した場合はプレビューを更新して公開範囲の確認をやり直します。
展開済みPathを確認後の要求へ固定し、UUIDの末尾(Wiki単独は`rss-`、タスク併設は`mail-`)で
同名記事の衝突を避けます。表示された親Path自体を記事ファイルとして上書きする仕様ではありません。
Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。既存Pathを上書きせず、Page・Path・ Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。既存Pathを上書きせず、Page・Path・
初回Revision・活動outbox・再送receiptを同じDB transactionで保存します。権限はtransaction内でも 初回Revision・活動outbox・再送receiptを同じDB transactionで保存します。権限はtransaction内でも
再確認します。初期版の単独保存は通常Wiki空間のみで、独自所有契約を持つ`/u`・`/g`は対象外です。 再確認します。初期版の単独保存は通常Wiki空間のみで、独自所有契約を持つ`/u`・`/g`は対象外です。
@@ -283,6 +335,7 @@ Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。
- [ ] RSS-5:FreshRSS実環境の接続先・版・API資格情報を指定してread-only受入。 - [ ] RSS-5:FreshRSS実環境の接続先・版・API資格情報を指定してread-only受入。
- [ ] RSS-6:大規模利用時の公平性、host別並列上限、Retry-After/backoff、資格情報rotation UI。 - [ ] RSS-6:大規模利用時の公平性、host別並列上限、Retry-After/backoff、資格情報rotation UI。
- [x] RSS-7:FreshRSSの購読一覧・カテゴリを使うnavigation。同名ID分離、複数カテゴリ、cache内絞り込み、背景での原子的更新、失敗時保持。 - [x] RSS-7:FreshRSSの購読一覧・カテゴリを使うnavigation。同名ID分離、複数カテゴリ、cache内絞り込み、背景での原子的更新、失敗時保持。
- [x] RSS-7b:分類フォルダの継承、空フォルダ・未分類、開閉状態保存、50件ずつの購読描画、分類移動への追従。schema v6の再実行・失敗rollbackと1440px/390pxの合成試験。
隔離試験はRSS/Atom・FreshRSS login/read、欠落ID・巨大/不正feed、条件付きGET、失敗時cache保持、 隔離試験はRSS/Atom・FreshRSS login/read、欠落ID・巨大/不正feed、条件付きGET、失敗時cache保持、
本人分離・失効・readonly、二重送信・版競合・旧worker拒否、migration再実行/失敗rollback、 本人分離・失効・readonly、二重送信・版競合・旧worker拒否、migration再実行/失敗rollback、
+32 -5
View File
@@ -5,6 +5,7 @@ import (
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
"time"
"github.com/google/uuid" "github.com/google/uuid"
"pageswiki/internal/store" "pageswiki/internal/store"
@@ -38,7 +39,18 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
taskError(w, e) taskError(w, e)
return return
} }
s.renderWithContext(w, r, "feeds.gohtml", map[string]any{"Title": "RSS", "FeedWritable": active}) prefix := ""
linkMode := "tab"
if s.systemExtensionEnabled(domain, "organizer.tasks") {
preferences, e := s.store.TaskPreferences(r.Context(), domain, actor)
if e != nil {
taskError(w, e)
return
}
prefix = preferences.WikiPrefix
linkMode = preferences.RSSLinkMode
}
s.renderWithContext(w, r, "feeds.gohtml", map[string]any{"Title": "RSS", "FeedWritable": active, "FeedWikiPrefix": prefix, "FeedLinkMode": linkMode, "FeedShareX": s.systemExtensionEnabled(domain, "sharing.x")})
return return
} }
key := strings.TrimPrefix(r.URL.Path, feedsAPI) key := strings.TrimPrefix(r.URL.Path, feedsAPI)
@@ -50,13 +62,28 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
return return
} }
switch { switch {
case key == "catalog" && r.Method == "GET": case key == "capture-preview" && r.Method == "POST":
catalog, e := s.store.FeedCatalog(r.Context(), domain, actor, r.URL.Query().Get("source")) var input struct {
Prefix string `json:"prefix"`
Title string `json:"title"`
}
if !taskJSON(w, r, &input) {
return
}
prefix, e := store.ExpandWikiPrefix(input.Prefix, input.Title, time.Now().In(s.getLocation(domain)))
if e != nil { if e != nil {
taskError(w, e) taskError(w, e)
return return
} }
writeEventJSON(w, 200, map[string]any{"subscriptions": catalog}) writeEventJSON(w, 200, map[string]string{"prefix": prefix})
return
case key == "catalog" && r.Method == "GET":
catalog, e := s.store.FeedCatalogSnapshot(r.Context(), domain, actor, r.URL.Query().Get("source"))
if e != nil {
taskError(w, e)
return
}
writeEventJSON(w, 200, catalog)
return return
case key == "note" && r.Method == "POST": case key == "note" && r.Method == "POST":
var input struct { var input struct {
@@ -170,7 +197,7 @@ func (s *Server) handleFeeds(w http.ResponseWriter, r *http.Request) {
return return
} }
} }
items, e := s.store.FeedItems(r.Context(), domain, actor, q.Get("source"), q.Get("filter"), q.Get("q"), before, q.Get("key"), q.Get("feed"), q.Get("category")) items, e := s.store.FeedItems(r.Context(), domain, actor, q.Get("source"), q.Get("filter"), q.Get("q"), before, q.Get("key"), q.Get("feed"), q.Get("category"), q.Get("category_mode"))
if e != nil { if e != nil {
taskError(w, e) taskError(w, e)
return return
@@ -0,0 +1,50 @@
package server
import (
"context"
"encoding/json"
"strings"
"testing"
)
func TestRSSLinkPreference(t *testing.T) {
s, token, domain, actor, _ := feedFixture(t)
p, err := s.store.TaskPreferences(context.Background(), domain, actor)
if err != nil || p.RSSLinkMode != "tab" {
t.Fatal(p.RSSLinkMode, err)
}
p.RSSLinkMode = "embedded"
if w := taskRequest(s, token, "PUT", "preferences", p, ""); w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
p, err = s.store.TaskPreferences(context.Background(), domain, actor)
if err != nil || p.RSSLinkMode != "embedded" {
t.Fatal(p.RSSLinkMode, err)
}
p.RSSLinkMode = "unsafe"
if w := taskRequest(s, token, "PUT", "preferences", p, ""); w.Code != 422 {
t.Fatal(w.Code, w.Body)
}
}
func TestFeedCapturePreview(t *testing.T) {
s, token, _, _, _ := feedFixture(t)
for _, tt := range []struct {
prefix string
status int
}{{"/notes/{YYYY}/{MM}/{DD}/{Subject}", 200}, {"/notes/{unknown}", 422}, {"/a/../b", 422}} {
w := feedRequestTest(s, token, "POST", "capture-preview", map[string]string{"prefix": tt.prefix, "title": "日本語 / test"})
if w.Code != tt.status {
t.Fatal(w.Code, w.Body)
}
if w.Code == 200 {
var data map[string]string
if e := json.Unmarshal(w.Body.Bytes(), &data); e != nil || strings.ContainsAny(data["prefix"], "{}") || !strings.HasSuffix(data["prefix"], "/日本語---test") {
t.Fatal(data, e)
}
}
}
if w := feedRequestTest(s, "", "POST", "capture-preview", map[string]string{"prefix": "/notes"}); w.Code != 401 {
t.Fatal(w.Code)
}
}
+16 -3
View File
@@ -49,6 +49,7 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
} }
calls := 0 calls := 0
failCatalog := false failCatalog := false
failFolders := false
client := &http.Client{Transport: feedTransportFunc(func(r *http.Request) (*http.Response, error) { client := &http.Client{Transport: feedTransportFunc(func(r *http.Request) (*http.Response, error) {
calls++ calls++
body := "" body := ""
@@ -63,7 +64,7 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
t.Error("article request") t.Error("article request")
} }
body = `{"items":[{"id":"a","title":"First","origin":{"title":"Same title","streamId":"feed/1"},"categories":["user/alice/label/Tech"]},{"id":"b","title":"Second","origin":{"title":"Same title","streamId":"feed/2"},"categories":["user/alice/label/Other"]}]}` body = `{"items":[{"id":"a","title":"First","origin":{"title":"Same title","streamId":"feed/1"},"categories":["user/alice/label/Tech"]},{"id":"b","title":"Second","origin":{"title":"Same title","streamId":"feed/2"},"categories":["user/alice/label/Other"]}]}`
if failCatalog { if failCatalog || failFolders {
body = `{"items":[]}` body = `{"items":[]}`
} }
case strings.HasSuffix(r.URL.Path, "/subscription/list"): case strings.HasSuffix(r.URL.Path, "/subscription/list"):
@@ -74,6 +75,11 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
return nil, errors.New("synthetic timeout") return nil, errors.New("synthetic timeout")
} }
body = testFeedCatalog body = testFeedCatalog
case strings.HasSuffix(r.URL.Path, "/tag/list"):
if failFolders {
return nil, errors.New("synthetic folder failure")
}
body = `{"tags":[{"id":"user/-/label/Empty/Folder","type":"folder"},{"id":"user/-/label/Not a folder","type":"tag"}]}`
default: default:
t.Fatalf("unexpected external request %s %s", r.Method, r.URL.Path) t.Fatalf("unexpected external request %s %s", r.Method, r.URL.Path)
} }
@@ -89,7 +95,7 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
} }
} }
run() run()
if calls != 3 { if calls != 4 {
t.Fatal("fetch count", calls) t.Fatal("fetch count", calls)
} }
w := feedRequestTest(s, token, "GET", "catalog?source="+v.UUID, nil) w := feedRequestTest(s, token, "GET", "catalog?source="+v.UUID, nil)
@@ -127,9 +133,16 @@ func TestFeedCatalogBackgroundSnapshotIsolation(t *testing.T) {
if _, e := s.store.FeedCatalog(ctx, uuid.NewString(), actor, v.UUID); e == nil { if _, e := s.store.FeedCatalog(ctx, uuid.NewString(), actor, v.UUID); e == nil {
t.Fatal("cross-domain catalog leak") t.Fatal("cross-domain catalog leak")
} }
if calls != 3 { if calls != 4 {
t.Fatal("foreground external request") t.Fatal("foreground external request")
} }
failFolders = true
run()
kept, e := s.store.FeedCatalogSnapshot(ctx, domain, actor, v.UUID)
if e != nil || len(kept.Folders) != 3 || len(kept.Subscriptions) != 3 {
t.Fatal("folder failure erased snapshot", kept, e)
}
failFolders = false
failCatalog = true failCatalog = true
run() run()
catalog, e := s.store.FeedCatalog(ctx, domain, actor, v.UUID) catalog, e := s.store.FeedCatalog(ctx, domain, actor, v.UUID)
+19 -3
View File
@@ -345,7 +345,7 @@ func freshRSSLogin(ctx context.Context, client *http.Client, v store.FeedSource,
} }
return auth, nil return auth, nil
} }
func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource, user, password string, catalogs ...*[]store.FeedRemoteSubscription) ([]store.FeedItem, error) { func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource, user, password string, catalogs ...*store.FeedCatalogSnapshot) ([]store.FeedItem, error) {
base := strings.TrimRight(v.URL, "/") base := strings.TrimRight(v.URL, "/")
auth, e := freshRSSLogin(ctx, client, v, user, password) auth, e := freshRSSLogin(ctx, client, v, user, password)
if e != nil { if e != nil {
@@ -368,7 +368,23 @@ func fetchFreshRSS(ctx context.Context, client *http.Client, v store.FeedSource,
if e != nil { if e != nil {
return nil, e return nil, e
} }
*catalogs[0] = catalog raw, _, _, e = feedRequest(ctx, client, "GET", base+"/reader/api/0/tag/list?output=json", auth, nil, nil)
if e != nil {
return nil, e
}
folders, e := parseFreshRSSFolders(raw)
if e != nil {
return nil, e
}
folders, e = store.FeedFolders(catalog, folders)
if e != nil {
return nil, errFeedInvalid
}
snapshot := store.FeedCatalogSnapshot{Subscriptions: catalog, Folders: folders}
if _, _, e = snapshot.Encode(); e != nil {
return nil, errFeedInvalid
}
*catalogs[0] = snapshot
} }
return items, nil return items, nil
} }
@@ -504,7 +520,7 @@ func (s *Server) syncFeedSourcesWithClient(ctx context.Context, job *store.Event
} }
child, stop := context.WithTimeout(ctx, 8*time.Second) child, stop := context.WithTimeout(ctx, 8*time.Second)
var items []store.FeedItem var items []store.FeedItem
var catalog []store.FeedRemoteSubscription var catalog store.FeedCatalogSnapshot
etag, modified := v.ETag, v.Modified etag, modified := v.ETag, v.Modified
unchanged := false unchanged := false
if !validCalendarSourceURL(v.URL) { if !validCalendarSourceURL(v.URL) {
+42
View File
@@ -0,0 +1,42 @@
package server
import (
"encoding/json"
"strings"
"unicode/utf8"
"pageswiki/internal/store"
)
func parseFreshRSSFolders(raw []byte) ([]store.FeedCategory, error) {
if len(raw) > 4<<20 || !utf8.Valid(raw) {
return nil, errFeedInvalid
}
var response struct {
Tags []struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"tags"`
}
if json.Unmarshal(raw, &response) != nil || response.Tags == nil || len(response.Tags) > 10000 {
return nil, errFeedInvalid
}
folders := []store.FeedCategory{}
seen := map[string]bool{}
for _, tag := range response.Tags {
// Article tags and system state tags are not subscription folders.
if tag.Type != "folder" {
continue
}
prefix, label, ok := strings.Cut(tag.ID, "/label/")
if !ok || !strings.HasPrefix(prefix, "user/") || len(prefix) <= 5 || label == "" || !store.ValidFeedRemoteID(tag.ID) || seen[tag.ID] {
return nil, errFeedInvalid
}
seen[tag.ID] = true
folders = append(folders, store.FeedCategory{ID: tag.ID, Label: feedText(label, 512)})
}
if _, e := store.FeedFolders(nil, folders); e != nil {
return nil, errFeedInvalid
}
return folders, nil
}
+95
View File
@@ -0,0 +1,95 @@
package server
import (
"context"
"encoding/json"
"fmt"
"net/url"
"strings"
"testing"
"pageswiki/internal/store"
)
func TestFreshRSSFoldersParsing(t *testing.T) {
folders, e := parseFreshRSSFolders([]byte(`{"tags":[{"id":"user/-/state/com.google/starred"},{"id":"user/-/label/ArticleTag","type":"tag"},{"id":"user/-/label/技術/Linux","type":"folder"}]}`))
if e != nil || len(folders) != 1 || folders[0].Label != "技術/Linux" {
t.Fatal(folders, e)
}
for _, raw := range []string{`{}`, `{"tags":null}`, `{"tags":[{"id":"invalid","type":"folder"}]}`, `{"tags":[{"id":"user/-/label/","type":"folder"}]}`, `{"tags":[{"id":"user/-/label/A","type":"folder"},{"id":"user/-/label/A","type":"folder"}]}`} {
if _, e = parseFreshRSSFolders([]byte(raw)); e == nil {
t.Fatal("invalid folder accepted", raw)
}
}
tags := []map[string]string{}
for i := 0; i < 1001; i++ {
tags = append(tags, map[string]string{"id": fmt.Sprintf("user/-/label/%d", i), "type": "folder"})
}
raw, _ := json.Marshal(map[string]any{"tags": tags})
if _, e = parseFreshRSSFolders(raw); e == nil {
t.Fatal("unbounded folders")
}
if _, e = store.FeedFolders([]store.FeedRemoteSubscription{{ID: "feed/1", Categories: []store.FeedCategory{{ID: "cat", Label: "A"}}}}, []store.FeedCategory{{ID: "cat", Label: "B"}}); e == nil {
t.Fatal("conflicting labels")
}
large := store.FeedCatalogSnapshot{}
for i := 0; i < 1000; i++ {
large.Subscriptions = append(large.Subscriptions, store.FeedRemoteSubscription{ID: fmt.Sprintf("feed/%d", i), Title: strings.Repeat("s", 512)})
large.Folders = append(large.Folders, store.FeedCategory{ID: fmt.Sprintf("user/-/label/%d", i), Label: strings.Repeat("f", 512)})
}
if _, e := store.FeedCatalogJSON(large.Subscriptions); e != nil {
t.Fatal("catalog alone should fit", e)
}
if _, _, e := large.Encode(); e != store.ErrTaskDAVLimit {
t.Fatal("combined snapshot limit", e)
}
}
func TestFeedFolderMembershipAndUncategorized(t *testing.T) {
s, token, domain, actor, source := feedActionFixture(t)
ctx := context.Background()
if _, e := s.store.DB.Exec(`UPDATE feed_sources SET next_ms=0 WHERE uuid=?`, source.UUID); e != nil {
t.Fatal(e)
}
sources, e := s.store.FeedSources(ctx, domain, actor)
if e != nil {
t.Fatal(e)
}
for _, v := range sources {
if v.UUID == source.UUID {
source = v
}
}
claim, e := s.store.ClaimFeed(ctx, source)
if e != nil {
t.Fatal(e)
}
cat := store.FeedCategory{ID: "user/-/label/New/Folder", Label: "New/Folder"}
snapshot := store.FeedCatalogSnapshot{Subscriptions: []store.FeedRemoteSubscription{{ID: "feed/1", Title: "Moved", Categories: []store.FeedCategory{cat}}, {ID: "feed/2", Title: "Unclassified", Categories: []store.FeedCategory{}}}, Folders: []store.FeedCategory{{ID: "user/-/label/Empty", Label: "Empty"}}}
items := []store.FeedItem{{ID: "a", Title: "Moved", RemoteFeed: "feed/1", RemoteCategories: []string{"user/-/label/Old"}}, {ID: "b", Title: "Unclassified", RemoteFeed: "feed/2", RemoteCategories: []string{"user/-/label/ArticleTag"}}, {ID: "c", Title: "Unknown subscription", RemoteFeed: "feed/unknown"}}
if e = s.store.CompleteFeed(ctx, claim, items, "", "", "", false, snapshot); e != nil {
t.Fatal(e)
}
for _, test := range []struct {
query string
want string
}{{"category=" + url.QueryEscape(cat.ID), "a"}, {"category_mode=uncategorized", "b"}, {"category=user%2F-%2Flabel%2FOld", ""}, {"category=user%2F-%2Flabel%2FEmpty", ""}} {
w := feedRequestTest(s, token, "GET", "items?source="+source.UUID+"&"+test.query, nil)
var data struct {
Items []store.FeedItem `json:"items"`
}
json.Unmarshal(w.Body.Bytes(), &data)
if w.Code != 200 || (test.want == "" && len(data.Items) != 0) || (test.want != "" && (len(data.Items) != 1 || data.Items[0].ID != test.want)) {
t.Fatal(test.query, w.Code, w.Body)
}
}
for _, query := range []string{"category_mode=uncategorized", "source=" + source.UUID + "&category_mode=bad", "source=" + source.UUID + "&category_mode=uncategorized&category=" + url.QueryEscape(cat.ID)} {
if w := feedRequestTest(s, token, "GET", "items?"+query, nil); w.Code != 422 {
t.Fatal(query, w.Code)
}
}
got, e := s.store.FeedCatalogSnapshot(ctx, domain, actor, source.UUID)
if e != nil || len(got.Folders) != 2 {
t.Fatal(got, e)
}
}
+15 -1
View File
@@ -531,6 +531,15 @@ func TestFeedsChromium(t *testing.T) {
t.Skip("opt-in Chromium") t.Skip("opt-in Chromium")
} }
s, token, domain, actor, source := feedFixture(t) s, token, domain, actor, source := feedFixture(t)
prefs, err := s.store.TaskPreferences(context.Background(), domain, actor)
if err != nil {
t.Fatal(err)
}
prefs.WikiPrefix = "/notes/{YYYY}/{MM}/{DD}/{Subject}"
prefs.RSSLinkMode = "embedded"
if _, err = s.store.SaveTaskPreferences(context.Background(), domain, actor, prefs, time.Now()); err != nil {
t.Fatal(err)
}
claim, e := s.store.ClaimFeed(context.Background(), source) claim, e := s.store.ClaimFeed(context.Background(), source)
if e != nil { if e != nil {
t.Fatal(e) t.Fatal(e)
@@ -569,7 +578,7 @@ func TestFeedsChromium(t *testing.T) {
if e != nil { if e != nil {
t.Fatal(e) t.Fatal(e)
} }
if e = s.store.CompleteFeed(context.Background(), claim, []store.FeedItem{{ID: "catalog-a", Title: "Catalog first", RemoteFeed: "feed/1", RemoteCategories: []string{"user/alice/label/Tech"}}, {ID: "catalog-b", Title: "Catalog second", RemoteFeed: "feed/2", RemoteCategories: []string{"user/alice/label/Other"}}}, "", "", "", false, catalog); e != nil { if e = s.store.CompleteFeed(context.Background(), claim, []store.FeedItem{{ID: "catalog-a", Title: "Catalog first", RemoteFeed: "feed/1", RemoteCategories: []string{"user/alice/label/Tech"}}, {ID: "catalog-b", Title: "Catalog second", RemoteFeed: "feed/2", RemoteCategories: []string{"user/alice/label/Other"}}}, "", "", "", false, store.FeedCatalogSnapshot{Subscriptions: catalog, Folders: []store.FeedCategory{{ID: "user/-/label/Empty/Folder", Label: "Empty/Folder"}}}); e != nil {
t.Fatal(e) t.Fatal(e)
} }
s.store.BackgroundJobsDisabled = true s.store.BackgroundJobsDisabled = true
@@ -582,6 +591,11 @@ func TestFeedsChromium(t *testing.T) {
web := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { web := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Host = "localhost" r.Host = "localhost"
r.Header.Set("Authorization", "Bearer "+token) r.Header.Set("Authorization", "Bearer "+token)
if r.URL.Path == "/fixture/embedded" {
w.Header().Set("Content-Type", "text/html")
io.WriteString(w, `<h1>Isolated external article fixture</h1><script>parent.postMessage('rss-external-fixture-loaded','*')</script>`)
return
}
if r.URL.Path == "/fixture/run-feed-actions" && r.Method == "POST" { if r.URL.Path == "/fixture/run-feed-actions" && r.Method == "POST" {
fake := &feedRemoteFake{id: "catalog-b"} fake := &feedRemoteFake{id: "catalog-b"}
if e := s.syncFeedActions(r.Context(), fake.client(t)); e != nil { if e := s.syncFeedActions(r.Context(), fake.client(t)); e != nil {
+2 -1
View File
@@ -256,7 +256,8 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
writeEventJSON(w, 422, map[string]string{"error": "wiki_prefix_required"}) writeEventJSON(w, 422, map[string]string{"error": "wiki_prefix_required"})
return return
} }
if !store.ValidTaskWikiPrefix(prefix) { prefix, err = store.ExpandWikiPrefix(prefix, item.Title, time.Now().In(s.getLocation(domain)))
if err != nil {
taskError(w, store.ErrTaskInvalid) taskError(w, store.ErrTaskInvalid)
return return
} }
+19 -6
View File
@@ -4,12 +4,17 @@
const frame=document.createElement('iframe');frame.style='display:block;width:100%;height:100vh;border:0';document.body.append(frame); const frame=document.createElement('iframe');frame.style='display:block;width:100%;height:100vh;border:0';document.body.append(frame);
try{ try{
await new Promise(resolve=>{frame.onload=resolve;frame.src='/v/feeds';});const d=frame.contentDocument,w=frame.contentWindow; await new Promise(resolve=>{frame.onload=resolve;frame.src='/v/feeds';});const d=frame.contentDocument,w=frame.contentWindow;
for(const key of Object.keys(w.localStorage))if(key.startsWith('pageswiki.feed-folders.v1:'))w.localStorage.removeItem(key);
await wait(()=>d.querySelectorAll('.feed-row').length===100); await wait(()=>d.querySelectorAll('.feed-row').length===100);
assert(d.documentElement.scrollWidth<=w.innerWidth,'Viewport overflow'); assert(d.documentElement.scrollWidth<=w.innerWidth,'Viewport overflow');
assert(d.title.startsWith('RSS ·'),'RSS title');assert(d.getElementById('feed-status').textContent==='','Unrequested status copy');assert(w.getComputedStyle(d.getElementById('feed-status')).display==='none','Empty status takes space'); assert(d.title.startsWith('RSS ·'),'RSS title');assert(d.getElementById('feed-status').textContent==='','Unrequested status copy');assert(w.getComputedStyle(d.getElementById('feed-status')).display==='none','Empty status takes space');
for(const a of d.querySelectorAll('.organizer-nav a')){assert(a.getAttribute('aria-label'),'Unnamed navigation');if(w.innerWidth<=700)assert(w.getComputedStyle(a.querySelector('span')).display==='none','Mobile tab label visible');} for(const a of d.querySelectorAll('.organizer-nav a')){assert(a.getAttribute('aria-label'),'Unnamed navigation');if(w.innerWidth<=700)assert(w.getComputedStyle(a.querySelector('span')).display==='none','Mobile tab label visible');}
d.getElementById('feed-rows').focus();d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'j',bubbles:true})); d.getElementById('feed-rows').focus();d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'j',bubbles:true}));
await wait(()=>d.querySelector('#feed-reader .feed-body'));const html=d.querySelector('#feed-reader .feed-body').shadowRoot;assert(html?.querySelector('h2')&&html.querySelector('table')&&html.querySelector('strong'),'HTML not rendered');assert(!html.querySelector('script,img,iframe,form'),'Active article HTML');assert(!w.rssAttack,'Script executed');assert(html.querySelector('a').target==='_blank','Article link target');assert(d.querySelector('.feed-original svg')&&!d.querySelector('.feed-original').textContent,'Original link not icon'); await wait(()=>d.querySelector('#feed-reader .feed-body'));const html=d.querySelector('#feed-reader .feed-body').shadowRoot;assert(html?.querySelector('h2')&&html.querySelector('table')&&html.querySelector('strong'),'HTML not rendered');assert(!html.querySelector('script,img,iframe,form'),'Active article HTML');assert(!w.rssAttack,'Script executed');assert(html.querySelector('a').target==='_blank','Article link target');assert(d.querySelector('.feed-original svg')&&!d.querySelector('.feed-original').textContent,'Original link not icon');
const share=d.querySelector('.feed-share-x'),intent=new URL(share.href);assert(share.target==='_blank'&&share.rel.includes('noopener')&&intent.searchParams.get('url')==='https://example.org/article'&&intent.searchParams.get('text').includes('日本語のRSS記事')&&!intent.searchParams.get('text').includes('https://'),'RSS share URL or duplicate URL in text');
assert(d.getElementById('feeds-app').dataset.linkMode==='embedded','Link preference missing');assert(!d.querySelector('.feed-external iframe'),'External page fetched before click');const externalURL=new URL('/fixture/embedded',w.location.href);externalURL.hostname='localhost';let externalLoaded=0;w.addEventListener('message',e=>{if(e.data==='rss-external-fixture-loaded'&&e.origin==='null')externalLoaded++;});const original=d.querySelector('.feed-original');original.href=externalURL.href;original.click();await wait(()=>d.querySelector('.feed-external[open] iframe'));await wait(()=>externalLoaded===1);let previewFrame=d.querySelector('.feed-external iframe');assert(previewFrame.src===externalURL.href&&previewFrame.getAttribute('sandbox')==='allow-scripts'&&previewFrame.referrerPolicy==='no-referrer','Unsafe external frame');assert(d.querySelector('.feed-external a').target==='_blank','Missing fallback');d.querySelector('.feed-external button').click();await wait(()=>!d.querySelector('.feed-external'));assert(d.querySelector('#feed-reader .feed-body'),'External preview lost article');const articleLink=html.querySelector('a');articleLink.href=externalURL.href;articleLink.click();await wait(()=>externalLoaded===2);d.querySelector('.feed-external').close();await wait(()=>!d.querySelector('.feed-external'));
const help=d.getElementById('feed-help'),helpButton=d.querySelector('[aria-controls="feed-help"]'),key=k=>d.dispatchEvent(new w.KeyboardEvent('keydown',{key:k,bubbles:true}));
d.getElementById('feed-status').textContent='Synthetic status';key('?');await wait(()=>!help.hidden);assert(helpButton.getAttribute('aria-expanded')==='true','Help toggle state');key('Escape');assert(help.hidden&&d.querySelector('.feed-layout').classList.contains('reading'),'Closing help changed reader');assert(d.getElementById('feed-status').textContent==='Synthetic status','Help erased status');key('?');await wait(()=>!help.hidden);key('?');await wait(()=>help.hidden);helpButton.click();await wait(()=>!help.hidden);help.querySelector('button').click();await wait(()=>help.hidden);assert(helpButton.getAttribute('aria-expanded')==='false','Help state not reset');d.getElementById('feed-status').textContent='';
d.querySelectorAll('.feed-row')[1].click();await wait(()=>d.querySelector('#feed-reader .feed-body')&&!d.querySelector('#feed-reader .feed-body').shadowRoot);assert(d.querySelector('#feed-reader .feed-body').textContent.includes('<script>'),'Literal text not preserved');d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body')?.shadowRoot); d.querySelectorAll('.feed-row')[1].click();await wait(()=>d.querySelector('#feed-reader .feed-body')&&!d.querySelector('#feed-reader .feed-body').shadowRoot);assert(d.querySelector('#feed-reader .feed-body').textContent.includes('<script>'),'Literal text not preserved');d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body')?.shadowRoot);
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'*',bubbles:true}));await wait(()=>d.querySelector('.feed-row[aria-selected=true]').textContent.includes('★')); d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'*',bubbles:true}));await wait(()=>d.querySelector('.feed-row[aria-selected=true]').textContent.includes('★'));
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));await wait(()=>!d.querySelector('.feed-layout').classList.contains('reading')); d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));await wait(()=>!d.querySelector('.feed-layout').classList.contains('reading'));
@@ -17,7 +22,8 @@
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'/',bubbles:true}));await wait(()=>d.activeElement.type==='search');d.activeElement.value='119';d.activeElement.dispatchEvent(new w.Event('input',{bubbles:true}));await wait(()=>d.querySelectorAll('.feed-row').length===1); d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'/',bubbles:true}));await wait(()=>d.activeElement.type==='search');d.activeElement.value='119';d.activeElement.dispatchEvent(new w.Event('input',{bubbles:true}));await wait(()=>d.querySelectorAll('.feed-row').length===1);
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body')); d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));
d.querySelector('#feed-reader .feed-actions button:last-child').click();await wait(()=>d.querySelector('#feed-reader form')); d.querySelector('#feed-reader .feed-actions button:last-child').click();await wait(()=>d.querySelector('#feed-reader form'));
const form=d.querySelector('#feed-reader form'),inputs=form.querySelectorAll('input');inputs[2].value='/notes/feed-ui';inputs[2].dispatchEvent(new w.Event('input'));inputs[5].checked=true;form.requestSubmit();await wait(()=>d.querySelector('#feed-reader a[href^="/v/uuid:"]')); assert(!['rgba(0, 0, 0, 0)','transparent'].includes(w.getComputedStyle(d.querySelector('.feed-capture')).backgroundColor),'Capture dialog background transparent');
const form=d.querySelector('#feed-reader form'),inputs=form.querySelectorAll('input');assert(inputs[2].value==='/notes/{YYYY}/{MM}/{DD}/{Subject}','Wiki default not filled');assert(form.closest('dialog').open&&d.querySelector('#feed-reader .feed-body'),'Capture replaced article');assert(form.querySelector('a[href="/-/sys/config?panel=organizer"]'),'Default settings link missing');await wait(()=>form.querySelector('output').textContent.includes('/rss-'));assert(!form.querySelector('output').textContent.includes('{'),'Template not expanded');inputs[2].value='/notes/feed-ui';inputs[2].dispatchEvent(new w.Event('input'));await wait(()=>form.querySelector('output').textContent.startsWith('/notes/feed-ui/rss-'));inputs[5].checked=true;form.requestSubmit();await wait(()=>d.querySelector('#feed-reader a[href^="/v/uuid:"]'));d.querySelector('.feed-capture button').click();await wait(()=>!d.querySelector('.feed-capture'));assert(d.querySelector('#feed-reader .feed-body'),'Closing capture lost article');
const search=d.querySelector('#feed-toolbar input');search.value='';search.dispatchEvent(new w.Event('input',{bubbles:true}));await wait(()=>d.querySelectorAll('.feed-row').length===100);d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body')); const search=d.querySelector('#feed-toolbar input');search.value='';search.dispatchEvent(new w.Event('input',{bubbles:true}));await wait(()=>d.querySelectorAll('.feed-row').length===100);d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));
assert(d.documentElement.scrollWidth<=w.innerWidth,'Reader overflow'); assert(d.documentElement.scrollWidth<=w.innerWidth,'Reader overflow');
d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file')); d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file'));
@@ -27,10 +33,15 @@
assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML overflow');d.querySelector('.feed-import-options input[type=checkbox]').checked=false;d.getElementById('feed-opml-preview').requestSubmit();await wait(()=>!d.getElementById('feed-opml-preview')); assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML overflow');d.querySelector('.feed-import-options input[type=checkbox]').checked=false;d.getElementById('feed-opml-preview').requestSubmit();await wait(()=>!d.getElementById('feed-opml-preview'));
assert(d.getElementById('feed-sources').textContent.includes('Import '+w.innerWidth),'Imported source missing');d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file'));choose();await wait(()=>d.querySelectorAll('#feed-opml-preview tbody tr').length===3);assert(d.querySelector('#feed-opml-preview tbody input').disabled,'Duplicate after import'); assert(d.getElementById('feed-sources').textContent.includes('Import '+w.innerWidth),'Imported source missing');d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file'));choose();await wait(()=>d.querySelectorAll('#feed-opml-preview tbody tr').length===3);assert(d.querySelector('#feed-opml-preview tbody input').disabled,'Duplicate after import');
assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML preview overflow'); assert(d.documentElement.scrollWidth<=w.innerWidth,'OPML preview overflow');
[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='FreshRSS fixture').click();await wait(()=>d.querySelectorAll('.feed-subscriptions button').length===4&&d.querySelectorAll('.feed-row').length===2); const freshButton=()=>[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='FreshRSS fixture');freshButton().click();await wait(()=>d.querySelectorAll('.feed-folder').length===4&&d.querySelectorAll('.feed-row').length===2);
const category=d.getElementById('feed-category');category.value='user/alice/label/Tech';category.dispatchEvent(new w.Event('change'));await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog first')); const folder=id=>[...d.querySelectorAll('.feed-folder')].find(n=>n.dataset.category===id),tech=()=>folder('user/alice/label/Tech');
assert(d.querySelectorAll('.feed-subscriptions button').length===2,'Category navigation'); tech().querySelector('.feed-folder-name').click();await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog first'));
d.getElementById('feed-category').value='';d.getElementById('feed-category').dispatchEvent(new w.Event('change'));await wait(()=>d.querySelectorAll('.feed-row').length===2); assert(tech().querySelector('.feed-folder-toggle').getAttribute('aria-expanded')==='false','Selecting folder expands it unexpectedly');tech().querySelector('.feed-folder-toggle').click();await wait(()=>tech().querySelector('button[data-feed="feed/1"]'));
const empty=folder('user/-/label/Empty/Folder');assert(empty.querySelector('.feed-folder-name span').textContent==='Empty/Folder','Slash label split');empty.querySelector('.feed-folder-toggle').click();assert(!empty.querySelector('button[data-feed]'),'Empty folder fabricated a feed');empty.querySelector('.feed-folder-name').click();await wait(()=>d.querySelectorAll('.feed-row').length===0);
d.querySelector('.feed-folder[data-mode="uncategorized"] .feed-folder-name').click();await wait(()=>d.querySelectorAll('.feed-row').length===0);
d.querySelector('.feed-catalog .feed-tree-all').click();await wait(()=>d.querySelectorAll('.feed-row').length===2);
[...d.querySelectorAll('.feed-source>button:first-child')].find(b=>b.textContent==='Synthetic news').click();await wait(()=>!d.querySelector('.feed-catalog'));freshButton().click();await wait(()=>tech()?.querySelector('button[data-feed="feed/1"]'));assert(tech().querySelector('.feed-folder-toggle').getAttribute('aria-expanded')==='true','Folder expansion not retained');
folder('user/alice/label/Other').querySelector('.feed-folder-toggle').click();await wait(()=>d.querySelector('.feed-subscriptions button[data-feed="feed/2"]'));
d.querySelector('.feed-subscriptions button[data-feed="feed/2"]').click();await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog second')); d.querySelector('.feed-subscriptions button[data-feed="feed/2"]').click();await wait(()=>d.querySelectorAll('.feed-row').length===1&&d.querySelector('.feed-row').textContent.includes('Catalog second'));
d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));assert(d.querySelectorAll('#feed-reader .feed-actions button:disabled').length===2,'FreshRSS not read-only'); d.querySelector('.feed-row').click();await wait(()=>d.querySelector('#feed-reader .feed-body'));assert(d.querySelectorAll('#feed-reader .feed-actions button:disabled').length===2,'FreshRSS not read-only');
[...d.querySelectorAll('.feed-source')].find(n=>n.textContent.includes('FreshRSS fixture')).querySelector('button:last-child').click();await wait(()=>d.querySelector('#feed-reader form')); [...d.querySelectorAll('.feed-source')].find(n=>n.textContent.includes('FreshRSS fixture')).querySelector('button:last-child').click();await wait(()=>d.querySelector('#feed-reader form'));
@@ -52,6 +63,8 @@
const hs=d.getElementById('feed-history-state');hs.value='all';hs.dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]')); const hs=d.getElementById('feed-history-state');hs.value='all';hs.dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]'));
d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));assert(!d.querySelector('.feed-layout').classList.contains('action-history'),'History escape'); d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'Escape',bubbles:true}));assert(!d.querySelector('.feed-layout').classList.contains('action-history'),'History escape');
d.getElementById('feed-history').click();await wait(()=>receipt(seed.orphan));d.getElementById('feed-history-state').value='all';d.getElementById('feed-history-state').dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]')); d.getElementById('feed-history').click();await wait(()=>receipt(seed.orphan));d.getElementById('feed-history-state').value='all';d.getElementById('feed-history-state').dispatchEvent(new w.Event('change'));await wait(()=>receipt(seed.missing)?.querySelector('[data-state=confirmed]'));
assert(d.documentElement.scrollWidth<=w.innerWidth,'History final overflow');document.body.dataset.vimReady='1'; assert(d.documentElement.scrollWidth<=w.innerWidth,'History final overflow');
const probe=document.createElement('iframe');probe.hidden=true;document.body.append(probe);await new Promise(resolve=>{probe.onload=resolve;probe.src='/v/feeds?source='+encodeURIComponent(source.uuid);});await wait(()=>probe.contentDocument.querySelector('.feed-folder[data-category="user/alice/label/Tech"] .feed-folder-toggle')?.getAttribute('aria-expanded')==='true');probe.remove();
freshButton().click();await wait(()=>tech()?.querySelector('button[data-feed="feed/1"]'));if(w.innerWidth<=700){d.querySelector('#feed-toolbar button').click();await wait(()=>d.querySelector('.feed-layout').classList.contains('sources-open'));assert(w.getComputedStyle(d.getElementById('feed-sources')).display!=='none','Mobile folders hidden');}assert(d.documentElement.scrollWidth<=w.innerWidth,'Folder tree overflow');document.body.dataset.vimReady='1';
}catch(e){const out=document.createElement('pre');out.id='error';out.textContent=e.stack;document.body.append(out);} }catch(e){const out=document.createElement('pre');out.id='error';out.textContent=e.stack;document.body.append(out);}
})(); })();
+36 -6
View File
@@ -54,6 +54,10 @@ var feedMigrations = []db.SQLMigration{{Version: 1, Name: "private_feed_reader",
`CREATE TRIGGER feed_actions_source_change AFTER UPDATE OF version ON feed_sources BEGIN UPDATE feed_actions SET status=CASE WHEN status IN ('sending','unknown','check_queued','checking') THEN 'unknown' ELSE 'cancelled' END,error='source_changed' WHERE source_uuid=old.uuid AND status IN ('queued','preparing','sending','unknown','check_queued','checking'); END`, `CREATE TRIGGER feed_actions_source_change AFTER UPDATE OF version ON feed_sources BEGIN UPDATE feed_actions SET status=CASE WHEN status IN ('sending','unknown','check_queued','checking') THEN 'unknown' ELSE 'cancelled' END,error='source_changed' WHERE source_uuid=old.uuid AND status IN ('queued','preparing','sending','unknown','check_queued','checking'); END`,
`CREATE TRIGGER feed_actions_source_delete AFTER DELETE ON feed_sources BEGIN UPDATE feed_actions SET status=CASE WHEN status IN ('sending','unknown','check_queued','checking') THEN 'unknown' ELSE 'cancelled' END,error='source_deleted' WHERE source_uuid=old.uuid AND status IN ('queued','preparing','sending','unknown','check_queued','checking'); END`, `CREATE TRIGGER feed_actions_source_delete AFTER DELETE ON feed_sources BEGIN UPDATE feed_actions SET status=CASE WHEN status IN ('sending','unknown','check_queued','checking') THEN 'unknown' ELSE 'cancelled' END,error='source_deleted' WHERE source_uuid=old.uuid AND status IN ('queued','preparing','sending','unknown','check_queued','checking'); END`,
}, Assertions: []string{schemaColumns("feed_sources", "write_enabled"), schemaUnique("feed_actions", "domain_uuid,owner_uuid,request_id")}, }, Assertions: []string{schemaColumns("feed_sources", "write_enabled"), schemaUnique("feed_actions", "domain_uuid,owner_uuid,request_id")},
}, {
Version: 6, Name: "freshrss_empty_folders", Statements: []string{
`ALTER TABLE feed_sources ADD COLUMN remote_folders TEXT NOT NULL DEFAULT '[]'`,
}, Assertions: []string{schemaColumns("feed_sources", "remote_folders")},
}} }}
// CaptureFeedNote creates an inert Wiki note and receipt atomically. It does not // CaptureFeedNote creates an inert Wiki note and receipt atomically. It does not
@@ -330,7 +334,7 @@ func (s *Store) FeedSourceAction(ctx context.Context, domain, owner, id, action
} }
func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, query string, before int64, beforeID string, scope ...string) ([]FeedItem, error) { func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, query string, before int64, beforeID string, scope ...string) ([]FeedItem, error) {
remoteFeed, category := "", "" remoteFeed, category := "", ""
if len(scope) > 2 { if len(scope) > 3 {
return nil, ErrTaskInvalid return nil, ErrTaskInvalid
} }
if len(scope) > 0 { if len(scope) > 0 {
@@ -339,6 +343,13 @@ func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, qu
if len(scope) > 1 { if len(scope) > 1 {
category = scope[1] category = scope[1]
} }
mode := ""
if len(scope) > 2 {
mode = scope[2]
}
if mode != "" && (mode != "uncategorized" || source == "" || category != "") {
return nil, ErrTaskInvalid
}
if (remoteFeed != "" && !ValidFeedRemoteID(remoteFeed)) || (category != "" && !ValidFeedRemoteID(category)) || ((remoteFeed != "" || category != "") && source == "") { if (remoteFeed != "" && !ValidFeedRemoteID(remoteFeed)) || (category != "" && !ValidFeedRemoteID(category)) || ((remoteFeed != "" || category != "") && source == "") {
return nil, ErrTaskInvalid return nil, ErrTaskInvalid
} }
@@ -348,7 +359,14 @@ func (s *Store) FeedItems(ctx context.Context, domain, owner, source, filter, qu
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil { if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
return nil, e return nil, e
} }
rows, e := s.DB.QueryContext(ctx, `SELECT i.source_uuid,i.id,i.title,i.url,i.published_ms,i.feed,CASE WHEN s.folder<>'' THEN s.folder ELSE i.folder END,CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END,CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END,COALESCE(t.version,0),s.provider FROM feed_items i JOIN feed_sources s ON s.uuid=i.source_uuid LEFT JOIN feed_states t ON t.source_uuid=i.source_uuid AND t.id=i.id WHERE s.domain_uuid=? AND s.owner_uuid=? AND (?='' OR s.uuid=?) AND (?='' OR instr(lower(i.title),lower(?))>0 OR instr(lower(i.feed),lower(?))>0) AND (?<0 OR i.published_ms<? OR (i.published_ms=? AND (i.source_uuid||':'||i.id)<?)) AND (?<>'unread' OR (CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END)=0) AND (?<>'starred' OR (CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END)=1) AND (?='' OR i.remote_feed=?) AND (?='' OR EXISTS(SELECT 1 FROM json_each(i.remote_categories) WHERE value=?)) ORDER BY i.published_ms DESC,i.source_uuid||':'||i.id DESC LIMIT 101`, domain, owner, source, source, query, query, query, before, before, before, beforeID, filter, filter, remoteFeed, remoteFeed, category, category) args := []any{domain, owner, source, source, query, query, query, before, before, before, beforeID, filter, filter, remoteFeed, remoteFeed, category, category}
extra := ""
if mode == "uncategorized" {
// The uncorrelated list is built once, not a catalog scan per article.
extra = ` AND i.remote_feed IN (SELECT json_extract(c.value,'$.id') FROM feed_sources cs,json_each(cs.remote_catalog) c WHERE cs.uuid=? AND cs.domain_uuid=? AND cs.owner_uuid=? AND json_array_length(c.value,'$.categories')=0)`
args = append(args, source, domain, owner)
}
rows, e := s.DB.QueryContext(ctx, `SELECT i.source_uuid,i.id,i.title,i.url,i.published_ms,i.feed,CASE WHEN s.folder<>'' THEN s.folder ELSE i.folder END,CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END,CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END,COALESCE(t.version,0),s.provider FROM feed_items i JOIN feed_sources s ON s.uuid=i.source_uuid LEFT JOIN feed_states t ON t.source_uuid=i.source_uuid AND t.id=i.id WHERE s.domain_uuid=? AND s.owner_uuid=? AND (?='' OR s.uuid=?) AND (?='' OR instr(lower(i.title),lower(?))>0 OR instr(lower(i.feed),lower(?))>0) AND (?<0 OR i.published_ms<? OR (i.published_ms=? AND (i.source_uuid||':'||i.id)<?)) AND (?<>'unread' OR (CASE WHEN s.provider='local' THEN COALESCE(t.is_read,0) ELSE i.is_read END)=0) AND (?<>'starred' OR (CASE WHEN s.provider='local' THEN COALESCE(t.starred,0) ELSE i.starred END)=1) AND (?='' OR i.remote_feed=?) AND (?='' OR EXISTS(SELECT 1 FROM json_each(i.remote_categories) WHERE value=?))`+extra+` ORDER BY i.published_ms DESC,i.source_uuid||':'||i.id DESC LIMIT 101`, args...)
if e != nil { if e != nil {
return nil, e return nil, e
} }
@@ -465,17 +483,29 @@ func (s *Store) ClaimFeed(ctx context.Context, v FeedSource) (FeedSource, error)
} }
// Failed fetches preserve the previous cache. Version and claim token fence stale workers. // Failed fetches preserve the previous cache. Version and claim token fence stale workers.
func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem, etag, modified, code string, unchanged bool, catalogs ...[]FeedRemoteSubscription) error { func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem, etag, modified, code string, unchanged bool, catalogs ...FeedCatalogSnapshot) error {
if len(catalogs) > 1 { if len(catalogs) > 1 {
return ErrTaskInvalid return ErrTaskInvalid
} }
var catalog string var catalog, folders string
if len(catalogs) == 1 { if len(catalogs) == 1 {
var e error var e error
catalog, e = FeedCatalogJSON(catalogs[0]) catalog, folders, e = catalogs[0].Encode()
if e != nil { if e != nil {
return e return e
} }
if v.Provider == "freshrss" {
membership := map[string][]string{}
for _, sub := range catalogs[0].Subscriptions {
for _, c := range sub.Categories {
membership[sub.ID] = append(membership[sub.ID], c.ID)
}
}
items = append([]FeedItem(nil), items...)
for n := range items {
items[n].RemoteCategories = membership[items[n].RemoteFeed]
}
}
} }
if len(items) > 500 || len(etag) > 1024 || len(modified) > 1024 { if len(items) > 500 || len(etag) > 1024 || len(modified) > 1024 {
return ErrTaskInvalid return ErrTaskInvalid
@@ -511,7 +541,7 @@ func (s *Store) CompleteFeed(ctx context.Context, v FeedSource, items []FeedItem
return nil return nil
} }
if catalog != "" { if catalog != "" {
if _, e = tx.ExecContext(ctx, `UPDATE feed_sources SET remote_catalog=? WHERE uuid=?`, catalog, v.UUID); e != nil { if _, e = tx.ExecContext(ctx, `UPDATE feed_sources SET remote_catalog=?,remote_folders=? WHERE uuid=?`, catalog, folders, v.UUID); e != nil {
return e return e
} }
} }
+85 -10
View File
@@ -18,6 +18,51 @@ type FeedRemoteSubscription struct {
Categories []FeedCategory `json:"categories"` Categories []FeedCategory `json:"categories"`
} }
type FeedCatalogSnapshot struct {
Subscriptions []FeedRemoteSubscription `json:"subscriptions"`
Folders []FeedCategory `json:"folders"`
}
// Merge membership-derived folders with explicit folders, including empty
// ones. IDs, not labels or slash-delimited paths, are the identity boundary.
func FeedFolders(catalog []FeedRemoteSubscription, folders []FeedCategory) ([]FeedCategory, error) {
out := []FeedCategory{}
seen := map[string]string{}
add := func(c FeedCategory) error {
if !ValidFeedRemoteID(c.ID) || len(c.Label) > 512 || !utf8.ValidString(c.Label) {
return ErrTaskInvalid
}
if label, ok := seen[c.ID]; ok {
if label != c.Label {
return ErrTaskInvalid
}
return nil
}
seen[c.ID] = c.Label
out = append(out, c)
if len(out) > 1000 {
return ErrTaskDAVLimit
}
return nil
}
if len(folders) > 1000 {
return nil, ErrTaskDAVLimit
}
for _, c := range folders {
if e := add(c); e != nil {
return nil, e
}
}
for _, sub := range catalog {
for _, c := range sub.Categories {
if e := add(c); e != nil {
return nil, e
}
}
}
return out, nil
}
func ValidFeedRemoteID(id string) bool { func ValidFeedRemoteID(id string) bool {
return id != "" && len(id) <= 2048 && utf8.ValidString(id) && !strings.ContainsAny(id, "\x00\r\n") return id != "" && len(id) <= 2048 && utf8.ValidString(id) && !strings.ContainsAny(id, "\x00\r\n")
} }
@@ -59,17 +104,47 @@ func FeedCatalogJSON(catalog []FeedRemoteSubscription) (string, error) {
return string(raw), nil return string(raw), nil
} }
func (s *Store) FeedCatalog(ctx context.Context, domain, owner, source string) ([]FeedRemoteSubscription, error) { // Validate the complete snapshot before persisting or reporting fetch success.
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil { func (v FeedCatalogSnapshot) Encode() (string, string, error) {
return nil, e catalog, e := FeedCatalogJSON(v.Subscriptions)
if e != nil {
return "", "", e
} }
var raw string folders, e := FeedFolders(v.Subscriptions, v.Folders)
if e := s.DB.QueryRowContext(ctx, `SELECT remote_catalog FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, source, domain, owner).Scan(&raw); e != nil { if e != nil {
return nil, e return "", "", e
} }
var catalog []FeedRemoteSubscription raw, e := json.Marshal(folders)
if e := json.Unmarshal([]byte(raw), &catalog); e != nil { if e != nil {
return nil, e return "", "", e
} }
return catalog, nil if len(raw)+len(catalog) > 1<<20 {
return "", "", ErrTaskDAVLimit
}
return catalog, string(raw), nil
}
func (s *Store) FeedCatalog(ctx context.Context, domain, owner, source string) ([]FeedRemoteSubscription, error) {
v, e := s.FeedCatalogSnapshot(ctx, domain, owner, source)
return v.Subscriptions, e
}
func (s *Store) FeedCatalogSnapshot(ctx context.Context, domain, owner, source string) (FeedCatalogSnapshot, error) {
v := FeedCatalogSnapshot{}
if e := feedActor(ctx, s.DB, domain, owner, false); e != nil {
return v, e
}
var raw, folders string
if e := s.DB.QueryRowContext(ctx, `SELECT remote_catalog,remote_folders FROM feed_sources WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, source, domain, owner).Scan(&raw, &folders); e != nil {
return v, e
}
if e := json.Unmarshal([]byte(raw), &v.Subscriptions); e != nil {
return v, e
}
if e := json.Unmarshal([]byte(folders), &v.Folders); e != nil {
return v, e
}
var e error
v.Folders, e = FeedFolders(v.Subscriptions, v.Folders)
return v, e
} }
+38
View File
@@ -188,3 +188,41 @@ func TestFeedActionsMigrationRollbackAndRepeat(t *testing.T) {
t.Fatal(status, e) t.Fatal(status, e)
} }
} }
func TestFeedFoldersMigrationRollbackAndRepeat(t *testing.T) {
st := newSchemaTestStore(t)
ctx := context.Background()
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", feedMigrations[:5]); e != nil {
t.Fatal(e)
}
const catalog = `[{"id":"feed/1","title":"Title","categories":[{"id":"category","label":"Folder"}]}]`
if _, e := st.DB.Exec(`INSERT INTO feed_sources(uuid,domain_uuid,owner_uuid,provider,title,folder,url,version,enabled,interval_seconds,lease,next_ms,remote_catalog) VALUES('s','d','u','freshrss','Title','','https://example.org',7,1,300,'worker',999,?);
INSERT INTO feed_actions(domain_uuid,owner_uuid,request_id,source_uuid,item_id,field,desired,source_version,status,created_ms) VALUES('d','u','r','s','i','read',1,7,'queued',1)`, catalog); e != nil {
t.Fatal(e)
}
broken := append([]db.SQLMigration(nil), feedMigrations...)
broken[5].Statements = append(append([]string(nil), feedMigrations[5].Statements...), `INSERT INTO no_such_feed_table VALUES(1)`)
if e := db.ApplySQLiteMigrations(ctx, st.DB, "feeds", broken); e == nil {
t.Fatal("expected failure")
}
var count int
if e := st.DB.QueryRow(`SELECT count(*) FROM pragma_table_info('feed_sources') WHERE name='remote_folders'`).Scan(&count); e != nil || count != 0 {
t.Fatal("partial schema", count, e)
}
for range 2 {
if e := st.ensureSchemaComponent("feeds"); e != nil {
t.Fatal(e)
}
}
var version, next int
var got, folders, lease, status string
if e := st.DB.QueryRow(`SELECT version,next_ms,lease,remote_catalog,remote_folders FROM feed_sources WHERE uuid='s'`).Scan(&version, &next, &lease, &got, &folders); e != nil || version != 7 || next != 999 || lease != "worker" || got != catalog || folders != "[]" {
t.Fatal("existing state changed", version, next, lease, got, folders, e)
}
if e := st.DB.QueryRow(`SELECT status FROM feed_actions WHERE request_id='r'`).Scan(&status); e != nil || status != "queued" {
t.Fatal("pending action changed", status, e)
}
if e := st.DB.QueryRow(`PRAGMA integrity_check`).Scan(&status); e != nil || status != "ok" {
t.Fatal(status, e)
}
}
+28
View File
@@ -35,6 +35,34 @@ func ValidTaskWikiPrefix(p string) bool {
return true return true
} }
// Expand only the documented placeholders. Subject is one safe path component,
// never a source of separators or URI operators. Callers choose the timezone.
func ExpandWikiPrefix(template, subject string, now time.Time) (string, error) {
if len(template) > 500 || !utf8.ValidString(template) || !utf8.ValidString(subject) {
return "", ErrTaskInvalid
}
name := strings.Map(func(r rune) rune {
if unicode.IsControl(r) || unicode.IsSpace(r) || strings.ContainsRune(`/\?#%:{}<>"|`, r) {
return '-'
}
return r
}, subject)
name = strings.Trim(name, " .-_")
for len(name) > 180 {
_, n := utf8.DecodeLastRuneInString(name)
name = name[:len(name)-n]
}
name = strings.Trim(name, " .-_")
if name == "" {
name = "untitled"
}
result := strings.NewReplacer("{YYYY}", now.Format("2006"), "{MM}", now.Format("01"), "{DD}", now.Format("02"), "{Subject}", name).Replace(template)
if strings.ContainsAny(result, "{}") || !ValidTaskWikiPrefix(result) {
return "", ErrTaskInvalid
}
return result, nil
}
// The CLI derives the request UUID from origin, user and Message-ID (or a raw // 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. // mail hash). Keep subjects in the title, never in the URL's identity segment.
func TaskCaptureWikiPath(prefix, title, request string) string { func TaskCaptureWikiPath(prefix, title, request string) string {
+9 -2
View File
@@ -64,6 +64,7 @@ type TaskPreferences struct {
Version int64 `json:"version"` Version int64 `json:"version"`
ProjectUUID string `json:"project_uuid"` ProjectUUID string `json:"project_uuid"`
WikiPrefix string `json:"wiki_prefix"` WikiPrefix string `json:"wiki_prefix"`
RSSLinkMode string `json:"rss_link_mode"`
AssigneeUUID string `json:"assignee_uuid"` AssigneeUUID string `json:"assignee_uuid"`
DueDays *int `json:"due_days"` DueDays *int `json:"due_days"`
StartDays *int `json:"start_days"` StartDays *int `json:"start_days"`
@@ -80,7 +81,7 @@ type TaskPreferences struct {
} }
func (s *Store) TaskPreferences(ctx context.Context, domain, actor string) (TaskPreferences, error) { func (s *Store) TaskPreferences(ctx context.Context, domain, actor string) (TaskPreferences, error) {
p := TaskPreferences{AssigneeUUID: actor, Complexity: 1, ReminderTime: "09:00", DigestTime: "09:00", Timezone: "UTC"} p := TaskPreferences{AssigneeUUID: actor, Complexity: 1, ReminderTime: "09:00", DigestTime: "09:00", Timezone: "UTC", RSSLinkMode: "tab"}
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil { if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
return p, err return p, err
} }
@@ -120,7 +121,13 @@ func (s *Store) SaveTaskPreferences(ctx context.Context, domain, actor string, p
if s.ReadOnly { if s.ReadOnly {
return p, ErrReadOnly return p, ErrReadOnly
} }
if !ValidTaskWikiPrefix(p.WikiPrefix) { if _, err := ExpandWikiPrefix(p.WikiPrefix, "subject", now); err != nil {
return p, ErrTaskInvalid
}
if p.RSSLinkMode == "" {
p.RSSLinkMode = "tab"
}
if p.RSSLinkMode != "tab" && p.RSSLinkMode != "embedded" {
return p, ErrTaskInvalid return p, ErrTaskInvalid
} }
// Older clients do not send this field. Preserve their default clock. // Older clients do not send this field. Preserve their default clock.
+32
View File
@@ -0,0 +1,32 @@
package store
import (
"strings"
"testing"
"time"
)
func TestExpandWikiPrefix(t *testing.T) {
now := time.Date(2026, 12, 31, 18, 0, 0, 0, time.UTC).In(time.FixedZone("JST", 9*3600))
for _, tt := range []struct{ template, subject, want string }{
{"/notes/{YYYY}/{MM}/{DD}/{Subject}", "日本語 / ../ x?y#z", "/notes/2027/01/01/日本語---..--x-y-z"},
{"/notes/{Subject}", "../", "/notes/untitled"},
{"/notes/{Subject}", "{YYYY}", "/notes/YYYY"},
{"/notes", "unused", "/notes"},
{"", "", ""},
} {
got, err := ExpandWikiPrefix(tt.template, tt.subject, now)
if err != nil || got != tt.want {
t.Fatalf("%q: %q, %v; want %q", tt.template, got, err, tt.want)
}
}
for _, bad := range []string{"/notes/{YY}", "/notes/{{Subject}}", "/notes/{Subject", "/a/../b/{YYYY}", "/_/api/{Subject}", "relative/{YYYY}"} {
if _, err := ExpandWikiPrefix(bad, "subject", now); err == nil {
t.Fatal("accepted", bad)
}
}
got, err := ExpandWikiPrefix("/notes/{Subject}", strings.Repeat("日本語", 200), now)
if err != nil || len(got) > len("/notes/")+180 || !ValidTaskWikiPrefix(got) {
t.Fatal(got, err)
}
}
+4
View File
@@ -1,4 +1,8 @@
.feeds-page{height:100dvh;overflow:hidden;display:flex;flex-direction:column;background:var(--bg);color:var(--fg)} .feeds-page{height:100dvh;overflow:hidden;display:flex;flex-direction:column;background:var(--bg);color:var(--fg)}
.feed-external{width:calc(100vw - 1.5rem);height:calc(100dvh - 1.5rem);max-width:none;max-height:none;box-sizing:border-box;margin:auto;padding:0;background:var(--bg,#111);color:var(--fg);border:1px solid var(--border,#8885);border-radius:.5rem;overflow:hidden}.feed-external[open]{display:flex;flex-direction:column}.feed-external::backdrop{background:#0009}.feed-external-bar{display:flex;align-items:center;gap:.5rem;padding:.3rem .5rem;flex-shrink:0}.feed-external-bar span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.feed-external-bar a{padding:.3rem;text-decoration:none;font-size:1.2rem}.feed-external iframe{flex:1;width:100%;min-height:0;border:0;background:#fff}@media(max-width:600px){.feed-external{width:100vw;height:100dvh;border:0;border-radius:0}}
.feed-help{display:flex;align-items:center;gap:.5rem;padding:.25rem 0;font-size:.78rem;flex-shrink:0}.feed-help[hidden]{display:none}.feed-help span{flex:1;min-width:0;overflow-wrap:anywhere}.feed-help button{flex-shrink:0}
.feed-capture{width:min(42rem,calc(100vw - 2rem));max-height:calc(100dvh - 2rem);box-sizing:border-box;overflow:auto;background:var(--bg,#111);color:var(--fg);border:1px solid var(--border,#8885);border-radius:.6rem;padding:1rem;box-shadow:0 1rem 4rem #0007}.feed-capture::backdrop{background:#0008}.feed-capture-heading{display:flex;align-items:center;justify-content:space-between;gap:.5rem}.feed-capture h2{font-size:1.05rem;margin:0}.feed-capture-heading,.feed-capture-field,.feed-capture-tokens,.feed-capture-destination,.feed-capture-actions,.feed-capture .feed-warning{grid-column:1/-1}#feeds-app .feed-capture form{grid-template-columns:1fr 1fr;gap:.65rem}#feeds-app .feed-capture .feed-capture-check{display:flex;align-items:center;gap:.4rem}#feeds-app .feed-capture input[type=checkbox]{width:1rem;min-height:1rem;flex-shrink:0}.feed-capture-check:has([name=confirm]){grid-column:1/-1}.feed-capture-tokens,.feed-capture-actions{display:flex;gap:.35rem;flex-wrap:wrap}.feed-capture-actions{justify-content:flex-end}.feed-capture-destination{font-size:.75rem;overflow-wrap:anywhere;opacity:.8}.feed-capture .feed-warning:empty{display:none}.feed-capture-field:has([name=prefix]){position:relative}.feed-capture-field:has([name=prefix]) a{position:absolute;right:.1rem;top:0;text-decoration:none}@media(max-width:600px){#feeds-app .feed-capture form{grid-template-columns:1fr}.feed-capture{padding:.75rem}}
.feed-folder-row{display:flex;align-items:center;min-width:0}#feeds-app .feed-folder-toggle{flex:0 0 1.7rem;border:0;padding:.15rem;min-width:1.7rem}#feeds-app .feed-folder-name{display:flex;align-items:center;gap:.3rem;flex:1;min-width:0;text-align:left;border:0;font-size:.78rem;padding:.2rem}.feed-folder-name span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.feed-folder-name svg{width:1rem;height:1rem;flex-shrink:0;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linejoin:round}.feed-folder>.feed-subscriptions{padding-left:1.1rem;border-left:1px solid var(--border,#8885);margin-left:.8rem}.feed-catalog .feed-subscriptions[hidden]{display:none}.feed-folder small{font-size:.7rem;opacity:.7;padding:.3rem}.feed-catalog button[aria-current=true]{background:color-mix(in srgb,var(--accent,#659de4) 22%,transparent)!important}.feed-tree-all{width:100%;text-align:left}.feed-folders{min-width:0}
.feed-layout.action-history{grid-template-columns:12rem minmax(0,1fr)}.feed-layout.action-history .feed-index{display:none}.feed-layout.action-history #feed-reader{display:block}.feed-history-controls{display:flex;gap:.3rem;flex-wrap:wrap;margin:.4rem 0}.feed-history-controls select{max-width:100%}.feed-history table{width:100%;table-layout:fixed;border-collapse:collapse;font-size:.8rem}.feed-history th,.feed-history td{padding:.3rem .4rem;text-align:left;border-bottom:1px solid var(--border,#8885);vertical-align:middle;overflow-wrap:anywhere}.feed-history th:first-child{width:7.5rem}.feed-history th:nth-child(3){width:6rem}.feed-history th:last-child{width:7rem}.feed-history td:nth-child(2)>span,.feed-history small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.feed-history small{font-size:.72rem;opacity:.7}.feed-history-buttons{display:flex;gap:.2rem;justify-content:flex-end}.feed-history-buttons a{display:inline-flex;align-items:center;justify-content:center;min-width:1.8rem;min-height:1.8rem;border:1px solid var(--border,#6666);border-radius:.2rem;text-decoration:none}.feed-history [data-state=unknown],.feed-history [data-state=conflict],.feed-history [data-state=failed]{color:var(--danger,#e57a7a)}.feed-history .feed-warning:empty{display:none} .feed-layout.action-history{grid-template-columns:12rem minmax(0,1fr)}.feed-layout.action-history .feed-index{display:none}.feed-layout.action-history #feed-reader{display:block}.feed-history-controls{display:flex;gap:.3rem;flex-wrap:wrap;margin:.4rem 0}.feed-history-controls select{max-width:100%}.feed-history table{width:100%;table-layout:fixed;border-collapse:collapse;font-size:.8rem}.feed-history th,.feed-history td{padding:.3rem .4rem;text-align:left;border-bottom:1px solid var(--border,#8885);vertical-align:middle;overflow-wrap:anywhere}.feed-history th:first-child{width:7.5rem}.feed-history th:nth-child(3){width:6rem}.feed-history th:last-child{width:7rem}.feed-history td:nth-child(2)>span,.feed-history small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.feed-history small{font-size:.72rem;opacity:.7}.feed-history-buttons{display:flex;gap:.2rem;justify-content:flex-end}.feed-history-buttons a{display:inline-flex;align-items:center;justify-content:center;min-width:1.8rem;min-height:1.8rem;border:1px solid var(--border,#6666);border-radius:.2rem;text-decoration:none}.feed-history [data-state=unknown],.feed-history [data-state=conflict],.feed-history [data-state=failed]{color:var(--danger,#e57a7a)}.feed-history .feed-warning:empty{display:none}
@media(max-width:1100px){.feed-layout.action-history{grid-template-columns:10rem minmax(0,1fr)}} @media(max-width:1100px){.feed-layout.action-history{grid-template-columns:10rem minmax(0,1fr)}}
@media(max-width:600px){.feed-history thead{display:none}.feed-history tbody,.feed-history tr{display:block}.feed-history tr{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.15rem .3rem;padding:.5rem 0;border-bottom:1px solid var(--border,#8885)}.feed-history td{display:block;border:0;padding:0 .2rem;min-width:0}.feed-history td:first-child{grid-column:1;grid-row:1;font-size:.7rem;opacity:.7}.feed-history td:nth-child(2){grid-column:1;grid-row:2}.feed-history td:nth-child(3){grid-column:1;grid-row:3;font-size:.75rem}.feed-history td:last-child{grid-column:2;grid-row:1/4;align-self:center}.feed-history-buttons a{min-width:2.3rem;min-height:2.3rem}} @media(max-width:600px){.feed-history thead{display:none}.feed-history tbody,.feed-history tr{display:block}.feed-history tr{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.15rem .3rem;padding:.5rem 0;border-bottom:1px solid var(--border,#8885)}.feed-history td{display:block;border:0;padding:0 .2rem;min-width:0}.feed-history td:first-child{grid-column:1;grid-row:1;font-size:.7rem;opacity:.7}.feed-history td:nth-child(2){grid-column:1;grid-row:2}.feed-history td:nth-child(3){grid-column:1;grid-row:3;font-size:.75rem}.feed-history td:last-child{grid-column:2;grid-row:1/4;align-self:center}.feed-history-buttons a{min-width:2.3rem;min-height:2.3rem}}
+68 -24
View File
@@ -10,7 +10,9 @@
async function request(path,options={}){const response=await fetch(api+path,{credentials:'same-origin',cache:'no-store',...options,headers:{'Content-Type':'application/json',...options.headers}});if(response.redirected||response.status===401)throw Error(t('Please sign in again.','再度ログインしてください。'));const data=await response.json().catch(()=>({}));if(!response.ok)throw Error(response.status===412?t('Changed elsewhere or refresh is cooling down. Reload before retrying.','別の操作と競合したか、更新の待機時間中です。再読込して確認してください。'):t('Request failed: ','操作に失敗しました: ')+(data.error||response.status));return data;} async function request(path,options={}){const response=await fetch(api+path,{credentials:'same-origin',cache:'no-store',...options,headers:{'Content-Type':'application/json',...options.headers}});if(response.redirected||response.status===401)throw Error(t('Please sign in again.','再度ログインしてください。'));const data=await response.json().catch(()=>({}));if(!response.ok)throw Error(response.status===412?t('Changed elsewhere or refresh is cooling down. Reload before retrying.','別の操作と競合したか、更新の待機時間中です。再読込して確認してください。'):t('Request failed: ','操作に失敗しました: ')+(data.error||response.status));return data;}
const post=(path,body)=>request(path,{method:'POST',body:JSON.stringify(body)}); const post=(path,body)=>request(path,{method:'POST',body:JSON.stringify(body)});
let sources=[],items=[],selected=-1,currentSource='',filter='',search='',next=null,loading=false,seq=0,detailSeq=0,editing=false,controller,detailController; let sources=[],items=[],selected=-1,currentSource='',filter='',search='',next=null,loading=false,seq=0,detailSeq=0,editing=false,controller,detailController;
let remoteFeed='',remoteCategory='',catalog=[],catalogSeq=0,catalogController; let remoteFeed='',remoteCategory='',categoryMode='',catalog=[],catalogFolders=[],catalogLoaded=false,catalogSearch='',catalogSeq=0,catalogController;
const folderStates=new Map();
function folderState(source){if(folderStates.has(source))return folderStates.get(source);let state=new Set();try{const raw=localStorage.getItem('pageswiki.feed-folders.v1:'+source);if(raw&&raw.length<=1<<20){const saved=JSON.parse(raw);if(Array.isArray(saved)&&saved.length<=1001)state=new Set(saved.filter(x=>typeof x==='string'&&x.length<=2100));}}catch{}folderStates.set(source,state);return state;}
let actionTimer; let actionTimer;
const pendingAction=a=>a&&['queued','preparing','sending','unknown','check_queued','checking'].includes(a.status); const pendingAction=a=>a&&['queued','preparing','sending','unknown','check_queued','checking'].includes(a.status);
async function updateAction(item){const version=detailSeq;const data=await request('action?'+new URLSearchParams({source:item.source,id:item.id}));if(version!==detailSeq||items[selected]!==item||editing)return;item.action=data.action;item.actionLoading=false; async function updateAction(item){const version=detailSeq;const data=await request('action?'+new URLSearchParams({source:item.source,id:item.id}));if(version!==detailSeq||items[selected]!==item||editing)return;item.action=data.action;item.actionLoading=false;
@@ -25,10 +27,12 @@
if(writable)toolbar.append(button('+',t('Add source','購読元を追加'),()=>sourceForm())); if(writable)toolbar.append(button('+',t('Add source','購読元を追加'),()=>sourceForm()));
const transfer=button('⇄','OPML',opmlForm);transfer.id='feed-opml';toolbar.append(transfer); const transfer=button('⇄','OPML',opmlForm);transfer.id='feed-opml';toolbar.append(transfer);
const history=button('◷',t('Operation history','操作履歴'),actionHistory);history.id='feed-history';toolbar.append(history); const history=button('◷',t('Operation history','操作履歴'),actionHistory);history.id='feed-history';toolbar.append(history);
toolbar.append(button('?',t('Keyboard shortcuts','キー操作'),showHelp)); const helpButton=button('?',t('Keyboard shortcuts','キー操作'),showHelp),help=el('div',undefined,'feed-help');help.id='feed-help';help.hidden=true;helpButton.setAttribute('aria-controls',help.id);helpButton.setAttribute('aria-expanded','false');
help.append(el('span',t('j/k move · Enter read · Esc index · / search · n unread · m read/unread · * star · r refresh · ? / Esc close help','j/k 移動 · Enter 本文 · Esc 一覧 · / 検索 · n 次の未読 · m 既読/未読 · * star · r 更新 · ? / Esc ヘルプを閉じる')),button('×',t('Close help','ヘルプを閉じる'),hideHelp));status.before(help);toolbar.append(helpButton);
let debounce;searchbox.addEventListener('input',()=>{clearTimeout(debounce);debounce=setTimeout(()=>{search=searchbox.value.trim();load(false).catch(report);},180);}); let debounce;searchbox.addEventListener('input',()=>{clearTimeout(debounce);debounce=setTimeout(()=>{search=searchbox.value.trim();load(false).catch(report);},180);});
const columns=document.getElementById('feed-columns');for(const s of ['',t('Date','日付'),t('Feed','配信元'),t('Subject','件名')])columns.append(el('span',s)); const columns=document.getElementById('feed-columns');for(const s of ['',t('Date','日付'),t('Feed','配信元'),t('Subject','件名')])columns.append(el('span',s));
function showHelp(){status.textContent=t('j/k move · Enter read · Esc index · / search · n unread · m read/unread · * star · r refresh','j/k 移動 · Enter 本文 · Esc 一覧 · / 検索 · n 次の未読 · m 既読/未読 · * star · r 更新');} function hideHelp(){if(help.contains(document.activeElement))helpButton.focus();help.hidden=true;helpButton.setAttribute('aria-expanded','false');}
function showHelp(){if(!help.hidden){hideHelp();return;}help.hidden=false;helpButton.setAttribute('aria-expanded','true');}
function date(ms){return ms?new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{month:'2-digit',day:'2-digit'}).format(new Date(ms)):'—';} function date(ms){return ms?new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{month:'2-digit',day:'2-digit'}).format(new Date(ms)):'—';}
function closeReader(){editing=false;detailSeq++;detailController?.abort();layout.classList.remove('reading','action-history');rows.focus();} function closeReader(){editing=false;detailSeq++;detailController?.abort();layout.classList.remove('reading','action-history');rows.focus();}
function drawSources(){sourcesView.replaceChildren();const all=button(t('All sources','すべての購読元'),'',()=>chooseSource(''));sourcesView.append(all);let folder=null; function drawSources(){sourcesView.replaceChildren();const all=button(t('All sources','すべての購読元'),'',()=>chooseSource(''));sourcesView.append(all);let folder=null;
@@ -38,46 +42,76 @@
} }
} }
function drawCatalog(parent){ function drawCatalog(parent){
const nav=el('div',undefined,'feed-catalog'),categories=el('select'),names=new Map();categories.ariaLabel=t('FreshRSS category','FreshRSSカテゴリ');categories.id='feed-category'; if(!catalogLoaded)return;
for(const sub of catalog)for(const cat of sub.categories)names.set(cat.id,cat.label); const nav=el('nav',undefined,'feed-catalog');nav.ariaLabel=t('FreshRSS folders','FreshRSSのフォルダ');const source=currentSource,state=folderState(source),groups=new Map();
for(const [id,name]of [['',t('All categories','すべてのカテゴリ')],...Array.from(names).sort((a,b)=>a[1].localeCompare(b[1]))]){const option=el('option',name);option.value=id;categories.append(option);}categories.value=remoteCategory; for(const c of catalogFolders)groups.set(c.id,{id:c.id,label:c.label,mode:'',subs:[]});
categories.onchange=()=>{remoteCategory=categories.value;remoteFeed='';drawSources();load(false).catch(report);};nav.append(categories); const uncategorized={id:'',label:t('Uncategorized','未分類'),mode:'uncategorized',subs:[]};
const find=el('input');find.type='search';find.placeholder=find.ariaLabel=t('Find subscription','購読を絞り込む');nav.append(find); for(const sub of catalog){if(!sub.categories.length)uncategorized.subs.push(sub);for(const c of sub.categories){if(!groups.has(c.id))groups.set(c.id,{id:c.id,label:c.label,mode:'',subs:[]});groups.get(c.id).subs.push(sub);}}
const list=el('div',undefined,'feed-subscriptions');nav.append(list);parent.append(nav); const ordered=[...groups.values()].sort((a,b)=>a.label.localeCompare(b.label)||a.id.localeCompare(b.id));if(uncategorized.subs.length)ordered.push(uncategorized);
const draw=()=>{list.replaceChildren();const subs=catalog.filter(sub=>(!remoteCategory||sub.categories.some(c=>c.id===remoteCategory))&&sub.title.toLocaleLowerCase().includes(find.value.toLocaleLowerCase())).sort((a,b)=>a.title.localeCompare(b.title)); const key=g=>JSON.stringify([g.mode,g.id]),valid=new Set(ordered.map(key));for(const k of state)if(!valid.has(k))state.delete(k);
const add=(id,title)=>{const b=button(title,title,async()=>{remoteFeed=id;for(const node of list.children)node.setAttribute('aria-current',String(node===b));layout.classList.remove('sources-open');await load(false);});b.dataset.feed=id;b.setAttribute('aria-current',String(id===remoteFeed));list.append(b);};add('',t('All subscriptions','すべての購読'));for(const sub of subs)add(sub.id,sub.title||sub.id); const persist=()=>{try{localStorage.setItem('pageswiki.feed-folders.v1:'+source,JSON.stringify([...state]));}catch{}};
const mark=()=>{for(const b of nav.querySelectorAll('button[data-category]'))b.setAttribute('aria-current',String((b.dataset.feed||'')===remoteFeed&&b.dataset.category===remoteCategory&&b.dataset.mode===categoryMode));};
const choose=async(id,mode,feed='')=>{remoteCategory=id;categoryMode=mode;remoteFeed=feed;mark();layout.classList.remove('sources-open');await load(false);};
const select=(label,g,feed='')=>{const b=button(label,label,()=>choose(g.id,g.mode,feed));b.dataset.category=g.id;b.dataset.mode=g.mode;if(feed)b.dataset.feed=feed;b.setAttribute('aria-current',String(feed===remoteFeed&&g.id===remoteCategory&&g.mode===categoryMode));return b;};
const all=select(t('All subscriptions','すべての購読'),{id:'',mode:''});all.className='feed-tree-all';nav.append(all);
const find=el('input');find.type='search';find.placeholder=find.ariaLabel=t('Find subscription / folder','購読・フォルダを検索');find.value=catalogSearch;nav.append(find);
const list=el('div',undefined,'feed-folders');nav.append(list);parent.append(nav);
function subscriptions(target,subs,g){let count=0;const sorted=[...subs].sort((a,b)=>a.title.localeCompare(b.title)||a.id.localeCompare(b.id));const more=button('↓',t('More subscriptions','購読元をさらに表示'),append);
function append(){more.remove();for(const sub of sorted.slice(count,count+50)){const group=g||{id:'',mode:''},b=select(sub.title||sub.id,group,sub.id);b.title=(sub.title||sub.id)+(sub.categories.length?' · '+sub.categories.map(c=>c.label).join(' / '):'');target.append(b);}count+=50;if(count<sorted.length)target.append(more);}append();
}
const draw=()=>{list.replaceChildren();const query=find.value.trim().toLocaleLowerCase();catalogSearch=find.value;
if(query){const matches=catalog.filter(s=>s.title.toLocaleLowerCase().includes(query)||s.categories.some(c=>c.label.toLocaleLowerCase().includes(query)));const results=el('div',undefined,'feed-subscriptions');list.append(results);subscriptions(results,matches,null);if(!matches.length)results.append(el('small',t('No subscriptions','購読なし')));return;}
for(const g of ordered){const group=el('div',undefined,'feed-folder'),line=el('div',undefined,'feed-folder-row'),children=el('div',undefined,'feed-subscriptions');group.dataset.category=g.id;group.dataset.mode=g.mode;
const name=select(g.label||g.id,g);name.className='feed-folder-name';name.title=(g.label||g.id)+(g.id?' · '+g.id:'');const label=el('span',g.label||g.id);name.replaceChildren();
const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'),path=document.createElementNS(svg.namespaceURI,'path');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');path.setAttribute('d','M3 6h7l2 3h9v11H3z');svg.append(path);name.append(svg,label);
let open=state.has(key(g));const toggle=button('',t('Expand folder','フォルダを展開')+' · '+g.label,()=>{open=!open;if(open)state.add(key(g));else state.delete(key(g));persist();paint();});toggle.className='feed-folder-toggle';
const paint=()=>{toggle.textContent=open?'▾':'▸';toggle.setAttribute('aria-expanded',String(open));toggle.title=toggle.ariaLabel=(open?t('Collapse folder','フォルダを折りたたむ'):t('Expand folder','フォルダを展開'))+' · '+g.label;children.hidden=!open;children.replaceChildren();if(open){subscriptions(children,g.subs,g);if(!g.subs.length)children.append(el('small',t('Empty folder','空のフォルダ')));}};
line.append(toggle,name);group.append(line,children);list.append(group);paint();
}mark();
};find.oninput=draw;draw(); };find.oninput=draw;draw();
} }
async function loadCatalog(){catalogController?.abort();catalogController=new AbortController();const version=++catalogSeq;catalog=[];if(sources.find(s=>s.uuid===currentSource)?.provider!=='freshrss')return; async function loadCatalog(){catalogController?.abort();catalogController=new AbortController();const version=++catalogSeq;catalogLoaded=false;catalog=[];catalogFolders=[];if(sources.find(s=>s.uuid===currentSource)?.provider!=='freshrss')return;
const data=await request('catalog?'+new URLSearchParams({source:currentSource}),{signal:catalogController.signal});if(version!==catalogSeq)return;catalog=data.subscriptions;drawSources(); const data=await request('catalog?'+new URLSearchParams({source:currentSource}),{signal:catalogController.signal});if(version!==catalogSeq)return;catalog=data.subscriptions;catalogFolders=data.folders||[];catalogLoaded=true;drawSources();
} }
async function chooseSource(id){currentSource=id;remoteFeed=remoteCategory='';catalog=[];drawSources();layout.classList.remove('reading');editing=false;await Promise.all([loadCatalog(),load(false)]);if(sources.find(s=>s.uuid===id)?.provider!=='freshrss')layout.classList.remove('sources-open');} async function chooseSource(id){currentSource=id;remoteFeed=remoteCategory=categoryMode=catalogSearch='';catalog=[];catalogFolders=[];catalogLoaded=false;drawSources();layout.classList.remove('reading');editing=false;await Promise.all([loadCatalog(),load(false)]);if(sources.find(s=>s.uuid===id)?.provider!=='freshrss')layout.classList.remove('sources-open');}
function rowNode(item,index){const row=el('div',undefined,'feed-row'+(item.read?'':' unread'));row.id='feed-row-'+index;row.setAttribute('role','option');row.setAttribute('aria-selected',String(index===selected));for(const text of [(item.starred?'★':item.read?' ':'●'),date(item.published_ms),item.feed||sources.find(s=>s.uuid===item.source)?.title||'',item.title||t('(Untitled)','(無題)')])row.append(el('span',text));row.title=item.title;row.onclick=()=>open(index).catch(report);return row;} function rowNode(item,index){const row=el('div',undefined,'feed-row'+(item.read?'':' unread'));row.id='feed-row-'+index;row.setAttribute('role','option');row.setAttribute('aria-selected',String(index===selected));for(const text of [(item.starred?'★':item.read?' ':'●'),date(item.published_ms),item.feed||sources.find(s=>s.uuid===item.source)?.title||'',item.title||t('(Untitled)','(無題)')])row.append(el('span',text));row.title=item.title;row.onclick=()=>open(index).catch(report);return row;}
function drawRows(){rows.replaceChildren(...items.map(rowNode));more.hidden=!next;more.textContent='↓';more.title=more.ariaLabel=t('More articles','続きを表示');if(!items.length)rows.append(el('p',t('No articles','記事なし'),'feed-warning'));} function drawRows(){rows.replaceChildren(...items.map(rowNode));more.hidden=!next;more.textContent='↓';more.title=more.ariaLabel=t('More articles','続きを表示');if(!items.length)rows.append(el('p',t('No articles','記事なし'),'feed-warning'));}
async function load(append){if(append&&(!next||loading))return;controller?.abort();controller=new AbortController();const version=++seq;loading=true;more.disabled=true; async function load(append){if(append&&(!next||loading))return;controller?.abort();controller=new AbortController();const version=++seq;loading=true;more.disabled=true;
try{const q=new URLSearchParams({source:currentSource,filter,q:search,feed:remoteFeed,category:remoteCategory});if(append){q.set('before',next.ms);q.set('key',next.key);}const data=await request('items?'+q,{signal:controller.signal});if(version!==seq)return; try{const q=new URLSearchParams({source:currentSource,filter,q:search,feed:remoteFeed,category:remoteCategory,category_mode:categoryMode});if(append){q.set('before',next.ms);q.set('key',next.key);}const data=await request('items?'+q,{signal:controller.signal});if(version!==seq)return;
if(!append){detailSeq++;items=[];selected=-1;reader.replaceChildren();layout.classList.remove('reading','action-history');editing=false;}items.push(...data.items);const last=data.items.at(-1);next=data.more&&last?{ms:last.published_ms,key:last.source+':'+last.id}:null;drawRows();status.textContent=''; if(!append){detailSeq++;items=[];selected=-1;reader.replaceChildren();layout.classList.remove('reading','action-history');editing=false;}items.push(...data.items);const last=data.items.at(-1);next=data.more&&last?{ms:last.published_ms,key:last.source+':'+last.id}:null;drawRows();status.textContent='';
}finally{if(version===seq){loading=false;more.disabled=false;}} }finally{if(version===seq){loading=false;more.disabled=false;}}
} }
more.onclick=()=>load(true).catch(report); more.onclick=()=>load(true).catch(report);
async function reload(){sources=(await request('sources')).sources;if(!sources.some(s=>s.uuid===currentSource)){currentSource=remoteFeed=remoteCategory='';}drawSources();await loadCatalog();if(remoteCategory&&!catalog.some(s=>s.categories.some(c=>c.id===remoteCategory)))remoteCategory='';if(remoteFeed&&!catalog.some(s=>s.id===remoteFeed))remoteFeed='';drawSources();await load(false);} async function reload(){sources=(await request('sources')).sources;if(!sources.some(s=>s.uuid===currentSource)){currentSource=remoteFeed=remoteCategory=categoryMode='';}drawSources();await loadCatalog();if(remoteCategory&&!catalogFolders.some(c=>c.id===remoteCategory))remoteCategory='';if(remoteFeed&&!catalog.some(s=>s.id===remoteFeed))remoteFeed='';drawSources();await load(false);}
async function queueRefresh(){const targets=sources.filter(s=>s.enabled&&(!currentSource||currentSource===s.uuid));for(const s of targets)await post('sources/'+s.uuid+'/refresh',{version:s.version});status.textContent=t('Refresh queued','更新を予約しました');} async function queueRefresh(){const targets=sources.filter(s=>s.enabled&&(!currentSource||currentSource===s.uuid));for(const s of targets)await post('sources/'+s.uuid+'/refresh',{version:s.version});status.textContent=t('Refresh queued','更新を予約しました');}
toolbar.append(button('⟳',t('Reload cached list','取得済み一覧を再読込'),reload)); toolbar.append(button('⟳',t('Reload cached list','取得済み一覧を再読込'),reload));
async function open(index){if(index<0||index>=items.length)return;editing=false;selected=index;detailController?.abort();detailController=new AbortController();const version=++detailSeq;for(const [i,row]of [...rows.querySelectorAll('.feed-row')].entries())row.setAttribute('aria-selected',String(i===index));rows.setAttribute('aria-activedescendant','feed-row-'+index);document.getElementById('feed-row-'+index)?.scrollIntoView({block:'nearest'}); async function open(index){if(index<0||index>=items.length)return;editing=false;selected=index;detailController?.abort();detailController=new AbortController();const version=++detailSeq;for(const [i,row]of [...rows.querySelectorAll('.feed-row')].entries())row.setAttribute('aria-selected',String(i===index));rows.setAttribute('aria-activedescendant','feed-row-'+index);document.getElementById('feed-row-'+index)?.scrollIntoView({block:'nearest'});
layout.classList.remove('action-history');layout.classList.add('reading');reader.replaceChildren(el('p',t('Loading…','読み込み中…')));const item=(await request('item?'+new URLSearchParams({source:items[index].source,id:items[index].id}),{signal:detailController.signal})).item;if(version!==detailSeq)return;items[index]=item;if(item.provider==='freshrss'){item.actionLoading=true;renderItem(item);await updateAction(item);}else renderItem(item); layout.classList.remove('action-history');layout.classList.add('reading');reader.replaceChildren(el('p',t('Loading…','読み込み中…')));const item=(await request('item?'+new URLSearchParams({source:items[index].source,id:items[index].id}),{signal:detailController.signal})).item;if(version!==detailSeq)return;items[index]=item;if(item.provider==='freshrss'){item.actionLoading=true;renderItem(item);await updateAction(item);}else renderItem(item);
} }
function openArticleLink(event,href){
if(root.dataset.linkMode!=='embedded'||event.button!==0||event.ctrlKey||event.metaKey||event.altKey||event.shiftKey)return;
let url;try{url=new URL(href,location.href);}catch{return;}if(!['https:','http:'].includes(url.protocol)||url.origin===location.origin||url.username||url.password)return;
event.preventDefault();const wasEditing=editing;editing=true;detailSeq++;clearTimeout(actionTimer);
const dialog=el('dialog',undefined,'feed-external'),bar=el('div',undefined,'feed-external-bar'),name=el('span',url.hostname),external=el('a','↗'),frame=el('iframe');dialog.ariaLabel=t('Original article preview','原文プレビュー');name.title=url.href;
external.href=url.href;external.target='_blank';external.rel='noopener noreferrer';external.title=external.ariaLabel=t('Open in a new tab if embedding is blocked','埋め込みできない場合は新しいタブで開く');
const close=button('×',t('Close preview','プレビューを閉じる'),()=>dialog.close());bar.append(name,external,close);frame.title=dialog.ariaLabel;frame.setAttribute('sandbox','allow-scripts');frame.referrerPolicy='no-referrer';frame.src=url.href;dialog.append(bar,frame);root.append(dialog);
dialog.addEventListener('keydown',e=>e.stopPropagation());dialog.addEventListener('close',()=>{frame.src='about:blank';dialog.remove();editing=wasEditing;const item=items[selected];if(item&&!editing)pollAction(item);});dialog.showModal();close.focus();
}
function renderItem(item){reader.replaceChildren();const actions=el('div',undefined,'feed-actions');actions.append(button('←',t('Back to list','一覧へ戻る'),closeReader)); function renderItem(item){reader.replaceChildren();const actions=el('div',undefined,'feed-actions');actions.append(button('←',t('Back to list','一覧へ戻る'),closeReader));
const canWrite=item.provider==='local'||sources.some(s=>s.uuid===item.source&&s.enabled&&s.write_enabled); const canWrite=item.provider==='local'||sources.some(s=>s.uuid===item.source&&s.enabled&&s.write_enabled);
const read=button(item.read?'●':'○',t('Toggle read state (m)','既読/未読 (m)'),()=>setState(!item.read,item.starred));const star=button(item.starred?'★':'☆',t('Toggle star (*)','star切替 (*)'),()=>setState(item.read,!item.starred));read.disabled=star.disabled=!writable||!canWrite||item.actionLoading||pendingAction(item.action);actions.append(read,star); const read=button(item.read?'●':'○',t('Toggle read state (m)','既読/未読 (m)'),()=>setState(!item.read,item.starred));const star=button(item.starred?'★':'☆',t('Toggle star (*)','star切替 (*)'),()=>setState(item.read,!item.starred));read.disabled=star.disabled=!writable||!canWrite||item.actionLoading||pendingAction(item.action);actions.append(read,star);
if(item.action){const a=item.action,labels={queued:t('Queued','送信待ち'),preparing:t('Checking','確認中'),sending:t('Sending','送信中'),checking:t('Rechecking','再確認中'),check_queued:t('Recheck queued','再確認待ち'),confirmed:t('Confirmed','確認済み'),unknown:t('Result unknown — recheck after one minute','結果不明 — 1分後に再確認'),conflict:t('Changed elsewhere — review before retrying','状態が一致しません。確認してから再操作してください'),failed:t('Not sent','未送信'),cancelled:t('Cancelled','中止')};const label=labels[a.status]||a.status; if(item.action){const a=item.action,labels={queued:t('Queued','送信待ち'),preparing:t('Checking','確認中'),sending:t('Sending','送信中'),checking:t('Rechecking','再確認中'),check_queued:t('Recheck queued','再確認待ち'),confirmed:t('Confirmed','確認済み'),unknown:t('Result unknown — recheck after one minute','結果不明 — 1分後に再確認'),conflict:t('Changed elsewhere — review before retrying','状態が一致しません。確認してから再操作してください'),failed:t('Not sent','未送信'),cancelled:t('Cancelled','中止')};const label=labels[a.status]||a.status;
const state=button(a.status==='unknown'?'↻':pendingAction(a)?'◷':a.status==='confirmed'?'✓':'!',label,async()=>{if(a.status!=='unknown')return;await post('action/check',{request_id:a.request_id});await updateAction(item);});state.className='feed-action-status';state.disabled=a.status!=='unknown'||!writable;state.title+=(a.error?' · '+a.error:'');actions.append(state);} const state=button(a.status==='unknown'?'↻':pendingAction(a)?'◷':a.status==='confirmed'?'✓':'!',label,async()=>{if(a.status!=='unknown')return;await post('action/check',{request_id:a.request_id});await updateAction(item);});state.className='feed-action-status';state.disabled=a.status!=='unknown'||!writable;state.title+=(a.error?' · '+a.error:'');actions.append(state);}
if(item.url){const a=el('a',undefined,'feed-original');a.title=a.ariaLabel=t('Open original','原文を開く');a.href=item.url;a.target='_blank';a.rel='noopener noreferrer';const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'),path=document.createElementNS(svg.namespaceURI,'path');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');path.setAttribute('d','M14 3h7v7M21 3l-11 11M10 5H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5');svg.append(path);a.append(svg);actions.append(a);} if(item.url){const a=el('a',undefined,'feed-original');a.title=a.ariaLabel=t('Open original','原文を開く');a.href=item.url;a.target='_blank';a.rel='noopener noreferrer';const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'),path=document.createElementNS(svg.namespaceURI,'path');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');path.setAttribute('d','M14 3h7v7M21 3l-11 11M10 5H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5');svg.append(path);a.append(svg);actions.append(a);}
const original=actions.querySelector('.feed-original');if(original)original.addEventListener('click',e=>openArticleLink(e,original.href));
if(item.url&&root.dataset.shareX==='true'){const share=el('a',undefined,'feed-share-x feed-original');share.title=share.ariaLabel=t('Share original article on X','原文の記事をXでシェア');share.href='https://twitter.com/intent/tweet?'+new URLSearchParams({text:item.title||'',url:item.url});share.target='_blank';share.rel='noopener noreferrer';const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'),path=document.createElementNS(svg.namespaceURI,'path');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');path.setAttribute('d','M18 3h3l-7 8 8 10h-6l-5-7-6 7H2l7-9L2 3h6l5 6z');svg.append(path);share.append(svg);actions.append(share);}
if(writable)actions.append(button(t('+ Wiki / Task','+ Wiki・タスク'),t('Capture with attribution','出典付きで取り込む'),()=>captureForm(item))); if(writable)actions.append(button(t('+ Wiki / Task','+ Wiki・タスク'),t('Capture with attribution','出典付きで取り込む'),()=>captureForm(item)));
reader.append(actions,el('h1',item.title||t('(Untitled)','(無題)')),el('p',(item.feed||'')+' · '+(item.published_ms?new Date(item.published_ms).toLocaleString():t('Date unknown','日付不明')),'feed-meta')); reader.append(actions,el('h1',item.title||t('(Untitled)','(無題)')),el('p',(item.feed||'')+' · '+(item.published_ms?new Date(item.published_ms).toLocaleString():t('Date unknown','日付不明')),'feed-meta'));
if(item.provider==='freshrss'&&!canWrite)read.title=star.title=t('FreshRSS · read only','FreshRSS · 読取専用'); if(item.provider==='freshrss'&&!canWrite)read.title=star.title=t('FreshRSS · read only','FreshRSS · 読取専用');
const body=el('div',undefined,'feed-body'); const body=el('div',undefined,'feed-body');
if(item.body_html){body.classList.add('feed-body-html');const shadow=body.attachShadow({mode:'open'}),style=el('style',':host{display:block;overflow-wrap:anywhere;line-height:1.6}p{margin:.6em 0}h1,h2,h3{line-height:1.3}a{color:var(--link,var(--accent,#659de4))}pre{white-space:pre-wrap;overflow-wrap:anywhere;padding:.5em;background:color-mix(in srgb,currentColor 5%,transparent)}blockquote{margin:.5em 0;padding-left:1em;border-left:3px solid var(--border,#8885)}table{border-collapse:collapse;max-width:100%;display:block;overflow:auto}th,td{padding:.3em .6em;border:1px solid var(--border,#8885)}');const content=el('div');content.innerHTML=item.body_html;shadow.append(style,content);} if(item.body_html){body.classList.add('feed-body-html');const shadow=body.attachShadow({mode:'open'}),style=el('style',':host{display:block;overflow-wrap:anywhere;line-height:1.6}p{margin:.6em 0}h1,h2,h3{line-height:1.3}a{color:var(--link,var(--accent,#659de4))}pre{white-space:pre-wrap;overflow-wrap:anywhere;padding:.5em;background:color-mix(in srgb,currentColor 5%,transparent)}blockquote{margin:.5em 0;padding-left:1em;border-left:3px solid var(--border,#8885)}table{border-collapse:collapse;max-width:100%;display:block;overflow:auto}th,td{padding:.3em .6em;border:1px solid var(--border,#8885)}');const content=el('div');content.innerHTML=item.body_html;shadow.append(style,content);}
else body.textContent=item.body||t('(No article text)','(本文なし)'); else body.textContent=item.body||t('(No article text)','(本文なし)');
if(body.shadowRoot)body.shadowRoot.addEventListener('click',e=>{const link=e.target.closest?.('a[href]');if(link)openArticleLink(e,link.href);});
reader.append(body); reader.append(body);
pollAction(item); pollAction(item);
} }
@@ -153,22 +187,32 @@
form.onsubmit=async event=>{event.preventDefault();save.disabled=true;try{await post('sources',{uuid:sourceID,version:source?.version||0,provider:provider.value,title:title.value,folder:folder.value,url:url.value,interval_seconds:Number(interval.value)*60,enabled:enabled.checked,write_enabled:provider.value==='freshrss'&&write.checked,username:user.value,password:password.value});password.value='';await reload();status.textContent=t('Saved','保存しました');}catch(e){report(e);}finally{save.disabled=false;}};title.focus(); form.onsubmit=async event=>{event.preventDefault();save.disabled=true;try{await post('sources',{uuid:sourceID,version:source?.version||0,provider:provider.value,title:title.value,folder:folder.value,url:url.value,interval_seconds:Number(interval.value)*60,enabled:enabled.checked,write_enabled:provider.value==='freshrss'&&write.checked,username:user.value,password:password.value});password.value='';await reload();status.textContent=t('Saved','保存しました');}catch(e){report(e);}finally{save.disabled=false;}};title.focus();
} }
function captureForm(item){ function captureForm(item){
editing=true;detailSeq++;reader.replaceChildren();const form=el('form');reader.append(form);form.append(el('h1',t('Attributed Wiki note / task','出典付きWikiメモ・タスク'))); editing=true;detailSeq++;clearTimeout(actionTimer);const dialog=el('dialog',undefined,'feed-capture'),form=el('form');dialog.ariaLabel=t('Capture Wiki / task','Wiki・タスク追加');reader.append(dialog);dialog.append(form);
const close=()=>{if(!busy)dialog.close();},heading=el('div',undefined,'feed-capture-heading');heading.append(el('h2',t('Capture Wiki / task','Wiki・タスク追加')),button('×',t('Close','閉じる'),close));form.append(heading);
dialog.addEventListener('close',()=>{clearTimeout(previewTimer);generation++;dialog.remove();editing=false;pollAction(item);});dialog.addEventListener('cancel',e=>{if(busy)e.preventDefault();});dialog.addEventListener('keydown',e=>e.stopPropagation());
const title=field(form,t('Title','件名'),item.title.slice(0,250));title.required=true;title.maxLength=300; const title=field(form,t('Title','件名'),item.title.slice(0,250));title.required=true;title.maxLength=300;
const task=field(form,t('Also create a task','タスクを作成する'),'','checkbox');task.disabled=root.dataset.tasks!=='true'; const task=field(form,t('Also create a task','タスクを作成する'),'','checkbox');task.disabled=root.dataset.tasks!=='true';
const prefix=field(form,t('Wiki parent Path (empty = task only)','Wikiの親Path(空ならタスクのみ)'),'');prefix.placeholder='/notes/feeds';prefix.required=true; const prefix=field(form,t('Wiki parent Path (empty = task only)','Wikiの親Path(空ならタスクのみ)'),root.dataset.wikiPrefix||'');prefix.placeholder='/notes/feeds';prefix.required=true;prefix.maxLength=500;
if(root.dataset.tasks==='true'){const settings=el('a','⚙');settings.href='/-/sys/config?panel=organizer';settings.target='_blank';settings.rel='noopener';settings.title=settings.ariaLabel=t('Configure default Wiki parent path in personal settings','個人設定で既定のWiki親Pathを設定');prefix.parentElement.append(settings);}
const tokens=el('div',undefined,'feed-capture-tokens');for(const token of ['{YYYY}','{MM}','{DD}','{Subject}'])tokens.append(button(token,t('Insert ','挿入: ')+token,()=>{prefix.setRangeText(token,prefix.selectionStart??prefix.value.length,prefix.selectionEnd??prefix.value.length,'end');prefix.dispatchEvent(new Event('input',{bubbles:true}));prefix.focus();}));form.append(tokens);
const destination=el('output',undefined,'feed-capture-destination');destination.ariaLabel=t('Destination','保存先');form.append(destination);
const notes=field(form,t('Your note','メモ'));const copy=field(form,t('Include cached text (explicit copy)','取得済み本文も保存する(明示コピー)'),'','checkbox'); const notes=field(form,t('Your note','メモ'));const copy=field(form,t('Include cached text (explicit copy)','取得済み本文も保存する(明示コピー)'),'','checkbox');
const confirm=field(form,t('I checked the destination publication policy and the material to copy.','保存先の公開範囲と、コピーする内容を確認しました。'),'','checkbox');confirm.required=true; const confirm=field(form,t('I checked the destination publication policy and the material to copy.','保存先の公開範囲と、コピーする内容を確認しました。'),'','checkbox');confirm.required=true;
const validate=()=>{prefix.required=!task.checked;confirm.required=!!prefix.value.trim()||!task.checked;};task.onchange=prefix.oninput=validate; for(const [name,input]of Object.entries({title,task,prefix,notes,copy,confirm})){input.name=name;if(input.type==='checkbox')input.parentElement.classList.add('feed-capture-check');else input.parentElement.classList.add('feed-capture-field');}
const save=el('button',t('Create','作成'));save.type='submit';form.append(save,button(t('Cancel','取消'),'',()=>{editing=false;renderItem(item);}));let pending=null; const notice=el('p',undefined,'feed-warning');notice.role='status';const actions=el('div',undefined,'feed-capture-actions'),save=el('button',t('Create','作成'));save.type='submit';actions.append(button(t('Cancel','取消'),'',close),save);form.append(notice,actions);
form.onsubmit=async event=>{event.preventDefault();const body='Source: '+item.url+'\nFeed: '+item.feed+'\n\n'+notes.value+(copy.checked?'\n\n'+item.body:'');const spec={title:title.value,notes:notes.value,prefix:prefix.value.trim(),body,task:task.checked};const fingerprint=JSON.stringify(spec);if(!pending||pending.fingerprint!==fingerprint)pending={fingerprint,request_id:crypto.randomUUID()};save.disabled=true; let pending=null,generation=0,previewTimer,resolved=null,busy=false;const requestID=crypto.randomUUID();
const preview=()=>{clearTimeout(previewTimer);const n=++generation;resolved=null;confirm.checked=false;prefix.required=!task.checked;confirm.required=!!prefix.value.trim()||!task.checked;save.disabled=true;notice.textContent='';destination.textContent='';
if(!prefix.value.trim()){resolved='';destination.textContent=task.checked?t('Task only','タスクのみ'):'';save.disabled=!task.checked;return;}
previewTimer=setTimeout(async()=>{try{const data=await post('capture-preview',{prefix:prefix.value.trim(),title:title.value});if(n!==generation||!dialog.isConnected)return;resolved=data.prefix;destination.textContent=resolved.replace(/\/$/,'')+'/'+(task.checked?'mail-':'rss-')+requestID;save.disabled=false;}catch(e){if(n===generation&&dialog.isConnected){notice.textContent=t('Check the parent Path and placeholders.','親Pathとプレースホルダを確認してください。');}}},180);
};task.onchange=prefix.oninput=title.oninput=preview;copy.onchange=()=>{confirm.checked=false;};dialog.showModal();preview();title.focus();
form.onsubmit=async event=>{event.preventDefault();if(busy||resolved===null||!form.reportValidity())return;const body='Source: '+item.url+'\nFeed: '+item.feed+'\n\n'+notes.value+(copy.checked?'\n\n'+item.body:'');const spec={title:title.value,notes:notes.value,prefix:resolved,body,task:task.checked};const fingerprint=JSON.stringify(spec);if(!pending||pending.fingerprint!==fingerprint)pending={fingerprint,request_id:requestID};busy=true;save.disabled=true;
try{let data;if(task.checked){const input={request_id:pending.request_id,title:title.value,notes:(notes.value+'\nSource: '+item.url).trim()};if(spec.prefix){input.wiki_prefix=spec.prefix;input.wiki_body=body;}const res=await fetch('/_/api/v1/extension/organizer.tasks/capture',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(input)});data=await res.json().catch(()=>({}));if(!res.ok||res.redirected)throw Error(t('Capture failed: ','作成に失敗: ')+(data.error||res.status));} try{let data;if(task.checked){const input={request_id:pending.request_id,title:title.value,notes:(notes.value+'\nSource: '+item.url).trim()};if(spec.prefix){input.wiki_prefix=spec.prefix;input.wiki_body=body;}const res=await fetch('/_/api/v1/extension/organizer.tasks/capture',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(input)});data=await res.json().catch(()=>({}));if(!res.ok||res.redirected)throw Error(t('Capture failed: ','作成に失敗: ')+(data.error||res.status));}
else data=await post('note',{request_id:pending.request_id,source:item.source,id:item.id,path:spec.prefix.replace(/\/$/,'')+'/rss-'+pending.request_id,title:title.value,body,confirm_publication:confirm.checked}); else data=await post('note',{request_id:pending.request_id,source:item.source,id:item.id,path:spec.prefix.replace(/\/$/,'')+'/rss-'+pending.request_id,title:title.value,body,confirm_publication:confirm.checked});
reader.replaceChildren(el('p',t('Created.','作成しました。')));if(data.item){const a=el('a',t('Open task','タスクを開く'));a.href='/v/plan/task/'+encodeURIComponent(data.item.uuid);reader.append(a);}const page=data.page_uuid||data.item?.page_uuid;if(page){const a=el('a',t('Open Wiki','Wikiを開く'));a.href='/v/uuid:'+encodeURIComponent(page);reader.append(el('p'),a);}editing=false; dialog.replaceChildren(el('h2',t('Created','作成しました')));if(data.item){const a=el('a',t('Open task','タスクを開く'));a.href='/v/plan/task/'+encodeURIComponent(data.item.uuid);dialog.append(a);}const page=data.page_uuid||data.item?.page_uuid;if(page){const a=el('a',t('Open Wiki','Wikiを開く'));a.href='/v/uuid:'+encodeURIComponent(page);dialog.append(el('p'),a);}const done=button(t('Close','閉じる'),'',close);dialog.append(el('p'),done);done.focus();
}catch(e){report(e);}finally{save.disabled=false;} }catch(e){notice.textContent=e.message;}finally{busy=false;save.disabled=resolved===null;}
}; };
} }
document.addEventListener('keydown',event=>{if(event.defaultPrevented||event.isComposing||event.ctrlKey||event.altKey||event.metaKey)return;const input=event.target.closest?.('input,textarea,select,[contenteditable=true]');if(input){if(event.key==='Escape'){event.target.blur();event.preventDefault();}return;}if(event.key==='Enter'&&event.target.closest?.('button,a'))return;if(editing){if(event.key==='Escape'){closeReader();event.preventDefault();}return;} document.addEventListener('keydown',event=>{if(event.defaultPrevented||event.isComposing||event.ctrlKey||event.altKey||event.metaKey)return;if(event.key==='Escape'&&!help.hidden){hideHelp();event.preventDefault();return;}const input=event.target.closest?.('input,textarea,select,[contenteditable=true]');if(input){if(event.key==='Escape'){event.target.blur();event.preventDefault();}return;}if(event.key==='?'&&!help.hidden){hideHelp();event.preventDefault();return;}if(event.key==='Enter'&&event.target.closest?.('button,a'))return;if(editing){if(event.key==='Escape'){closeReader();event.preventDefault();}return;}
let action;switch(event.key){case 'j':case 'ArrowDown':action=()=>open(Math.min(items.length-1,selected+1));break;case 'k':case 'ArrowUp':action=()=>open(Math.max(0,selected-1));break;case 'Enter':case 'l':action=()=>open(Math.max(0,selected));break;case 'Escape':case 'h':action=closeReader;break;case '/':action=()=>searchbox.focus();break;case 'r':if(writable)action=queueRefresh;break;case 'm':action=()=>setState(!items[selected]?.read,!!items[selected]?.starred);break;case '*':action=()=>setState(!!items[selected]?.read,!items[selected]?.starred);break;case 'n':action=()=>{const i=items.findIndex((x,i)=>i>selected&&!x.read);if(i>=0)return open(i);};break;case '?':action=showHelp;break;}if(action){event.preventDefault();Promise.resolve().then(action).catch(report);} let action;switch(event.key){case 'j':case 'ArrowDown':action=()=>open(Math.min(items.length-1,selected+1));break;case 'k':case 'ArrowUp':action=()=>open(Math.max(0,selected-1));break;case 'Enter':case 'l':action=()=>open(Math.max(0,selected));break;case 'Escape':case 'h':action=closeReader;break;case '/':action=()=>searchbox.focus();break;case 'r':if(writable)action=queueRefresh;break;case 'm':action=()=>setState(!items[selected]?.read,!!items[selected]?.starred);break;case '*':action=()=>setState(!!items[selected]?.read,!items[selected]?.starred);break;case 'n':action=()=>{const i=items.findIndex((x,i)=>i>selected&&!x.read);if(i>=0)return open(i);};break;case '?':action=showHelp;break;}if(action){event.preventDefault();Promise.resolve().then(action).catch(report);}
}); });
(async()=>{const q=new URLSearchParams(location.search);currentSource=q.get('source')||'';await reload();if(q.has('settings')&&writable){sourceForm();return;}if(q.has('id')&&currentSource){let index=items.findIndex(x=>x.source===currentSource&&x.id===q.get('id'));if(index<0){const data=await request('item?'+new URLSearchParams({source:currentSource,id:q.get('id')}));items.unshift(data.item);index=0;drawRows();}await open(index);}})().catch(report); (async()=>{const q=new URLSearchParams(location.search);currentSource=q.get('source')||'';await reload();if(q.has('settings')&&writable){sourceForm();return;}if(q.has('id')&&currentSource){let index=items.findIndex(x=>x.source===currentSource&&x.id===q.get('id'));if(index<0){const data=await request('item?'+new URLSearchParams({source:currentSource,id:q.get('id')}));items.unshift(data.item);index=0;drawRows();}await open(index);}})().catch(report);
+6 -4
View File
@@ -5,7 +5,8 @@
const word={tasks:['Tasks','タスク'],report:['Activity report','達成度・作業レポート'],settings:['Task defaults and email','タスクの既定値・メール'],contacts:['Contacts','連絡先'],completed:['Completed','完了件数'],points:['Points','ポイント'],work:['Work hours','作業時間'],focus:['Pomodoro hours','集中時間'],save:['Save','保存'],saved:['Saved','保存しました'],refresh:['Refresh','更新'],project_uuid:['Default project','既定のプロジェクト'],assignee_uuid:['Assignee UUID (annotation only)','担当者UUID(管理用メモ)'],due_days:['Due in days','期限までの日数'],start_days:['Start in days','着手までの日数'],planned_days:['Plan in days','取り組む日までの日数'],review_days:['Review in days','見直しまでの日数'],estimate_minutes:['Estimated minutes','見込み工数(分)'],complexity:['Complexity (1–5)','複雑度(1〜5)'],digest_enabled:['Email daily task list to my account email','毎日のやることリストを自分のメールに送る'],digest_time:['Delivery time','配信時刻'],timezone:['IANA timezone','タイムゾーン(IANA)'],none:['None','なし'],empty:['No records in this period.','この期間の記録はありません。'],partial:['Partial results: narrow the period.','件数上限に達しました。期間を狭めてください。'],error:['Request failed. Input is retained.','処理に失敗しました。入力は保持しています。'],email_required:['Set your account email first.','先にプロフィールにメールアドレスを設定してください。'],smtp_unavailable:['Ask an administrator to configure SMTP.','管理者によるSMTP設定が必要です。']}; const word={tasks:['Tasks','タスク'],report:['Activity report','達成度・作業レポート'],settings:['Task defaults and email','タスクの既定値・メール'],contacts:['Contacts','連絡先'],completed:['Completed','完了件数'],points:['Points','ポイント'],work:['Work hours','作業時間'],focus:['Pomodoro hours','集中時間'],save:['Save','保存'],saved:['Saved','保存しました'],refresh:['Refresh','更新'],project_uuid:['Default project','既定のプロジェクト'],assignee_uuid:['Assignee UUID (annotation only)','担当者UUID(管理用メモ)'],due_days:['Due in days','期限までの日数'],start_days:['Start in days','着手までの日数'],planned_days:['Plan in days','取り組む日までの日数'],review_days:['Review in days','見直しまでの日数'],estimate_minutes:['Estimated minutes','見込み工数(分)'],complexity:['Complexity (1–5)','複雑度(1〜5)'],digest_enabled:['Email daily task list to my account email','毎日のやることリストを自分のメールに送る'],digest_time:['Delivery time','配信時刻'],timezone:['IANA timezone','タイムゾーン(IANA)'],none:['None','なし'],empty:['No records in this period.','この期間の記録はありません。'],partial:['Partial results: narrow the period.','件数上限に達しました。期間を狭めてください。'],error:['Request failed. Input is retained.','処理に失敗しました。入力は保持しています。'],email_required:['Set your account email first.','先にプロフィールにメールアドレスを設定してください。'],smtp_unavailable:['Ask an administrator to configure SMTP.','管理者によるSMTP設定が必要です。']};
const t=k=>(word[k]||[k,k])[ja?1:0],el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;}; const t=k=>(word[k]||[k,k])[ja?1:0],el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
Object.assign(word,{notify_due:['Notify on due dates','期限日に通知する'],notify_planned:['Notify on planned dates','取り組む日に通知する'],reminder_time:['Default notification time','通知の既定時刻']}); Object.assign(word,{notify_due:['Notify on due dates','期限日に通知する'],notify_planned:['Notify on planned dates','取り組む日に通知する'],reminder_time:['Default notification time','通知の既定時刻']});
Object.assign(word,{wiki_prefix:['Default Wiki parent path for mail','メール本文の既定Wiki親Path']}); Object.assign(word,{wiki_prefix:['Default Wiki parent path for mail / RSS','メール・RSS取り込みの既定Wiki親Path']});
Object.assign(word,{rss_link_mode:['Open RSS article links','RSSの記事リンクの開き方']});
const status=root.querySelector('#productivity-status'),content=root.querySelector('#productivity-content'); const status=root.querySelector('#productivity-status'),content=root.querySelector('#productivity-content');
root.querySelectorAll('[data-word]').forEach(n=>n.textContent=t(n.dataset.word));root.querySelector('h1,h2,h3').textContent=t(root.dataset.view==='settings'?'settings':'report'); root.querySelectorAll('[data-word]').forEach(n=>n.textContent=t(n.dataset.word));root.querySelector('h1,h2,h3').textContent=t(root.dataset.view==='settings'?'settings':'report');
async function request(path,options={}){const timeout=AbortSignal.timeout(15000);const r=await fetch(api+path,{credentials:'same-origin',cache:'no-store',signal:signal?AbortSignal.any([signal,timeout]):timeout,...options,headers:{'Content-Type':'application/json',...options.headers}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(t(d.error||'error'));return d;} async function request(path,options={}){const timeout=AbortSignal.timeout(15000);const r=await fetch(api+path,{credentials:'same-origin',cache:'no-store',signal:signal?AbortSignal.any([signal,timeout]):timeout,...options,headers:{'Content-Type':'application/json',...options.headers}});const d=await r.json().catch(()=>({}));if(!r.ok||r.redirected)throw Error(t(d.error||'error'));return d;}
@@ -14,11 +15,12 @@
const data=await request('preferences'),p=data.preferences;const form=el('form');form.className='productivity-settings';const fields={}; const data=await request('preferences'),p=data.preferences;const form=el('form');form.className='productivity-settings';const fields={};
const projects=await request('items?kind=project&view=all&limit=100'); const projects=await request('items?kind=project&view=all&limit=100');
if(p.project_uuid&&!projects.items.some(x=>x.uuid===p.project_uuid)){try{const current=await request('items/'+encodeURIComponent(p.project_uuid));if(current.item.kind==='project')projects.items.unshift(current.item);}catch{ /* Keep the saved reference visible without exposing inaccessible data. */ }} if(p.project_uuid&&!projects.items.some(x=>x.uuid===p.project_uuid)){try{const current=await request('items/'+encodeURIComponent(p.project_uuid));if(current.item.kind==='project')projects.items.unshift(current.item);}catch{ /* Keep the saved reference visible without exposing inaccessible data. */ }}
for(const key of ['project_uuid','wiki_prefix','assignee_uuid','due_days','start_days','planned_days','review_days','estimate_minutes','complexity','notify_due','notify_planned','reminder_time','digest_enabled','digest_time','timezone']){ for(const key of ['project_uuid','wiki_prefix','rss_link_mode','assignee_uuid','due_days','start_days','planned_days','review_days','estimate_minutes','complexity','notify_due','notify_planned','reminder_time','digest_enabled','digest_time','timezone']){
if(key==='notify_due')form.append(el('h3',ja?'新規タスクのInbox通知':'Inbox reminders for new tasks')); if(key==='notify_due')form.append(el('h3',ja?'新規タスクのInbox通知':'Inbox reminders for new tasks'));
if(key==='digest_enabled')form.append(el('h3',ja?'日次メール':'Daily email')); if(key==='digest_enabled')form.append(el('h3',ja?'日次メール':'Daily email'));
const label=el('label',t(key));label.className='productivity-setting';const input=el(key==='project_uuid'?'select':'input');input.name=key; const label=el('label',t(key));label.className='productivity-setting';const input=el(['project_uuid','rss_link_mode'].includes(key)?'select':'input');input.name=key;
if(key==='project_uuid'){const empty=el('option',t('none'));empty.value='';input.append(empty);for(const item of projects.items){const option=el('option',item.title);option.value=item.uuid;input.append(option);}if(p[key]&&!projects.items.some(x=>x.uuid===p[key])){const current=el('option',p[key]);current.value=p[key];input.append(current);}} if(key==='project_uuid'){const empty=el('option',t('none'));empty.value='';input.append(empty);for(const item of projects.items){const option=el('option',item.title);option.value=item.uuid;input.append(option);}if(p[key]&&!projects.items.some(x=>x.uuid===p[key])){const current=el('option',p[key]);current.value=p[key];input.append(current);}}
else if(key==='rss_link_mode'){for(const [value,label]of [['tab',ja?'新しいタブ':'New tab'],['embedded',ja?'本文上のポップアップ':'Popup over article']]){const option=el('option',label);option.value=value;input.append(option);}p[key] ||= 'tab';}
else if(['digest_enabled','notify_due','notify_planned'].includes(key)){input.type='checkbox';input.checked=!!p[key];input.setAttribute('role','switch');} else if(['digest_enabled','notify_due','notify_planned'].includes(key)){input.type='checkbox';input.checked=!!p[key];input.setAttribute('role','switch');}
else if(key.endsWith('_days')||['estimate_minutes','complexity'].includes(key)){input.type='number';input.min=key==='complexity'?1:0;input.max=key.endsWith('_days')?3650:key==='complexity'?5:10080;input.step=1;} else if(key.endsWith('_days')||['estimate_minutes','complexity'].includes(key)){input.type='number';input.min=key==='complexity'?1:0;input.max=key.endsWith('_days')?3650:key==='complexity'?5:10080;input.step=1;}
else input.type=['digest_time','reminder_time'].includes(key)?'time':'text'; else input.type=['digest_time','reminder_time'].includes(key)?'time':'text';
@@ -26,7 +28,7 @@
if(key==='project_uuid')for(const option of input.options)option.defaultSelected=option.selected=option.value===(p.project_uuid||''); if(key==='project_uuid')for(const option of input.options)option.defaultSelected=option.selected=option.value===(p.project_uuid||'');
else if(input.type==='checkbox')input.defaultChecked=input.checked; else if(input.type==='checkbox')input.defaultChecked=input.checked;
else input.defaultValue=input.value; else input.defaultValue=input.value;
if(key==='wiki_prefix'){input.placeholder='/private/mail';input.maxLength=500;const help=el('p',ja?'メール本文をWikiに保存する親Pathです。空欄ならプロジェクトのWiki配下を使います。保存した本文はそのPathの公開範囲・閲覧権限に従います。':'Parent path for mail Wiki pages. If blank, use the project Wiki subtree. Saved mail inherits the destination path’s visibility and read permissions.');help.className='productivity-note';form.append(help);} if(key==='wiki_prefix'){input.placeholder='/notes/{YYYY}/{MM}/{Subject}';input.maxLength=500;const help=el('p',ja?'メール・RSS取り込みの保存先。{YYYY}・{MM}・{DD}は作成日(ドメインのタイムゾーン)、{Subject}は件名です。RSSでは入力欄を空にすればタスクのみ作成できます。設定が空欄の場合、メールはプロジェクトのWiki配下を使い、RSSは未入力になります。保存内容はそのPathの公開範囲・閲覧権限に従います。':'Mail / RSS capture destination. {YYYY}, {MM}, {DD} use the creation date in the Domain timezone; {Subject} uses the title. Clear the RSS field for task-only capture. If unset, mail uses the project Wiki subtree and RSS leaves the field blank. Content inherits destination visibility and permissions.');help.className='productivity-note';form.append(help);}
if(key==='reminder_time'){const help=el('p',ja?'新規タスクの対応する日付が設定されている場合だけ通知します。既存タスクは変更しません。通知時刻は保存時のドメインのタイムゾーン('+data.timezone+')を使用します。':'Reminders apply only to new tasks with the corresponding date. Existing tasks are unchanged. Times use the Domain timezone on save ('+data.timezone+').');help.className='productivity-note';form.append(help);} if(key==='reminder_time'){const help=el('p',ja?'新規タスクの対応する日付が設定されている場合だけ通知します。既存タスクは変更しません。通知時刻は保存時のドメインのタイムゾーン('+data.timezone+')を使用します。':'Reminders apply only to new tasks with the corresponding date. Existing tasks are unchanged. Times use the Domain timezone on save ('+data.timezone+').');help.className='productivity-note';form.append(help);}
} }
const note=el('p',ja?'日数は作成日からの暦日です。空欄は未設定、0は当日。担当者の指定では閲覧権限は付与されません。メールは今日の計画・期限到来分を最大100件送ります。SMTPは管理者設定を使用し、配信時刻にはキュー待ちの遅延があります。':'Offsets are calendar days from creation; blank means unset, 0 means today. Assignment does not grant access. Email includes up to 100 tasks planned or due today, using administrator SMTP settings. Queue delays may apply.');note.className='productivity-note';form.append(note); const note=el('p',ja?'日数は作成日からの暦日です。空欄は未設定、0は当日。担当者の指定では閲覧権限は付与されません。メールは今日の計画・期限到来分を最大100件送ります。SMTPは管理者設定を使用し、配信時刻にはキュー待ちの遅延があります。':'Offsets are calendar days from creation; blank means unset, 0 means today. Assignment does not grant access. Email includes up to 100 tasks planned or due today, using administrator SMTP settings. Queue delays may apply.');note.className='productivity-note';form.append(note);
+3 -3
View File
@@ -1,9 +1,9 @@
{{ define "feeds.gohtml" }}<!doctype html> {{ define "feeds.gohtml" }}<!doctype html>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> <html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{ T "feeds.title" }} · {{ .WikiName }}</title> <title>{{ T "feeds.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/feeds.css?v=6"></head> <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/feeds.css?v=8"></head>
<body class="mode-view organizer-page feeds-page"><header class="topbar"><div class="brand"><a href="/">{{ .WikiName }}</a></div>{{ template "auth-menu" . }}</header>{{ template "organizer-nav" . }} <body class="mode-view organizer-page feeds-page"><header class="topbar"><div class="brand"><a href="/">{{ .WikiName }}</a></div>{{ template "auth-menu" . }}</header>{{ template "organizer-nav" . }}
<main id="feeds-app" data-writable="{{ .FeedWritable }}" data-tasks="{{ .TasksEnabled }}"> <main id="feeds-app" data-writable="{{ .FeedWritable }}" data-tasks="{{ .TasksEnabled }}" data-wiki-prefix="{{ .FeedWikiPrefix }}" data-share-x="{{ .FeedShareX }}" data-link-mode="{{ .FeedLinkMode }}">
<div id="feed-toolbar"></div><p id="feed-status" role="status" aria-live="polite"></p> <div id="feed-toolbar"></div><p id="feed-status" role="status" aria-live="polite"></p>
<div class="feed-layout"><aside id="feed-sources" aria-label="{{ T "feeds.title" }}"></aside><section class="feed-index"><div id="feed-columns" aria-hidden="true"></div><div id="feed-rows" tabindex="0" role="listbox" aria-label="{{ T "feeds.title" }}"></div><button type="button" id="feed-more" hidden>↓</button></section><article id="feed-reader" tabindex="0"></article></div> <div class="feed-layout"><aside id="feed-sources" aria-label="{{ T "feeds.title" }}"></aside><section class="feed-index"><div id="feed-columns" aria-hidden="true"></div><div id="feed-rows" tabindex="0" role="listbox" aria-label="{{ T "feeds.title" }}"></div><button type="button" id="feed-more" hidden>↓</button></section><article id="feed-reader" tabindex="0"></article></div>
</main><script src="/static/js/feeds.js?v=6" defer></script></body></html>{{ end }} </main><script src="/static/js/feeds.js?v=8" defer></script></body></html>{{ end }}
+1 -1
View File
@@ -4,4 +4,4 @@
{{ template "organizer-nav" . }} {{ template "organizer-nav" . }}
<main id="organizer-dashboard" data-writable="{{ .TaskWritable }}" data-calendar="{{ .CalendarEnabled }}" data-today="{{ .Today }}" data-timezone="{{ .Timezone }}"> <main id="organizer-dashboard" data-writable="{{ .TaskWritable }}" data-calendar="{{ .CalendarEnabled }}" data-today="{{ .Today }}" data-timezone="{{ .Timezone }}">
<header class="dashboard-toolbar"><div><h1>{{ T "organizer.dashboard" }}</h1><small>{{ .Today }} · {{ .Timezone }}</small></div><div id="dashboard-controls"></div></header><p id="dashboard-status" role="status" aria-live="polite"></p><div id="dashboard-grid"></div> <header class="dashboard-toolbar"><div><h1>{{ T "organizer.dashboard" }}</h1><small>{{ .Today }} · {{ .Timezone }}</small></div><div id="dashboard-controls"></div></header><p id="dashboard-status" role="status" aria-live="polite"></p><div id="dashboard-grid"></div>
</main><script src="/static/js/organizer-dashboard.js?v=1" defer></script><script src="/static/js/task-productivity.js?v=6" defer></script></body></html>{{ end }} </main><script src="/static/js/organizer-dashboard.js?v=1" defer></script><script src="/static/js/task-productivity.js?v=7" defer></script></body></html>{{ end }}
+1 -1
View File
@@ -6,4 +6,4 @@
{{ if .FeedsEnabled }}<section><h2>{{ T "feeds.title" }}</h2><p>{{ T "feeds.help" }}</p><a href="/v/feeds?settings=1">⚙ {{ T "feeds.title" }}</a></section>{{ end }} {{ if .FeedsEnabled }}<section><h2>{{ T "feeds.title" }}</h2><p>{{ T "feeds.help" }}</p><a href="/v/feeds?settings=1">⚙ {{ T "feeds.title" }}</a></section>{{ end }}
{{ if .TasksEnabled }}<section id="task-productivity" data-view="settings" data-writable="{{ .TaskWritable }}"><h2></h2><p id="productivity-status" role="status" aria-live="polite"></p><div id="productivity-content"></div></section><section id="task-digest-history" data-writable="{{ .TaskWritable }}"></section>{{ end }} {{ if .TasksEnabled }}<section id="task-productivity" data-view="settings" data-writable="{{ .TaskWritable }}"><h2></h2><p id="productivity-status" role="status" aria-live="polite"></p><div id="productivity-content"></div></section><section id="task-digest-history" data-writable="{{ .TaskWritable }}"></section>{{ end }}
{{ if .CalendarEnabled }}<section id="organizer-calendar-defaults" data-writable="{{ .TaskWritable }}"><h2>{{ T "organizer.calendar_defaults" }}</h2><p role="status"></p><div data-calendar-defaults></div></section>{{ end }} {{ if .CalendarEnabled }}<section id="organizer-calendar-defaults" data-writable="{{ .TaskWritable }}"><h2>{{ T "organizer.calendar_defaults" }}</h2><p role="status"></p><div data-calendar-defaults></div></section>{{ end }}
</section></div></main><script src="/static/js/task-productivity.js?v=6" defer></script><script src="/static/js/task-digest-history.js?v=1" defer></script><script src="/static/js/organizer-settings.js?v=1" defer></script></body></html>{{ end }} </section></div></main><script src="/static/js/task-productivity.js?v=7" defer></script><script src="/static/js/task-digest-history.js?v=1" defer></script><script src="/static/js/organizer-settings.js?v=1" defer></script></body></html>{{ end }}