9 Commits
Author SHA1 Message Date
Anya Tokugawa 2cbaa9342d fix: restore nested Markdown lists and use object routes for Wiki links
Build and publish container images / images (push) Successful in 8m56s
Release container images / release (push) Successful in 21s
2026-11-10 11:06:01 +09:00
Anya Tokugawa 38b0fe2a94 fix(dashboard): normalize recoverable layout preferences on save
Build and publish container images / images (push) Successful in 9m27s
Release container images / release (push) Successful in 20s
2026-11-10 07:36:32 +09:00
Anya Tokugawa 667776e43f feat(tasks): add keyboard index and productivity dashboard improvements
Build and publish container images / images (push) Successful in 9m29s
Release container images / release (push) Successful in 18s
2026-11-10 07:12:15 +09:00
Anya Tokugawa 02edb51b8a test(tasks): preserve mail Wiki path diagnostics and regression coverage 2026-11-10 07:12:10 +09:00
Anya Tokugawa b61fbc38a4 docs: record v0.16.0 production deployment [skip ci] 2026-11-09 05:59:11 +09:00
Anya Tokugawa 02fb77f72b feat(slides): add sandboxed Reveal.js viewer and editor preview
Build and publish container images / images (push) Successful in 9m2s
Release container images / release (push) Successful in 21s
2026-11-08 22:10:52 +09:00
Anya Tokugawa 09afb438c9 feat(editor): support atomic multi-cell CSV paste 2026-11-08 21:48:32 +09:00
Anya Tokugawa 2d6ceac0d7 feat(editor): add lossless bounded CSV table editing 2026-11-08 20:58:19 +09:00
Anya Tokugawa bd80ff6a0c docs: record v0.15.0 production deployment [skip ci] 2026-11-08 20:42:17 +09:00
98 changed files with 2930 additions and 193 deletions

No files matched your search

+2 -2
View File
@@ -35,8 +35,8 @@ jobs:
[worker.oci]
max-parallelism = 2
- name: Test release tooling and wallpaper palette
run: node --test tools/ci/release-images.test.mjs static/js/home-palette-core.test.cjs
- name: Test release tooling and browser logic
run: node --test tools/ci/release-images.test.mjs static/js/home-palette-core.test.cjs static/js/csv-core.test.cjs
- name: Test
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
+1
View File
@@ -5,6 +5,7 @@ data/*
!data/test_cli_dr.py
!data/pageswiki-remote
/data2/
/docs/local/
/.codex/
/.agents/
/.env
+6
View File
@@ -342,6 +342,12 @@ window.PagesWikiEditor = {
}),
];
if (options.preserveLineEndings) {
// Split only at LF, keeping any CR bytes in the document. This
// preserves mixed LF/CRLF CSV sources instead of rewriting them.
extensions.push(EditorState.lineSeparator.of("\n"));
}
if (keymapName === "vim") {
installVimCommands();
extensions.push(vim());
+5
View File
@@ -0,0 +1,5 @@
services:
app:
image: pageswiki-app:task-index-20261109
app2:
image: pageswiki-app:task-index-20261109
+10 -3
View File
@@ -55,7 +55,12 @@
- `POST /_/api/v1/editor/convert`:作業中 HTML を安全な authoring Markdown に変換。
`POST /_/api/v1/render/markdown` の `authoring:true` で保護フェンスを元の HTML に戻す。
`projection:true` と併用したプレビューでは従来の sanitizer・macro 展開を適用する。
- 変換できない HTML は文書全体を保護する保守的な実装。フェンスは
- 2026-11-09から、全体変換が構造を保てない場合はbody直下のブロック単位に変換する。
往復で構造が一致する見出し・段落・リスト等はMarkdownへ戻し、不一致のブロックだけを保護する。
再結合後も文書全体を比較し、head内要素等を失う場合は全文保護へ戻す。
保護ブロックはDOM再シリアライズを避け、原文の引用符・タグ表記をそのまま保持する。
分割は最大1024区間。省略終了タグ等で境界を確定できない場合も全文保護へ戻す。
リスト・表の構造要素間の空白は比較時に正規化し、インラインの単語境界やコード内空白は保持する。フェンスは
`` ```{=html} `` 形式(本文にバッククォートがある場合はそれより長い区切り)。
任意の属性、コメント、未知要素、表の結合、画像キャプション、コード内空白を保持。
フェンス内を編集でき、外側に Markdown を追記できる。通常のコードフェンス内にある
@@ -70,7 +75,7 @@
- `+` は挿入・下書き、`文` は言語の編集・分岐、`↶` は旧リビジョンを作業バッファへ
読み込む。復元は明示保存で新 Revision を追加し、旧 Revision を書き換えない。
履歴は50件ずつ追加取得し、現在言語で絞り込む。分岐は翻訳生成ではなく本文のコピー。
- 挿入は子ページ・表・画像キャプション・補足・コード・引用の6種の初期パレット。
- 挿入は子ページ・表・画像キャプション・補足・コード・引用・CSV macroの初期パレット。
画像 URL 等のプレースホルダーは編集が必要。ファイルピッカー、図形・外部 widget の
パラメータ編集、プラグインによる挿入パーツ登録は既存の HTML editor 設計に残る。
- touch/coarse pointer + hover 不可の端末ではデスクトップの Vim 設定を上書きせず、
@@ -78,11 +83,13 @@
## 次段階の実装順序
CSVの表編集は既存保存・下書き・履歴の契約へ接続済みです。CSVはHTML変換と文字列自動マージを行わず、競合時は比較して採否を決めます。BOMと混在改行を保持するため、CSV初期値はHTMLのtextarea解析を通さず安全なJS文字列として渡し、CodeMirrorはLFのみで分割します。初期フォーカスの遅延処理も、表セルなどへ移ったフォーカスを奪いません。詳細な上限と残件は[表設計](extensions.md)を参照してください。
1. **E6a presence**:編集中リースの共有ストアと認可付き API、別端末を含む表示。
管理者にだけ見える監視ではなく、同じ Page/language を編集できる参加者に限定する。
2. **E6b realtime**:下記 CRDT 詳細設計・採用ライブラリ・同時変換ルールを確定した後に
feature flag 付きで実装。現時点の CAS を最終コミット時の保護として残す。
3. **E5b / E3b**:HTML ブロック単位の保護、hosted editor/CLI への保護フェンス対応、
3. **E5b / E3b**:入れ子コンポーネント内のより細粒度なMarkdown復元、hosted editor/CLI への保護フェンス対応、
アセットピッカーと拡張挿入パーツ。通常の Markdown だけを扱う外部エディタへ
このフェンスを無断で渡さない。既存の外部エディタ変換経路は本変更の対象外。
4. 保存 API の旧クライアント移行と base 必須化、下書き大容量化・明示破棄 UX、
+15 -3
View File
@@ -48,13 +48,25 @@ IPアドレス管理(IPAM)、DNSゾーン/レコード管理、機器・
## CSV/表・スライド拡張(設計TODO)
初期CSV macroは実装済みです。`{{csv:/data/items.csv range=A1:H200 header=true}}` を認証済みProjectionで展開し、`rev=` で同じObjectのRevisionへ固定できます。現在のPath閲覧権限を毎回検査し、外部URL、匿名公開、asset指定、共有キャッシュ、CSV編集はこの段階に含めません。入力256 KiB・UTF-8、表示200行×32列、走査2,000行・100列、セル16 KiB、Projection当たり4種類のCSVまでに制限します。引用符・改行・BOMに対応し、セルはHTML escapeしてmacroや数式を実行しません。処理不能時は内容を漏らさない警告に置き換えます。Authoringでは元のmacroを保持します。
初期CSV macroは実装済みです。`{{csv:/data/items.csv range=A1:H200 header=true}}` を認証済みProjectionで展開し、`rev=` で同じObjectのRevisionへ固定できます。現在のPath閲覧権限を毎回検査し、外部URL、匿名公開、asset指定、共有キャッシュはこの段階に含めません。入力256 KiB・UTF-8、表示200行×32列、走査2,000行・100列、セル16 KiB、Projection当たり4種類のCSVまでに制限します。引用符・改行・BOMに対応し、セルはHTML escapeしてmacroや数式を実行しません。処理不能時は内容を漏らさない警告に置き換えます。Authoringでは元のmacroを保持します。
CSVをPage本文へ複製せず、認可済みの別Documentをテーブルとして投影するmacroを用意します。候補構文は `{{csv:/data/items.csv range=A1:H200 header=true}}` とし、Path、Revision(またはasset hash)、列・行上限、表示モードを正規化してキャッシュキーに含めます。macroは表示時にboundedなProjectionを作るだけで、結果HTMLを正本へ逆流させません。CSV Editorは元Revisionを編集し、表投影とは別の操作・競合・権限として扱います。
既存CSVの編集は `/e/-/{path}` の組み込みエディタで行います。デスクトップはソースと表を並べ、700px以下では表を全幅表示してソースへ切り替えます。セル編集、行・列追加/削除、20操作までの表のUndo/Redoに対応。表は200行・32列・セル16 KiB以内を25行ずつ描画し、先頭行を自動でヘッダ扱いしません。矩形でない行の欠落セルは表示だけでは補わず、列追加・貼り付けで必要になった部分だけ空セルを補います。全体256 KiB・UTF-8以内を対象とし、超過・不正形式の表を部分編集可能にして保存することはありません。表上限を超えても全体上限内ならソースで編集できます。
表計算ソフトからの複数セル貼り付けは、フォーカス中のセルを左上として反映します。クリップボードの `text/plain` にタブまたは改行があればタブ区切り表として解析し、引用符内の改行・タブ・二重引用符を保持します。カンマは列区切りにせずセル値として扱い、単一行の通常テキストはセル内への貼り付けです。複数行を一つのセルへ貼る場合は引用符で囲むかソースを編集します。HTML形式のクリップボードは使いません。必要な行・セルの拡張を含めて1操作でUndo/Redoでき、構文・行列・セル・変換後CSV全体の上限を検査してから一括反映します。失敗時は部分反映せず、既存のUndo履歴も変更しません。貼り付け範囲外のセルと改行形式は維持します。
CSV正本をHTMLへ変換せず、未変更fieldの引用符、BOM、混在LF/CRLFを保持します。セル内のHTML、macro、数式は実行しません。表編集も既存の下書き・認証切れ検出・言語別Revision CAS・履歴復元を使用し、他の保存と競合したCSVは文字列の自動マージをせず比較画面へ送ります。原文と編集済み表の両方を別正本として保存しません。DBスキーマ変更はありません。CSV新規作成ウィザード、TSVファイル/文字コード変換、大容量表のwindow編集、矩形選択/範囲コピー、列型/数式、ODSは残件です。
CSVをPage本文へ複製せず、認可済みの別Documentをテーブルとして投影します。共有キャッシュを将来追加する際は、Path、Revision(またはasset hash)、列・行上限、表示モードと権限を考慮します。macroは表示時にboundedなProjectionを作るだけで、結果HTMLを正本へ逆流させません。CSV Editorは元Revisionを編集し、表投影とは別の操作・競合・権限として扱います。
交換形式はRFC 4180互換CSV(UTF-8、CRLF、引用符・改行を含むfield、BOMの扱いを明示)を第一正本とします。複数シート、型、数式、結合セル、書式が必要な場合はODSを別アダプタ/Assetとして扱い、CSVへの不可逆変換を黙って行いません。行数、列数、セル長、総バイト、ネストmacroを制限し、malformed inputは安全なテキスト表示へfallbackします。
スライドは、Markdown/HTMLの正本からReveal.js互換のProjectionを生成する連携アダプタを設けます。HedgeDoc、Slidevは外部originのホスト型アダプタとして、保存・公開・ユーザー情報をPages Wikiの権限へ自動昇格させず、read-only preview→明示的なimport/saveの順にします。JSを使用できない環境向けには、CSS scroll-snap/`:target`/print CSSだけでページ送りできるCSS-only Slide Editorを別実装します。外部ランタイム停止時は静的HTML/Markdownへ安全にfallbackし、任意script、remote import、iframe権限を本文から許可しません。
スライドはローカル同梱のReveal.js 6.0.2で表示します。`/v/slides/{path}` は通常のPath閲覧権限でHTML/Markdownの最新Revisionを取得し、HTMLページのスライドアイコンや「連携アダプタで開く」から移動できます。組み込みHTML/Markdownエディタのスライドアイコンは、未保存の本文を通常プレビューと同じ変換経路で投影します。表示DOMを保存せず、保存・下書き・競合処理は既存エディタに任せます。Markdownの空行で囲んだ `---`、HTMLの直下の `<hr>` が横方向の区切りで、直下の `<section>` も1枚として扱います。コードブロック内の区切りは分割しません。
Reveal実行は `allow-scripts allow-popups` のsandbox iframeに隔離し、`allow-same-origin` は付けません。本文のscript・CSS・iframe・フォーム・任意data属性を渡さず、独自プラグインや外部Markdownを読み込みません。画像は同一originだけ、リンクはHTTP(S)だけです。矢印キー・タッチ・画面内コントロールで移動し、履歴やURL hashを変更しません。ビューアは全画面に対応し、背景・文字色はテーマから引き継ぎます。ライブラリ読込失敗時は静的なサニタイズ済み本文へfallbackします。本文256 KiB・100枚・DOM 10,000ノード/深さ64を上限とし、常時バックグラウンド生成や共有キャッシュは持ちません。`viewer.slides` は拡張設定でドメイン単位に停止でき、停止後のページではビューア・編集切替・アダプタ候補を表示しません。MITライセンス・固定版・配布元・hashは `static/vendor/reveal/` に同梱します。DBスキーマ変更はありません。
700px以下の編集画面ではスライドプレビューを全幅表示し、既存のプレビュー非表示ボタンでソースへ戻ります。小画面で自動スクロール形式に変わらないよう `scrollActivationWidth: null` を指定します([Reveal.js公式仕様](https://revealjs.com/scroll-view/))。
縦方向のスライド、fragments、発表者ノート、macroの非同期展開、スライド専用印刷、外部画像の承認連携は残件です。HedgeDoc、Slidevは外部originのホスト型アダプタとして、保存・公開・ユーザー情報をPages Wikiの権限へ自動昇格させず、read-only preview→明示的なimport/saveの順にします。JSを使用できない環境向けには、CSS scroll-snap/`:target`/print CSSだけでページ送りできるCSS-only Slide Editorを別実装します。
ネットワーク図ではnwdiagを追加候補とします。ソースをbounded parserで検証し、renderer version/theme/document hashをキーに静的SVGをキュー生成します。include、外部画像・font、未知directive、危険なSVG属性は拒否し、renderer停止時はescaped sourceまたは最後に検証済みの静的画像へfallbackします。編集アダプタの保存はone-use ticketと楽観的Revision競合を使い、Kroki経由の場合もorigin、timeout、quotaを明示します。
+3 -3
View File
@@ -103,8 +103,8 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
| SHARE-01 / P2 | 未実装:委譲share URL、期限/失効/監査、説明可能な権限総覧 | AUTH-01、PUB-01。login/adapter/federation資格情報と別目的、単一Page投影、caveat・依存物の失効を検証 | [公開](publication.md)、[Schutzaria](schutzaria.md) |
| COLLAB-01 / P2 | 一部実装:Page等の変更購読、最近閲覧/編集、集約通知。コメント/反応/評価は未実装 | OUT-01。現在権限で再投影、private履歴のopt-in/保持。inline commentはRevision変更時の孤立・再接続を扱う | [拡張](extensions.md) |
| BLOG-01 / P2 | 一部実装:安全なtDiary import、最近コメント、遠隔ブログ射影 | COLLAB-01、遠隔はFED-01。importは再開/重複抑止/dry-run。同一instance射影を再実装しない | [ブログ・日記](blog-diary.md) |
| CSV-01 / P2 | viewerと有界CSV macroを実装。残件:CSV editor、匿名投影、asset指定、ODS境界 | 行列・セル・総量上限、Revision固定、権限、CSV引用/改行fixture。表示HTMLをCSV正本へ逆流させない | [表設計](extensions.md) |
| DIAGRAM-01 / P2 | 一部実装:nwdiag/Draw.io provider、slide preview/editor | RENDER-01。安全なSVG・include拒否・renderer版固定、ticket/CAS保存、print。既存Excalidraw/Krokiとは分ける | [Kunstzeal](kunstzeal.md) |
| CSV-01 / P2 | viewer・有界CSV macro・既存CSVの表編集/複数セル貼り付けを実装。残件:新規作成UI、大容量編集、矩形選択/範囲コピー、匿名投影、asset指定、ODS境界 | BOM/改行保持、25行描画、行列・セル・総量上限、貼り付けの一括検証/Undo、Revision CAS、権限、競合確認/履歴復元fixture。表示HTMLをCSV正本へ逆流させない | [表設計](extensions.md) |
| DIAGRAM-01 / P2 | Reveal.jsビューア/編集プレビューを実装。残件:nwdiag/Draw.io provider、縦スライド・notes・専用print | RENDER-01。有界入力、sandbox、固定版ローカル同梱、ドメイン単位停止、Path認可。SVG・include拒否・ticket/CAS保存はprovider別に検証 | [Kunstzeal](kunstzeal.md)、[スライド](extensions.md) |
| RECIPE-01 / P2 | 未実装:構造化レシピmetadataとPage投影の初期slice | 材料・数量・未知単位を保持、人数変更は派生値、Asset認可、版競合、出典・公開確認 | [料理レシピ](recipe-management.md) |
## D. 選定・別サブプロジェクト
@@ -126,7 +126,7 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
- **HOLD-01**:`/tasks/` 配下のメールWikiルーティング調査。利用者の棚上げ指定を維持。関連未コミットファイルを今回の実装・文書コミットへ混ぜない。
- **HOLD-02**:vim.wasm runtime改善とnativeアプリ起動。既存設定UIは残すが、自動的に再開しない。
- **HOLD-03**:全面WYSIWYG、E6 CRDT/OT共同編集。まずEDIT-01と認可/presence契約、保存量・オフライン・競合モデルを確定する。
- **HOLD-04**:本番への反映。作業履歴/日次メールのv3/v4移行を含む同世代保全と隔離復元試験、容量確認、SMTP副作用照合が必要。古いbinaryを新schemaへ向ける切戻しは禁止。
- **HOLD-04**:本番反映は実装と別ゲート。[v0.15.0までの配備](../../operations/releases/2026-11-08-v0.15.0.md)は完了。追加変更には同世代保全と隔離復元試験、容量確認、外部副作用照合が必要。古いbinaryを新schemaへ向ける切戻しは禁止。
## 実装と分けて管理する受入
+2 -1
View File
@@ -111,7 +111,8 @@ Cache-Control: private, no-store
- [ ] ディスクcacheの容量・TTL・清掃、renderer更新時の不整合、障害後の一時ファイル残留を管理する。
- [ ] provider宛通信と描画サービス内の外部参照を分け、送信許可・接続先・ネットワーク隔離・バージョン固定を契約化する。
- [ ] nwdiagの有界parser・安全なSVG出力・編集preview、Draw.io等のproviderを追加する。現在のregistryにnwdiagは実装されていない。
- [ ] Reveal互換・HedgeDoc・Slidev・CSS-onlyスライドのimport/save/printを独立providerとして設計する。
- [x] Reveal.jsの有界ビューア・既存HTML/Markdownエディタ内previewをローカル固定版で接続する。Path認可・sandbox・ドメイン停止を持ち、正本への保存は既存エディタを利用する([スライド設計](extensions.md))。
- [ ] Revealの縦スライド・発表者notes・専用print、HedgeDoc・Slidev・CSS-onlyスライドのimport/save/printを独立providerとして設計する。
- [ ] Excalidrawのhosted/browser実行とPDF/動画サムネイル・metadata subprocessを、各々の安全境界を維持したまま段階的に接続する。
## 検証と反映
+66 -4
View File
@@ -1,6 +1,6 @@
# オーガナイザーのナビゲーションと個人ダッシュボード
タスク・カレンダー・連絡先の入口を共通化し、個人設定と日々の振り返りを分離する。ダッシュボードは本人の作業を見る画面であり、サーバーの実行状態・リソース監視画面とは別に扱う。以下は2026-11-02のソース実装範囲で、2026-11-04にv0.7.0として本番へ反映した。移行・検証・復旧点は[本番反映記録](../../operations/deployments/2026-11-04-v0.7.0.md)を参照する。
タスク・カレンダー・連絡先の入口を共通化し、個人設定と日々の振り返りを分離する。ダッシュボードは本人の作業を見る画面であり、サーバーの実行状態・リソース監視画面とは別に扱う。初期実装は2026-11-04にv0.7.0として本番へ反映した。2026-11-09の追加実装は、明日の予定・コマンドウィジェット、件名Markdown、参照欄、個人の外観設定。これらの追加分は本番未反映。
## 入口と設定の配置
@@ -10,13 +10,14 @@
| --- | --- |
| `/v/plan/dashboard` | ウィジェット形式の個人ダッシュボード |
| `/v/plan/tasks` | 既存のインライン編集可能なタスク一覧 |
| `/v/plan/tasks/index` | neomutt風のキーボード操作によるタスク一覧 |
| `/v/plan` | 既存のカレンダー表示。保存されたビューを尊重 |
| `/v/plan/contacts` | 個人アドレス帳・履歴・CardDAV接続 |
| `/-/sys/config?panel=organizer` | タスクの既定値、日次メール、既定のカレンダー |
| `/-/sys/config?panel=organizer` | タスクの既定値、日次メール、既定のカレンダー、個人の外観 |
旧 `/v/plan/tasks/report` はダッシュボードの達成度ウィジェットへ、旧 `/v/plan/tasks/settings` は個人設定へ303リダイレクトする。カレンダーの表示選択ダイアログはその場の表示変更に使い、既定値の永続化は個人設定へ移す。
個人設定は通常の設定画面と同じURI体系・テーマを使うが、専用の軽量な画面として返す。GET/HEADかつ正確な `panel=organizer` の場合だけ個人向けハンドラーに振り分け、管理用設定やアカウント一覧は取得・描画しない。POSTの管理者チェックは緩和しない。保存先は既存の本人用APIであり、一般利用者に管理権限を付与しない。
個人設定は通常の設定画面と同じURI体系・テーマを使うが、専用の軽量な画面として返す。GET/HEADかつ正確な `panel=organizer`、またはPOSTで `panel=organizer&section=appearance` の場合だけ個人向けハンドラーに振り分ける。管理用設定のPOSTは従来どおり管理者を要求する。個人設定の保存は本人のactiveアカウントに限定し、管理権限を付与しない。
## タスク編集画面と通知既定値
@@ -26,6 +27,43 @@
760px以下では1カラムにし、主な入力と選択ボタンは44px以上のタッチ領域を確保する。個人設定には新規タスクの期限日・取り組む日のInbox通知と通知時刻を設ける。適用条件と既存データの扱いは[タスク通知](task-reminders.md)を参照する。
## キーボード操作のタスク一覧
`/v/plan/tasks/index` を既存のインライン編集とは別の表示として提供する。タスク画面の「キーボード一覧」から開く。左側はプロジェクト、右側は状態・件名・期限・取り組む日・優先度・関連Wikiの表。件名Markdownと選択行のテーマ色を使い、サブタスクは矢印で区別する。順序は指定ソートを優先し、親子の隣接は保証しない。
| キー | 操作 |
| --- | --- |
| `j` / `k`、上下矢印 | 次/前のタスクを選択 |
| `Ctrl+j` / `Ctrl+k` | 次/前のプロジェクトへ表示を切り替え(所属変更ではない) |
| `o` / `O` | ソート選択欄へ/昇順・降順を反転 |
| `l` / `Esc` | 絞り込み欄へ/一覧へ戻る。絞り込みはEnterで適用 |
| `d` | 選択タスクを完了。削除やアーカイブではない |
| `s` | 選択タスクで25分Pomodoroを開始。実行中セッションは上書きしない |
| `c` / `m` | 作成/既存の編集ダイアログを開く |
| `w` | 関連Wikiへ移動。リンクがなければ案内し、暗黙に新規作成しない |
| `?` | キーと絞り込み式のヘルプ |
入力欄、IME変換中、ダイアログ表示中にはショートカットを実行しない。更新系キーはキーリピートを無視する。作成時は選択中のプロジェクトを引き継ぎ、「すべて」では個人の既定値、「プロジェクトなし」では明示的な未所属とする。ブラウザやOSが予約しているキーをページ側へ渡さない環境では、同じ操作を画面のボタンから行う。
初期絞り込みは `~active`。複数条件はAND、`!` を条件の前に付けると否定する。OR・括弧・正規表現は扱わない。空欄はアーカイブ以外の全状態を表示する。
| 書式 | 意味 |
| --- | --- |
| `~s "リリース準備"` | 件名の部分一致。空白を含む値は引用符で囲む |
| `~active` / `~todo` / `~doing` / `~done` / `~cancelled` | 未完了/未着手/着手中/完了/取りやめ |
| `~overdue` | ドメインの今日より前に期限を迎えた未完了タスク |
| `~due <=today` / `~planned tomorrow` / `~start >=2026-11-01` / `~review <today` | 期限・取り組む日・着手日・見直す日。日付はYYYY-MM-DD、today、tomorrow。比較は `= < <= > >=` |
| `~due none` | 日付なし。planned、start、reviewにも使用可能 |
| `~bucket inbox` / `~bucket backlog` / `~bucket someday` | 整理先 |
| `~priority 3` | 優先度0〜3の一致 |
| `~wiki` / `~attachment` / `~archived` | 関連Wikiあり/URL・Path参照あり/アーカイブ済み |
例:`~s "リリース" ~doing !~overdue`。プロジェクト・条件・ソートはURLクエリへreplaceStateで保持し、操作ごとに履歴エントリを増やさない。
取得は既存 `items` APIの `view=index`。`filter`、`sort`(due/planned/title/status/priority/created/updated)、`order`(asc/desc)、`project`、`before`を使う。未所属は `project=none`。サーバーで対象全体を絞り込み・ソートして100件ずつ取得し、末尾での下移動または追加読込で次を取得する。ソート値とUUIDによる順序を使い、他ユーザーのカーソルから内容を返さない。日付未設定は昇順の末尾、完全な逆順では先頭になる。並行更新時の固定スナップショットではないため、再読込で最新状態を確認する。
条件は1000バイト・最大64トークン。SQLは値をバインドし、ソート列は許可リストから選ぶ。不正条件は422で、旧表示を残して操作ボタンを無効化する。プロジェクトも検索・50件単位の追加読込とし、一括取得しない。完了は表示時のversionをIf-Matchで送る。別更新があれば412で止め、メモ等を最新取得しても古い選択行からの更新を無条件に通さない。本人の権限・読み取り専用制限は既存APIに従う。この一覧追加にDBスキーマ変更はない。
## ウィジェット
初期構成は次の6種類。任意のHTML・iframe・外部URL・スクリプトを登録する機能ではなく、サーバーが許可する組み込みIDを使う。
@@ -39,13 +77,15 @@
| `schedule` | 既定カレンダーにある今日の予定 |
| `activity` | 完了数・ポイント・作業時間・集中時間、日別ヒートマップ |
追加メニューには `feeds`(RSS)、`tomorrow-schedule`(明日の予定)、`commands`(タスクコマンド)も用意する。既存の保存済み配置に自動追加せず、追加後に「配置を保存」で確定する。予定は時刻範囲・件名・カレンダー名をカード状に配置し、開催中の予定を強調する。終日予定は時刻の代わりに「終日」を表示する。
タブはウィジェットの枠内で内容を切り替える。iframeを使わず、ページやブラウザ履歴を移動しない。タスク件名や右上の矢印は既存の詳細・一覧へ移動する。タスクの編集操作は従来の一覧・詳細画面を利用する。
達成率の分母は `planned_on=今日`、分子はそのうち `status=done` の件数。取りやめ・アーカイブ・プロジェクトを除く。日付はドメインのタイムゾーンで判定する。対象0件は100%でなく「—」を表示する。期限超過を含む「本日のタスク」の件数とは意図的に異なり、画面に定義を明記する。ヒートマップのポイント計算は[タスクの集計契約](task-productivity-contacts.md)に従う。
## 配置と保存
デスクトップは12列グリッド。幅は3〜12列、高さは2〜10単位、1単位の表示基準は72pxと12pxの間隔。順序に従ってグリッドへ配置するため、幅の組み合わせによって空白が生じる。任意の絶対座標を保持するレイアウトではない。
デスクトップは画面幅いっぱいの12列グリッド。幅は3〜12列、高さは2〜10単位、1単位の表示基準は72pxと12pxの間隔。順序に従ってグリッドへ配置するため、幅の組み合わせによって空白が生じる。任意の絶対座標を保持するレイアウトではない。
歯車で配置モードを開き、ハンドルのドラッグで並べ替え、右下のハンドルでサイズを変える。矢印ボタンと幅・高さの選択欄でも同じ操作が可能。追加・除去・初期配置への復帰に対応し、「配置を保存」で確定する。タブの選択も配置の一部として保存できる。未保存の離脱を警告し、保存失敗・競合時には編集中の配置を残す。ブラウザ再起動をまたぐ未保存レイアウトの下書きは持たない。
@@ -69,6 +109,28 @@ APIは `/_/api/v1/extension/organizer.tasks/` 配下。
## 検証と後続範囲
### タスク表示と参照
件名の保存形式は文字列のまま。Web一覧では太字、斜体、取り消し線、インラインコード、リンクのラベルをDOMで描画する。HTML・画像・マクロを実行しない。インライン編集のフォーカス中はMarkdownソースをそのまま入力できる。関連Wikiがある行は塗りつぶした文書アイコンとテーマ色で区別する。
`TaskRecord.references` はURLまたはWiki Pathの配列(最大20件、1件4096バイト)で、タスクの編集画面の詳細設定から変更する。http/httpsと同一サイトの絶対Pathだけを認め、認証情報入りURL・プロトコル相対URL・制御文字は拒否する。リンク先の取得や公開範囲の変更は行わない。Path参照は文字列のためrenameには追従しない。rename追従が必要な主たる関連Wikiには従来の `page_uuid` を使う。
正本JSONと変更履歴に参照を保存し、タスクの列追加は不要。旧CLI等がこのフィールドを省略した更新では既存値を維持し、明示的な空配列で解除する。CalDAV更新でも維持するが、VTODOのATTACHへの投影は後続範囲。
### タスクコマンド
`add task 件名`、`today UUID`、`tomorrow UUID`、`due UUID YYYY-MM-DD`、`due UUID clear`、`done UUID`、`delete UUID` を提供する。対象は件名検索のサジェストから選ぶとUUIDが入る(250ms debounce、最大10件)。シェルコマンドではない。追加は個人の既定値を読み、通信失敗時は同じUUIDで再試行できる。既存タスクへの操作は取得時のversionをIf-Matchで送信し、競合時は上書きしない。削除は件名を確認してから実行する。今日・明日はダッシュボード読込時のドメイン日付を基準とする。
### 個人の外観とログイン画面
壁紙Path・不透明度・グラス透明度・壁紙からの色抽出を個人設定へ追加する。トップ画面の歯車も同じ本人用保存先を使う。初回は既存のドメイン設定を初期値として引き継ぎ、保存後は個人値を優先する。空の壁紙Pathは「壁紙なし」。フォルダ選択時は従来どおり閲覧可能な直下の画像から選ぶ。
`personal_appearance` はDomain UUIDと本人UUIDを複合キーにしたJSON+versionのテーブル。起動時の設定テーブル初期化で追加する。既存テーブル・正本を破壊せず、保存はversion比較で競合409を返す。タスク既定値・メール同意のversionを変更しない。ドメイン設定画面の外観項目は初期値用として区別する。
ログイン画面は壁紙なしとし、旧 `/_/auth/wallpaper` は404を返す。個人・ドメインのトップ壁紙をログイン前に公開しない。別のログイン専用背景Pathは今回追加しない。
### 回帰検証
合成データで、所有者分離、CAS、読み取り専用、匿名拒否、管理設定への権限拡大がないこと、空配置、禁止ウィジェット、メール設定の不変、今日の集計・予定範囲を検証する。ブラウザではデスクトップとスマホの導線、タブ、設定保存、配置保存、横はみ出しを確認し、デスクトップのドラッグ・リサイズには実ポインター入力を使う。本番の外部取り込みカレンダーは検証に使わない。
次段階は以下を別途設計する。
@@ -0,0 +1,45 @@
# メールWikiのPath依存404の調査
## 状態と回避策
2026年11月6日、別インスタンスでNeoMuttから作成したWikiが一覧には見える一方、`/tasks` とその配下への直接アクセスで `{"detail":"Not Found"}` になる報告があった。同じオブジェクトに `/prj/awesome` 側のリンクを追加すると表示できた。原因は未確定で、修正済みとは扱わない。
回避策は表示できるWiki親prefixを既定値にし、既存オブジェクトには別Pathのリンクを使うこと。メールの再取り込み、オブジェクトの削除、既存Pathの一括移動は不要。Pathごとに権限が異なりうるため、新しいリンク先の公開範囲も確認する。
## アプリ内で確認した境界
タスク画面は `/v/plan/tasks`、APIは `/_/api/v1/extension/organizer.tasks/`。`/tasks` は予約ルートではなく、通常のWiki Pathとして解決する。末尾スラッシュは301で取り除く。
NeoMuttの `pipe_decode=no`・`pipe_split=yes` 相当の標準入力を使い、CLIプロセスから一時DBのフルHTTPハンドラへ取り込む試験を追加した。42パターンは、親prefix7種類、UTF-8/ISO-2022-JPの件名、ML連番/Message-ID/原文hashの組合せ。公開CLI v0.4.0でも一覧のdata-path、直接表示、末尾スラッシュ、言語指定を確認し、代表3パターンをChromiumで表示した。実メール・実アカウント設定は使用しない。
Python・Chromiumに依存しないGoテストでは、実際のAPIへ既定prefix `/tasks` を設定して取り込み、同一オブジェクトの `/tasks/...` と `/prj/awesome` の両方がHTMLの200を返すことを検証する。未認証閲覧のログイン誘導、一覧表示、旧CLI形式も対象。CIでPythonがない場合もこのテストは実行される。
親に文書がない場合は、仮想フォルダページ無効ならHTMLの404、有効ならchildren一覧の200となる。これは作成済み子ページまでJSONの404になる報告とは区別する。設定箇所は `/-/sys/config?panel=home` の「仮想フォルダページ」。設定は対象ドメイン単位で、調査のために自動変更しない。
## 機密情報を共有しない切り分け
以下は問題のインスタンス内で行う。実URL・メール本文・Cookie・Bearer token・ログ全文を外部へ共有しない。
1. 問題のPathへのGET時刻を控え、PagesWikiプロセスのアクセスログに同じ要求が到達するか確認する。到達しない場合はプロキシ、ブラウザ、キャッシュなどアプリより手前を調べる。ログ出力先の取り違えにも注意する。
2. 公開HTTPSとPagesWikiの直接待受で応答を比較する。Domainの振り分けが変わらないよう、同じHostとPathを使う。まず資格情報なし・リダイレクトを追わないGETのstatusとContent-Typeを比較すれば、メール本文を取得せずに判断できる。認証後の比較が必要ならローカル環境内の安全な手順を使い、コマンド履歴に資格情報を残さない。
3. 直接待受は正常でプロキシ経由だけ失敗する場合、`/tasks` に一致するlocation、正規表現location、rewrite、別upstream、Custom Locationsを確認する。実際の設定で確認できるまではプロキシが原因と断定しない。
4. PagesWikiへの直接要求も失敗する場合は、稼働イメージrevision、HostによるDomain選択、Path別ACL、既存リンクの対象UUIDをローカルで確認する。同一オブジェクトの別名が読めても、元Pathの権限が同じとは限らない。
X-Request-IDやServerヘッダーだけで応答元を断定しない。プロキシによる付加・上書きがありうる。原因が判明するまで、推測による `/tasks` 専用ルート追加や権限の緩和はしない。
## 回帰テストと残件
```sh
go test ./internal/server -run 'TestTaskWikiPrefixRouting|TestNeoMuttMailViewerFlow' -count=1
# Chromiumがある開発環境のみ
PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1
# 配布ELFでも同じ一時プロファイルを用いて確認する場合
PAGES_CLI_TEST_BINARY=/absolute/path/to/pages PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1
```
- [x] `/tasks` 配下のメール作成から通常ビューアまでの合成HTTP試験。
- [x] 同一オブジェクトの別名、親の仮想フォルダ設定、認証境界のGo回帰テスト。
- [ ] 問題インスタンスで、直接待受とプロキシ経由の差分を確定する。
- [ ] 特定された原因に修正を適用し、元の `/tasks` でも表示できることを確認する。
テストと調査記録の追加は障害修正リリースではない。既存の回避策とデータを維持する。
@@ -0,0 +1,48 @@
# PagesWiki v0.15.0とpages-cli v0.5.0
ブラウザアップロード、信頼端末ログイン、RSSの配信時刻、CSV投影とタスクの関連ページ導線を追加します。Geckoの整備コードと配布イメージも含みますが、専用relayの本番有効化は行いません。
## 変更内容
- `/v/browser` のファイルドロップと右下のキュー。逐次送信、待機取消、折りたたみ、同名保護、一覧だけの更新。ページを閉じた後の再開とフォルダ再帰アップロードは未対応。
- ログイン時の信頼端末選択。管理者指定の最大30日・絶対期限で、既存セッションは延長しません。パスワード/TOTP、OIDC、LDAP、マジックリンクに選択を引き継ぎます。
- CLIの `login --remember` と期限切れ再ログイン時の作業パス/保留下書き保持。
- RSS一覧の配信時刻とDomainタイムゾーン。本文の日付表示も同じタイムゾーンへ統一。
- 保存済みタスクの関連Wikiページを開くボタン。
- 認証済み閲覧者の権限を確認する有界CSV macro。`{{csv:/data/items.csv range=A1:H200 header=true}}` と同じObjectのRevision固定に対応。CSV編集・匿名投影・外部URL取得は含みません。
- Geckoの日本語ページ内検索、起動上限・失敗時のiframe破棄、固定ソース/notice付き配布物検査。Safari実機、IME・コピー、運用firewallと低メモリ受入は残件。
## リリースと検証
本体commitは `b90aef79d03c21332cd49a47aba015a30f6de1a0`。Gitea [build 76](https://git.anya.jp/anya/pages/actions/runs/76)、[release 79](https://git.anya.jp/anya/pages/actions/runs/79) が成功し、SHAイメージを再ビルドせず `v0.15.0` へ昇格しました。
CLI commitは `bee03094f3bf2fa0c2dab80313d2f4bd15452c3d`。[v0.5.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.5.0) のCIと55単体テストが成功。公開した4ファイルのSHA256SUMS照合、Pythonソース一致、取得したLinux ELFのバージョン・ログイン・タスク/メール取り込み・下書き回復等の合成スモークテストを確認しました。未検証のmacOS/Windowsバイナリは追加していません。
本体は `go test ./...`、`go vet ./...`、リリースツールと壁紙テスト、Gecko配布ツールのテストが成功。Chromiumで認証・タスク・RSS・Gecko・アップロードの合成試験を実施しました。アップロードキューは1280px/390px幅、逐次送信、同名保護、取消、一覧更新を検証しています。
## DBと復旧
`cli-auth` v1→v2で `auth_cli_requests.remember` を既定0・0/1制約付きで追加します。他の管理対象componentのversionは変わりません。両インスタンスの独立コピーで、ネットワークを遮断しworkerを停止して新イメージを起動し、schema checkとSQLite integrity_checkが成功しました。実外部カレンダーやメール内容は検証に使用していません。
保全先は `.deployment-backups/release-v0.15.0-20261108/`。`config/` に旧設定、`cutover/data` と `cutover/data2` に停止時点のデータを保存します。旧3イメージの `rollback-before-v0.15.0-20261108` タグと既存バックアップを保持します。
新しいmigration履歴を旧版が受け付けるとは限らないため、旧イメージだけのダウングレードは行いません。切戻しが必要ならwriterを止め、切替後データも保全し、停止時バックアップとの変更差分を扱ってからDB・ファイル・設定・イメージを同じ復旧点へ戻します。運用開始後の書き込みを黙って破棄しません。
## 本番反映
2026-11-08 20:41:33 JSTに配備後確認を完了しました。20:40:05に停止し、20:41:10に停止時バックアップを検証、20:41:16に新版の起動とhealthを確認しています。
- app・app2・adaptor-gateway・excalidraw-viewerはすべて対象commitと一致し、running・再起動回数0。
- 両DBのquick_checkはok、管理対象13componentはcurrent。legacy領域全体の検証を意味するものではありません。
- 外部HTTPSのhealth・ログイン画面200。匿名タスク/dashboard/RSS画面303、タスクAPI・DELETE・captureは401。
- tasks、RSS、Gecko、アップロードキュー、信頼端末UIの配信JS/CSSはリリースcommitとSHA-256一致。公開ログイン画面の信頼端末選択も確認。
- 起動直後のfatal/panic、DB/schema failure、event job failureは両アプリとも0件。
- `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.15.0`。Gecko relayコンテナは起動せず、通常3イメージ・4サービスだけを更新。
配備イメージのmanifest digest:
| イメージ(`git.anya.jp/anya/`) | digest |
| --- | --- |
| pageswiki-app | `sha256:43c398f2c294c7802987aaae1bfdf27b3d0c7ea24fa73df912ac03ea312366b0` |
| pageswiki-adaptor-gateway | `sha256:aebc515c3b3e36b58b03ecab1646e6d95b0dd21074a1a863ca5806cb7fde4df1` |
| pageswiki-excalidraw-viewer | `sha256:4a80354aa4567abe52ff17e32a6f224e85d8cd2e0f1a466e5690b4b353d901cc` |
@@ -0,0 +1,39 @@
# PagesWiki v0.16.0
2026-11-09 05:58:14 JSTに本番の配備後確認を完了しました。CSVの表編集・複数セル貼り付けと、Reveal.jsのビューア・編集プレビューを追加します。
## 変更と利用方法
- 既存CSVを `/e/-/{path}` で表編集。行列操作、Undo/Redo、タブ区切りの複数セル貼り付け、既存の下書き・履歴・競合確認に対応します。未変更セルの引用符・BOM・改行を保持し、上限超過時は部分反映しません。
- HTMLページのスライドアイコン、または `/v/slides/{path}` でReveal.js表示。エディタのスライドアイコンで未保存HTML/Markdownをプレビューします。Markdownの空行で囲んだ `---`、HTML直下の `<hr>` で区切ります。
- Reveal.js 6.0.2をMITライセンスとともにローカル同梱。sandbox、Path認可、入力上限、テーマ追従、スマホの全幅プレビューに対応。拡張設定の `viewer.slides` でドメイン単位に停止できます。
CSVは全体256 KiB、表200行・32列・セル16 KiB以内。スライドは256 KiB・100枚以内です。縦スライド・発表者ノート・専用印刷・外部画像承認連携は含みません。通常HTMLの自動表示をスライドへ置き換えません。
## リリースと検証
対象commitは `02fb77f72b45c342c6b458d733f840b38cc3ae56`。[build 80](https://git.anya.jp/anya/pages/actions/runs/80)と[release 81](https://git.anya.jp/anya/pages/actions/runs/81)が成功し、同じSHAのイメージを再ビルドせずv0.16.0へ昇格しました。
開発環境で全Goテスト・go vet・JS単体テスト、1280px/390pxのChromium試験を実施しました。CSV保存・競合・履歴・貼り付け拒否、スライドのライブ更新・通常プレビュー復帰・左右キー・履歴非変更・隔離を確認しています。
本番ではapp・app2・adaptor-gateway・excalidraw-viewerのrevision一致、running、再起動0を確認。両アプリのhealth、外部HTTPSのhealth/login 200、匿名タスク・スライドの303、タスクAPIの401を確認しました。CSV/Reveal.js関連の11配信ファイルはリリースcommitとSHA-256一致。両DBのquick_checkはok、管理対象13componentはcurrentで版変更なしです。legacy領域全体の移行検証を意味しません。起動直後のpanic・fatal・DB/schema失敗・event job失敗に該当するログはありませんでした。
本番の実コンテンツを編集する試験、外部カレンダー・メール内容の取得は行っていません。pages-cliは変更せず、Gecko relayも起動していません。
## 保全と切替
DBスキーマ・ストレージ形式の変更はありません。保全先は `.deployment-backups/release-v0.16.0-20261109/`。`config/` に旧設定、`cutover/data` と `cutover/data2` に停止時点のファイルを保持しています。DBだけは容量を考慮して `pages.db.gz` とし、gzip検査と展開内容のバイト一致を確認しました。他のファイルは停止時checksum比較で一致しています。復旧用に展開する場合は、稼働DBを上書きせず別の停止済み復旧領域に `pages.db` として展開します。
初回は圧縮で変わったバックアップ先フォルダmtimeを厳密差分検査が検出し、新版起動前にv0.15.0へ自動復帰しました。圧縮後にフォルダmtimeを元に合わせる修正を行い、内容の検証は省略せず再実行しています。再試行は05:54:59 JSTに停止、05:57:28にバックアップ検証完了、05:57:34に新版health確認完了です。
旧イメージは `rollback-before-v0.16.0-20261109` タグで保持し、過去のバックアップも削除していません。今回のUI機能を切り戻す場合はwriterを止め、現データを保持してv0.15.0のイメージへ戻せます。バックアップ時点へのデータ復旧を選ぶ場合は、切替後の書き込みを別途保全して差分を扱い、黙って破棄しません。
`.env.release` は `PAGESWIKI_IMAGE_TAG=v0.16.0`。配備後の空き容量は約8.1 GiBのため、次の大きなビルド・バックアップの前に保持世代と不要キャッシュの整理が必要です。
## 配備イメージ
- `pageswiki-app`: `sha256:428f4c38297e7d2b529af13b32d45e6a9b40f58915fbd170148a0ad07958a034`
- `pageswiki-adaptor-gateway`: `sha256:cdf99b4f02a9abade8862caea1c23cfe775f229118c5c1aabf2584d84a02be50`
- `pageswiki-excalidraw-viewer`: `sha256:854fa1d0bb931642e81af394ab4631b47397a94264eb1b34d4f8ff0ca5435e25`
レジストリのprefixは `git.anya.jp/anya/`、共通タグは `v0.16.0` です。
+1
View File
@@ -21,6 +21,7 @@ type Manifest struct {
func Catalog() []Manifest {
return []Manifest{
{ID: "viewer.slides", APIVersion: 1, Version: "0.1.0", Kind: "viewer", Scope: "domain", NameKey: "slides.title", DescriptionKey: "slides.help", Capabilities: []string{"path.read"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "client-compute+bounded-read"},
{ID: "viewer.gecko", APIVersion: 1, Version: "0.1.0", Kind: "viewer", Scope: "domain", NameKey: "feeds.gecko", DescriptionKey: "feeds.gecko_help", Capabilities: []string{"feeds.own.read"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: false, ResourceClass: "client-compute+relay-network"},
{ID: "organizer.feeds", APIVersion: 1, Version: "0.1.0", Kind: "feeds", Scope: "domain", NameKey: "feeds.title", DescriptionKey: "feeds.help", Capabilities: []string{"feeds.own.read", "feeds.own.write"}, Events: []string{"feed.source.sync"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "background+network+index"},
{ID: "organizer.contacts", APIVersion: 1, Version: "0.2.0", Kind: "contacts", Scope: "domain", NameKey: "contacts.title", DescriptionKey: "contacts.help", Capabilities: []string{"contacts.own.read", "contacts.own.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
+102 -2
View File
@@ -3,6 +3,8 @@ package grammaratur
import (
"bytes"
"encoding/json"
"io"
"regexp"
"sort"
"strings"
@@ -12,17 +14,93 @@ import (
// HTMLToMarkdownAuthoring keeps source HTML when conversion loses structure,
// attributes, comments or text. This is not a sanitization boundary.
var nestedListGap = regexp.MustCompile(`\n[\t ]*\n([\t ]+(?:[-+*]|[0-9]+\.) )`)
func authoringMarkdown(source string) (string, error) {
md, err := HTMLToMarkdown(source)
if err != nil {
return md, err
}
// The converter inserts a loose-list gap before nested lists. Only accept
// tightening when the resulting DOM matches; code and real paragraphs stay protected.
tight := nestedListGap.ReplaceAllString(md, "\n$1")
if tight != md && htmlStructure(source) == htmlStructure(MarkdownToHTML(tight)) {
return tight, nil
}
return md, nil
}
func HTMLToMarkdownAuthoring(source string) (string, error) {
converted, err := HTMLToMarkdown(source)
converted, err := authoringMarkdown(source)
if err != nil {
return "", err
}
if htmlStructure(source) != htmlStructure(MarkdownToHTML(converted)) {
return rawHTMLBlock(source), nil
// Protect only the blocks which cannot round-trip. One custom component
// must not turn the headings, lists and paragraphs around it into HTML.
blocks, ok := authoringBlocks(source)
if !ok {
return rawHTMLBlock(source), nil
}
var parts []string
for _, raw := range blocks {
if strings.TrimSpace(raw) == "" {
continue
}
md, e := authoringMarkdown(raw)
if e != nil || htmlStructure(raw) != htmlStructure(MarkdownToHTML(md)) {
md = rawHTMLBlock(raw)
}
parts = append(parts, md)
}
mixed := strings.Join(parts, "\n\n")
// Includes head content, comments outside body and fragment edge cases.
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(mixed)) {
return rawHTMLBlock(source), nil
}
return mixed, nil
}
return converted, nil
}
// Token boundaries retain the exact source of protected components (including
// attribute quoting and void-element syntax). Never serialize the parsed DOM
// back over their source. Malformed/implicit nesting uses whole-document fallback.
func authoringBlocks(source string) ([]string, bool) {
z := html.NewTokenizer(strings.NewReader(source))
var stack, blocks []string
start, offset := 0, 0
for {
kind := z.Next()
if kind == html.ErrorToken {
return blocks, z.Err() == io.EOF && len(stack) == 0 && offset == len(source)
}
offset += len(z.Raw())
switch kind {
case html.StartTagToken:
name, _ := z.TagName()
switch string(name) {
case "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr":
default:
stack = append(stack, string(name))
}
case html.EndTagToken:
name, _ := z.TagName()
if len(stack) == 0 || stack[len(stack)-1] != string(name) {
return nil, false
}
stack = stack[:len(stack)-1]
}
if len(stack) == 0 {
blocks = append(blocks, source[start:offset])
start = offset
if len(blocks) > 1024 {
return nil, false
}
}
}
}
// {=html} is an explicit authoring fence, not an ordinary code sample. The
// closing delimiter is longer than any run in the source, so arbitrary HTML
// (including Markdown examples) cannot accidentally terminate it.
@@ -110,6 +188,28 @@ func htmlStructure(source string) string {
literal = literal || n.Data == "pre" || n.Data == "code" || n.Data == "script" || n.Data == "style"
data := n.Data
if n.Type == html.TextNode && !literal {
// Formatting whitespace beside a nested block is not an inline word
// separator. Keep all whitespace between inline siblings significant.
if n.Parent != nil && n.Parent.Data == "li" {
isList := func(x *html.Node) bool {
return x != nil && x.Type == html.ElementNode && (x.Data == "ul" || x.Data == "ol")
}
if isList(n.NextSibling) {
data = strings.TrimRight(data, " \t\r\n")
}
if isList(n.PrevSibling) {
data = strings.TrimLeft(data, " \t\r\n")
}
if data == "" {
return
}
}
if strings.TrimSpace(data) == "" && n.Parent != nil {
switch n.Parent.Data {
case "ul", "ol", "table", "thead", "tbody", "tfoot", "tr":
return
}
}
if strings.TrimSpace(data) == "" && (n.Parent == nil || n.Parent.Data == "body" || n.Parent.Data == "html") {
return
}
+16
View File
@@ -65,3 +65,19 @@ func TestAuthoringWhitespaceComparisonIsConservative(t *testing.T) {
t.Fatal("word boundaries ignored")
}
}
func TestAuthoringPartialMarkdownRecovery(t *testing.T) {
source := `<h1>Title</h1><p>Some <strong>bold</strong> text.</p><figure data-x="keep"><img src="/image"><figcaption>Caption</figcaption></figure><ul><li>First</li><li>Second</li></ul>`
md, err := HTMLToMarkdownAuthoring(source)
if err != nil || !strings.HasPrefix(md, "# Title") || !strings.Contains(md, "**bold**") || strings.Count(md, "{=html}") != 1 || !strings.Contains(md, "- First") {
t.Fatalf("markdown not recovered: %q %v", md, err)
}
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(md)) {
t.Fatal("HTML lost during partial conversion")
}
protected := `<figure data-x='original'><img src=/image><figcaption>Caption</figcaption></figure>`
md, err = HTMLToMarkdownAuthoring("<h1>Title</h1>" + protected + "<p>Tail</p>")
if err != nil || !strings.Contains(MarkdownAuthoringHTML(md), protected) || !strings.HasPrefix(md, "# Title") {
t.Fatalf("protected bytes changed: %q %v", md, err)
}
}
+33
View File
@@ -0,0 +1,33 @@
package grammaratur
import (
"strings"
"testing"
)
func TestAuthoringNestedLists(t *testing.T) {
for _, source := range []string{
"<ul><li>Parent<ul><li>Child</li></ul></li></ul>",
"<ul>\n<li>Parent\n<ul>\n<li>Child</li>\n</ul>\n</li>\n</ul>",
"<ul><li>Parent<ul><li>Child<ul><li>Grandchild</li></ul></li></ul></li><li>Sibling</li></ul>",
"<ol><li>Parent<ul><li>Child</li></ul></li></ol>",
"<ul><li><strong>Parent</strong><ul><li>Child</li></ul></li></ul>",
} {
md, err := HTMLToMarkdownAuthoring(source)
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(md)) {
t.Errorf("list structure changed: %q", md)
}
if err != nil || strings.Contains(md, "{=html}") {
plain, _ := HTMLToMarkdown(source)
t.Errorf("source=%q md=%q plain=%q rendered=%q err=%v", source, md, plain, MarkdownToHTML(plain), err)
}
}
}
func TestAuthoringNestedListPreservesAttributes(t *testing.T) {
source := `<ul><li data-custom="keep">Parent<ul><li>Child</li></ul></li></ul>`
md, err := HTMLToMarkdownAuthoring(source)
if err != nil || MarkdownAuthoringHTML(md) != source {
t.Fatalf("protected list changed: %q %v", md, err)
}
}
+6 -1
View File
@@ -227,4 +227,9 @@ func textMediaType(descriptor Descriptor) bool {
}
// Catalog returns a copy; callers cannot reorder or disable the shared registry.
func Catalog() []Adapter { return append([]Adapter(nil), projectionAdapters...) }
func Catalog() []Adapter {
items := append([]Adapter(nil), projectionAdapters...)
// Explicitly selected projection. It must not replace normal HTML/text
// viewing in the automatic MIME classifier.
return append(items, Adapter{ID: "reveal", Kind: "slides", Delivery: DeliveryRawFrame, Match: func(Descriptor) bool { return false }})
}
+1 -1
View File
@@ -47,7 +47,7 @@ func TestAdapterCatalogIsCopyAndConcurrent(t *testing.T) {
for _, a := range catalog {
ids = append(ids, a.ID)
}
if strings.Join(ids, ",") != "html,excalidraw,csv,archive,debian-package,eml,pe,json,text,image,audio,video,pdf,download" {
if strings.Join(ids, ",") != "html,excalidraw,csv,archive,debian-package,eml,pe,json,text,image,audio,video,pdf,download,reveal" {
t.Fatal("catalog order changed", ids)
}
catalog[0].ID = "corrupt"
+3
View File
@@ -185,6 +185,9 @@ func (s *Server) adapterActionsForPath(r *http.Request, semanticPath string) ([]
{ID: "download", Name: "download", Mode: "viewer", Builtin: true,
OpenURL: rawProjectionURL("rev:" + revision.UUID)},
}
if (mediaType == "text/html" || mediaType == "text/markdown" || mediaType == "text/x-markdown") && s.systemExtensionEnabled(domainUUID, "viewer.slides") {
actions = append(actions, adapterAction{ID: "reveal", Name: "Reveal.js", Mode: "viewer", Builtin: true, OpenURL: "/v/slides" + semanticPath})
}
if selected.NeedsText || selected.ID == "html" || selected.ID == "excalidraw" {
actions = append(actions, adapterAction{
ID: "editor", Name: "Pages Wiki Editor", Mode: "editor",
+1 -9
View File
@@ -9,7 +9,6 @@ import (
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
@@ -321,13 +320,6 @@ func (s *Server) renderAuthPage(w http.ResponseWriter, r *http.Request, data map
transparency := s.homeGlassTransparency(domainUUID)
data["HomeGlassTransparency"] = transparency
data["HomeGlassOpacity"] = 100 - transparency
configured, opacity := s.homeWallpaperConfig(domainUUID)
data["HomeWallpaperOpacity"] = strconv.FormatFloat(float64(opacity)/100, 'f', 2, 64)
if configured != "" {
// Only the administrator-selected login wallpaper is exposed; the
// request cannot choose an arbitrary document address.
data["HomeWallpaperURL"] = "/_/auth/wallpaper"
w.Header().Set("Cache-Control", "private, no-store")
}
// Login has no wallpaper: private home images must not become public.
s.renderWithContext(w, r, "auth.gohtml", data)
}
@@ -72,6 +72,15 @@ func TestCalendarUpcomingDefaultsAndBounds(t *testing.T) {
t.Fatal("tomorrow event in today's widget", event.Start)
}
}
w = calendarRequest(s, token, "GET", calendarAPI+"upcoming?period=day&date="+end.Format("2006-01-02"), "", "")
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
t.Fatal(w.Code, w.Body)
}
for _, event := range result.Events {
if !event.Start.Before(end.AddDate(0, 0, 1)) || !event.End.After(end) {
t.Fatal("event outside tomorrow", event.Start, event.End)
}
}
if w = calendarRequest(s, "", "GET", calendarAPI+"upcoming", "", ""); w.Code != 403 {
t.Fatal("anonymous access", w.Code)
}
+150
View File
@@ -0,0 +1,150 @@
package server
import (
"bytes"
"context"
"encoding/json"
"html"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"time"
)
const csvEditorFixtureBody = "\ufeff\"name\",description\r\n日本語,\"a,b\r\nnext\"\r\n"
func TestCSVEditorRevisionAndBounds(t *testing.T) {
s, token, domain, _ := editorFixture(t)
object, err := s.store.CreatePageAtPathInDomain(domain, "/table.csv")
if err != nil {
t.Fatal(err)
}
first, err := s.store.SaveRevisionContent(object, []byte(csvEditorFixtureBody), "", "und", "text/csv; charset=utf-8", "table.csv")
if err != nil {
t.Fatal(err)
}
for _, query := range []string{"", "?edittype=markdown", "?lang=und"} {
w := configRequest(s, token, "GET", "/e/-/table.csv"+query, nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), `data-csv="true"`) || !strings.Contains(w.Body.String(), `value="code"`) || strings.Contains(w.Body.String(), `data-editor-action="markdown"`) {
t.Fatalf("editor %d %s", w.Code, w.Body.String())
}
}
head, _ := s.store.GetRevisionForExactLanguage(object, "und")
if head.UUID != first.UUID {
t.Fatal("GET changed revision")
}
save := func(auth, base, body string) int {
data, _ := json.Marshal(map[string]any{"object_uuid": object, "body": body, "lang": "und", "content_type": "text/csv; charset=utf-8", "filename": "table.csv", "base_revision_uuid": base})
r := httptest.NewRequest("POST", "http://localhost/_/api/v1/revisions/save", bytes.NewReader(data))
r.Header.Set("Authorization", "Bearer "+auth)
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(w, r)
return w.Code
}
changed := strings.Replace(csvEditorFixtureBody, "日本語", "更新", 1)
if code := save(token, first.UUID, changed); code != 200 {
t.Fatal("save", code)
}
if code := save(token, first.UUID, "stale"); code != 409 {
t.Fatal("stale save", code)
}
head, _ = s.store.GetRevisionForExactLanguage(object, "und")
if head.Body != changed || head.ContentType != "text/csv; charset=utf-8" || head.Filename != "table.csv" {
t.Fatal("CSV altered")
}
state := configRequest(s, token, "GET", "/_/api/v1/editor/state?uuid="+object+"&lang=und&revision="+first.UUID, nil)
var content struct {
Body string
Editable bool
}
if err = json.Unmarshal(state.Body.Bytes(), &content); err != nil || state.Code != 200 || !content.Editable || content.Body != csvEditorFixtureBody {
t.Fatal("restore", state.Code, err)
}
reader, err := s.store.CreatePasswordAccount(domain, "csvreader", "a long test password", "Reader", "")
if err != nil {
t.Fatal(err)
}
if err = s.store.SetPrincipalState(domain, reader.UUID, "readonly"); err != nil {
t.Fatal(err)
}
denied, _ := s.store.CreateAuthSession(domain, reader.UUID)
if code := save(denied, head.UUID, "forbidden"); code != 403 {
t.Fatal("readonly save", code)
}
// Initial CSV is embedded as an escaped JS string to preserve CRLF. A
// field must not terminate that script or become executable markup.
if _, err = s.store.SaveRevisionContent(object, []byte("\"</script><script>alert(1)</script>\",value\r\n"), "", "und", "text/csv", "table.csv"); err != nil {
t.Fatal(err)
}
escaped := configRequest(s, token, "GET", "/e/-/table.csv", nil)
if escaped.Code != 200 || strings.Contains(escaped.Body.String(), "<script>alert(1)</script>") || !strings.Contains(escaped.Body.String(), `\u003c/script\u003e`) {
t.Fatal("CSV script string was not escaped")
}
for _, input := range []struct {
body []byte
code int
}{{[]byte(strings.Repeat("x", maxCSVMacroBytes+1)), 413}, {[]byte{0xff, 0xfe}, 415}, {[]byte("a,\x00"), 415}} {
rev, e := s.store.SaveRevisionContent(object, input.body, "", "und", "text/csv", "table.csv")
if e != nil {
t.Fatal(e)
}
w := configRequest(s, token, "GET", "/e/-/table.csv", nil)
if w.Code != input.code {
t.Fatalf("editor bounds %d wanted %d", w.Code, input.code)
}
w = configRequest(s, token, "GET", "/_/api/v1/editor/state?uuid="+object+"&lang=und&revision="+rev.UUID, nil)
if w.Code != input.code {
t.Fatalf("state bounds %d wanted %d", w.Code, input.code)
}
}
}
func TestCSVEditorChromium(t *testing.T) {
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
t.Skip("opt-in Chromium")
}
for _, width := range []string{"1280", "390"} {
t.Run(width, func(t *testing.T) {
s, token, domain, _ := editorFixture(t)
object, err := s.store.CreatePageAtPathInDomain(domain, "/table.csv")
if err != nil {
t.Fatal(err)
}
if _, err = s.store.SaveRevisionContent(object, []byte(csvEditorFixtureBody), "", "und", "text/csv; charset=utf-8", "table.csv"); err != nil {
t.Fatal(err)
}
script, err := os.ReadFile("internal/server/testdata/csv-editor.js")
if err != nil {
t.Fatal(err)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Host = "localhost"
r.Header.Set("Authorization", "Bearer "+token)
if r.URL.Path == "/e/-/table.csv" {
rec := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(rec, r)
for k, v := range rec.Header() {
w.Header()[k] = v
}
w.WriteHeader(rec.Code)
_, policy, _ := strings.Cut(rec.Header().Get("Content-Security-Policy"), "'nonce-")
nonce, _, _ := strings.Cut(policy, "'")
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", `<script nonce="`+html.EscapeString(nonce)+`">`+string(script)+"</script></body>", 1)))
return
}
s.withAuthorization(s.mux).ServeHTTP(w, r)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", server.URL+"/e/-/table.csv", t.TempDir(), "/tmp/pageswiki-csv-editor-"+width+".png", width, "850").CombinedOutput()
if err != nil {
t.Fatalf("browser: %v %s", err, out)
}
})
}
}
+2 -2
View File
@@ -2,8 +2,8 @@ package server
func init() {
for lang, entries := range map[string]map[string]string{
"en": {"editor.tools": "Insert component / drafts", "editor.language": "Edit / fork language", "editor.restore": "Restore a revision into the editor"},
"ja": {"editor.tools": "コンポーネント挿入・下書き", "editor.language": "言語の編集・分岐", "editor.restore": "過去のリビジョンをエディタに復元"},
"en": {"editor.tools": "Insert component / drafts", "editor.language": "Edit / fork language", "editor.restore": "Restore a revision into the editor", "editor.csv_source": "CSV source", "editor.csv_table": "CSV table"},
"ja": {"editor.tools": "コンポーネント挿入・下書き", "editor.language": "言語の編集・分岐", "editor.restore": "過去のリビジョンをエディタに復元", "editor.csv_source": "CSVソースを表示", "editor.csv_table": "CSVの表を表示"},
} {
for key, value := range entries {
translations[lang][key] = value
+16 -2
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"net/http"
"strings"
"unicode/utf8"
"pageswiki/internal/grammaratur"
)
@@ -73,7 +74,20 @@ func (s *Server) handleEditorState(w http.ResponseWriter, r *http.Request) {
}
out := map[string]any{"revision_uuid": rev.UUID, "head_revision_uuid": head, "lang": rev.Language, "content_type": rev.ContentType, "filename": rev.Filename, "principal_uuid": owner}
if r.URL.Query().Get("metadata") != "1" {
if rev.UUID != "" {
csv := selectProjectionAdapter(contentDescriptor{MediaType: strings.ToLower(strings.TrimSpace(strings.Split(rev.ContentType, ";")[0])), Filename: rev.Filename}).Kind == "csv"
if csv {
size, e := s.store.DocumentSizeContext(r.Context(), rev.DocumentHash)
if e != nil || size > maxCSVMacroBytes {
http.Error(w, "CSV editor size limit exceeded", 413)
return
}
window, e := s.store.ReadDocumentWindowContext(r.Context(), rev.DocumentHash, 0, maxCSVMacroBytes)
if e != nil || window.Truncated || !utf8.Valid(window.Data) || strings.ContainsRune(string(window.Data), 0) {
http.Error(w, "CSV source unavailable or not UTF-8", 415)
return
}
rev.Body = string(window.Data)
} else if rev.UUID != "" {
rev, err = s.store.GetRevision(rev.UUID)
}
if err != nil {
@@ -90,7 +104,7 @@ func (s *Server) handleEditorState(w http.ResponseWriter, r *http.Request) {
}
out["body"], out["markdown"] = rev.Body, markdown
kind := revisionContentView(rev, "").Kind
out["editable"] = rev.UUID == "" || kind == "html" || kind == "code"
out["editable"] = rev.UUID == "" || kind == "html" || kind == "code" || (csv && utf8.ValidString(rev.Body) && !strings.ContainsRune(rev.Body, 0))
}
_ = json.NewEncoder(w).Encode(out)
}
+1 -1
View File
@@ -189,7 +189,7 @@ func readEndpointResolver(path string) (endpointTargetResolver, string) {
return resolveHandler, "read"
case strings.HasPrefix(path, "/_/view/print/"):
return resolvePrint, "read"
case strings.HasPrefix(path, "/v/preview"), strings.HasPrefix(path, "/v/plain"), strings.HasPrefix(path, "/v/markdown"):
case strings.HasPrefix(path, "/v/preview"), strings.HasPrefix(path, "/v/plain"), strings.HasPrefix(path, "/v/markdown"), path == "/v/slides", strings.HasPrefix(path, "/v/slides/"):
return resolveViewPath, "read"
case strings.HasPrefix(path, "/o/e/"):
return resolveObjectURL, "write"
+1 -1
View File
@@ -268,7 +268,7 @@ func objectIDFromRoute(path string) string {
}
func semanticViewPath(route string) string {
for _, prefix := range []string{"/v/preview", "/v/plain", "/v/markdown", "/v/browser"} {
for _, prefix := range []string{"/v/preview", "/v/plain", "/v/markdown", "/v/browser", "/v/slides"} {
if strings.HasPrefix(route, prefix) {
path := strings.TrimPrefix(route, prefix)
if path == "" {
+6 -66
View File
@@ -1,7 +1,6 @@
package server
import (
"bytes"
"crypto/rand"
"math/big"
"mime"
@@ -9,7 +8,6 @@ import (
pathpkg "path"
"strconv"
"strings"
"time"
"pageswiki/internal/store"
)
@@ -23,75 +21,16 @@ type homeWallpaperView struct {
Key string
}
// configuredLoginWallpaper returns only the image selected by the Domain
// administrator as the home/login wallpaper. It intentionally does not use
// the requesting principal's document permissions: choosing an image as the
// login wallpaper makes that one image public on the sign-in surface.
func (s *Server) configuredLoginWallpaper(domainUUID string) *store.Revision {
configured, _ := s.homeWallpaperConfig(domainUUID)
if configured == "" {
return nil
}
if objectUUID, err := s.store.ResolvePathInDomain(domainUUID, configured); err == nil {
revision, revisionErr := s.store.GetLatestRevisionForLanguages(objectUUID, []string{s.getLocale(domainUUID), "und"})
if revisionErr == nil && imageContentType(revision.ContentType) {
return revision
}
}
entries, err := s.store.ListBrowserEntriesInDomain(domainUUID, configured)
if err != nil {
return nil
}
candidates := make([]store.BrowserEntry, 0, len(entries))
for _, entry := range entries {
if !entry.IsDir && entry.RevisionUUID != "" && imageContentType(entry.ContentType) {
candidates = append(candidates, entry)
}
}
if len(candidates) == 0 {
return nil
}
index := 0
if value, randomErr := rand.Int(rand.Reader, big.NewInt(int64(len(candidates)))); randomErr == nil {
index = int(value.Int64())
}
revision, err := s.store.GetRevision(candidates[index].RevisionUUID)
if err != nil || !imageContentType(revision.ContentType) {
return nil
}
return revision
}
// Legacy route retained as a deliberate 404. Home wallpapers are never
// published to unauthenticated clients through the sign-in screen.
func (s *Server) handleAuthWallpaper(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
revision := s.configuredLoginWallpaper(s.domainUUIDForRequest(r))
if revision == nil {
http.NotFound(w, r)
return
}
contentType := revision.ContentType
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil || !strings.HasPrefix(strings.ToLower(mediaType), "image/") {
http.NotFound(w, r)
return
}
filename := strings.TrimSpace(revision.Filename)
if filename == "" {
filename = "wallpaper"
}
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": filename}))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("ETag", `"`+revision.DocumentHash+`"`)
if strings.EqualFold(mediaType, "image/svg+xml") {
w.Header().Set("Content-Security-Policy", "default-src 'none'; sandbox")
}
http.ServeContent(w, r, filename, time.UnixMilli(revision.CreatedAtMS), bytes.NewReader([]byte(revision.Body)))
http.NotFound(w, r)
}
func normalizePickerPath(raw string) (string, bool) {
@@ -135,7 +74,8 @@ func (s *Server) homeWallpaperConfig(domainUUID string) (string, int) {
func (s *Server) homeWallpaperForRequest(r *http.Request) homeWallpaperView {
domainUUID := s.domainUUIDForRequest(r)
configured, opacity := s.homeWallpaperConfig(domainUUID)
p := s.appearanceForRequest(r)
configured, opacity := p.Path, p.Opacity
view := homeWallpaperView{Path: configured, Opacity: strconv.FormatFloat(float64(opacity)/100, 'f', 2, 64)}
if configured == "" {
return view
+5 -4
View File
@@ -22,7 +22,7 @@ func saveWallpaperFixture(t *testing.T, s *Server, domain, path, contentType str
}
}
func TestAuthPageUsesConfiguredWallpaperAndGlass(t *testing.T) {
func TestAuthPageDoesNotPublishHomeWallpaper(t *testing.T) {
s, _, domain := configFixture(t)
s.mux.HandleFunc("/_/auth/", s.handleAuth)
saveWallpaperFixture(t, s, domain, "/wallpapers/login.jpg", "image/jpeg")
@@ -46,8 +46,6 @@ func TestAuthPageUsesConfiguredWallpaperAndGlass(t *testing.T) {
for _, expected := range []string{
`class="auth-page"`,
`--home-glass-opacity:53%`,
`class="home-wallpaper" src="/_/auth/wallpaper"`,
`style="opacity:0.41"`,
`/static/css/auth.css?v=1`,
`class="auth-provider-button"`,
`OpenID Connectでログイン`,
@@ -56,10 +54,13 @@ func TestAuthPageUsesConfiguredWallpaperAndGlass(t *testing.T) {
t.Fatalf("auth page missing %q: status=%d body=%s", expected, response.Code, body)
}
}
if strings.Contains(body, `class="home-wallpaper"`) || strings.Contains(body, `/_/auth/wallpaper`) {
t.Fatal("private home wallpaper exposed at login")
}
wallpaper := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(wallpaper, httptest.NewRequest(http.MethodGet, "http://localhost/_/auth/wallpaper?path=/private/ignored", nil))
if wallpaper.Code != http.StatusOK || wallpaper.Body.String() != "fixture" || wallpaper.Header().Get("Content-Type") != "image/jpeg" || wallpaper.Header().Get("X-Content-Type-Options") != "nosniff" {
if wallpaper.Code != http.StatusNotFound || wallpaper.Body.String() == "fixture" {
t.Fatalf("login wallpaper: status=%d type=%q body=%q", wallpaper.Code, wallpaper.Header().Get("Content-Type"), wallpaper.Body.String())
}
+1 -1
View File
@@ -37,7 +37,7 @@ func parseTrustedTemplates(t *template.Template) (*template.Template, error) {
func safeProjectionTemplate(name string) bool {
switch name {
case "periodical.gohtml", "public_periodical.gohtml", "periodical_new.gohtml":
case "periodical.gohtml", "public_periodical.gohtml", "periodical_new.gohtml", "slides.gohtml":
return true
case "city_map.gohtml", "public_tree.gohtml", "anonymous_view.gohtml", "page.gohtml", "home.gohtml", "search_home.gohtml", "object_view.gohtml", "revision_view.gohtml", "preview.gohtml", "print.gohtml", "profile.gohtml", "editor.gohtml", "object_editor.gohtml":
return true
+2 -2
View File
@@ -239,7 +239,7 @@ var translations = map[string]map[string]string{
"home.palette_brightness": "Light and dark",
"home.palette_preserve": "Keep the current theme brightness",
"home.palette_auto": "Choose from the displayed wallpaper",
"home.palette_help": "Applies only to the home page and its dialogs. Warning colors are preserved. If extraction fails, the selected theme remains. Shared by this domain.",
"home.palette_help": "Applies only to the home page and its dialogs. Warning colors are preserved. If extraction fails, the selected theme remains.",
"home.glass_transparency": "Glass transparency (%)",
"home.glass_help": "Controls the shared transparency of the home search, menus, suggestions, cards, and dialogs. Higher values are more transparent.",
"picker.open": "Browse PagesWiki",
@@ -1019,7 +1019,7 @@ var translations = map[string]map[string]string{
"home.palette_brightness": "明暗",
"home.palette_preserve": "現在のテーマの明暗を維持",
"home.palette_auto": "表示中の壁紙から自動判定",
"home.palette_help": "トップ画面とその上のダイアログにのみ適用します。警告色は変更しません。色を抽出できない場合は選択中のテーマを維持します。このドメインで共通の設定です。",
"home.palette_help": "トップ画面とその上のダイアログにのみ適用します。警告色は変更しません。色を抽出できない場合は選択中のテーマを維持します。",
"home.glass_transparency": "グラスの透明度(%)",
"home.glass_help": "トップ画面の検索、メニュー、サジェスト、カード、ダイアログに共通の透明度です。数値を上げるほど背景が透けます。",
"picker.open": "PagesWikiから選択",
+14 -2
View File
@@ -9,7 +9,7 @@ import (
)
func personalOrganizerSettings(r *http.Request) bool {
return r.URL.Path == "/-/sys/config" && r.URL.Query().Get("panel") == "organizer" && (r.Method == "GET" || r.Method == "HEAD")
return r.URL.Path == "/-/sys/config" && r.URL.Query().Get("panel") == "organizer" && (r.Method == "GET" || r.Method == "HEAD" || r.Method == "POST" && r.URL.Query().Get("section") == "appearance")
}
func (s *Server) handleOrganizerDashboard(w http.ResponseWriter, r *http.Request) {
@@ -33,7 +33,13 @@ func (s *Server) handleOrganizerSettings(w http.ResponseWriter, r *http.Request)
s.authRequired(w, r)
return
}
s.renderWithContext(w, r, "organizer_settings.gohtml", map[string]any{"TaskWritable": active})
if r.Method == "POST" {
s.savePersonalAppearance(w, r, actor, active)
return
}
data := s.appearanceData(r)
data["TaskWritable"] = active
s.renderWithContext(w, r, "organizer_settings.gohtml", data)
}
func (s *Server) handleDashboardData(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
@@ -110,6 +116,12 @@ func organizerSection(path string) string {
}
func init() {
translations["en"]["home.domain_appearance_defaults"] = "Appearance defaults (personal settings take precedence)"
translations["ja"]["home.domain_appearance_defaults"] = "外観の初期値(個人設定を優先)"
translations["en"]["home.personal_wallpaper"] = "Personal wallpaper Path (empty: none)"
translations["ja"]["home.personal_wallpaper"] = "個人の壁紙Path(空欄:なし)"
translations["en"]["home.personal_opacity"] = "Wallpaper opacity (%)"
translations["ja"]["home.personal_opacity"] = "壁紙の不透明度(%)"
translations["en"]["task.work_history"] = "Work history"
translations["ja"]["task.work_history"] = "作業記録"
for lang, entries := range map[string]map[string]string{
+11 -1
View File
@@ -69,12 +69,22 @@ func TestOrganizerDashboardLayoutIsolationAndCAS(t *testing.T) {
if err = json.Unmarshal(w.Body.Bytes(), &layout); err != nil || len(layout.Widgets) != 0 {
t.Fatal("empty layout reset", layout, err)
}
for _, invalid := range [][]store.DashboardWidget{{{ID: "iframe", Width: 4, Height: 3}}, {{ID: "tasks", Width: 13, Height: 3, Tab: "inbox"}}, {{ID: "tasks", Width: 4, Height: 3, Tab: "secret"}}, {{ID: "progress", Width: 4, Height: 3}, {ID: "progress", Width: 4, Height: 3}}} {
for _, invalid := range [][]store.DashboardWidget{{{ID: "iframe", Width: 4, Height: 3}}} {
w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": layout.Version, "widgets": invalid}, "")
if w.Code != 422 {
t.Fatal("invalid accepted", w.Code, w.Body)
}
}
for _, id := range []string{"commands", "tomorrow-schedule", "feeds"} {
input := []store.DashboardWidget{{ID: "tasks", Width: 13, Height: 0}, {ID: id, Width: 6, Height: 4, Tab: "obsolete"}, {ID: id, Width: 6, Height: 4}}
w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": layout.Version, "widgets": input}, "")
if w.Code != 200 {
t.Fatal("normalizable layout rejected", w.Code, w.Body)
}
if err = json.Unmarshal(w.Body.Bytes(), &layout); err != nil || len(layout.Widgets) != 2 || layout.Widgets[0].Width != 12 || layout.Widgets[0].Height != 2 || layout.Widgets[0].Tab != "inbox" || layout.Widgets[1].Tab != "" {
t.Fatal("normalization", layout, err)
}
}
other, err := s.store.CreatePasswordAccount(domain, "dashboardother", "long test password", "Other", "")
if err != nil {
t.Fatal(err)
+123
View File
@@ -0,0 +1,123 @@
package server
import (
"database/sql"
"encoding/json"
"errors"
"net/http"
"strconv"
)
// Personal appearance is separate from domain defaults and from organizer mail
// preferences. It never makes the selected documents publicly readable.
type personalAppearance struct {
Version int64
Path string
Opacity int
Glass int
Palette homePaletteSettings
}
func (s *Server) appearanceForRequest(r *http.Request) personalAppearance {
domain := s.domainUUIDForRequest(r)
path, opacity := s.homeWallpaperConfig(domain)
p := personalAppearance{Path: path, Opacity: opacity, Glass: s.homeGlassTransparency(domain), Palette: s.homePalette(domain)}
principal := s.requestPrincipal(r)
if principal == nil {
return p
}
var raw string
var version int64
if s.store.DB.QueryRowContext(r.Context(), `SELECT version,data FROM personal_appearance WHERE domain_uuid=? AND owner_uuid=?`, domain, principal.UUID).Scan(&version, &raw) == nil {
var saved personalAppearance
if json.Unmarshal([]byte(raw), &saved) == nil {
saved.Version = version
return saved
}
}
return p
}
func (s *Server) appearanceData(r *http.Request) map[string]any {
p := s.appearanceForRequest(r)
return map[string]any{"AppearanceVersion": p.Version, "HomeWallpaperPath": p.Path, "HomeWallpaperPercent": p.Opacity, "HomeGlassTransparency": p.Glass, "HomePalette": p.Palette}
}
func (s *Server) savePersonalAppearance(w http.ResponseWriter, r *http.Request, actor string, active bool) {
if !active || s.store.ReadOnly {
http.Error(w, "forbidden", 403)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 16384)
if r.ParseForm() != nil {
http.Error(w, "invalid form", 400)
return
}
domain := s.domainUUIDForRequest(r)
p := s.appearanceForRequest(r)
version, err := strconv.ParseInt(r.FormValue("version"), 10, 64)
if err != nil || version < 0 {
http.Error(w, "invalid version", 400)
return
}
if p.Version != version {
http.Error(w, "Settings changed elsewhere; reload before saving.", 409)
return
}
if p.Glass, err = normalizeHomeGlassTransparency(r.FormValue("home_glass_transparency")); err != nil {
http.Error(w, "invalid transparency", 400)
return
}
if p.Palette, err = s.parseHomePalette(domain, r.Form); err != nil {
http.Error(w, "invalid palette", 400)
return
}
if r.Form.Has("home_wallpaper_path") {
var ok bool
p.Path, ok = normalizePickerPath(r.FormValue("home_wallpaper_path"))
if !ok {
http.Error(w, "invalid Path", 400)
return
}
if p.Path != "" && !s.requestCanReadPath(r, p.Path) {
http.Error(w, "Path not readable", 403)
return
}
}
if r.Form.Has("home_wallpaper_opacity") {
p.Opacity, err = strconv.Atoi(r.FormValue("home_wallpaper_opacity"))
if err != nil || p.Opacity < 0 || p.Opacity > 100 {
http.Error(w, "invalid opacity", 400)
return
}
}
p.Version = version + 1
raw, _ := json.Marshal(p)
result, err := s.store.DB.ExecContext(r.Context(), `INSERT INTO personal_appearance(domain_uuid,owner_uuid,version,data) SELECT ?,?,?,? WHERE ?=0 ON CONFLICT(domain_uuid,owner_uuid) DO NOTHING`, domain, actor, p.Version, string(raw), version)
if err == nil {
var n int64
n, err = result.RowsAffected()
if err == nil && n == 0 {
result, err = s.store.DB.ExecContext(r.Context(), `UPDATE personal_appearance SET version=?,data=? WHERE domain_uuid=? AND owner_uuid=? AND version=?`, p.Version, string(raw), domain, actor, version)
if err == nil {
n, err = result.RowsAffected()
if n == 0 {
err = sql.ErrNoRows
}
}
}
}
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, "Settings changed elsewhere; reload before saving.", 409)
return
}
if err != nil {
http.Error(w, "Unable to save settings", 500)
return
}
if r.Header.Get("Accept") == "application/json" {
writeEventJSON(w, 200, map[string]any{"version": p.Version})
return
}
http.Redirect(w, r, "/-/sys/config?panel=organizer#appearance", http.StatusSeeOther)
}
@@ -0,0 +1,54 @@
package server
import (
"net/url"
"strings"
"testing"
)
func TestPersonalAppearanceIsolationAndCAS(t *testing.T) {
s, admin, domain := configFixture(t)
p, err := s.store.CreatePasswordAccount(domain, "appearanceuser", "long test password", "Member", "")
if err != nil {
t.Fatal(err)
}
token, err := s.store.CreateAuthSession(domain, p.UUID)
if err != nil {
t.Fatal(err)
}
endpoint := "/-/sys/config?panel=organizer&section=appearance"
form := url.Values{"version": {"0"}, "home_wallpaper_path": {""}, "home_wallpaper_opacity": {"50"}, "home_glass_transparency": {"71"}, "home_palette_mode": {"accent"}, "home_palette_strength": {"55"}, "home_palette_brightness": {"preserve"}}
w := configRequest(s, token, "POST", endpoint, form)
if w.Code != 303 || w.Header().Get("Location") != "/-/sys/config?panel=organizer#appearance" {
t.Fatal(w.Code, w.Body)
}
if w = configRequest(s, token, "POST", endpoint, form); w.Code != 409 {
t.Fatal("stale write", w.Code, w.Body)
}
w = configRequest(s, token, "GET", "/-/sys/config?panel=organizer", nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), `name="home_glass_transparency" type="number" min="0" max="85" value="71"`) {
t.Fatal("personal value missing", w.Code, w.Body)
}
w = configRequest(s, admin, "GET", "/-/sys/config?panel=organizer", nil)
if w.Code != 200 || strings.Contains(w.Body.String(), `max="85" value="71"`) {
t.Fatal("owner leakage", w.Code)
}
raw, _ := s.store.GetConfigInDomain(domain, "home_glass_transparency")
if raw == "71" {
t.Fatal("changed domain settings")
}
if w = configRequest(s, "", "POST", endpoint, form); w.Code == 303 && w.Header().Get("Location") == "/-/sys/config?panel=organizer#appearance" {
t.Fatal("anonymous write")
}
if err = s.store.SetPrincipalState(domain, p.UUID, "readonly"); err != nil {
t.Fatal(err)
}
token, err = s.store.CreateAuthSession(domain, p.UUID)
if err != nil {
t.Fatal(err)
}
form.Set("version", "1")
if w = configRequest(s, token, "POST", endpoint, form); w.Code != 403 {
t.Fatal("readonly write", w.Code)
}
}
+11 -6
View File
@@ -69,27 +69,32 @@ func (s *Server) renderWithContext(
data["TasksEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.tasks")
data["ContactsEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.contacts")
data["FeedsEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.feeds")
data["SlidesEnabled"] = s.systemExtensionEnabled(domainUUID, "viewer.slides")
data["OrganizerSection"] = organizerSection(r.URL.Path)
if r.URL.Path == "/" {
data["IsHome"] = true
data["BookmarkSections"] = s.bookmarkSections(r)
canConfigureHome := s.canManageAssets(r)
if controlled, err := s.store.DomainEntryControlled(domainUUID); err != nil || controlled {
canConfigureHome = false
_, canConfigureHome := s.calendarActor(r)
if s.requestPrincipal(r) != nil {
w.Header().Set("Cache-Control", "private, no-store")
}
data["CanManageBookmarks"] = s.canManageAssets(r)
data["CanConfigureHome"] = canConfigureHome
transparency := s.homeGlassTransparency(domainUUID)
appearance := s.appearanceForRequest(r)
for k, v := range s.appearanceData(r) {
data[k] = v
}
transparency := appearance.Glass
data["HomeGlassTransparency"] = transparency
data["HomeGlassOpacity"] = 100 - transparency
wallpaper := s.homeWallpaperForRequest(r)
data["HomeWallpaperURL"] = wallpaper.URL
data["HomeWallpaperOpacity"] = wallpaper.Opacity
data["HomeWallpaperKey"] = wallpaper.Key
data["HomePalette"] = s.homePalette(domainUUID)
data["HomePalette"] = appearance.Palette
data["HomePaletteDomain"] = domainUUID
if wallpaper.URL != "" {
w.Header().Set("Cache-Control", "private, no-cache")
w.Header().Set("Cache-Control", "private, no-store")
}
if data["CanManageBookmarks"] == true {
data["ManagedBookmarks"] = s.managedBookmarks(domainUUID)
+3
View File
@@ -16,6 +16,7 @@ type UIHandlers struct {
Preview http.HandlerFunc
PlainView http.HandlerFunc
MarkdownView http.HandlerFunc
Slides http.HandlerFunc
CompileMarkdown http.HandlerFunc
CompileDiagram http.HandlerFunc
Config http.HandlerFunc
@@ -93,6 +94,8 @@ func RegisterUIRoutes(
handleIfNotNil(mux, "/v/markdown", h.MarkdownView)
handleIfNotNil(mux, "/v/markdown/", h.MarkdownView)
handleIfNotNil(mux, "/v/slides", h.Slides)
handleIfNotNil(mux, "/v/slides/", h.Slides)
handleIfNotNil(mux, "/:/compile/markdown", h.CompileMarkdown)
handleIfNotNil(mux, "/:/compile/markdown/", h.CompileMarkdown)
+44 -9
View File
@@ -9,6 +9,7 @@ import (
"path"
"strings"
"time"
"unicode/utf8"
"pageswiki/internal/grammaratur"
"pageswiki/internal/store"
@@ -211,16 +212,43 @@ func (s *Server) handleSemanticEditor(
}
}
latest, err :=
s.latestRevisionForRequest(
r,
objectUUID,
)
body := ""
// CSV editing needs the complete source, never the viewer's truncated window.
// Check metadata before loading a potentially large document.
metadata, metaErr := s.store.GetLatestRevisionMetadataForLanguagesContext(r.Context(), objectUUID, s.revisionLanguageCandidates(r))
if lang := r.URL.Query().Get("lang"); lang != "" {
latest, err = s.store.GetRevisionForExactLanguage(objectUUID, lang)
metadata, metaErr = s.store.GetRevisionMetadataForExactLanguage(objectUUID, lang)
}
if metaErr != nil || metadata == nil {
http.Error(w, "revision unavailable or invalid language", http.StatusBadRequest)
return
}
csvEditor := selectProjectionAdapter(contentDescriptor{MediaType: strings.ToLower(strings.TrimSpace(strings.Split(metadata.ContentType, ";")[0])), Filename: metadata.Filename}).Kind == "csv"
if csvEditor {
size, sizeErr := s.store.DocumentSizeContext(r.Context(), metadata.DocumentHash)
if sizeErr != nil || size > maxCSVMacroBytes {
http.Error(w, "CSV editor requires a complete document of at most 256 KiB", http.StatusRequestEntityTooLarge)
return
}
}
var latest *store.Revision
if csvEditor {
// Load the immutable revision we checked; a concurrent new head is
// handled by the normal save CAS, not by an unbounded second read.
window, readErr := s.store.ReadDocumentWindowContext(r.Context(), metadata.DocumentHash, 0, maxCSVMacroBytes)
if readErr != nil || window.Truncated {
http.Error(w, "CSV source unavailable", http.StatusServiceUnavailable)
return
}
latest = metadata
latest.Body = string(window.Data)
} else {
latest, err = s.latestRevisionForRequest(r, objectUUID)
if lang := r.URL.Query().Get("lang"); lang != "" {
latest, err = s.store.GetRevisionForExactLanguage(objectUUID, lang)
}
}
body := ""
if err != nil {
http.Error(w, "revision unavailable or invalid language", 400)
return
@@ -233,7 +261,13 @@ func (s *Server) handleSemanticEditor(
if err == nil {
if latest.UUID != "" {
view := revisionContentView(latest, path)
if view.Kind == "code" {
if view.Kind == "csv" {
if !csvEditor || !utf8.ValidString(latest.Body) || strings.ContainsRune(latest.Body, 0) || len(latest.Body) > maxCSVMacroBytes {
http.Error(w, "CSV editor requires bounded UTF-8 text", http.StatusUnsupportedMediaType)
return
}
editType = "code"
} else if view.Kind == "code" {
editType = "code"
if strings.EqualFold(strings.TrimSpace(strings.Split(latest.ContentType, ";")[0]), "text/plain") {
editType = "plain"
@@ -294,6 +328,7 @@ func (s *Server) handleSemanticEditor(
"BaseBody": baseBody,
"BaseRevision": latest.UUID,
"EditType": editType,
"CSVEditor": csvEditor,
"PageLanguage": latest.Language,
"PageContentType": contentType,
"PageFilename": filename,
+1
View File
@@ -257,6 +257,7 @@ func (s *Server) registerRoutes() {
Preview: s.handlePreview,
PlainView: s.handlePlainView,
MarkdownView: s.handleMarkdownView,
Slides: s.handleSlides,
CompileMarkdown: s.handleCompileMarkdown,
CompileDiagram: s.handleCompileDiagram,
Config: s.handleConfig,
+6 -1
View File
@@ -77,9 +77,14 @@ func TestBookmarkAndVimSettingsChromium(t *testing.T) {
if len(items) != 2 || items[0].Kind != "section" || !items[0].Children || items[0].Href != "/docs" || items[1].Label != "Reference" {
t.Fatalf("saved bookmarks: %#v", items)
}
if got := s.homeGlassTransparency(domain); got != 57 {
r := httptest.NewRequest("GET", "http://localhost/", nil)
r.Header.Set("Authorization", "Bearer "+token)
if got := s.appearanceForRequest(r).Glass; got != 57 {
t.Fatalf("saved glass transparency: %d", got)
}
if s.homeGlassTransparency(domain) == 57 {
t.Fatal("personal appearance changed domain defaults")
}
vim := s.domainVimSettings(domain)
if !vim.Enabled || vim.Vimrc != "set tabstop=3\n" || vim.ColorName != "uploaded.vim" || !strings.Contains(vim.Colorscheme, "Normal") {
t.Fatalf("saved vim: %#v", vim)
+68
View File
@@ -0,0 +1,68 @@
package server
import (
"net/http"
"strings"
"unicode/utf8"
"pageswiki/internal/grammaratur"
)
const maxSlideSourceBytes = 256 << 10
func (s *Server) handleSlides(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
domain := s.domainUUIDForRequest(r)
if !s.systemExtensionEnabled(domain, "viewer.slides") {
http.NotFound(w, r)
return
}
path := semanticViewPath(r.URL.Path)
if !s.requestCanReadPath(r, path) {
http.NotFound(w, r)
return
}
object, err := s.store.ResolvePathInDomain(domain, path)
if err != nil {
http.NotFound(w, r)
return
}
revision, err := s.store.GetLatestRevisionMetadataForLanguagesContext(r.Context(), object, s.revisionLanguageCandidates(r))
if err != nil || revision == nil {
http.NotFound(w, r)
return
}
media := strings.ToLower(strings.TrimSpace(strings.Split(revision.ContentType, ";")[0]))
if media != "text/html" && media != "text/markdown" && media != "text/x-markdown" {
http.Error(w, "slides require HTML or Markdown", http.StatusUnsupportedMediaType)
return
}
size, err := s.store.DocumentSizeContext(r.Context(), revision.DocumentHash)
if err != nil {
http.NotFound(w, r)
return
}
if size > maxSlideSourceBytes {
http.Error(w, "slides source exceeds 256 KiB", http.StatusRequestEntityTooLarge)
return
}
window, err := s.store.ReadDocumentWindowContext(r.Context(), revision.DocumentHash, 0, maxSlideSourceBytes)
if err != nil || window.Truncated || !utf8.Valid(window.Data) {
http.Error(w, "invalid slides source", http.StatusUnsupportedMediaType)
return
}
source := string(window.Data)
if media != "text/html" {
source = grammaratur.MarkdownAuthoringHTML(source)
}
source = s.safeHTMLProjection(r, source, path, false)
w.Header().Set("Cache-Control", "private, no-store")
if r.Method == http.MethodHead {
return
}
s.renderWithContext(w, r, "slides.gohtml", map[string]any{"Title": path, "Path": path, "SlideSource": source})
}
+12
View File
@@ -0,0 +1,12 @@
package server
func init() {
for lang, entries := range map[string]map[string]string{
"en": {"slides.title": "Slides", "slides.help": "Local Reveal.js viewer and editor preview. Separate slides with a horizontal rule.", "slides.preview": "Slide preview", "slides.close": "Return to page", "slides.fullscreen": "Fullscreen", "slides.error": "Slides could not be displayed. Use the document view (limit: 256 KiB, 100 slides)."},
"ja": {"slides.title": "スライド", "slides.help": "ローカル同梱のReveal.jsで閲覧・編集プレビュー。水平線でスライドを区切ります。", "slides.preview": "スライドプレビュー", "slides.close": "ページへ戻る", "slides.fullscreen": "全画面", "slides.error": "スライドを表示できません。通常表示を使用してください(上限256 KiB・100枚)。"},
} {
for key, value := range entries {
translations[lang][key] = value
}
}
}
+143
View File
@@ -0,0 +1,143 @@
package server
import (
"context"
"html"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"time"
"pageswiki/internal/server/routes"
)
const slideFixture = `<h1>First slide</h1><p>日本語のスライド</p><hr><h2>Second slide</h2><ul><li>Local Reveal.js</li><li>No source mutation</li></ul>`
func TestSlidesAccessAndLimits(t *testing.T) {
s, token, domain, _ := editorFixture(t)
routes.RegisterUIRoutes(s.mux, routes.UIHandlers{Slides: s.handleSlides})
s.mux.HandleFunc("/deck", s.handleSemanticRoute)
object, err := s.store.CreatePageAtPathInDomain(domain, "/deck")
if err != nil {
t.Fatal(err)
}
save := func(body, media string) {
t.Helper()
if _, e := s.store.SaveRevisionContent(object, []byte(body), "", "und", media, ""); e != nil {
t.Fatal(e)
}
}
save(slideFixture, "text/html")
w := configRequest(s, token, "GET", "/v/slides/deck", nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), "data-slides-viewer") || !strings.Contains(w.Body.String(), "&lt;h1&gt;First slide") {
t.Fatalf("slides %d %s", w.Code, w.Body.String())
}
if !strings.Contains(w.Header().Get("Content-Security-Policy"), "'nonce-") {
t.Fatal("missing CSP")
}
page := configRequest(s, token, "GET", "/deck", nil)
if !strings.Contains(page.Body.String(), `href="/v/slides/deck"`) {
t.Fatal("viewer action missing")
}
editor := configRequest(s, token, "GET", "/e/-/deck", nil)
if !strings.Contains(editor.Body.String(), `data-editor-action="slides"`) {
t.Fatal("preview action missing")
}
// A missing or unauthorized semantic path is not exposed via the new view.
req := httptest.NewRequest("GET", "http://localhost/v/slides/deck", nil)
denied := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(denied, req)
if denied.Code == 200 || strings.Contains(denied.Body.String(), "First slide") {
t.Fatal("anonymous private content exposed")
}
if configRequest(s, token, "GET", "/v/slides/missing", nil).Code != 404 {
t.Fatal("missing deck")
}
if p := policyForRequest(httptest.NewRequest("GET", "/v/slides/deck", nil)); p.Resolver != resolveViewPath || p.Capability != "read" {
t.Fatal("wrong policy")
}
if semanticViewPath("/v/slides/deck") != "/deck" {
t.Fatal("wrong target")
}
save("# Markdown\n\n---\n\n## Second", "text/markdown")
if w = configRequest(s, token, "GET", "/v/slides/deck", nil); w.Code != 200 || !strings.Contains(w.Body.String(), "&lt;hr") {
t.Fatal("markdown projection", w.Code)
}
save("%PDF-synthetic", "application/pdf")
if configRequest(s, token, "GET", "/v/slides/deck", nil).Code != 415 {
t.Fatal("binary accepted")
}
save(strings.Repeat("x", maxSlideSourceBytes+1), "text/html")
if configRequest(s, token, "GET", "/v/slides/deck", nil).Code != 413 {
t.Fatal("oversize accepted")
}
save(slideFixture, "text/html")
if err = s.setSystemExtensionEnabled(domain, "viewer.slides", false); err != nil {
t.Fatal(err)
}
if configRequest(s, token, "GET", "/v/slides/deck", nil).Code != 404 {
t.Fatal("disabled viewer active")
}
editor = configRequest(s, token, "GET", "/e/-/deck", nil)
if strings.Contains(editor.Body.String(), `data-editor-action="slides"`) {
t.Fatal("disabled preview action")
}
}
func TestSlidesChromium(t *testing.T) {
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
t.Skip("opt-in Chromium")
}
for _, mode := range []string{"viewer", "editor"} {
for _, width := range []string{"1280", "390"} {
t.Run(mode+width, func(t *testing.T) {
s, token, domain, _ := editorFixture(t)
routes.RegisterUIRoutes(s.mux, routes.UIHandlers{Slides: s.handleSlides})
object, err := s.store.CreatePageAtPathInDomain(domain, "/deck")
if err != nil {
t.Fatal(err)
}
if _, err = s.store.SaveRevisionContent(object, []byte(slideFixture), "", "und", "text/html", ""); err != nil {
t.Fatal(err)
}
script, err := os.ReadFile("internal/server/testdata/slides.js")
if err != nil {
t.Fatal(err)
}
route := "/v/slides/deck"
if mode == "editor" {
route = "/e/-/deck"
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Host = "localhost"
r.Header.Set("Authorization", "Bearer "+token)
if r.URL.Path == route {
rec := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(rec, r)
for k, v := range rec.Header() {
w.Header()[k] = v
}
w.WriteHeader(rec.Code)
_, policy, _ := strings.Cut(rec.Header().Get("Content-Security-Policy"), "'nonce-")
nonce, _, _ := strings.Cut(policy, "'")
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", `<script nonce="`+html.EscapeString(nonce)+`">`+string(script)+"</script></body>", 1)))
return
}
s.withAuthorization(s.mux).ServeHTTP(w, r)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", server.URL+route, t.TempDir(), "/tmp/pageswiki-slides-"+mode+width+".png", width, "850")
cmd.Env = append(os.Environ(), "PAGESWIKI_SLIDES_BROWSER=1")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("browser %v: %s", err, out)
}
})
}
}
}
@@ -0,0 +1,66 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"time"
)
func TestTaskIndexChromium(t *testing.T) {
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
t.Skip("opt-in Chromium")
}
for _, width := range []string{"1440", "390"} {
t.Run(width, func(t *testing.T) {
s, token, domain, actor := taskFixture(t)
for i, title := range []string{"**Alpha**", "Beta", "Gamma"} {
task := newTaskRecord("task", title)
if i < 2 {
project, err := s.store.SaveTask(context.Background(), domain, actor, newTaskRecord("project", "Project "+title), 0)
if err != nil {
t.Fatal(err)
}
task.ProjectUUID = project.UUID
}
if i == 1 {
task.Status = "doing"
}
if _, err := s.store.SaveTask(context.Background(), domain, actor, task, 0); err != nil {
t.Fatal(err)
}
}
script, err := os.ReadFile("internal/server/testdata/task-index.js")
if err != nil {
t.Fatal(err)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Host = "localhost"
r.Header.Set("Authorization", "Bearer "+token)
if r.URL.Path == "/v/plan/tasks/index" {
rec := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(rec, r)
for k, v := range rec.Header() {
w.Header()[k] = v
}
w.WriteHeader(rec.Code)
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", browserFixtureScript(rec.Header(), script)+"</body>", 1)))
return
}
s.withAuthorization(s.mux).ServeHTTP(w, r)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", strings.Replace(server.URL, "127.0.0.1", "localhost", 1)+"/v/plan/tasks/index", t.TempDir(), "/tmp/pages-task-index-"+width+".png", width, "900")
cmd.Env = append(os.Environ(), "PAGESWIKI_TASK_INDEX_BROWSER=1")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("browser %v: %s", err, out)
}
})
}
}
+143
View File
@@ -0,0 +1,143 @@
package server
import (
"context"
"encoding/json"
"net/url"
"testing"
"time"
"pageswiki/internal/store"
)
func TestTaskIndexFilteringSortingPagination(t *testing.T) {
s, token, domain, actor := taskFixture(t)
today := time.Now().In(s.getLocation(domain)).Format("2006-01-02")
project, err := s.store.SaveTask(context.Background(), domain, actor, newTaskRecord("project", "Index project"), 0)
if err != nil {
t.Fatal(err)
}
page, err := s.store.CreatePageAtPathInDomain(domain, "/index-related")
if err != nil {
t.Fatal(err)
}
for i, title := range []string{"Alpha release", "Beta release", "Gamma", "Delta"} {
task := newTaskRecord("task", title)
task.DueOn = []string{"2020-01-01", "2020-01-01", "2099-01-01", ""}[i]
if i == 0 {
task.Status = "doing"
task.Priority = 3
task.References = []string{"/files/ref.pdf"}
task.ProjectUUID = project.UUID
task.PageUUID = page
task.StartOn = "2019-01-01"
task.PlannedOn = today
task.ReviewOn = today
}
if i == 2 {
task.Status = "done"
}
if i == 3 {
task.Archived = true
}
if _, err = s.store.SaveTask(context.Background(), domain, actor, task, 0); err != nil {
t.Fatal(err)
}
}
type result struct {
Items []store.TaskRecord
Next string
}
get := func(filter, sort, order, project, before string, limit int) result {
t.Helper()
q := url.Values{"view": {"index"}, "filter": {filter}, "sort": {sort}, "order": {order}, "project": {project}, "before": {before}, "limit": {"1"}}
if limit > 1 {
q.Set("limit", "100")
}
w := taskRequest(s, token, "GET", "items?"+q.Encode(), nil, "")
var d result
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &d) != nil {
t.Fatal(w.Code, w.Body)
}
return d
}
first := get("~active", "title", "asc", "", "", 1)
if len(first.Items) != 1 || first.Items[0].Title != "Alpha release" || first.Next == "" {
t.Fatal(first)
}
second := get("~active", "title", "asc", "", first.Next, 1)
if len(second.Items) != 1 || second.Items[0].Title != "Beta release" || second.Next != "" {
t.Fatal(second)
}
reverse := get("~active", "title", "desc", "", "", 100)
if len(reverse.Items) != 2 || reverse.Items[0].Title != "Beta release" {
t.Fatal(reverse)
}
cases := map[string]string{`~s "Alpha release" ~doing ~overdue ~priority 3 ~attachment`: "Alpha release", `~due <=today !~doing ~active`: "Beta release", `~done !~overdue`: "Gamma", `~archived ~due none`: "Delta", `~s release ~due <` + today + ` ~doing`: "Alpha release"}
for filter, title := range cases {
r := get(filter, "due", "asc", "", "", 100)
if len(r.Items) != 1 || r.Items[0].Title != title {
t.Fatal(filter, r)
}
}
for _, filter := range []string{"~wiki", "~start <=2020-01-01 ~planned today ~review =today"} {
r := get(filter, "due", "asc", "", "", 100)
if len(r.Items) != 1 || r.Items[0].Title != "Alpha release" {
t.Fatal(filter, r)
}
}
for _, key := range []string{"due", "planned", "title", "status", "priority", "created", "updated"} {
a := get("~active", key, "asc", "", "", 1)
b := get("~active", key, "asc", "", a.Next, 1)
rev := get("~active", key, "desc", "", "", 100)
if a.Next == "" || len(b.Items) != 1 || b.Items[0].UUID == a.Items[0].UUID || len(rev.Items) != 2 || rev.Items[0].UUID != b.Items[0].UUID {
t.Fatal("unstable sort", key, a, b, rev)
}
}
if r := get("~active", "due", "asc", "none", "", 100); len(r.Items) != 1 || r.Items[0].Title != "Beta release" {
t.Fatal(r)
}
if r := get("", "due", "asc", project.UUID, "", 100); len(r.Items) != 1 || r.Items[0].Title != "Alpha release" {
t.Fatal(r)
}
for _, filter := range []string{`~unknown`, `~s`, `~s "unfinished`, `~due 2026-02-30`, `~priority 8`, `~bucket whatever`} {
w := taskRequest(s, token, "GET", "items?view=index&filter="+url.QueryEscape(filter), nil, "")
if w.Code != 422 {
t.Fatal("invalid accepted", filter, w.Code)
}
}
if w := taskRequest(s, token, "GET", "items?view=index&sort=title%3BDROP+TABLE+organizer_items", nil, ""); w.Code != 422 {
t.Fatal(w.Code)
}
if w := configRequest(s, token, "GET", "/v/plan/tasks/index", nil); w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
other, err := s.store.CreatePasswordAccount(domain, "indexother", "long test password", "Other", "")
if err != nil {
t.Fatal(err)
}
otherToken, err := s.store.CreateAuthSession(domain, other.UUID)
if err != nil {
t.Fatal(err)
}
w := taskRequest(s, otherToken, "GET", "items?view=index&before="+first.Next, nil, "")
var empty result
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &empty) != nil || len(empty.Items) != 0 {
t.Fatal("cross-owner leakage", w.Code, w.Body)
}
if err = s.store.SetPrincipalState(domain, actor, "readonly"); err != nil {
t.Fatal(err)
}
readonlyToken, err := s.store.CreateAuthSession(domain, actor)
if err != nil {
t.Fatal(err)
}
if w = taskRequest(s, readonlyToken, "GET", "items?view=index", nil, ""); w.Code != 200 {
t.Fatal("readonly read", w.Code)
}
item := first.Items[0]
item.Status = "done"
if w = taskRequest(s, readonlyToken, "PUT", "items/"+item.UUID, item, `"1"`); w.Code != 403 {
t.Fatal("readonly mutation", w.Code)
}
}
+102
View File
@@ -0,0 +1,102 @@
package server
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"time"
)
// Exercise the actual CLI executable boundary, full production router and
// browser-session authentication. All mail, credentials and storage are synthetic.
func TestNeoMuttMailViewerFlow(t *testing.T) {
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("python3 not installed")
}
fixture, token, domain := configFixture(t)
fixture.store.BackgroundJobsDisabled = true
s := New(fixture.store)
p, err := s.store.PrincipalForSession(domain, token)
if err != nil {
t.Fatal(err)
}
browser, err := s.store.CreateBrowserAuthSession(domain, p.UUID, 0)
if err != nil {
t.Fatal(err)
}
handler := s.handler()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Host = "localhost"
if r.URL.Path == "/fixture-browser-login" {
s.setAuthCookie(w, r, browser)
http.Redirect(w, r, r.URL.Query().Get("return"), http.StatusSeeOther)
return
}
handler.ServeHTTP(w, r)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
input, _ := json.Marshal(map[string]any{"origin": server.URL, "browser": browser, "root": t.TempDir(), "chromium": os.Getenv("PAGESWIKI_BROWSER_TEST") == "1"})
cmd := exec.CommandContext(ctx, "python3", "pages-cli/test_neomutt_viewer.py")
cmd.Stdin = bytes.NewReader(input)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("NeoMutt flow: %v\n%s", err, out)
}
if !strings.Contains(string(out), "MAIL_VIEWER_OK") {
t.Fatalf("missing verification: %s", out)
}
t.Log(string(out))
// Capture creates only the leaf document: prefix and date/list directories
// remain virtual. Exercise the parent URLs under both documented settings.
request := func(path string) *httptest.ResponseRecorder {
r := httptest.NewRequest(http.MethodGet, "http://localhost"+strings.ReplaceAll(path, " ", "%20"), nil)
r.AddCookie(&http.Cookie{Name: authCookieName, Value: browser})
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
return w
}
for _, enabled := range []bool{false, true} {
value, expected := "false", http.StatusNotFound
if enabled {
value, expected = "true", http.StatusOK
}
if err := s.store.SetConfigInDomain(domain, "virtual_folder_pages", value); err != nil {
t.Fatal(err)
}
if w := request("/tasks/"); w.Code != http.StatusMovedPermanently || w.Header().Get("Location") != "/tasks" {
t.Fatalf("tasks trailing slash: %d %s", w.Code, w.Header().Get("Location"))
}
for _, path := range []string{"/tasks", "/tasks/example.list", "/tasks/2026/01", "/mail", "/mail/example.list", "/private/mail", "/private/mail/2026", "/private/mail/2026/01", "/受信 メール", "/docs/mail", "/api/mail"} {
w := request(path)
if w.Code != expected || !strings.Contains(strings.ToLower(w.Body.String()), "<!doctype html>") {
t.Fatalf("parent %s virtual=%t: %d %s", path, enabled, w.Code, w.Body.String())
}
if strings.Contains(w.Body.String(), `{"detail":"Not Found"}`) {
t.Fatal("unexpected JSON error")
}
}
t.Logf("parent prefix/list/year/month: virtual_folder_pages=%t status=%d HTML", enabled, expected)
}
if err := s.store.SetConfigInDomain(domain, "virtual_folder_pages", "false"); err != nil {
t.Fatal(err)
}
id, err := s.store.CreatePageAtPathInDomain(domain, "/private/mail")
if err != nil {
t.Fatal(err)
}
if _, err = s.store.SaveRevisionContent(id, []byte("<h1>Synthetic mail portal</h1>{{children}}"), "", "und", "text/html", ""); err != nil {
t.Fatal(err)
}
if w := request("/private/mail"); w.Code != 200 || !strings.Contains(w.Body.String(), "Synthetic mail portal") {
t.Fatalf("explicit parent document: %d", w.Code)
}
t.Log("explicit parent document: status=200 HTML with virtual folders disabled")
}
+50
View File
@@ -0,0 +1,50 @@
package server
import (
"context"
"encoding/json"
"testing"
)
func TestTaskReferencesRoundTripAndLegacyUpdate(t *testing.T) {
s, token, domain, actor := taskFixture(t)
task := newTaskRecord("task", "**Bold** and `code`")
task.References = []string{"https://example.test/doc", "/files/資料.pdf"}
w := taskRequest(s, token, "POST", "items", task, "")
if w.Code != 201 {
t.Fatal(w.Code, w.Body)
}
task.References = nil
task.Title = "Updated"
w = taskRequest(s, token, "PUT", "items/"+task.UUID, task, `"1"`)
if w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
got, err := s.store.GetTask(context.Background(), domain, actor, task.UUID)
if err != nil || len(got.References) != 2 {
t.Fatal(got, err)
}
raw, _ := json.Marshal(got)
var body map[string]any
json.Unmarshal(raw, &body)
body["references"] = []string{}
w = taskRequest(s, token, "PUT", "items/"+task.UUID, body, `"2"`)
if w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
got, err = s.store.GetTask(context.Background(), domain, actor, task.UUID)
if err != nil || len(got.References) != 0 {
t.Fatal("references not cleared", got, err)
}
for _, ref := range []string{"javascript:alert(1)", "data:text/html,hi", "//evil.test/x", "/\\evil.test/x", "https://user:pass@example.test", "https://example.test/\nheader"} {
bad := newTaskRecord("task", "bad")
bad.References = []string{ref}
if w = taskRequest(s, token, "POST", "items", bad, ""); w.Code != 422 {
t.Fatal("unsafe reference accepted", ref, w.Code)
}
}
widgets := []map[string]any{{"id": "tomorrow-schedule", "width": 6, "height": 4}, {"id": "commands", "width": 6, "height": 3}}
if w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": 0, "widgets": widgets}, ""); w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
}
+122
View File
@@ -0,0 +1,122 @@
package server
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/google/uuid"
"pageswiki/internal/store"
)
// No Python/Chromium dependency: the production route and authorization stack
// must continue to serve /tasks as Wiki space, not the organizer task UI/API.
func TestTaskWikiPrefixRouting(t *testing.T) {
fixture, token, domain := configFixture(t)
fixture.store.BackgroundJobsDisabled = true
s := New(fixture.store)
p, err := s.store.PrincipalForSession(domain, token)
if err != nil {
t.Fatal(err)
}
cookie, err := s.store.CreateBrowserAuthSession(domain, p.UUID, 0)
if err != nil {
t.Fatal(err)
}
handler := s.handler()
request := func(method, target string, payload any, authenticated bool) *httptest.ResponseRecorder {
body, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
r := httptest.NewRequest(method, "http://localhost"+target, bytes.NewReader(body))
if authenticated {
if method == http.MethodGet {
r.AddCookie(&http.Cookie{Name: authCookieName, Value: cookie})
} else {
r.Header.Set("Authorization", "Bearer "+token)
}
}
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
return w
}
prefs, err := s.store.TaskPreferences(t.Context(), domain, p.UUID)
if err != nil {
t.Fatal(err)
}
prefs.WikiPrefix = "/tasks"
if w := request("PUT", tasksAPI+"preferences", prefs, true); w.Code != 200 {
t.Fatalf("preferences: %d %s", w.Code, w.Body)
}
for i, suffix := range []string{"example/123", "2026/11/" + uuid.NewString(), "2026/11/" + strings.Repeat("a", 64), ""} {
input := map[string]any{"request_id": uuid.NewString(), "title": "合成メール", "wiki_body": "Synthetic routing test body"}
if suffix != "" {
input["wiki_suffix"] = suffix
}
w := request("POST", tasksAPI+"capture", input, true)
if w.Code != 201 {
t.Fatalf("capture: %d %s", w.Code, w.Body)
}
var result struct {
Item store.TaskRecord `json:"item"`
Path string `json:"page_path"`
}
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(result.Path, "/tasks/") {
t.Fatal(result.Path)
}
alias := "/prj/awesome"
if i != 0 {
alias += "/" + strconv.Itoa(i)
}
if err := s.store.AddPathLinkInDomain(domain, result.Item.PageUUID, alias); err != nil {
t.Fatal(err)
}
for _, target := range []string{result.Path, alias} {
if taskRoute(target) {
t.Fatalf("Wiki path captured by organizer routing: %s", target)
}
id, err := s.store.ResolvePathInDomain(domain, target)
if err != nil || id != result.Item.PageUUID {
t.Fatalf("alias identity: %s %v", id, err)
}
w := request("GET", target, nil, true)
if w.Code != 200 || !strings.Contains(w.Body.String(), "Synthetic routing test body") || !strings.Contains(strings.ToLower(w.Body.String()), "<!doctype html>") {
t.Fatalf("viewer %s: %d %s", target, w.Code, w.Body)
}
if w := request("GET", target+"/", nil, true); w.Code != 301 || w.Header().Get("Location") != target {
t.Fatalf("trailing slash %s: %d", target, w.Code)
}
if w := request("GET", target, nil, false); w.Code != 303 || strings.Contains(w.Body.String(), "Synthetic routing test body") {
t.Fatalf("anonymous isolation %s: %d", target, w.Code)
}
}
parent := result.Path[:strings.LastIndex(result.Path, "/")]
if w := request("GET", "/v/browser"+parent, nil, true); w.Code != 200 || !strings.Contains(w.Body.String(), `data-path="`+result.Path+`"`) {
t.Fatalf("listing: %d", w.Code)
}
}
for _, enabled := range []string{"false", "true"} {
if err := s.store.SetConfigInDomain(domain, "virtual_folder_pages", enabled); err != nil {
t.Fatal(err)
}
expected := http.StatusNotFound
if enabled == "true" {
expected = http.StatusOK
}
for _, target := range []string{"/tasks", "/tasks/example", "/tasks/2026", "/tasks/2026/11"} {
w := request("GET", target, nil, true)
if w.Code != expected || !strings.Contains(strings.ToLower(w.Body.String()), "<!doctype html>") {
t.Fatalf("virtual parent %s enabled=%s: %d", target, enabled, w.Code)
}
}
}
}
+2 -2
View File
@@ -146,7 +146,7 @@ func (s *Server) handleTaskPage(w http.ResponseWriter, r *http.Request) {
selectedDate, view = d.Format("2006-01-02"), "day"
}
switch view {
case "inbox", "backlog", "someday", "review", "done", "archived", "carryover", "day":
case "inbox", "backlog", "someday", "review", "done", "archived", "carryover", "day", "index":
case "tomorrow":
selectedDate = time.Now().In(s.getLocation(domain)).AddDate(0, 0, 1).Format("2006-01-02")
view = "day"
@@ -315,7 +315,7 @@ func (s *Server) handleTasksAPI(w http.ResponseWriter, r *http.Request) {
selected = q.Get("date")
}
hierarchy := q.Get("hierarchy") == "1"
items, next, err := s.store.ListTasks(ctx, domain, actor, store.TaskQuery{Kind: kind, View: view, Project: q.Get("project"), Parent: q.Get("parent"), Search: q.Get("q"), Today: selected, Before: q.Get("before"), Limit: limit, Hierarchy: hierarchy})
items, next, err := s.store.ListTasks(ctx, domain, actor, store.TaskQuery{Kind: kind, View: view, Project: q.Get("project"), Parent: q.Get("parent"), Search: q.Get("q"), Today: selected, Before: q.Get("before"), Limit: limit, Hierarchy: hierarchy, Filter: q.Get("filter"), Sort: q.Get("sort"), Order: q.Get("order")})
if err != nil {
taskError(w, err)
return
+67
View File
@@ -0,0 +1,67 @@
(async()=>{
const assert=(ok,msg)=>{if(!ok)throw Error(msg)},delay=ms=>new Promise(r=>setTimeout(r,ms));
const wait=async fn=>{for(let n=0;n<150;n++){if(fn())return;await delay(25)}throw Error('Timeout '+fn)};
await wait(()=>window.PagesWikiCodeMirror&&document.querySelector('.csv-edit-scroll textarea'));
const e=window.PagesEditor;setEditorPreviewVisible(true);e.paused=true;
if(innerWidth<=700){assert(getComputedStyle(document.querySelector('.editor-pane')).display==='none','Mobile table is not full width');setEditorPreviewVisible(false);assert(getComputedStyle(document.querySelector('.editor-pane')).display!=='none','Mobile source inaccessible');setEditorPreviewVisible(true);}
const original=e.text(),base=e.baseRevision;
const cell=(r,c)=>document.querySelector(`.csv-edit-scroll textarea[data-row="${r}"][data-column="${c}"]`);
const button=text=>[...document.querySelectorAll('.csv-edit-toolbar button')].find(b=>b.textContent===text);
let input=cell(1,0);input.focus();input.value='新しい,名前';input.dispatchEvent(new Event('input',{bubbles:true}));
await delay(400);assert(document.activeElement===input,'Table caret lost; connected='+input.isConnected+' active='+document.activeElement?.className);
assert(e.text()==='\ufeff"name",description\r\n"新しい,名前","a,b\r\nnext"\r\n','Untouched CSV changed');
e.persist();assert(localStorage.getItem(e.keyPrefix()+e.tab),'CSV draft missing');
button('↶').click();assert(e.text()===original,'Undo not lossless');button('↷').click();
assert(await e.saveNow(),'CSV save failed');assert(e.baseRevision!==base,'Revision unchanged');
let state=await e.state();assert(state.body===e.text()&&state.content_type==='text/csv; charset=utf-8'&&state.editable,'CSV metadata changed');
// Markup and formulas are text, never document nodes or evaluated values.
e.paused=true;input=cell(1,0);input.value='<img src=x onerror=alert(1)>';input.dispatchEvent(new Event('input',{bubbles:true}));
assert(!document.querySelector('.csv-edit-pane img'),'CSV injected markup');
assert(await e.saveNow(),'Markup-as-data save failed');
// A competing change is always reviewed, even on different CSV fields.
const remoteBody=PagesCSV.edit(e.text(),'cell',0,1,'remote');
const remote=await e.post('/_/api/v1/revisions/save',{object_uuid:e.value('object-uuid'),body:remoteBody,lang:'und',content_type:e.value('page-content-type'),filename:'table.csv',base_revision_uuid:e.baseRevision,editor_principal_uuid:e.owner});
e.paused=true;e.setText(PagesCSV.edit(e.text(),'cell',1,0,'local'));
assert(!await e.saveNow(),'Conflicting CSV silently saved');
assert(document.querySelector('#editor-dialog textarea[readonly]'),'CSV conflict comparison missing');
assert((await e.state()).revision_uuid===remote.revision_uuid,'Remote CSV overwritten');
const merged=PagesCSV.edit(remoteBody,'cell',1,0,'local');
const areas=document.querySelectorAll('#editor-dialog textarea');areas[areas.length-1].value=merged;
document.querySelector('#editor-dialog footer button:last-child').click();await wait(()=>!document.querySelector('#editor-dialog'));
assert(await e.saveNow(),'Reviewed CSV failed to save');
// Restore stages the old CSV, retains MIME and creates a new revision on save.
e.paused=true;await e.historyDialog();const history=document.querySelector('#editor-dialog select');history.value=base;
document.querySelector('#editor-dialog footer button:last-child').click();await wait(()=>!document.querySelector('#editor-dialog'));
assert(e.text()===original,'History did not restore exact CSV');assert(await e.saveNow(),'Restore save failed');
// Source syntax errors do not cause a truncated table to be written back.
e.paused=true;e.setText('"unfinished');await e.renderPreview();assert(!document.querySelector('.csv-edit-scroll'),'Malformed CSV table editable');assert(e.text()==='"unfinished','Malformed source lost');
e.setText(original);await e.renderPreview();
for(let i=0;i<27;i++)button('+↧').click();
assert(PagesCSV.parse(e.text()).rows.length===29,'Row append failed');
assert(document.querySelectorAll('.csv-edit-scroll tbody tr').length<=25,'Table was not paged');
button('‹').click();assert(document.querySelectorAll('.csv-edit-scroll tbody tr').length===25,'Previous page missing');
button('+→').click();assert(PagesCSV.parse(e.text()).rows[0].cells.length===3,'Column append failed');
cell(1,1).focus();button('−→').click();assert(PagesCSV.parse(e.text()).rows[0].cells.length===2,'Column delete failed');
button('↶').click();cell(1,1).focus();button('−↧').click();assert(PagesCSV.parse(e.text()).rows.length===28,'Row delete failed');
button('↶').click();
// Spreadsheet clipboard paste is one atomic undo step, including new rows.
e.setText(original);await e.renderPreview();
const paste=(r,c,text)=>{const data=new DataTransfer();data.setData('text/plain',text);data.setData('text/html','<img src=x onerror=alert(1)>');const target=cell(r,c);target.focus();const event=new ClipboardEvent('paste',{clipboardData:data,bubbles:true,cancelable:true});target.dispatchEvent(event);return event;};
assert(paste(1,0,'first\t"multi\nline"\r\n<img src=x onerror=alert(1)>\t=1+1\r\n').defaultPrevented,'Table paste not intercepted');
const pasted=e.text();assert(PagesCSV.parse(pasted).rows.length===3,'Paste did not grow rows');
assert(cell(1,1).value==='multi\nline','Quoted multiline clipboard broken');
assert(!document.querySelector('.csv-edit-pane img'),'Clipboard HTML executed');
assert(document.activeElement===cell(1,0),'Paste focus lost');
assert(await e.saveNow(),'Pasted CSV save failed');assert((await e.state()).body===pasted,'Pasted CSV not persisted exactly');e.paused=true;
button('↶').click();assert(e.text()===original,'Paste not undone atomically');
button('↷').click();assert(e.text()===pasted,'Paste redo changed bytes');
assert(paste(1,0,'valid\tdata\n"unfinished').defaultPrevented,'Malformed paste fell through');
assert(e.text()===pasted,'Malformed paste partially applied');
assert(paste(1,0,'a\n'.repeat(200)).defaultPrevented,'Oversize paste fell through');
assert(e.text()===pasted,'Oversize paste partially applied');
assert(!paste(1,0,'ordinary, text').defaultPrevented,'Single-cell text paste intercepted');
button('↶').click();assert(e.text()===original,'Rejected paste polluted undo');
const css=getComputedStyle(document.querySelector('.csv-edit-toolbar'));assert(css.color!==css.backgroundColor,'Toolbar lacks contrast');
clearTimeout(e.autosaveTimer);clearInterval(e.stateTimer);e.paused=true;
document.body.dataset.vimReady='true';
})().catch(error=>{const p=document.createElement('pre');p.id='error';p.textContent=error.stack;document.body.append(p)});
+3
View File
@@ -109,6 +109,9 @@
e.tools();
const style=w.getComputedStyle(d.querySelector('#editor-dialog'));
assert(style.color!==style.backgroundColor&&style.backgroundColor!=='rgba(0, 0, 0, 0)','Dialog not themed');
const components=d.querySelector('#editor-dialog select');components.selectedIndex=components.options.length-1;
d.querySelector('#editor-dialog footer button:nth-child(2)').click();await wait(()=>!d.querySelector('#editor-dialog'));
assert(e.text().includes('{{csv:/data/table.csv')&&!e.text().includes('{=html}'),'CSV macro insertion was wrapped in protected HTML');
document.body.dataset.vimReady='true';
} catch(error) {const box=document.createElement('div');box.id='error';box.textContent=error.stack||error.message;document.body.prepend(box)}
})();
+1 -1
View File
@@ -27,7 +27,7 @@
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'));
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 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^="/o/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'));
assert(d.documentElement.scrollWidth<=w.innerWidth,'Reader overflow');
d.getElementById('feed-opml').click();await wait(()=>d.getElementById('feed-opml-file'));
+23 -1
View File
@@ -8,7 +8,8 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
const prefs=await fetch(api+'preferences').then(r=>r.json());const saved=await fetch(api+'preferences',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({...prefs.preferences,notify_due:true,notify_planned:true,reminder_time:'10:35'})});if(!saved.ok)throw Error('Preferences save failed');
document.querySelector('#tasks-new').click();await wait(()=>input('page_path'));
if(input('notify_due').checked||input('notify_planned').checked)throw Error('Undated task enabled reminders');
fill(input('title'),'タスク編集のレイアウト確認');fill(input('notes'),'主要項目を左右に整理。日付と通知をまとめて設定します。');
fill(input('title'),'**タスク編集のレイアウト確認**');fill(input('notes'),'主要項目を左右に整理。日付と通知をまとめて設定します。');
fill(input('references'),'https://example.test/doc\n/files/資料.pdf');
fill(input('planned_on'),'2030-01-01');fill(input('due_on'),'2030-01-02');
if(!input('notify_due').checked||!input('notify_planned').checked||input('reminder_time').value!=='10:35')throw Error('Dated defaults missing');
input('notify_due').click();fill(input('due_on'),'2030-01-03');if(input('notify_due').checked)throw Error('Explicit reminder choice overwritten');
@@ -18,6 +19,9 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
if(task.status!=='doing'||task.bucket!=='backlog'||task.complexity!==4||!task.notify_planned||task.notify_due||task.reminder_time!=='10:35')throw Error('Editor fields not persisted');
await wait(()=>document.querySelector('[data-task-id="'+task.uuid+'"] [data-action=detail]'));document.querySelector('[data-task-id="'+task.uuid+'"] [data-action=detail]').click();await wait(()=>input('page_path'));
if(input('notify_due').checked)throw Error('Defaults changed existing task');
if(task.references?.length!==2||input('references').value!=='https://example.test/doc\n/files/資料.pdf')throw Error('Task references lost');
const preview=document.querySelector('.task-title-preview');if(!preview?.querySelector('strong')||getComputedStyle(preview).display==='none'||preview.getBoundingClientRect().height<10)throw Error('Markdown title preview missing');
const safe=document.createElement('div');PagesTaskPresentation.render(safe,'<img src=x onerror=alert(1)> [bad](javascript:alert) **safe**');if(safe.querySelector('img,a')||!safe.querySelector('strong'))throw Error('Unsafe task Markdown');
if(form.querySelector('.task-editor-advanced').open)throw Error('Advanced section should start collapsed');
const fields=document.querySelector('#tasks-fields'),rect=dialog.getBoundingClientRect();
if(rect.width>innerWidth+1||rect.height>innerHeight+1||fields.scrollWidth>fields.clientWidth+1)throw Error('Editor overflow');
@@ -46,6 +50,24 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
document.querySelector('#dashboard-controls button[aria-pressed]').click();const width=document.querySelector('[data-widget=tasks] [data-size=width]');width.value='6';width.dispatchEvent(new Event('change'));const height=document.querySelector('[data-widget=tasks] [data-size=height]');height.value='5';height.dispatchEvent(new Event('change'));
document.querySelector('[data-widget=tasks] .widget-arrange button').click();document.querySelector('#dashboard-controls button:last-child').click();await wait(()=>document.querySelector('#dashboard-status').textContent.includes('保存しました'));const layout=await fetch('/_/api/v1/extension/organizer.tasks/dashboard').then(r=>r.json());if(layout.widgets[2].id!=='tasks'||layout.widgets[2].width!==6||layout.widgets[2].height!==5||layout.widgets[2].tab!=='done')throw Error('Layout did not persist');
if(!document.querySelector('.organizer-nav a[href="/v/plan/contacts"]')||!document.querySelector('.organizer-nav a[aria-current="page"]'))throw Error('Shared navigation missing');
const add=document.querySelector('#dashboard-controls select');
for(const id of ['commands','tomorrow-schedule']){add.value=id;add.dispatchEvent(new Event('change'));}
await wait(()=>document.querySelector('.dashboard-command'));
const command=document.querySelector('.dashboard-command'),commandInput=command.querySelector('input'),api='/_/api/v1/extension/organizer.tasks/';
const run=async text=>{fill(commandInput,text);command.requestSubmit();await wait(()=>!command.querySelector('button').disabled);if(commandInput.value)throw Error('Command failed: '+command.parentElement.textContent);};
await run('add task **Command fixture**');
let items=await fetch(api+'items?q=Command%20fixture').then(r=>r.json());const id=items.items[0].uuid;
fill(commandInput,'today Command');await wait(()=>document.querySelector('#dashboard-command-tasks option'));if(!document.querySelector('#dashboard-command-tasks option').value.includes(id))throw Error('Command task suggestions missing');
await run('today '+id);let item=await fetch(api+'items/'+id).then(r=>r.json());if(item.item.planned_on!==document.querySelector('#organizer-dashboard').dataset.today)throw Error('Today command failed');
await run('tomorrow '+id);await run('due '+id+' 2030-12-31');item=await fetch(api+'items/'+id).then(r=>r.json());if(item.item.due_on!=='2030-12-31')throw Error('Due command failed');
await wait(()=>document.querySelector('[data-widget=tomorrow] strong'));
window.confirm=()=>false;fill(commandInput,'delete '+id);command.requestSubmit();await wait(()=>!command.querySelector('button').disabled);if(!(await fetch(api+'items/'+id)).ok)throw Error('Unconfirmed deletion');
window.confirm=()=>true;await run('delete '+id);if((await fetch(api+'items/'+id)).status!==404)throw Error('Deletion failed');
const date=new Date(document.querySelector('#organizer-dashboard').dataset.today+'T12:00:00Z');date.setUTCDate(date.getUTCDate()+1);const day=date.toISOString().slice(0,10),calAPI='/_/api/v1/extension/organizer.calendar/';
const calendars=await fetch(calAPI+'calendars').then(r=>r.json());const calendar=(calendars.calendars||calendars.items)[0];
const response=await fetch(calAPI+'calendars/'+calendar.id+'/events',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({summary:'Tomorrow visual fixture',start:day+'T03:00:00Z',end:day+'T04:00:00Z'})});if(!response.ok)throw Error('Event fixture failed');
document.querySelector('#dashboard-controls button').click();await wait(()=>document.querySelector('[data-widget=tomorrow-schedule] .agenda-event'));
if(!document.querySelector('[data-widget=tomorrow-schedule]').textContent.includes('Tomorrow visual fixture'))throw Error('Tomorrow schedule missing');
}else if(path==='/v/plan/tasks'){
const prefs=await fetch('/_/api/v1/extension/organizer.tasks/preferences').then(r=>r.json());await fetch('/_/api/v1/extension/organizer.tasks/preferences',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({...prefs.preferences,due_days:2,estimate_minutes:60})});
await wait(()=>document.querySelector('#tasks-quick-title'));fill(document.querySelector('#tasks-quick-title'),'Recording task');document.querySelector('#tasks-capture').requestSubmit();await wait(()=>document.querySelector('[data-action=work]'));document.querySelector('[data-action=work]').click();await wait(()=>document.querySelector('.task-work-bar a').textContent.includes('Recording task'));document.querySelector('.task-work-bar button').click();await wait(()=>document.querySelector('.task-work-bar').hidden);
+33
View File
@@ -0,0 +1,33 @@
(async()=>{
const assert=(ok,msg)=>{if(!ok)throw Error(msg)},delay=ms=>new Promise(r=>setTimeout(r,ms));
const wait=async fn=>{for(let n=0;n<300;n++){if(fn())return;await delay(25)}throw Error('Timeout '+fn)};
const ready=()=>document.querySelector('.slides-frame[data-ready=true]');
await wait(()=>window.PagesSlides);
const e=window.PagesEditor;
if(e){await wait(()=>document.querySelector('[data-editor-action=slides]')&&e.preview);e.paused=true;document.querySelector('[data-editor-action=slides]').click();}
await wait(ready);
const frame=ready(),source=e?.text(),historyLength=history.length;
assert(frame.dataset.count==='2','Wrong slide count');
assert(frame.sandbox.contains('allow-scripts')&&!frame.sandbox.contains('allow-same-origin'),'Isolation missing');
let isolated=false;try{isolated=!frame.contentDocument}catch{isolated=true}assert(isolated,'Frame can access parent origin');
assert(frame.getBoundingClientRect().height>=240,'Slide frame collapsed');
assert(frame.getBoundingClientRect().width<=innerWidth,'Mobile slide overflow');
if(e&&innerWidth<=700){assert(getComputedStyle(document.querySelector('.editor-pane')).display==='none','Mobile preview not full width');setEditorPreviewVisible(false);assert(getComputedStyle(document.querySelector('.editor-pane')).display!=='none','Mobile source inaccessible');setEditorPreviewVisible(true);}
const host=frame.parentElement;
// Verify the defensive DOM boundary independently of server sanitization.
PagesSlides.render(host,'<h1 onclick="alert(1)" data-background-iframe="https://evil.invalid">Safe</h1><script>alert(1)</scr'+'ipt><iframe src="https://evil.invalid"></iframe><img src="https://evil.invalid/x"><hr><p>Next</p>','/deck');
await wait(ready);
let projected=ready().srcdoc;
assert(!projected.includes('evil.invalid')&&!projected.includes('onclick=')&&!projected.includes('alert(1)'),'Unsafe content entered frame');
assert(!projected.includes('data-background-iframe'),'Reveal directives leaked');
assert(history.length===historyLength,'Slide render changed history');
let rejected=false;try{PagesSlides.render(host,'<p>x</p><hr>'.repeat(101),'/deck')}catch{rejected=true}assert(rejected,'Too many slides accepted');
if(e){
assert(e.text()===source,'Preview mutated canonical source');
e.setText('<h1>Edited</h1><hr><p>Second</p><hr><p>Third</p>');await e.renderPreview();await wait(ready);assert(ready().dataset.count==='3','Live preview stale');
document.querySelector('[data-editor-action=slides]').click();await wait(()=>!document.querySelector('.slides-frame'));assert(e.preview.textContent.includes('Edited'),'Normal preview not restored');
document.querySelector('[data-editor-action=slides]').click();await wait(ready);
clearTimeout(e.autosaveTimer);clearInterval(e.stateTimer);e.paused=true;
}else{PagesSlides.render(host,document.querySelector('[data-slides-source]').value,'/deck');await wait(ready);}
document.body.dataset.vimReady='true';
})().catch(error=>{const p=document.createElement('pre');p.id='error';p.textContent=error.stack;document.body.append(p)});
+29
View File
@@ -0,0 +1,29 @@
window.addEventListener('load',async()=>{
const wait=async fn=>{for(let n=0;n<120;n++){if(fn())return;await new Promise(r=>setTimeout(r,50));}throw Error('Timed out: '+fn);};
const assert=(ok,msg)=>{if(!ok)throw Error(msg);},key=(k,ctrl=false)=>document.activeElement.dispatchEvent(new KeyboardEvent('keydown',{key:k,ctrlKey:ctrl,bubbles:true,cancelable:true}));
const rows=()=>[...document.querySelectorAll('.task-index-grid tbody tr')],selected=()=>document.querySelector('.task-index-grid tr[aria-selected=true]'),api='/_/api/v1/extension/organizer.tasks/';
try{
const grid=document.querySelector('.task-index-grid'),form=document.querySelector('.task-index-filter'),filter=form.querySelector('input'),sort=form.querySelector('select');
const ready=()=>grid.getAttribute('aria-busy')!=='true';
await wait(()=>ready()&&rows().length===3&&document.querySelectorAll('.task-index-projects button').length===4);
grid.focus();key('o');assert(document.activeElement===sort,'o did not focus sort');sort.value='title';sort.dispatchEvent(new Event('change'));await wait(ready);key('Escape');
rows()[0].click();const first=selected().dataset.task;key('j');assert(selected().dataset.task!==first,'j failed');key('k');assert(selected().dataset.task===first,'k failed');assert(rows()[0].querySelector('strong'),'Markdown subject lost');
key('l');assert(document.activeElement===filter,'l did not focus limit');filter.value='~s Beta ~doing';form.requestSubmit();await wait(()=>ready()&&rows().length===1);const beta=selected().dataset.task;
filter.focus();key('d');let item=await fetch(api+'items/'+beta).then(r=>r.json());assert(item.item.status==='doing','Shortcut fired while typing');
const changed=await fetch(api+'items/'+beta,{method:'PUT',headers:{'Content-Type':'application/json','If-Match':'"'+item.item.version+'"'},body:JSON.stringify({...item.item,notes:'Changed in another client'})});assert(changed.ok,'Concurrent update fixture failed');
key('Escape');key('d');await wait(()=>document.querySelector('#tasks-status').textContent.includes('別の画面で更新'));
item=await fetch(api+'items/'+beta).then(r=>r.json());assert(item.item.status==='doing'&&item.item.notes==='Changed in another client','Stale completion overwrote another client');
form.requestSubmit();await wait(ready);key('d');await wait(()=>ready()&&rows().length===0);item=await fetch(api+'items/'+beta).then(r=>r.json());assert(item.item.status==='done'&&item.item.notes==='Changed in another client','d did not preserve full task data');
filter.value='~unknown';form.requestSubmit();await wait(()=>ready()&&document.querySelector('#tasks-status').textContent.includes('不正'));assert(form.querySelector('input').value==='~unknown','Invalid filter lost');
filter.value='~active';form.requestSubmit();await wait(()=>ready()&&rows().length===2);grid.focus();key('j',true);await wait(()=>ready()&&rows().length===1);assert(document.querySelector('.task-index-projects [aria-current=true]').dataset.project==='none','Ctrl+j did not switch project');
key('k',true);await wait(()=>ready()&&rows().length===2);key('O');await wait(ready);assert(rows()[0].textContent.includes('Gamma'),'Reverse sort failed');
grid.focus();key('?');const help=document.querySelector('.task-index-help');assert(help.open,'Help missing');const previous=selected().dataset.task;key('j');assert(selected().dataset.task===previous,'Shortcut fired through modal');help.querySelector('button').click();
key('m');await wait(()=>document.querySelector('#tasks-dialog').open&&document.querySelector('#tasks-form [name=page_path]'));key('j');assert(selected().dataset.task===previous,'Shortcut fired through editor');document.querySelector('#tasks-close').click();
const projectButton=[...document.querySelectorAll('.task-index-projects button')].find(b=>b.dataset.project&&b.dataset.project!=='none');projectButton.click();await wait(ready);const project=projectButton.dataset.project;grid.focus();key('c');
await wait(()=>document.querySelector('#tasks-dialog').open&&document.querySelector('#tasks-form [name=project_uuid]')?.value===project);const title=document.querySelector('#tasks-form [name=title]');title.value='Created from index';title.dispatchEvent(new Event('input',{bubbles:true}));document.querySelector('#tasks-form').requestSubmit();await wait(()=>!document.querySelector('#tasks-dialog').open&&ready()&&rows().some(row=>row.textContent.includes('Created from index')));
rows().find(row=>row.textContent.includes('Created from index')).click();const created=selected().dataset.task;key('w');await wait(()=>document.querySelector('#tasks-status').textContent.includes('関連Wikiページはありません'));
key('s');await wait(()=>document.querySelector('#tasks-focus').dataset.state==='running');const session=await fetch(api+'focus').then(r=>r.json());assert(session.item.task_uuid===created,'Pomodoro attached to wrong task');
assert(document.documentElement.scrollWidth<=innerWidth+2,'Page overflow');assert(!document.querySelector('#tasks-list input'),'Index must not be an inline form');
document.body.dataset.vimReady='true';
}catch(e){const p=document.createElement('pre');p.id='error';p.textContent=e.stack;document.body.append(p);}
});
+21
View File
@@ -44,6 +44,15 @@ try {
if (state.ready) { ready = true; break; }
await delay(200);
}
if(ready && process.env.PAGESWIKI_TASK_INDEX_BROWSER==='1'){
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;};
const key=async(key,modifiers=0)=>{await call('Input.dispatchKeyEvent',{type:'keyDown',key,code:'Key'+key.toUpperCase(),modifiers});await call('Input.dispatchKeyEvent',{type:'keyUp',key,code:'Key'+key.toUpperCase(),modifiers});};
await evaluate(`document.querySelector('.task-index-projects button').click();new Promise((resolve,reject)=>{let n=0;const id=setInterval(()=>{if(document.querySelector('.task-index-grid').getAttribute('aria-busy')!=='true'){clearInterval(id);document.querySelector('.task-index-grid tbody tr').click();resolve();}else if(++n>100){clearInterval(id);reject(Error('index loading'));}},30);})`);
const selected=()=>evaluate(`document.querySelector('.task-index-grid tr[aria-selected=true]').dataset.task`);
const before=await selected();await key('j');if(await selected()===before)throw Error('Native j did not move');await key('k');if(await selected()!==before)throw Error('Native k did not move');
await key('j',2);if(await evaluate(`document.querySelector('.task-index-projects [aria-current=true]').dataset.project`)!=='none')throw Error('Native Ctrl+j did not switch project');await key('k',2);
await evaluate(`new Promise(resolve=>{const id=setInterval(()=>{if(document.querySelector('.task-index-grid').getAttribute('aria-busy')!=='true'){clearInterval(id);resolve();}},30)})`);
}
if(ready && process.env.PAGESWIKI_DASHBOARD_DRAG==='1'){
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;};
const rect=async selector=>evaluate(`(()=>{const n=document.querySelector(${JSON.stringify(selector)});n.scrollIntoView({block:'center',behavior:'instant'});const r=n.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()`);
@@ -58,6 +67,18 @@ try {
const layout=await evaluate(`fetch('/_/api/v1/extension/organizer.tasks/dashboard').then(r=>r.json())`);if(layout.widgets[0].id!=='today'||layout.widgets.find(w=>w.id==='tasks').height!==4)throw Error('Pointer layout persistence failed');
await evaluate(`document.querySelector('#dashboard-controls button[aria-pressed]').click();scrollTo(0,0)`);
}
if (ready && process.env.PAGESWIKI_SLIDES_BROWSER === '1') {
const evaluate = async expression => (await call('Runtime.evaluate', {expression, returnByValue:true})).result.value;
const initialHistory = await evaluate('history.length');
await evaluate("document.querySelector('.slides-frame').focus()");
const key = async (key, code) => {await call('Input.dispatchKeyEvent',{type:'keyDown',key,code:key,windowsVirtualKeyCode:code});await call('Input.dispatchKeyEvent',{type:'keyUp',key,code:key,windowsVirtualKeyCode:code});};
await key('ArrowRight',39);
let advanced=false;for(let n=0;n<30;n++){if(await evaluate("document.querySelector('.slides-frame').parentElement.dataset.slideIndex") === '1'){advanced=true;break;}await delay(100);}
if(!advanced)throw Error('Slide keyboard navigation failed');
await key('ArrowLeft',37);await delay(150);
if(await evaluate("document.querySelector('.slides-frame').parentElement.dataset.slideIndex") !== '0')throw Error('Slide previous navigation failed');
if(await evaluate('history.length') !== initialHistory)throw Error('Slides polluted browser history');
}
if (screenshot) {
const {data} = await call('Page.captureScreenshot', {format: 'png'});
await writeFile(screenshot, Buffer.from(data, 'base64'));
+5
View File
@@ -3,6 +3,11 @@ package store
import "database/sql"
func (s *Store) EnsureConfigTable() error {
if _, err := s.DB.Exec(`CREATE TABLE IF NOT EXISTS personal_appearance (
domain_uuid TEXT NOT NULL, owner_uuid TEXT NOT NULL, version INTEGER NOT NULL,
data TEXT NOT NULL, PRIMARY KEY(domain_uuid,owner_uuid))`); err != nil {
return err
}
domain, err := s.GetDefaultDomain()
if err != nil {
return err
+32 -3
View File
@@ -21,13 +21,13 @@ func DefaultDashboard() []DashboardWidget {
}
func ValidateDashboard(items []DashboardWidget) error {
if len(items) > 7 {
if len(items) > 9 {
return ErrTaskInvalid
}
seen := map[string]bool{}
for _, item := range items {
switch item.ID {
case "progress", "today", "tomorrow", "tasks", "schedule", "activity", "feeds":
case "progress", "today", "tomorrow", "tasks", "schedule", "tomorrow-schedule", "commands", "activity", "feeds":
default:
return ErrTaskInvalid
}
@@ -53,6 +53,33 @@ type DashboardLayout struct {
Widgets []DashboardWidget `json:"widgets"`
}
func normalizeDashboard(items []DashboardWidget) ([]DashboardWidget, error) {
if len(items) > 100 {
return nil, ErrTaskInvalid
}
out := make([]DashboardWidget, 0, len(items))
seen := map[string]bool{}
for _, item := range items {
if seen[item.ID] {
continue
}
seen[item.ID] = true
item.Width = max(3, min(12, item.Width))
item.Height = max(2, min(10, item.Height))
if item.ID == "tasks" {
switch item.Tab {
case "inbox", "backlog", "someday", "review", "all", "done":
default:
item.Tab = "inbox"
}
} else {
item.Tab = ""
}
out = append(out, item)
}
return out, ValidateDashboard(out)
}
func (s *Store) Dashboard(ctx context.Context, domain, actor string) (DashboardLayout, error) {
p := DashboardLayout{Widgets: DefaultDashboard()}
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
@@ -79,9 +106,11 @@ func (s *Store) SaveDashboard(ctx context.Context, domain, actor string, version
if version < 0 {
return p, ErrTaskInvalid
}
if err := ValidateDashboard(widgets); err != nil {
normalized, err := normalizeDashboard(widgets)
if err != nil {
return p, err
}
widgets = normalized
tx, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return p, err
+186
View File
@@ -0,0 +1,186 @@
package store
import (
"strconv"
"strings"
"time"
"unicode"
)
// A small AND-only query language. Values are always bound parameters; neither
// filter text nor sort names can become SQL identifiers or expressions.
func taskIndexFilter(source, today string) (string, []any, error) {
if len(source) > 1000 {
return "", nil, ErrTaskInvalid
}
tokens, err := taskFilterTokens(source)
if err != nil {
return "", nil, err
}
parts := []string{}
args := []any{}
archived := false
for i := 0; i < len(tokens); i++ {
token := tokens[i]
neg := strings.HasPrefix(token, "!")
if neg {
token = strings.TrimPrefix(token, "!")
}
clause := ""
value := func() (string, error) {
i++
if i >= len(tokens) || tokens[i] == "" {
return "", ErrTaskInvalid
}
return tokens[i], nil
}
switch token {
case "~active":
clause = `status NOT IN ('done','cancelled')`
case "~todo", "~doing", "~done", "~cancelled":
clause = `status=?`
args = append(args, strings.TrimPrefix(token, "~"))
case "~overdue":
clause = `due_on!='' AND due_on<? AND status NOT IN ('done','cancelled')`
args = append(args, today)
case "~wiki":
clause = `COALESCE(json_extract(data,'$.page_uuid'),'')!=''`
case "~attachment":
clause = `COALESCE(json_array_length(data,'$.references'),0)>0`
case "~archived":
clause = `archived=1`
if !neg {
archived = true
}
case "~s":
v, e := value()
if e != nil {
return "", nil, e
}
clause = `instr(lower(title),lower(?))>0`
args = append(args, v)
case "~bucket":
v, e := value()
if e != nil || (v != "inbox" && v != "backlog" && v != "someday") {
return "", nil, ErrTaskInvalid
}
clause = `bucket=?`
args = append(args, v)
case "~priority":
v, e := value()
n, e2 := strconv.Atoi(v)
if e != nil || e2 != nil || n < 0 || n > 3 {
return "", nil, ErrTaskInvalid
}
clause = `COALESCE(json_extract(data,'$.priority'),0)=?`
args = append(args, n)
case "~due", "~planned", "~start", "~review":
v, e := value()
if e != nil {
return "", nil, e
}
op := "="
for _, prefix := range []string{"<=", ">=", "<", ">", "="} {
if strings.HasPrefix(v, prefix) {
op = prefix
v = strings.TrimPrefix(v, prefix)
break
}
}
column := map[string]string{"~due": "due_on", "~planned": "planned_on", "~start": "COALESCE(json_extract(data,'$.start_on'),'')", "~review": "review_on"}[token]
if v == "none" {
if op != "=" {
return "", nil, ErrTaskInvalid
}
clause = column + "=''"
break
}
if v == "today" {
v = today
}
if v == "tomorrow" {
day, _ := time.Parse("2006-01-02", today)
v = day.AddDate(0, 0, 1).Format("2006-01-02")
}
if v == "" || !validTaskDate(v) {
return "", nil, ErrTaskInvalid
}
clause = column + "!='' AND " + column + op + "?"
args = append(args, v)
default:
if strings.HasPrefix(token, "~") || token == "" {
return "", nil, ErrTaskInvalid
}
clause = `instr(lower(title),lower(?))>0`
args = append(args, token)
}
if neg {
clause = "NOT (" + clause + ")"
}
parts = append(parts, "("+clause+")")
}
if !archived {
parts = append(parts, "archived=0")
}
return strings.Join(parts, " AND "), args, nil
}
func taskFilterTokens(source string) ([]string, error) {
var tokens []string
var word strings.Builder
var quote rune
escaped, started := false, false
for _, r := range source {
if unicode.IsControl(r) && !unicode.IsSpace(r) {
return nil, ErrTaskInvalid
}
if escaped {
word.WriteRune(r)
escaped = false
started = true
continue
}
if r == '\\' {
escaped = true
started = true
continue
}
if quote != 0 {
if r == quote {
quote = 0
} else {
word.WriteRune(r)
}
continue
}
if r == '\'' || r == '"' {
quote = r
started = true
continue
}
if unicode.IsSpace(r) {
if started {
tokens = append(tokens, word.String())
word.Reset()
started = false
}
continue
}
word.WriteRune(r)
started = true
}
if quote != 0 || escaped {
return nil, ErrTaskInvalid
}
if started {
tokens = append(tokens, word.String())
}
if len(tokens) > 64 {
return nil, ErrTaskInvalid
}
return tokens, nil
}
func taskIndexOrder(key string) string {
return map[string]string{"": "COALESCE(NULLIF(due_on,''),'9999-99-99')", "due": "COALESCE(NULLIF(due_on,''),'9999-99-99')", "planned": "COALESCE(NULLIF(planned_on,''),'9999-99-99')", "title": "lower(title)", "status": "status", "priority": "COALESCE(json_extract(data,'$.priority'),0)", "created": "created_at_ms", "updated": "updated_at_ms"}[key]
}
+61 -5
View File
@@ -5,6 +5,7 @@ import (
"database/sql"
"encoding/json"
"errors"
"net/url"
"strings"
"time"
"unicode/utf8"
@@ -24,6 +25,7 @@ type TaskRecord struct {
Kind string `json:"kind"`
Title string `json:"title"`
Notes string `json:"notes"`
References []string `json:"references,omitempty"`
NotesSubpath string `json:"notes_subpath,omitempty"`
ProjectUUID string `json:"project_uuid"`
ParentUUID string `json:"parent_uuid,omitempty"`
@@ -51,6 +53,7 @@ type TaskRecord struct {
}
type TaskQuery struct {
Filter, Sort, Order string
Kind, View, Project, Search, Today, Before string
Parent string
Hierarchy bool
@@ -117,6 +120,22 @@ func validTaskDate(v string) bool {
}
func validateTask(item *TaskRecord) error {
if len(item.References) > 20 {
return ErrTaskInvalid
}
for _, ref := range item.References {
u, err := url.Parse(ref)
if err != nil || len(ref) > 4096 || strings.ContainsAny(ref, "\\\r\n\x00\t ") || u.User != nil || !utf8.ValidString(ref) {
return ErrTaskInvalid
}
if u.Scheme == "http" || u.Scheme == "https" {
if u.Hostname() == "" {
return ErrTaskInvalid
}
} else if u.Scheme != "" || u.Host != "" || !strings.HasPrefix(ref, "/") || strings.HasPrefix(ref, "//") {
return ErrTaskInvalid
}
}
if item.Complexity < 0 || item.Complexity > 5 {
return ErrTaskInvalid
}
@@ -262,6 +281,11 @@ func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRec
if err = json.Unmarshal([]byte(oldJSON), &old); err != nil {
return TaskRecord{}, err
}
// Older CLI/DAV clients omit this optional field. An explicit [] clears
// references; omission must not erase attachments during unrelated edits.
if expected > 0 && item.References == nil {
item.References = old.References
}
if expected == 0 { // Safe retry of a create with the same client-generated UUID.
candidate := item
candidate.Version, candidate.CreatedMS, candidate.UpdatedMS, candidate.CompletedMS = old.Version, old.CreatedMS, old.UpdatedMS, old.CompletedMS
@@ -408,6 +432,13 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
if query.Limit < 1 || query.Limit > 100 {
query.Limit = 60
}
index := query.View == "index"
if index && (query.Kind != "task" || query.Hierarchy || taskIndexOrder(query.Sort) == "" || (query.Order != "" && query.Order != "asc" && query.Order != "desc")) {
return nil, "", ErrTaskInvalid
}
if !index && (query.Filter != "" || query.Sort != "" || query.Order != "") {
return nil, "", ErrTaskInvalid
}
q := `SELECT data FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND kind=?`
args := []any{domain, actor, query.Kind}
hierarchy := query.Hierarchy && query.Kind == "task" && query.View != "family"
@@ -420,7 +451,14 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
WHERE i.domain_uuid=? AND i.owner_uuid=?
) SELECT data FROM task_rows WHERE kind=?`
}
if query.View == "family" {
if index {
filter, values, err := taskIndexFilter(query.Filter, query.Today)
if err != nil {
return nil, "", err
}
q += " AND " + filter
args = append(args, values...)
} else if query.View == "family" {
if query.Parent == "" || query.Kind != "task" {
return nil, "", ErrTaskInvalid
}
@@ -438,7 +476,11 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
}
if query.Project != "" {
q += ` AND project_uuid=?`
args = append(args, query.Project)
project := query.Project
if index && project == "none" {
project = ""
}
args = append(args, project)
}
if query.Kind == "task" {
switch query.View {
@@ -462,7 +504,7 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
case "all":
q += ` AND status NOT IN ('done','cancelled')`
case "archived":
case "family":
case "family", "index":
default:
return nil, "", ErrTaskInvalid
}
@@ -472,7 +514,15 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
args = append(args, query.Search)
}
if query.Before != "" {
if hierarchy {
if index {
comparison := ">"
if query.Order == "desc" {
comparison = "<"
}
key := taskIndexOrder(query.Sort)
q += " AND (" + key + ",uuid)" + comparison + "(SELECT " + key + ",uuid FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND kind='task' AND uuid=?)"
args = append(args, domain, actor, query.Before)
} else if hierarchy {
// A separate indexed cursor lookup keeps the wide task_rows CTE
// single-use, avoiding materialization of every private JSON body.
var familyCreated, created int64
@@ -494,7 +544,13 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
args = append(args, domain, actor, query.Before)
}
}
if hierarchy {
if index {
direction := "ASC"
if query.Order == "desc" {
direction = "DESC"
}
q += " ORDER BY " + taskIndexOrder(query.Sort) + " " + direction + ",uuid " + direction + " LIMIT ?"
} else if hierarchy {
q += ` ORDER BY family_created DESC,family_uuid DESC,family_head DESC,created_at_ms DESC,uuid DESC LIMIT ?`
} else {
q += ` ORDER BY created_at_ms DESC,uuid DESC LIMIT ?`
+109
View File
@@ -0,0 +1,109 @@
"""Synthetic NeoMutt pipe -> real CLI -> full HTTP router -> browser viewer.
Run by TestNeoMuttMailViewerFlow; never reads a real mail or CLI profile.
"""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
from email.header import Header
from html.parser import HTMLParser
from urllib.parse import quote, unquote, urlencode, urlsplit
from urllib.request import Request, urlopen
class Links(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if 'browser-row' in attrs.get('class', '').split():
self.links.append(attrs.get('data-path', ''))
if tag == 'a':
self.links.append(attrs.get('href', ''))
def main():
fixture = json.load(sys.stdin)
root = Path(fixture['root'])
env = {**os.environ, 'HOME': str(root), 'XDG_CONFIG_HOME': str(root / 'config')}
executable = str(Path(__file__).with_name('pages').resolve())
binary = os.environ.get('PAGES_CLI_TEST_BINARY')
command = [str(Path(binary).resolve())] if binary else [sys.executable, executable]
def cli(*args, data=b''):
run = subprocess.run([*command, *args], input=data,
capture_output=True, env=env, timeout=15)
assert run.returncode == 0, (args, run.stderr.decode())
return run.stdout
def get(path):
request = Request(fixture['origin'] + quote(path, safe='/:?=&%'),
headers={'Cookie': 'pageswiki_session=' + fixture['browser'],
'Accept-Language': 'ja,en;q=0.8'})
with urlopen(request, timeout=10) as response:
body = response.read().decode()
assert response.status == 200, (path, response.status)
assert response.headers.get_content_type() == 'text/html', (path, body[:100])
assert unquote(urlsplit(response.url).path) == unquote(urlsplit(path).path).rstrip('/'), response.url
return body
cli('configure', '--origin', fixture['origin'], '--username', 'admin')
cli('login', data=b'a long test password\n')
paths = []
for parent in ['/tasks', '/mail', '/private/mail', '/受信 メール', '/u/admin/mail', '/docs/mail', '/api/mail']:
cli('task', 'preferences', '--wiki-prefix', parent)
for charset in ['utf-8', 'iso-2022-jp']:
for kind in ['ml', 'message-id', 'hash']:
number = len(paths) + 1
title = '日本語の依頼'
subject = (f'[example.list {number:05d}] ' if kind == 'ml' else '') + title
# pipe_decode=no / pipe_split=yes: exactly one un-decoded RFC mail
# is delivered to the CLI's stdin, as in the published NeoMutt macro.
raw = ('From: Test <test@example.invalid>\r\n'
'Date: Sat, 31 Jan 2026 23:30:00 -0800\r\n'
'Subject: ' + Header(subject, charset).encode() + '\r\n'
+ (f'Message-ID: <synthetic-{number}@example.invalid>\r\n' if kind != 'hash' else '')
+ 'MIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n'
'Content-Transfer-Encoding: 8bit\r\n\r\n'
f'Synthetic mail body {number}. {{' + '{children}}\r\n').encode()
result = json.loads(cli('task', 'from-mail', data=raw))
path = result['page_path']
suffix = ('example.list/' + str(number) if kind == 'ml' else '2026/01/' +
(result['item']['uuid'] if kind == 'message-id' else hashlib.sha256(raw).hexdigest()))
assert path == parent + '/' + suffix, path
assert result['item']['title'] == title
# Confirm browser listing actually links to the same semantic URL.
listing = get('/v/browser' + path.rsplit('/', 1)[0])
links = Links(); links.feed(listing)
linked = next((href for href in links.links if unquote(urlsplit(href).path) == path), None)
assert linked is not None, ('missing listing link', path, links.links, listing[:600])
page = get(path)
assert f'Synthetic mail body {number}.' in page, path
assert title in page, path
assert '{"detail":"Not Found"}' not in page
assert f'Synthetic mail body {number}.' in get(linked)
assert f'Synthetic mail body {number}.' in get(path + '/')
assert f'Synthetic mail body {number}.' in get(path + '?lang=ja')
paths.append(path)
if fixture['chromium']:
# Real browser session, normal navigation and scripts, without injecting
# page HTML or bypassing the production handler.
for i, path in enumerate([paths[0], paths[14], paths[-1]]):
target = fixture['origin'] + '/fixture-browser-login?' + urlencode({'return': path})
run = subprocess.run(['chromium', '--headless', '--no-sandbox', '--disable-gpu',
'--disable-background-networking', '--no-proxy-server',
'--user-data-dir=' + str(root / ('chromium-' + str(i))),
'--dump-dom', '--virtual-time-budget=2000', target],
capture_output=True, timeout=20)
assert run.returncode == 0, run.stderr.decode()[-1000:]
assert 'Synthetic mail body' in run.stdout.decode(), (path, run.stdout.decode()[:500])
print('MAIL_VIEWER_OK cases=' + str(len(paths)) + ' chromium=' + str(fixture['chromium']))
if __name__ == '__main__':
main()
+17
View File
@@ -0,0 +1,17 @@
.csv-edit-pane{padding:0!important;display:flex;flex-direction:column;min-width:0;min-height:0;overflow:hidden}
.csv-edit-pane[hidden]{display:none!important}
.csv-edit-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:.2rem;padding:.3rem;border-bottom:1px solid var(--border,#444);flex:none;background:var(--bg,#fff);color:var(--fg,#222)}
.csv-edit-toolbar button{font:inherit;min-width:2rem;min-height:2rem;padding:.2rem .4rem;border:1px solid var(--border,#777);border-radius:.25rem;color:inherit;background:transparent;cursor:pointer}
.csv-edit-toolbar button:disabled{opacity:.4;cursor:default}
.csv-edit-toolbar svg{width:1.2rem;height:1.2rem;fill:none;stroke:currentColor;stroke-width:1.7;vertical-align:middle}
.csv-edit-toolbar button:focus-visible,.csv-edit-scroll textarea:focus-visible{outline:2px solid var(--accent,#768ad7);outline-offset:-2px}
.csv-edit-toolbar output{font-variant-numeric:tabular-nums;font-size:.8rem;white-space:nowrap}
.csv-edit-toolbar span{font-size:.8rem}
.csv-edit-scroll{overflow:auto;min-height:0;flex:1;overscroll-behavior:contain}
.csv-edit-scroll table{border-collapse:separate;border-spacing:0;width:max-content;min-width:100%;font-size:.85rem}
.csv-edit-scroll th,.csv-edit-scroll td{border-right:1px solid var(--border,#777);border-bottom:1px solid var(--border,#777);padding:0;vertical-align:top}
.csv-edit-scroll th{padding:.2rem .4rem;font-weight:normal;font-variant-numeric:tabular-nums;background:var(--bg,#fff);color:var(--fg,#222)}
.csv-edit-scroll thead th{position:sticky;top:0;z-index:1}
.csv-edit-scroll textarea{display:block;width:11rem;min-width:6rem;max-width:30rem;min-height:2rem;margin:0;padding:.3rem;border:0;border-radius:0;font:inherit;line-height:1.4;color:inherit;background:transparent;resize:both;box-sizing:border-box}
@media(max-width:600px){.csv-edit-toolbar button{min-width:2.75rem;min-height:2.75rem}.csv-edit-scroll textarea{min-height:2.75rem;font-size:16px}}
@media(max-width:700px){.csv-editor .editor-grid:not(.preview-hidden){grid-template-columns:1fr!important}.csv-editor .editor-grid:not(.preview-hidden)>.editor-pane{display:none}}
+3 -1
View File
@@ -6,7 +6,9 @@
.organizer-nav-icons{display:flex;align-items:center;gap:.15rem}.organizer-launch{display:inline-flex;align-items:center;justify-content:center;color:var(--fg);width:2.1rem;height:2.1rem;box-sizing:border-box;padding:.35rem;border-radius:50%}
.organizer-launch svg{width:100%;height:100%;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}.organizer-launch:hover{color:var(--accent)}
.organizer-page .topbar{flex-wrap:wrap;gap:.2rem}.organizer-settings-content{min-width:0;padding:.75rem 1rem}.organizer-settings-content #task-productivity{margin:0;padding:0}.organizer-calendar-options{display:grid;gap:.4rem}.organizer-calendar-options label{display:flex;align-items:center;gap:.5rem;min-height:2rem}
#organizer-dashboard{max-width:1800px;margin:auto;padding:1rem;box-sizing:border-box;color:var(--fg)}
#organizer-dashboard{width:100%;max-width:none;margin:auto;padding:.65rem;box-sizing:border-box;color:var(--fg)}
.personal-appearance fieldset{display:grid;gap:.6rem;border:0;padding:0;max-width:48rem}.personal-appearance label{display:flex;align-items:center;justify-content:space-between;gap:1rem}.personal-appearance input,.personal-appearance select{min-width:0;max-width:65%;color:var(--fg);background:var(--input-bg,var(--bg));border:1px solid var(--border);padding:.35rem}.personal-appearance .home-palette-controls{display:grid;gap:.6rem}
.dashboard-agenda li{align-items:stretch;gap:.65rem;padding:.45rem 0}.dashboard-agenda time{width:6.4rem;flex-shrink:0;padding-top:.35rem;font-variant-numeric:tabular-nums}.agenda-event{min-width:0;flex:1;border-left:3px solid var(--accent);border-radius:.3rem;background:color-mix(in srgb,var(--accent) 9%,var(--bg));padding:.35rem .55rem}.agenda-event a{display:block;white-space:normal;overflow-wrap:anywhere}.agenda-event small{display:block;opacity:.65;font-size:.72rem}.dashboard-agenda .is-current .agenda-event{background:color-mix(in srgb,var(--accent) 23%,var(--bg));box-shadow:0 0 0 1px var(--accent)}.dashboard-list a.dashboard-note{flex:0 0 auto}.dashboard-command{display:flex;gap:.25rem}.dashboard-command input{min-width:0;flex:1;font:inherit;color:var(--fg);background:var(--input-bg,var(--bg));border:1px solid var(--border);padding:.5rem}.widget-body pre{white-space:pre-wrap;overflow-wrap:anywhere}
.dashboard-toolbar{display:flex;justify-content:space-between;align-items:center;gap:.75rem;flex-wrap:wrap}.dashboard-toolbar h1{margin:0;font-size:1.5rem}#dashboard-controls{display:flex;gap:.35rem;align-items:center;flex-wrap:wrap}
#organizer-dashboard button,#organizer-dashboard select,#organizer-calendar-defaults button{font:inherit;color:var(--fg);background:var(--input-bg,var(--bg));border:1px solid var(--border,#8885);border-radius:.35rem;padding:.3rem .5rem;cursor:pointer}
#organizer-dashboard button:disabled{opacity:.5;cursor:default}#organizer-dashboard a{color:var(--link,var(--accent))}#dashboard-status{min-height:1.3em;margin:.4rem 0;font-size:.85rem}
+9
View File
@@ -0,0 +1,9 @@
html,body{height:100%;margin:0;overflow:hidden;font-family:system-ui,sans-serif}
.reveal{height:100%;font-size:30px;line-height:1.4;color:inherit}
.reveal .slides{text-align:left}.reveal h1{font-size:2em}.reveal h2{font-size:1.6em}.reveal h3{font-size:1.25em}
.reveal p,.reveal ul,.reveal ol,.reveal pre,.reveal table{margin:.6em 0}
.reveal ul,.reveal ol{display:block;margin-left:1.3em}.reveal li{margin:.2em 0}
.reveal pre{font-size:.65em;white-space:pre-wrap;padding:.5em;background:#8882;max-height:500px;overflow:auto}
.reveal code{font-family:ui-monospace,monospace}.reveal table{border-collapse:collapse;font-size:.8em}.reveal td,.reveal th{border:1px solid #8886;padding:.3em .5em}
.reveal img{max-width:90%;max-height:500px;object-fit:contain}.reveal a{color:inherit;text-decoration:underline}
.reveal .controls,.reveal .progress{color:inherit}.reveal .slide-number{font-size:16px}
+23
View File
@@ -0,0 +1,23 @@
.slides-page{height:100dvh;margin:0;display:flex;flex-direction:column;overflow:hidden}
.slides-page .topbar{position:static;flex-shrink:0;display:flex;gap:1rem;align-items:center;padding:.5rem 1rem}
.slides-page .topbar span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.slides-page [data-slides-viewer]{flex:1;min-height:0;width:100%}
.slides-preview{position:relative;min-height:300px;background:var(--bg);color:var(--fg)}
.slides-frame{display:block;border:0;width:100%;height:100%;min-height:300px;background:inherit}
.slides-frame[hidden],.slides-fallback[hidden]{display:none!important}
.slides-fallback{padding:1rem;overflow:auto;max-height:100%}
.slides-fallback section{padding:1rem;border-bottom:1px solid var(--border)}
.slides-preview:fullscreen{background:var(--bg);height:100dvh;width:100vw}
.mode-editor .slides-preview{padding:0!important;height:100%;overflow:hidden}
[data-editor-action=slides][aria-pressed=true]{color:var(--accent);background:var(--bg-elevated,var(--bg))}
@media(max-width:700px){.slides-frame{min-height:240px}.slides-page .topbar button,.slides-page .topbar a{min-height:44px;min-width:44px;display:grid;place-items:center}}
@media(max-width:700px){
body.mode-editor:has([data-editor-action=slides]){display:flex;flex-direction:column;height:100dvh}
body.mode-editor:has([data-editor-action=slides]) .topbar{height:auto;flex-shrink:0;flex-wrap:wrap;gap:.25rem}
body.mode-editor:has([data-editor-action=slides]) .topbar .brand,body.mode-editor:has([data-editor-action=slides]) .auth-user-name{display:none}
body.mode-editor:has([data-editor-action=slides]) .editor-head{flex:0 0 100%;order:1;gap:.5rem}
body.mode-editor:has([data-editor-action=slides]) .editor-head-right{flex-shrink:0}
body.mode-editor:has([data-editor-action=slides]) .container{flex:1;min-height:0;height:auto}
body.mode-editor .editor-grid:has(.slides-preview):not(.preview-hidden){grid-template-columns:1fr!important}
body.mode-editor .editor-grid:has(.slides-preview):not(.preview-hidden) .editor-pane{display:none}
}
+21
View File
@@ -0,0 +1,21 @@
#tasks-app[data-view=index]{max-width:none;grid-template-columns:13rem minmax(0,1fr);padding:.65rem;gap:.75rem}
[data-view=index] .task-inline-header,[data-view=index] #tasks-help,[data-view=index] #tasks-capture,[data-view=index] .tasks-search{display:none!important}
[data-view=index] .tasks-workspace{min-width:0}
[data-view=index] #tasks-focus{padding:.35rem .5rem;gap:.35rem;border-radius:.3rem;margin-bottom:.35rem;font-size:.85rem}
[data-view=index] #tasks-nav{min-width:0;max-height:80dvh;overflow:auto}
[data-view=index] #tasks-nav h2{font-size:1rem;margin:.25rem 0}
[data-view=index] #tasks-nav input{width:100%;box-sizing:border-box;min-width:0}
.task-index-projects{display:flex;flex-direction:column;gap:1px}.task-index-projects button{text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0!important;border-radius:0!important;font-size:.85rem!important}
.task-index-projects [aria-current=true]{color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 18%,var(--bg))!important}
.task-index-filter{display:flex;align-items:center;gap:.35rem;margin:.3rem 0}.task-index-filter input{flex:1;min-width:0;font-family:monospace}.task-index-filter select{max-width:9rem}
.task-index-actions{display:flex;gap:.25rem;margin:.25rem 0}.task-index-actions button{min-width:2rem}
[data-view=index] #tasks-status{margin:.25rem 0;min-height:1.3em;font-size:.8rem}
[data-view=index] .tasks-list-scroll{max-height:65dvh;overflow:auto;scrollbar-gutter:stable;overscroll-behavior:contain}
.task-index-grid{width:100%;border-collapse:collapse;table-layout:fixed;font-size:.85rem;outline-offset:-2px}
.task-index-grid th,.task-index-grid td{padding:.3rem .4rem;border-bottom:1px solid var(--border);text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.task-index-grid th{position:sticky;top:0;background:var(--bg);z-index:1;font-size:.75rem;color:var(--muted,var(--fg))}
.task-index-grid th:first-child{width:5.5rem}.task-index-grid th:nth-child(3),.task-index-grid th:nth-child(4){width:6rem}.task-index-grid th:nth-child(5){width:3.5rem}.task-index-grid th:last-child{width:2rem}
.task-index-grid tr[aria-selected=true]{background:color-mix(in srgb,var(--accent) 20%,var(--bg));box-shadow:inset 3px 0 var(--accent)}
.task-index-grid tr{cursor:default}.task-index-grid tbody tr:hover{background:color-mix(in srgb,var(--accent) 10%,var(--bg))}.task-index-grid td.task-index-overdue{color:var(--danger,#ff8a80)}
.task-index-help{color:var(--fg);background:var(--bg);border:1px solid var(--border);border-radius:.6rem;width:min(40rem,90vw);max-height:85dvh;overflow:auto}.task-index-help::backdrop{background:#0008}.task-index-help>button{float:right}.task-index-help dl{display:grid;grid-template-columns:auto 1fr;gap:.35rem 1rem}.task-index-help dd{margin:0}.task-index-help pre{white-space:pre-wrap;font-size:.85rem}
@media(max-width:760px){#tasks-app[data-view=index]{grid-template-columns:minmax(0,1fr)}[data-view=index] #tasks-nav{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.3rem;max-height:none;overflow:visible}[data-view=index] #tasks-nav h2{display:none}[data-view=index] #tasks-nav>input{grid-row:1;grid-column:1}[data-view=index] #tasks-nav>a{grid-row:1;grid-column:2;font-size:.8rem}.task-index-projects{grid-column:1/-1;grid-row:2;flex-direction:row;overflow:auto;max-width:100%}.task-index-projects button{flex-shrink:0;min-height:40px}.task-index-filter{flex-wrap:wrap}.task-index-filter input{flex-basis:70%}.task-index-grid th:nth-child(4),.task-index-grid td:nth-child(4),.task-index-grid th:nth-child(5),.task-index-grid td:nth-child(5){display:none}.task-index-grid td{padding:.7rem .3rem}.task-index-grid th:first-child{width:3.7rem}.task-index-grid th:last-child{width:1.2rem}.task-index-actions button{min-width:44px;min-height:44px}}
+7
View File
@@ -99,6 +99,13 @@ body:has(#tasks-dialog[open]){overflow:hidden}
.task-child-capture{display:flex;min-width:0;gap:.25rem}
.task-inline-row>a{color:var(--accent);font-size:.75rem}
.task-inline-title{position:relative}
.task-inline-title input:not(:focus){color:transparent!important;caret-color:var(--fg)}
.task-title-preview{position:absolute;inset:0;display:block;align-content:center;white-space:pre;overflow:hidden;text-overflow:ellipsis;pointer-events:none;padding:0 .3rem;color:var(--fg);font-size:.8rem}
.task-is-child .task-title-preview{padding-left:1.3rem}
.task-inline-row[data-done=true] .task-title-preview{text-decoration:line-through;opacity:.7}
@media(max-width:1023px){.task-title-preview{top:1.3rem;font-size:1rem}}
.task-inline-title input:focus+.task-title-preview{display:none}
.tasks-actions .has-wiki-note{color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 15%,var(--bg))!important}
.task-context-badge{position:absolute;right:.3rem;bottom:.65rem;font-size:.65rem;color:var(--muted,var(--fg));pointer-events:none}
#tasks-app .task-inline-row[data-context=true]>.task-inline-main input[name=title]{padding-right:2.5rem}
.task-date-nav,.task-date-nav>label{display:flex;align-items:center;gap:.35rem;flex-wrap:wrap}
+79
View File
@@ -0,0 +1,79 @@
(function(root) {
'use strict';
const limits={bytes:256*1024,rows:200,columns:32,cellBytes:16*1024};
const bytes=s=>new TextEncoder().encode(s).length;
function parseRecords(source,separator) {
if(typeof source!=='string'||bytes(source)>limits.bytes||source.includes('\0'))throw Error('size');
const bom=source.startsWith('\ufeff')?'\ufeff':'',rows=[];
let i=bom.length,lineEnding='',cells=[];
while(i<source.length||cells.length){
const start=i;let value='';
if(source[i]==='"'){
i++;let closed=false;
while(i<source.length){const c=source[i++];if(c==='"'){if(source[i]==='"'){value+='"';i++;}else{closed=true;break;}}else value+=c;}
if(!closed||i<source.length&&![separator,'\r','\n'].includes(source[i]))throw Error('syntax');
value=value.replace(/\r\n/g,'\n');
}else{
while(i<source.length&&![separator,'\r','\n'].includes(source[i])){if(source[i]==='"')throw Error('syntax');value+=source[i++];}
}
if(bytes(value)>limits.cellBytes||cells.length>=limits.columns)throw Error('size');
cells.push({value,raw:source.slice(start,i),original:value});
if(source[i]===separator){i++;continue;}
let end='';
if(source[i]==='\r'){if(source[i+1]!=='\n')throw Error('syntax');end='\r\n';i+=2;}
else if(source[i]==='\n'){end='\n';i++;}
if(!lineEnding&&end)lineEnding=end;
rows.push({cells,end});cells=[];if(rows.length>limits.rows)throw Error('size');
}
return {source,bom,lineEnding:lineEnding||'\r\n',rows};
}
function parse(source){return parseRecords(source,',');}
function encode(value){return /[",\r\n]/.test(value)||/^\s/.test(value)?'"'+value.replace(/"/g,'""')+'"':value;}
function serialize(model){
const source=model.bom+model.rows.map(row=>{const record=row.cells.map(c=>c.value===c.original?c.raw:encode(c.value)).join(',');return record+(row.end||(!record?model.lineEnding:''));}).join('');
parse(source);return source;
}
function edit(source,action,row=0,column=0,value=''){
const m=parse(source),blank=()=>({value:'',raw:'',original:''});
if(action==='cell'){
if(!m.rows[row]?.cells[column]||typeof value!=='string')throw Error('cell');
m.rows[row].cells[column].value=value;
}else if(action==='add-row'){
const last=m.rows.at(-1),cols=Math.max(1,...m.rows.map(r=>r.cells.length));
if(last&&!last.end)last.end=m.lineEnding;
// A newline is necessary to distinguish a blank final row from no row.
m.rows.push({cells:Array.from({length:cols},blank),end:m.lineEnding});
}else if(action==='add-column'){
if(!m.rows.length)m.rows.push({cells:[blank()],end:m.lineEnding});
const cols=Math.max(...m.rows.map(r=>r.cells.length));
for(const r of m.rows){while(r.cells.length<cols)r.cells.push(blank());r.cells.push(blank());}
}else if(action==='delete-row'){
if(!m.rows[row])throw Error('row');m.rows.splice(row,1);
}else if(action==='delete-column'){
if(!m.rows.some(r=>r.cells[column]))throw Error('column');
for(const r of m.rows){r.cells.splice(column,1);if(!r.cells.length)r.cells.push(blank());}
}else throw Error('action');
return serialize(m);
}
function paste(source,row,column,clipboard){
// Clipboard tables use tabs, not commas. Parse and validate the entire
// operation before returning anything to the editor or its undo history.
const m=parse(source),incoming=parseRecords(clipboard,'\t');
if(!Number.isInteger(row)||!Number.isInteger(column)||row<0||column<0||row>=limits.rows||column>=limits.columns)throw Error('cell');
if(!incoming.rows.length)return source;
const width=Math.max(...incoming.rows.map(r=>r.cells.length));
if(row+incoming.rows.length>limits.rows||column+width>limits.columns)throw Error('size');
const blank=()=>({value:'',raw:'',original:''});
while(m.rows.length<row+incoming.rows.length){
const last=m.rows.at(-1);if(last&&!last.end)last.end=m.lineEnding;
m.rows.push({cells:[blank()],end:m.lineEnding});
}
for(let r=0;r<incoming.rows.length;r++){
const target=m.rows[row+r].cells,fields=incoming.rows[r].cells;
while(target.length<column+fields.length)target.push(blank());
for(let c=0;c<fields.length;c++)target[column+c].value=fields[c].value;
}
return serialize(m);
}
root.PagesCSV={parse,edit,paste,serialize,limits};
})(typeof window==='undefined'?globalThis:window);
+62
View File
@@ -0,0 +1,62 @@
const test=require('node:test'),assert=require('node:assert/strict');
require('./csv-core.js');const csv=globalThis.PagesCSV;
test('CSV parsing preserves untouched bytes and logical field values',()=>{
for(const source of ['', '\ufeff', 'a', 'a,', '\n', '""', 'a\r\nb\n', '\ufeff"name",description\r\n日本語,"a,b\r\nnext"\r\n', '"a""b",=1+1\n'])assert.equal(csv.serialize(csv.parse(source)),source);
const s='\ufeff"name",description\r\n日本語,"a,b\r\nnext"\r\n';
assert.equal(csv.parse(s).rows[1].cells[1].value,'a,b\nnext');
assert.equal(csv.edit(s,'cell',1,0,'新しい,名前'),'\ufeff"name",description\r\n"新しい,名前","a,b\r\nnext"\r\n');
assert.equal(csv.edit(s,'cell',1,1,'a,b\nnext'),s);
assert.equal(csv.edit('a','cell',0,0,''),'\r\n');
});
test('Row and column operations preserve fields; empty and ragged data are explicit',()=>{
assert.equal(csv.edit('a,b\nc\n','add-column'),'a,b,\nc,,\n');
assert.equal(csv.edit('a,b\nc\n','delete-column',0,1),'a\nc\n');
assert.equal(csv.edit('a,b\r\n"c",d','delete-row',0),'"c",d');
assert.equal(csv.edit('a,b','add-row'),'a,b\r\n,\r\n');
assert.equal(csv.parse(csv.edit('','add-row')).rows.length,1);
assert.equal(csv.edit('a\n','delete-row',0),'');
});
test('Malformed and excessive data fail without truncation',()=>{
for(const source of ['"unfinished','a"b','"a"x','a\rb','a\0b','x'.repeat(256*1024+1),'x'.repeat(16385), 'a,'.repeat(32), 'a\n'.repeat(201)])assert.throws(()=>csv.parse(source));
assert.throws(()=>csv.edit('a\n'.repeat(200),'add-row'));
assert.throws(()=>csv.edit('a','cell',0,0,'x'.repeat(16385)));
assert.throws(()=>csv.edit('a','cell',2,0,'bad'));
});
test('Quotes, HTML, formulas and newlines remain inert CSV data',()=>{
for(const value of ['"','a,b','<img src=x onerror=alert(1)>','{{children}}','=SUM(A1:A9)',' leading','日本語\n次の行','a\r\nb']){
const source=csv.edit('old,unchanged\r\n','cell',0,0,value);
assert.equal(csv.parse(source).rows[0].cells[0].value,value.replace(/\r\n/g,'\n'));
assert.ok(source.endsWith(',unchanged\r\n'));
}
});
test('Tab-separated paste preserves untouched CSV bytes and treats commas as data',()=>{
const source='\ufeff"keep",old,last\r\n"unchanged",x,y\n';
assert.equal(csv.paste(source,0,1,'日本語,値\t"a""b"\r\nnext\tfinal\r\n'),
'\ufeff"keep","日本語,値","a""b"\r\n"unchanged",next,final\n');
assert.equal(csv.paste(source,0,0,'keep\told\tlast\nunchanged\tx\ty\n'),source);
assert.equal(csv.paste('a,b\n',0,0,'"line1\r\nline2"\t"tab\tvalue"\n'),'"line1\nline2",tab\tvalue\n');
});
test('Paste grows only required rows and cells, preserving ragged data',()=>{
assert.equal(csv.paste('a,b\nc\nz\n',0,1,'x\ty\nz'),'a,x,y\nc,z\nz\n');
assert.equal(csv.paste('a,b',0,1,'x\ty\nz\tw'),'a,x,y\r\n,z,w\r\n');
assert.equal(csv.paste('',0,0,'a\tb\n'),'a,b\r\n');
assert.equal(csv.paste('a,b\n',0,0,'\t\n'),',\n');
assert.equal(csv.paste('a,b\n',0,0,''),'a,b\n');
});
test('Paste validates both input and final CSV size without partial writes',()=>{
const source='original,untouched\r\n';
for(const text of ['a\tb\n"unfinished','a\0b\tc','x'.repeat(16385)+'\tb','a\n'.repeat(201),'a\t'.repeat(32)])assert.throws(()=>csv.paste(source,0,0,text));
for(const [row,col] of [[-1,0],[0,-1],[0.5,0],[0,NaN],[200,0],[0,32]])assert.throws(()=>csv.paste(source,row,col,'a\tb'));
assert.throws(()=>csv.paste(source,199,0,'a\nb'));
assert.throws(()=>csv.paste(source,0,31,'a\tb'));
// Valid individual cells can still exceed the total document limit.
const big=Array(16).fill('x'.repeat(16000)).join(',');
assert.throws(()=>csv.paste(big,0,16,'y'.repeat(16000)));
// Quoting comma-heavy clipboard data expands the resulting CSV.
assert.throws(()=>csv.paste('',0,0,Array(16).fill(','.repeat(16383)).join('\t')));
assert.equal(source,'original,untouched\r\n');
});
test('Pasted HTML, macros and formulas remain values rather than executable content',()=>{
const values=['<img src=x onerror=alert(1)>','{{children}}','=SUM(A1:A9)'];
assert.deepEqual(csv.parse(csv.paste('',0,0,values.join('\t'))).rows[0].cells.map(c=>c.value),values);
});
+87
View File
@@ -0,0 +1,87 @@
(() => {
'use strict';
const views=new WeakMap(),pageSize=25;
const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
class TableEditor {
constructor(editor){this.editor=editor;this.page=0;this.selected=null;this.last=null;this.undo=[];this.redo=[];}
t(en,ja){return this.editor.ja?ja:en;}
render(text){
if(this.last===text)return;
this.last=text;this.selected=null;
const pane=this.editor.preview;pane.classList.remove('code-preview');pane.classList.add('csv-edit-pane');pane.replaceChildren();
try{this.model=PagesCSV.parse(text);}catch{
const error=el('p',this.t('Table unavailable: check CSV syntax or limits (200 rows, 32 columns, 16 KiB per cell). Edit the source; no data was truncated.','表を表示できません。CSVの構文・上限(200行、32列、セル16 KiB)を確認してください。ソースで編集できます。データは切り捨てていません。'));
error.role='status';pane.append(error);return;
}
const toolbar=el('div');toolbar.className='csv-edit-toolbar';
const button=(icon,en,ja,fn)=>{const b=el('button',icon);b.type='button';b.title=b.ariaLabel=this.t(en,ja);b.onclick=fn;toolbar.append(b);return b;};
const save=button('','Save','保存',async()=>{save.disabled=true;try{await this.editor.saveNow();}finally{save.disabled=false;}});
save.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 4h12l2 2v14H5zM8 4v6h8V4M8 20v-6h8v6"/></svg>';
button('+↧','Add row','行を追加',()=>this.change('add-row'));
button('+→','Add column','列を追加',()=>this.change('add-column'));
this.deleteRow=button('−↧','Delete selected row','選択行を削除',()=>this.change('delete-row'));
this.deleteColumn=button('−→','Delete selected column','選択列を削除',()=>this.change('delete-column'));
this.deleteRow.disabled=this.deleteColumn.disabled=true;
const undo=button('↶','Undo table edit','表の編集を元に戻す',()=>this.history(false));undo.disabled=!this.undo.length;
const redo=button('↷','Redo table edit','表の編集をやり直す',()=>this.history(true));redo.disabled=!this.redo.length;
this.undoButton=undo;this.redoButton=redo;
this.page=Math.max(0,Math.min(this.page,Math.ceil(this.model.rows.length/pageSize)-1));
const previous=button('‹','Previous rows','前の行',()=>{this.page--;this.last=null;this.render(this.editor.text());});previous.disabled=this.page===0;
const first=this.page*pageSize,end=Math.min(first+pageSize,this.model.rows.length);
this.position=el('output',this.model.rows.length?`${first+1}–${end} / ${this.model.rows.length}`:'0');toolbar.append(this.position);
const next=button('›','Next rows','次の行',()=>{this.page++;this.last=null;this.render(this.editor.text());});next.disabled=end>=this.model.rows.length;
this.message=el('span');this.message.role='status';toolbar.append(this.message);
const saved=el('span',document.getElementById('editor-save-status')?.textContent||'');saved.dataset.csvSaveStatus='';saved.role='status';toolbar.append(saved);pane.append(toolbar);
const scroll=el('div');scroll.className='csv-edit-scroll';const table=el('table');table.setAttribute('aria-label',this.t('CSV cells','CSVのセル'));
const head=el('thead'),hr=el('tr');hr.append(el('th','#'));
const width=Math.max(0,...this.model.rows.map(r=>r.cells.length));
for(let c=0;c<width;c++){const th=el('th',String(c+1));th.scope='col';hr.append(th);}head.append(hr);table.append(head);
const body=el('tbody');
for(let r=first;r<end;r++){
const tr=el('tr'),number=el('th',String(r+1));number.scope='row';tr.append(number);
for(let c=0;c<width;c++){
const td=el('td'),cell=this.model.rows[r].cells[c];
if(cell){const input=el('textarea');input.value=cell.value;input.rows=cell.value.includes('\n')?3:1;input.spellcheck=false;input.dataset.row=r;input.dataset.column=c;input.ariaLabel=this.t(`Row ${r+1}, column ${c+1}`,`${r+1}行 ${c+1}列`);
input.addEventListener('focus',()=>{this.selected=[r,c];this.deleteRow.disabled=this.deleteColumn.disabled=false;});
input.addEventListener('input',()=>this.change('cell',r,c,input.value,input));td.append(input);
input.addEventListener('paste',event=>{
const text=event.clipboardData?.getData('text/plain');
if(typeof text!=='string'||!/[\t\r\n]/.test(text))return;
event.preventDefault();this.change('paste',r,c,text);
});
}
tr.append(td);
}
body.append(tr);
}
table.append(body);scroll.append(table);pane.append(scroll);
}
change(action,row=this.selected?.[0],column=this.selected?.[1],value,input){
const source=this.editor.text();
if(source!==this.last){this.last=null;this.render(source);return;}
try{
const next=action==='paste'?PagesCSV.paste(source,row,column,value):PagesCSV.edit(source,action,row,column,value);if(next===source)return;
this.undo.push({before:source,after:next});if(this.undo.length>20)this.undo.shift();this.redo=[];
if(action==='cell'){
// Keep the active textarea and its caret; delayed preview is a no-op.
this.model=PagesCSV.parse(next);this.last=next;this.editor.setText(next);
this.undoButton.disabled=false;this.redoButton.disabled=true;this.message.textContent='';
}else{
if(action==='add-row')this.page=Math.floor((PagesCSV.parse(next).rows.length-1)/pageSize);
this.last=null;this.editor.setText(next);this.render(next);
if(action==='paste')this.editor.preview.querySelector(`textarea[data-row="${row}"][data-column="${column}"]`)?.focus();
}
}catch{
if(input)input.value=this.model.rows[row].cells[column].value;
this.message.textContent=action==='paste'?this.t('Paste rejected: invalid tab-separated data or CSV limits exceeded. Source retained.','貼り付けできません。タブ区切りデータの形式またはCSVの上限を確認してください。元の内容を保持しました。'):this.t('Edit exceeds CSV limits. Source retained.','CSVの上限を超えます。元の内容を保持しました。');
}
}
history(forward){
const from=forward?this.redo:this.undo,to=forward?this.undo:this.redo;if(!from.length)return;
const item=from.at(-1),current=this.editor.text();
if(current!==(forward?item.before:item.after)){this.message.textContent=this.t('Source changed. Use source editor undo.','ソースが変更されています。ソース側の取り消しを使ってください。');return;}
from.pop();to.push(item);const text=forward?item.after:item.before;this.last=null;this.editor.setText(text);this.render(text);
}
}
window.PagesCSVEditor={render(editor,text){let view=views.get(editor);if(!view){view=new TableEditor(editor);views.set(editor,view);}view.render(text);}};
})();
+54
View File
@@ -0,0 +1,54 @@
(() => {
'use strict';
// Commands address exact UUIDs, never ambiguous titles. Mutations reuse the
// task API's ownership checks and revision CAS; this is not a shell.
window.PagesDashboardCommands=(body,{request,api,t,today,refresh,writable,signal})=>{
const form=document.createElement('form'),input=document.createElement('input'),submit=document.createElement('button'),help=document.createElement('details'),summary=document.createElement('summary'),examples=document.createElement('pre'),status=document.createElement('p');
form.className='dashboard-command';input.ariaLabel=t('Task command','タスクコマンド');input.placeholder='add task … / today UUID / tomorrow UUID';input.required=true;input.maxLength=500;submit.textContent='↵';submit.title=submit.ariaLabel=t('Run','実行');submit.disabled=input.disabled=!writable;status.role='status';summary.textContent='?';examples.textContent='add task 件名\ntoday UUID\ntomorrow UUID\ndue UUID YYYY-MM-DD\ndue UUID clear\ndone UUID\ndelete UUID';help.append(summary,examples);form.append(input,submit);body.replaceChildren(form,status,help);
const suggestions=document.createElement('datalist');suggestions.id='dashboard-command-tasks';input.setAttribute('list',suggestions.id);input.autocomplete='off';body.append(suggestions);
let pending=null,timer,lookup;
signal?.addEventListener('abort',()=>{clearTimeout(timer);lookup?.abort();},{once:true});
input.addEventListener('input',()=>{
clearTimeout(timer);lookup?.abort();suggestions.replaceChildren();
const match=/^(today|tomorrow|due|done|delete) (.*)$/.exec(input.value);
if(!match||/^[0-9a-f]{8}-/.test(match[2]))return;
const command=input.value;lookup=new AbortController();const requestSignal=lookup.signal;
timer=setTimeout(async()=>{
try {const data=await request(api+'items?'+new URLSearchParams({kind:'task',view:'all',limit:'10',q:match[2]}),{signal:AbortSignal.any([requestSignal,AbortSignal.timeout(10000)])});
if(input.value!==command||requestSignal.aborted||!body.isConnected)return;
for(const item of data.items){const option=document.createElement('option');option.value=match[1]+' '+item.uuid+(match[1]==='due'?' '+today:'');option.label=match[1]+' '+item.title;suggestions.append(option);}
}catch{/* Suggestions must never prevent command entry. */}
},250);
});
form.onsubmit=async e=>{
e.preventDefault();if(submit.disabled)return;
const command=input.value.trim(),tomorrow=new Date(today+'T12:00:00Z');tomorrow.setUTCDate(tomorrow.getUTCDate()+1);
submit.disabled=true;input.disabled=true;status.textContent='';
try{
let saved;
if(command.startsWith('add task ')){
const title=command.slice(9).trim();if(!title)throw Error(t('Enter a title.','件名を入力してください。'));
if(!pending||pending.command!==command){const preferences=await request(api+'preferences');pending={command,item:{...preferences.defaults,uuid:crypto.randomUUID(),kind:'task',title,notes:'',status:'todo',bucket:'inbox',priority:1,archived:false,version:0}};}
saved=await request(api+'items',{method:'POST',body:JSON.stringify(pending.item)});
}else{
const match=/^(today|tomorrow|due|done|delete) ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?: (\d{4}-\d{2}-\d{2}|clear))?$/.exec(command);
if(!match||(match[1]==='due')!==!!match[3])throw Error(t('Unknown command. See ?.','コマンドを確認してください(?)。'));
const [,action,id,date]=match,{item}=await request(api+'items/'+id);
if(item.kind!=='task')throw Error(t('Select a task, not a project.','プロジェクトではなくタスクを指定してください。'));
if(action==='delete'){
if(!confirm(item.title+'\n'+t('Permanently delete this task?','このタスクを完全に削除しますか?')))return;
await request(api+'items/'+id,{method:'DELETE',headers:{'If-Match':'"'+item.version+'"'}});
}else{
if(action==='due'){item.due_on=date==='clear'?'':date;if(!item.due_on)item.notify_due=false;}
if(action==='today'||action==='tomorrow')item.planned_on=action==='today'?today:tomorrow.toISOString().slice(0,10);
if(action==='done')item.status='done';
saved=await request(api+'items/'+id,{method:'PUT',headers:{'If-Match':'"'+item.version+'"'},body:JSON.stringify(item)});
}
}
pending=null;input.value='';status.textContent=t('Saved','保存しました');
if(saved?.item){const a=document.createElement('a');a.href='/v/plan/task/'+saved.item.uuid;a.textContent=' '+saved.item.title;status.append(a);}
refresh();
}catch(error){status.textContent=error.message;}finally{submit.disabled=input.disabled=!writable;input.focus();}
};
};
})();
+40 -10
View File
@@ -6,8 +6,12 @@ window.PagesEditor = {
this.mount = document.getElementById('editor-mount')
if (!this.editor || !this.preview || !this.mount) return
this.baseRevision = this.mount.dataset.baseRevision || ''
this.baseBody = document.getElementById('editor-base')?.value || ''
this.initialText = this.editor.value
// HTML textarea parsing and CodeMirror's default input both normalize
// CRLF. CSV receives an escaped JS string and uses LF-only splitting.
this.csvInitialSource = this.mount.dataset.csv === 'true' ? window.PagesCSVSource : undefined
delete window.PagesCSVSource
this.baseBody = this.csvInitialSource ?? (document.getElementById('editor-base')?.value || '')
this.initialText = this.csvInitialSource ?? this.editor.value
this.owner = this.mount.dataset.owner || ''
this.serial = 0
this.paused = false
@@ -25,6 +29,12 @@ window.PagesEditor = {
if (action === 'delete') window.PagesPathActions?.removeCurrentPath()
if (action === 'html' || action === 'markdown') this.switchFormat(action)
if (action === 'preview') window.toggleEditorPreview()
if (action === 'slides' && window.PagesSlides) {
this.slidePreview=!this.slidePreview
button.setAttribute('aria-pressed',String(this.slidePreview))
if(this.slidePreview)window.setEditorPreviewVisible?.(true)
this.renderPreview()
}
if (action === 'tools') this.tools()
if (action === 'language') this.languageDialog()
if (action === 'restore') this.historyDialog()
@@ -65,17 +75,21 @@ window.PagesEditor = {
exists:['指定言語には既に本文があります。編集として開いてください','This language already exists. Open it for editing'], history:['過去のリビジョンを復元','Restore a previous revision'],
signin:['再ログイン(別タブ)','Sign in again (new tab)'], insert:['挿入','Insert'], invalid:['言語タグを確認してください','Check the language tag'], identity:['別アカウントに切り替わっています。元のアカウントで開き直してください','Account changed. Reopen using the original account'],
incompatible:['ファイル形式が変更されています。下書きを退避して開き直してください','File type changed. Download your draft and reopen'], older:['さらに古い履歴','Older revisions'],
csvlimit:['CSVは256 KiB以内で保存してください。下書きは保持しています','CSV must be at most 256 KiB. Your draft is retained'],
children:['子ページ一覧','Children'], table:['表','Table'], figure:['画像とキャプション','Image + caption'], note:['補足','Note'], code:['コードブロック','Code block'], quote:['引用','Quote'],
csv:['CSVの表を埋め込む','Embed CSV table'],
protected:['Markdown で表せない HTML は {=html} ブロックに保持します。ブロック内も編集でき、保存・プレビュー時に HTML として扱います。','HTML not representable in Markdown is retained in editable {=html} blocks and rendered as HTML on save / preview.'],
}
return text[key]?.[this.ja ? 0 : 1] || key
},
value(id) { return document.getElementById(id)?.value || '' },
format() {return this.value('edit-type')},
text() {return window.PagesWikiCodeMirror?.state.doc.toString() ?? this.editor.value},
text() {return window.PagesWikiCodeMirror?.state.doc.toString() ?? this.csvInitialSource ?? this.editor.value},
status(key) {
const status = document.getElementById('editor-save-status')
if (status) {status.textContent = this.t(key); status.dataset.state = key}
const csvStatus=this.preview?.querySelector('[data-csv-save-status]')
if (csvStatus) csvStatus.textContent=this.t(key)
},
keyPrefix() {return 'pageswiki.draft.v1:'+JSON.stringify([this.mount.dataset.domain,this.owner,this.value('object-uuid'),this.value('page-language')||'und'])+':'},
expireDrafts() {
@@ -180,6 +194,7 @@ window.PagesEditor = {
}
},
async canonical(text = this.text(), format = this.format()) {
if (this.mount.dataset.csv === 'true' && (new TextEncoder().encode(text).length > 256*1024 || text.includes('\0'))) throw {kind:'csvlimit'}
if (text === this.initialText && format === this.initialFormat) return this.baseBody
if (format !== 'markdown') return text
const data = await this.post('/_/api/v1/render/markdown',{markdown:text,authoring:true})
@@ -192,6 +207,7 @@ window.PagesEditor = {
const controller = new AbortController()
this.previewController = controller
const text = this.text()
if (this.mount.dataset.csv === 'true' && window.PagesCSVEditor) {window.PagesCSVEditor.render(this,text); return}
if (this.format() === 'code' || this.format() === 'plain') {this.preview.classList.add('code-preview'); this.preview.textContent=text; return}
try {
const data = await this.post('/_/api/v1/render/markdown',{
@@ -199,10 +215,16 @@ window.PagesEditor = {
},{signal:controller.signal})
if (controller.signal.aborted || text !== this.text()) return
this.preview.classList.remove('code-preview')
if (this.slidePreview && window.PagesSlides) {
try {window.PagesSlides.render(this.preview,data.html,window.PagesWikiCurrentPath||'/');return}
catch {window.PagesSlides.clear(this.preview);this.preview.textContent=this.ja?'スライドの上限を超えています(256 KiB・100枚)。通常プレビューを使用してください。':'Slide limits exceeded (256 KiB, 100 slides). Use normal preview.';return}
}
window.PagesSlides?.clear(this.preview)
this.preview.innerHTML = data.html
window.PagesWikiLoadChildren?.(this.preview)
} catch (error) {
if (controller.signal.aborted) return
window.PagesSlides?.clear(this.preview)
this.preview.classList.add('code-preview'); this.preview.textContent=text
this.fail(error)
}
@@ -270,7 +292,9 @@ window.PagesEditor = {
this.dirty=false; this.paused=false; this.clearDraft(); this.status('saved'); return
}
if (serial !== this.serial) {this.status('remote'); this.persist(); return}
const merged = PagesEditorCore.merge(this.baseBody,local,remote.body)
// Text ranges do not describe CSV record boundaries. Review competing
// table edits rather than silently combining rows/columns incorrectly.
const merged = this.mount.dataset.csv === 'true' ? null : PagesEditorCore.merge(this.baseBody,local,remote.body)
const apply = result => {
this.baseRevision=remote.revision_uuid; this.baseBody=remote.body
document.getElementById('page-filename').value=remote.filename||''
@@ -301,12 +325,13 @@ window.PagesEditor = {
const oldFormat = this.format()
document.getElementById('edit-type').value=format
const status=document.getElementById('editor-format-status')
if (status) status.textContent=format
if (status) status.textContent=this.mount.dataset.csv === 'true' ? 'CSV' : format
this.editor.value=text
if (this.mount.dataset.csv === 'true') this.csvInitialSource=text
if (oldFormat !== format && window.PagesWikiCodeMirror) {
window.PagesWikiCodeMirror.destroy()
window.PagesWikiCodeMirror = window.PagesWikiEditor.create(this.mount,text,format,{
keymap:this.mount.dataset.keymap,syntax:this.mount.dataset.syntax==='true',autocomplete:this.mount.dataset.autocomplete==='true',
keymap:this.mount.dataset.keymap,syntax:this.mount.dataset.syntax==='true',autocomplete:this.mount.dataset.autocomplete==='true',preserveLineEndings:this.mount.dataset.csv==='true',
})
} else if (window.PagesWikiCodeMirror) {
const cm=window.PagesWikiCodeMirror
@@ -368,19 +393,24 @@ window.PagesEditor = {
const {dialog,content,button}=this.dialog('tools')
this.paragraph(content,this.t('privacy'))
const select=document.createElement('select'); select.setAttribute('aria-label',this.t('insert'))
this.paragraph(content,this.t('protected'))
const csvFile=this.mount.dataset.csv==='true'
if (!csvFile) this.paragraph(content,this.t('protected'))
const parts=[['children','{{children}}'],['table','<table>\n<thead><tr><th>Column</th></tr></thead>\n<tbody><tr><td>Value</td></tr></tbody>\n</table>'],['figure','<figure><img src="/_/obj/sha256:HASH" alt="Description"><figcaption>Caption</figcaption></figure>'],['note','<aside class="note"><p>Note</p></aside>'],['code','<pre><code class="language-text">code</code></pre>'],['quote','<blockquote><p>Quote</p></blockquote>']]
parts.push(['csv','{{csv:/data/table.csv range=A1:H200 header=true}}'])
parts.forEach(([label],i) => {const option=document.createElement('option'); option.value=i; option.textContent=this.t(label); select.append(option)})
content.append(select)
select.hidden=csvFile
const login=document.createElement('a'); login.href='/_/auth/login?return='+encodeURIComponent(location.pathname+location.search); login.target='_blank'; login.rel='noopener'; login.textContent=this.t('signin'); content.append(login)
button('insert',() => {
const insert=button('insert',() => {
if (csvFile) return
const part=parts[Number(select.value)]
const source=this.format()==='markdown' && part[0]!=='children' ? '```{=html}\n'+part[1]+'\n```' : part[1]
const source=this.format()==='markdown' && !['children','csv'].includes(part[0]) ? '```{=html}\n'+part[1]+'\n```' : part[1]
const text='\n\n'+source+'\n\n'
const cm=window.PagesWikiCodeMirror
if (cm) cm.dispatch(cm.state.replaceSelection(text)); else this.setText(this.text()+text)
dialog.close(); cm?.focus()
})
insert.hidden=csvFile
button('export',() => this.download())
button('discard',() => {
this.clearDraft()
@@ -429,7 +459,7 @@ window.PagesEditor = {
const serial=this.serial
const old=await this.state({revision:select.value})
if (serial!==this.serial || this.saving) return
if (!old.editable) throw {kind:'incompatible'}
if (!old.editable || this.mount.dataset.csv === 'true' && (old.content_type||'').split(';')[0] !== this.value('page-content-type').split(';')[0]) throw {kind:'incompatible'}
this.setText(this.format()==='markdown'?old.markdown:old.body)
this.persist(); dialog.close()
})
+1 -1
View File
@@ -273,7 +273,7 @@
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));}
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});
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();
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='/o/uuid:'+encodeURIComponent(page);dialog.append(el('p'),a);}const done=button(t('Close','閉じる'),'',close);dialog.append(el('p'),done);done.focus();
}catch(e){notice.textContent=e.message;}finally{busy=false;save.disabled=resolved===null;}
};
}
+6 -1
View File
@@ -10,6 +10,7 @@
let saved = Number(input.value);
const paletteNames = ['home_palette_mode','home_palette_strength','home_palette_brightness'];
let savedPalette = paletteNames.map(name => form.elements[name]?.value);
let savedWallpaper = ['home_wallpaper_path','home_wallpaper_opacity'].map(name=>form.elements[name]?.value);
const palettePreview = () => {
const strength = Number(form.elements.home_palette_strength?.value ?? 35);
const label = form.querySelector('[data-palette-strength]');
@@ -24,6 +25,7 @@
palettePreview();
};
const restore = () => {
['home_wallpaper_path','home_wallpaper_opacity'].forEach((name,i)=>{if(form.elements[name])form.elements[name].value=savedWallpaper[i];});
input.value = String(saved);
paletteNames.forEach((name,i) => { if (form.elements[name]) form.elements[name].value=savedPalette[i]; });
preview(saved);
@@ -71,11 +73,14 @@
signal: AbortSignal.timeout(15000),
});
if (!response.ok) throw new Error((await response.text()).trim());
await response.json();
const result=await response.json();form.elements.version.value=String(result.version);
const wallpaper=['home_wallpaper_path','home_wallpaper_opacity'].map(name=>submitted.get(name));
const wallpaperChanged=wallpaper.some((value,i)=>value!==savedWallpaper[i]);savedWallpaper=wallpaper;
saved = Number(submitted.get('home_glass_transparency'));
savedPalette = paletteNames.map(name => submitted.get(name));
preview(saved);
status.textContent = form.dataset.saved;
if(wallpaperChanged){location.reload();return;}
window.setTimeout(() => dialog.open && dialog.close(), 350);
} catch (error) {
status.textContent = error.message;
+14 -11
View File
@@ -8,7 +8,8 @@
const names={progress:t('Today’s completion','本日の達成率'),today:t('Today’s tasks','本日のタスク'),tomorrow:t('Tomorrow’s tasks','明日のタスク'),tasks:t('Tasks','タスク'),schedule:t('Today’s schedule','本日のスケジュール'),activity:t('Activity report','達成度・作業レポート')};
const defaults=[['progress',4,3],['today',4,3],['tomorrow',4,3],['tasks',8,4],['schedule',4,4],['activity',12,5]].map(([id,width,height])=>({id,width,height,...(id==='tasks'?{tab:'inbox'}:{})}));
names.feeds=t('RSS · latest cached articles','RSS · 最近の取得記事');
const available=[...defaults,{id:'feeds',width:6,height:4}];
names['tomorrow-schedule']=t('Tomorrow’s schedule','明日のスケジュール');names.commands=t('Task commands','タスクコマンド');
const available=[...defaults,{id:'feeds',width:6,height:4},{id:'tomorrow-schedule',width:6,height:4},{id:'commands',width:6,height:3}];
const tabs={inbox:'Inbox',backlog:'Backlog',someday:'Someday',review:'Review',all:'Incomplete',done:'Done'};
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
function button(text,label,fn){const b=el('button',text);b.type='button';b.title=b.ariaLabel=label;b.onclick=fn;return b;}
@@ -28,7 +29,7 @@
}
const save=button(t('Save layout','配置を保存'),t('Save layout','配置を保存'),async()=>{
if(saving||!loaded)return;saving=true;updateControls();
try{const data=await request(api+'dashboard',{method:'PUT',signal:AbortSignal.timeout(15000),body:JSON.stringify({version,widgets})});version=data.version;dirty=false;status.textContent=t('Layout saved','配置を保存しました');}
try{const data=await request(api+'dashboard',{method:'PUT',signal:AbortSignal.timeout(15000),body:JSON.stringify({version,widgets:widgets.map(({id,width,height,tab})=>({id,width,height,...(id==='tasks'?{tab:tab||'inbox'}:{})}))})});version=data.version;widgets=data.widgets;dirty=false;render();status.textContent=t('Layout saved','配置を保存しました');}
catch(e){status.textContent=e.message;}finally{saving=false;updateControls();}
});
const edit=button('⚙',t('Arrange widgets','ウィジェットを配置'),()=>{editing=!editing;root.classList.toggle('is-arranging',editing);edit.setAttribute('aria-pressed',String(editing));});edit.setAttribute('aria-pressed','false');
@@ -36,7 +37,7 @@
const add=el('select');add.ariaLabel=t('Add widget','ウィジェットを追加');add.onchange=()=>{const item=available.find(w=>w.id===add.value);if(item){widgets.push({...item});render();changed();}};
const reset=button(t('Reset layout','初期配置'),t('Reset layout','初期配置'),()=>{if(confirm(t('Replace this layout with the default layout? Save to apply.','初期配置に戻しますか? 保存するまでは確定しません。'))){widgets=defaults.map(x=>({...x}));render();changed();}});
controls.append(refresh);if(writable)controls.append(edit,add,reset,save);
function updateControls(){save.disabled=!dirty||saving||!loaded;edit.disabled=add.disabled=reset.disabled=saving||!loaded;refresh.disabled=!loaded;root.classList.toggle('dashboard-saving',saving);for(const card of cards.values())card.querySelectorAll('.widget-arrange button,.widget-arrange select,.widget-drag,.widget-resize').forEach(n=>n.disabled=saving);add.replaceChildren();const option=el('option',t('+ Add widget','+ ウィジェットを追加'));option.value='';add.append(option);for(const [id,name] of Object.entries(names)){if(widgets.some(w=>w.id===id)||id==='schedule'&&root.dataset.calendar!=='true')continue;const o=el('option',name);o.value=id;add.append(o);}}
function updateControls(){save.disabled=!dirty||saving||!loaded;edit.disabled=add.disabled=reset.disabled=saving||!loaded;refresh.disabled=!loaded;root.classList.toggle('dashboard-saving',saving);for(const card of cards.values())card.querySelectorAll('.widget-arrange button,.widget-arrange select,.widget-drag,.widget-resize').forEach(n=>n.disabled=saving);add.replaceChildren();const option=el('option',t('+ Add widget','+ ウィジェットを追加'));option.value='';add.append(option);for(const [id,name] of Object.entries(names)){if(widgets.some(w=>w.id===id)||['schedule','tomorrow-schedule'].includes(id)&&root.dataset.calendar!=='true')continue;const o=el('option',name);o.value=id;add.append(o);}}
function changed(){dirty=true;status.textContent=t('Unsaved layout changes','配置は未保存です');updateControls();}
window.addEventListener('beforeunload',event=>{if(dirty){event.preventDefault();event.returnValue='';}});
function applySize(item,card){card.style.setProperty('--widget-width',String(item.width));card.style.setProperty('--widget-height',String(item.height));}
@@ -47,7 +48,7 @@
const card=el('section',undefined,'dashboard-widget');card.id=item.id;card.dataset.widget=item.id;applySize(item,card);
const header=el('header',undefined,'widget-header'),heading=el('h2',names[item.id]);heading.id='widget-title-'+item.id;card.setAttribute('aria-labelledby',heading.id);
header.append(heading);const destinations={progress:'/v/plan/today',today:'/v/plan/today',tomorrow:'/v/plan/tasks/tomorrow',tasks:'/v/plan/tasks',schedule:'/v/plan',activity:'/v/plan/dashboard#activity'};
destinations.feeds='/v/feeds';
destinations.feeds='/v/feeds';destinations['tomorrow-schedule']='/v/plan';destinations.commands='/v/plan/tasks';
const open=link('↗',destinations[item.id]);open.title=open.ariaLabel=t('Open ','開く: ')+names[item.id];header.append(open);
const arrange=el('div',undefined,'widget-arrange');
if(writable){
@@ -81,6 +82,7 @@
if(controller.signal.aborted||!card.isConnected)return;
const signal=AbortSignal.any([controller.signal,AbortSignal.timeout(15000)]);
try{
if(item.id==='commands'){window.PagesDashboardCommands(body,{request,api,t,today,writable,signal:controller.signal,refresh:()=>{for(const w of widgets){if(w.id!=='commands')loadWidget(w,cards.get(w.id));}}});return;}
if(item.id==='feeds'){
const data=await request('/_/api/v1/extension/organizer.feeds/items',{signal});if(controller.signal.aborted)return;
const list=el('ul',undefined,'dashboard-list');for(const item of data.items.slice(0,12)){const row=el('li');row.append(el('span',item.read?'○':'●'),link(item.title||t('(Untitled)','(無題)'),'/v/feeds?'+new URLSearchParams({source:item.source,id:item.id})));list.append(row);}
@@ -94,12 +96,13 @@
const ring=el('div',percentage===null?'—':percentage+'%','dashboard-progress');ring.style.setProperty('--progress',(percentage||0)+'%');
body.append(ring,el('p',data.done+' / '+data.total));return;
}
if(item.id==='schedule'){
if(item.id==='schedule'||item.id==='tomorrow-schedule'){
if(root.dataset.calendar!=='true'){body.replaceChildren(el('p',t('Calendar extension is disabled.','カレンダー拡張は無効です。')));return;}
const data=await request(calendarAPI+'upcoming?period=day',{signal});if(controller.signal.aborted)return;
const list=el('ul',undefined,'dashboard-list'),format=new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{hour:'2-digit',minute:'2-digit',timeZone:zone});
for(const event of data.events){const row=el('li'),a=link(event.summary||t('(Untitled)','(無題)'),event.href);row.append(el('time',event.all_day?t('All day','終日'):format.format(new Date(event.start))),a);list.append(row);}
body.replaceChildren(list);if(!data.events.length)body.append(el('p',t('No events today.','本日の予定はありません。')));body.append(link(t('Open calendar →','カレンダーで確認 →'),'/v/plan'));return;
const date=new Date(today+'T12:00:00Z');if(item.id==='tomorrow-schedule')date.setUTCDate(date.getUTCDate()+1);const day=date.toISOString().slice(0,10);
const data=await request(calendarAPI+'upcoming?period=day&date='+day,{signal});if(controller.signal.aborted)return;const dayURL='/v/plan/cal/'+day.replaceAll('-','/');card.querySelector('.widget-header a').href=dayURL;
const list=el('ul',undefined,'dashboard-list dashboard-agenda'),format=new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{hour:'2-digit',minute:'2-digit',timeZone:zone});
for(const event of data.events){const row=el('li'),a=link(event.summary||t('(Untitled)','(無題)'),event.href);const time=el('time',event.all_day?t('All day','終日'):format.format(new Date(event.start))+'–'+format.format(new Date(event.end)));time.dateTime=event.start;const detail=el('div',undefined,'agenda-event');detail.append(a,el('small',event.calendar));row.append(time,detail);row.dataset.allDay=String(!!event.all_day);if(Date.parse(event.start)<=Date.now()&&Date.parse(event.end)>Date.now())row.classList.add('is-current');list.append(row);}
body.replaceChildren(list);if(!data.events.length)body.append(el('p',t('No events.','予定はありません。')));body.append(link(t('Open calendar →','カレンダーで確認 →'),dayURL));return;
}
const tabbar=el('div',undefined,'widget-tabs');tabbar.setAttribute('role','tablist');tabbar.ariaLabel=names.tasks;
const list=el('div');list.id='widget-panel-'+item.id;list.setAttribute('role','tabpanel');list.tabIndex=0;
@@ -117,9 +120,9 @@
if(!append)list.replaceChildren();panel.querySelector('[data-more]')?.remove();
const ul=el('ul',undefined,'dashboard-list');
for(const task of data.items){const row=el('li');row.dataset.task=task.uuid;
const title=link(task.title,'/v/plan/task/'+encodeURIComponent(task.uuid));title.title=task.title;
const title=link(task.title,'/v/plan/task/'+encodeURIComponent(task.uuid));title.title=task.title;window.PagesTaskPresentation?.render(title,task.title,false);
row.append(el('span',task.status==='done'?'✓':task.status==='cancelled'?'−':task.status==='doing'?'◐':'○'),title);
if(task.due_on)row.append(el('time',task.due_on));ul.append(row);
if(task.page_uuid){const note=link('▣','/o/uuid:'+encodeURIComponent(task.page_uuid));note.title=note.ariaLabel=t('Open linked Wiki page','関連Wikiページを開く');note.className='dashboard-note';row.append(note);}if(task.due_on)row.append(el('time',task.due_on));ul.append(row);
}
list.append(ul);if(!data.items.length&&!append)list.append(el('p',t('No matching tasks.','該当するタスクはありません。')));
if(data.next){const more=button(t('Load more','続きを表示'),t('Load more','続きを表示'),()=>{more.disabled=true;tasks(tab,true,data.next).finally(()=>{more.disabled=false;});});more.dataset.more='true';panel.append(more);}
+15
View File
@@ -0,0 +1,15 @@
(() => {
'use strict';
const token=document.body.dataset.token;
const deck=new Reveal(document.querySelector('.reveal'),{
embedded:true,hash:false,history:false,respondToHashChanges:false,
transition:'none',backgroundTransition:'none',controls:true,progress:true,
slideNumber:'c/t',autoSlide:0,autoPlayMedia:false,postMessage:false,
postMessageEvents:false,view:'slide',scrollActivationWidth:null,width:960,height:700,
});
deck.initialize().then(()=>{
deck.slide(Math.min(Number(document.body.dataset.index)||0,deck.getTotalSlides()-1));
parent.postMessage({type:'slides-ready',token,index:deck.getIndices().h},'*');
deck.on('slidechanged',()=>parent.postMessage({type:'slides-index',token,index:deck.getIndices().h},'*'));
});
})();
+85
View File
@@ -0,0 +1,85 @@
/* Reveal is a disposable projection. No slide DOM is ever saved as source. */
(() => {
'use strict';
const nonce=document.currentScript?.nonce||'', views=new WeakMap();
const allowed=new Set('p br hr div span h1 h2 h3 h4 h5 h6 blockquote pre code b strong i em u s del ins sub sup small mark kbd ul ol li dl dt dd table thead tbody tfoot tr th td caption figure figcaption section article a img'.split(' '));
const blocked=new Set('script style iframe object embed template form input button textarea select link meta base svg math audio video'.split(' '));
function slides(html,path){
if(new TextEncoder().encode(html).length>256*1024)throw Error('size');
const input=document.createElement('template');input.innerHTML=html;
const clean=document.createDocumentFragment();let count=0;
const base=new URL(path||'/',location.origin);
function copy(node,parent,depth=0){
if(++count>10000||depth>64)throw Error('size');
if(node.nodeType===Node.TEXT_NODE){parent.append(document.createTextNode(node.textContent));return;}
if(node.nodeType!==Node.ELEMENT_NODE)return;
const tag=node.localName;if(blocked.has(tag))return;
let target=parent;
if(allowed.has(tag)){
target=document.createElement(tag==='section'&&depth>0?'div':tag);parent.append(target);
// Never forward Reveal data-*, IDs, styles or event handlers from content.
for(const attr of ['title','alt','colspan','rowspan']){
const value=node.getAttribute(attr);
if(value!==null&&(!['colspan','rowspan'].includes(attr)||/^[1-9][0-9]{0,2}$/.test(value)))target.setAttribute(attr,value);
}
const attr=tag==='a'?'href':tag==='img'?'src':null;
if(attr&&node.hasAttribute(attr)){
try{const url=new URL(node.getAttribute(attr),base);
if(['http:','https:'].includes(url.protocol)&&!url.username&&!url.password&&(tag!=='img'||url.origin===location.origin)){
target.setAttribute(attr,url.href);
if(tag==='a'){target.target='_blank';target.rel='noopener noreferrer';}
else{target.loading='lazy';target.referrerPolicy='no-referrer';}
}
}catch{}
}
}
for(const child of node.childNodes)copy(child,target,depth+1);
}
for(const node of input.content.childNodes)copy(node,clean);
const result=[];let section=document.createElement('section');
const flush=()=>{if(section.textContent.trim()||section.querySelector('img,table,hr')){result.push(section);section=document.createElement('section');}};
for(const node of [...clean.childNodes]){
if(node.nodeName==='HR'){flush();}
else if(node.nodeName==='SECTION'){flush();result.push(node);}
else section.append(node);
}
flush();if(!result.length)result.push(section);if(result.length>100)throw Error('size');
return result;
}
function clear(host){const view=views.get(host);if(view){clearTimeout(view.timer);window.removeEventListener('message',view.listener);views.delete(host);}host.classList.remove('slides-preview');}
function render(host,html,path){
clear(host);
const sections=slides(html,path),doc=document.implementation.createHTMLDocument('Slides');
const token=crypto.randomUUID(),origin=location.origin;
const meta=doc.createElement('meta');meta.httpEquiv='Content-Security-Policy';
meta.content=`default-src 'none'; script-src 'nonce-${nonce}'; script-src-attr 'none'; style-src ${origin} 'unsafe-inline'; img-src ${origin}; connect-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'`;
doc.head.prepend(meta);
for(const file of ['/static/vendor/reveal/reveal.css','/static/css/slides-frame.css']){const link=doc.createElement('link');link.rel='stylesheet';link.href=origin+file;doc.head.append(link);}
const colors=getComputedStyle(host),style=doc.createElement('style');
// Computed colors only; no authored CSS enters this isolated document.
style.textContent=`html,body,.reveal-viewport{background:${colors.backgroundColor==='rgba(0, 0, 0, 0)'?getComputedStyle(document.body).backgroundColor:colors.backgroundColor}!important;color:${colors.color}!important}`;doc.head.append(style);
const root=doc.createElement('div');root.className='reveal';const container=doc.createElement('div');container.className='slides';
for(const section of sections)container.append(doc.importNode(section,true));root.append(container);doc.body.append(root);
doc.body.dataset.token=token;doc.body.dataset.index=host.dataset.slideIndex||'0';
for(const file of ['/static/vendor/reveal/reveal.js','/static/js/slides-frame.js']){const script=doc.createElement('script');script.setAttribute('nonce',nonce);script.src=origin+file;doc.body.append(script);}
const frame=document.createElement('iframe');frame.className='slides-frame';frame.title=document.documentElement.lang.startsWith('ja')?'スライド':'Slides';
frame.setAttribute('sandbox','allow-scripts allow-popups');frame.setAttribute('allow','fullscreen');frame.referrerPolicy='no-referrer';
const fallback=document.createElement('div');fallback.className='slides-fallback';for(const section of sections)fallback.append(section);
// Keep a static projection available when the local runtime fails to load.
host.classList.add('slides-preview');host.replaceChildren(frame,fallback);
const listener=event=>{
if(event.source!==frame.contentWindow||event.data?.token!==token)return;
if(event.data.type==='slides-ready'){frame.dataset.ready='true';frame.dataset.count=String(sections.length);frame.hidden=false;fallback.hidden=true;clearTimeout(timer);}
if(['slides-index','slides-ready'].includes(event.data.type)&&Number.isInteger(event.data.index)&&event.data.index>=0&&event.data.index<sections.length)host.dataset.slideIndex=String(event.data.index);
};
window.addEventListener('message',listener);
const timer=setTimeout(()=>{if(frame.dataset.ready!=='true'){frame.hidden=true;fallback.hidden=false;}},8000);
views.set(host,{listener,timer});frame.srcdoc='<!doctype html>'+doc.documentElement.outerHTML;
}
window.PagesSlides={render,clear};
document.addEventListener('DOMContentLoaded',()=>{
const host=document.querySelector('[data-slides-viewer]');if(!host)return;
try{render(host,document.querySelector('[data-slides-source]').value,host.dataset.path);}catch{host.textContent=host.dataset.error;}
document.querySelector('[data-slides-fullscreen]')?.addEventListener('click',()=>{if(document.fullscreenElement)document.exitFullscreen?.();else host.requestFullscreen?.().catch(()=>{});});
});
})();
+92
View File
@@ -0,0 +1,92 @@
(() => {
'use strict';
window.PagesTaskIndex={mount({app,open,setProject}){
const ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en;
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
const $=id=>document.getElementById('tasks-'+id),api='/_/api/v1/extension/organizer.tasks/items',writable=app.dataset.writable==='true';
const list=$('list'),status=$('status'),sidebar=$('nav');
let items=[],selected='',project='',projects=[],next='',projectNext='',loading=false,mutating=false,generation=0,projectGeneration=0,controller,projectController;
let applied='~active',sortKey='due',order='asc',validResult=false;
const initial=new URLSearchParams(location.search);if(initial.has('filter'))applied=initial.get('filter');if(initial.has('project'))project=initial.get('project');
const sorts={due:t('Due date','期限'),planned:t('Planned date','取り組む日'),title:t('Subject','件名'),status:t('Status','状態'),priority:t('Priority','優先度'),created:t('Created','作成日時'),updated:t('Updated','更新日時')};
if(initial.has('sort')&&sorts[initial.get('sort')])sortKey=initial.get('sort');if(initial.get('order')==='desc')order='desc';
const states={todo:t('To do','未着手'),doing:t('Doing','着手中'),done:t('Done','完了'),cancelled:t('Cancelled','取りやめ')};
const marks={todo:'○',doing:'◐',done:'✓',cancelled:'−'};
function button(label,text,fn){const b=el('button',text);b.type='button';b.title=b.ariaLabel=label;b.onclick=fn;return b;}
async function request(url,options={}){
const r=await fetch(url,{credentials:'same-origin',signal:AbortSignal.timeout(15000),...options,headers:{'Content-Type':'application/json',...options.headers}}),data=await r.json().catch(()=>({}));
if(r.redirected||r.status===401)throw Error(t('Sign in again.','再度ログインしてください。'));
if(!r.ok)throw Error(r.status===412?t('Changed elsewhere. Refresh before retrying.','別の画面で更新されました。再読込してから操作してください。'):r.status===422?t('Invalid filter or sort. See ? for syntax.','絞り込み式またはソートが不正です。? で書式を確認してください。'):t('Request failed. Check permissions and try again.','操作に失敗しました。権限を確認して再度お試しください。'));
return data;
}
$('heading').textContent=t('Task index','タスク一覧');$('help').hidden=$('capture').hidden=true;$('search').closest('label').hidden=true;
const filterForm=el('form',undefined,'task-index-filter'),filter=el('input'),sort=el('select'),reverse=button(t('Reverse sort (O)','逆ソート (O)'),'↑',()=>{order=order==='asc'?'desc':'asc';reload();});
filter.name='filter';filter.value=applied;filter.maxLength=1000;filter.autocomplete='off';filter.ariaLabel=t('Limit tasks (l)','タスクを絞り込む (l)');filter.placeholder='~s "release" ~overdue';
const apply=el('button',t('Apply','適用'));apply.type='submit';
for(const[key,label]of Object.entries(sorts)){const o=el('option',label);o.value=key;sort.append(o);}sort.value=sortKey;sort.ariaLabel=t('Sort (o)','ソート (o)');sort.onchange=()=>{sortKey=sort.value;reload();};
filterForm.append(filter,apply,sort,reverse);$('status').before(filterForm);
filterForm.onsubmit=e=>{e.preventDefault();applied=filter.value;reload().then(()=>grid.focus());};
const actions=el('div',undefined,'task-index-actions'),help=el('dialog',undefined,'task-index-help');
help.ariaLabel=t('Task index shortcuts','タスク一覧のショートカット');
const helpTitle=el('h2',help.ariaLabel),helpClose=button(t('Close','閉じる'),'×',()=>help.close()),helpTable=el('dl');
for(const[key,label]of [['j / k / ↓ / ↑',t('Select next / previous task','次/前のタスクを選択')],['Ctrl+j / Ctrl+k',t('Next / previous project','次/前のプロジェクト')],['o / O',t('Choose sort / reverse order','ソート選択/順序反転')],['l / Esc',t('Focus filter / return to list','絞り込みへ/一覧へ戻る')],['d',t('Mark done (not delete)','完了にする(削除ではありません)')],['s',t('Start Pomodoro (25 minutes)','Pomodoro開始(25分)')],['c',t('Create in current project','現在のプロジェクトに新規作成')],['m / Enter',t('Edit selected task','選択タスクを編集')],['w',t('Open linked Wiki page','関連Wikiページを開く')],['?',t('Show this help','このヘルプを表示')]]){helpTable.append(el('dt',key),el('dd',label));}
help.append(helpClose,helpTitle,helpTable,el('h3',t('Filters (AND; ! negates)','絞り込み(AND結合、! で否定)')),el('pre','~s "release notes"\n~active / ~todo / ~doing / ~done / ~cancelled\n~overdue / ~archived / ~wiki / ~attachment\n~due <=today / ~planned tomorrow / ~start >=2026-01-01\n~review <today / ~due none\n~bucket inbox / ~bucket backlog / ~bucket someday\n~priority 3 / !~done\n\n~s "release" ~doing !~overdue'));
app.append(help);const showHelp=()=>help.showModal();help.addEventListener('close',()=>grid.focus());
const done=button(t('Done (d)','完了 (d)'),'✓',()=>act('done')),focus=button(t('Pomodoro (s)','Pomodoro (s)'),'◷',()=>act('focus')),edit=button(t('Edit (m)','編集 (m)'),'✎',()=>act('edit')),wiki=button(t('Wiki (w)','Wiki (w)'),'▣',()=>act('wiki'));
actions.append(done,focus,edit,wiki,button(t('Shortcuts (?)','ショートカット (?)'),'? ',showHelp));filterForm.after(actions);
const grid=el('table',undefined,'task-index-grid'),head=el('thead'),header=el('tr'),body=el('tbody');grid.tabIndex=0;grid.setAttribute('role','grid');grid.ariaLabel=t('Tasks','タスク');
for(const text of [t('Status','状態'),t('Subject','件名'),t('Due','期限'),t('Planned','取り組む日'),t('Priority','優先度'),'▣']){const th=el('th',text);th.scope='col';if(text==='▣')th.ariaLabel=t('Linked Wiki','関連Wiki');header.append(th);}head.append(header);grid.append(head,body);list.replaceChildren(grid);list.removeAttribute('role');
$('dialog').addEventListener('close',()=>grid.focus());
const projectTitle=el('h2',t('Projects','プロジェクト')),projectSearch=el('input'),projectList=el('div',undefined,'task-index-projects'),projectMore=button(t('More projects','続きのプロジェクト'),'…',()=>loadProjects(true));
projectSearch.type='search';projectSearch.ariaLabel=projectSearch.placeholder=t('Find project','プロジェクト検索');
sidebar.replaceChildren(projectTitle,projectSearch,projectList,projectMore);const inline=el('a',t('Inline editing ↗','インライン編集 ↗'));inline.href='/v/plan/tasks';sidebar.append(inline);
let projectTimer;projectSearch.oninput=()=>{clearTimeout(projectTimer);projectTimer=setTimeout(()=>loadProjects(),200);};
function projectChoices(){return [{uuid:'',title:t('All projects','すべて')},{uuid:'none',title:t('No project','プロジェクトなし')},...projects];}
function paintProjects(){projectList.replaceChildren();for(const p of projectChoices()){const b=button(p.title,p.title,()=>chooseProject(p.uuid));window.PagesTaskPresentation.render(b,p.title,false);b.dataset.project=p.uuid;b.setAttribute('aria-current',p.uuid===project?'true':'false');projectList.append(b);}projectMore.hidden=!projectNext;}
async function loadProjects(append=false){const ticket=++projectGeneration;projectController?.abort();projectController=new AbortController();projectMore.disabled=true;
try{const q=new URLSearchParams({kind:'project',view:'all',q:projectSearch.value,limit:'50'});if(append&&projectNext)q.set('before',projectNext);const data=await request(api+'?'+q,{signal:AbortSignal.any([projectController.signal,AbortSignal.timeout(15000)])});if(ticket!==projectGeneration)return;if(!append)projects=[];for(const p of data.items)if(!projects.some(x=>x.uuid===p.uuid))projects.push(p);projectNext=data.next;paintProjects();}
catch(e){if(e.name!=='AbortError')status.textContent=e.message;}finally{if(ticket===projectGeneration)projectMore.disabled=false;}
}
function chooseProject(id){project=id;setProject(project);selected='';paintProjects();reload();}
async function moveProject(delta){let choices=projectChoices(),index=choices.findIndex(x=>x.uuid===project);if(index<0)index=0;if(delta>0&&index===choices.length-1&&projectNext&&!projectMore.disabled){await loadProjects(true);choices=projectChoices();}const p=choices[Math.max(0,Math.min(choices.length-1,index+delta))];if(p)chooseProject(p.uuid);}
function syncURL(){const q=new URLSearchParams();if(project)q.set('project',project);if(applied!=='~active')q.set('filter',applied);if(sortKey!=='due')q.set('sort',sortKey);if(order!=='asc')q.set('order',order);history.replaceState(history.state,'',location.pathname+(q.size?'?'+q:''));}
function paint(){body.replaceChildren();for(const item of items){const row=el('tr');row.id='task-index-'+item.uuid;row.dataset.task=item.uuid;row.setAttribute('aria-selected',String(item.uuid===selected));row.onclick=()=>select(item.uuid);row.ondblclick=()=>act('edit');
const state=el('td',marks[item.status]+' '+states[item.status]),subject=el('td',undefined,'task-index-subject'),due=el('td',item.due_on||'—'),planned=el('td',item.planned_on||'—'),priority=el('td',['↓','·','!','!!'][item.priority]||'·'),note=el('td',item.page_uuid?'▣':'');
window.PagesTaskPresentation.render(subject,item.title,false);subject.title=item.title;if(item.parent_uuid)subject.prepend(el('span','↳ '));state.title=states[item.status];note.title=item.page_uuid?t('Linked Wiki page (w)','関連Wikiページ (w)'):'';
if(item.due_on&&item.due_on<app.dataset.today&&!['done','cancelled'].includes(item.status))due.className='task-index-overdue';row.append(state,subject,due,planned,priority,note);body.append(row);
}selection();}
function selection(scroll=false){for(const row of body.children)row.setAttribute('aria-selected',String(row.dataset.task===selected));if(selected){grid.setAttribute('aria-activedescendant','task-index-'+selected);if(scroll)document.getElementById('task-index-'+selected)?.scrollIntoView({block:'nearest'});}else grid.removeAttribute('aria-activedescendant');const item=items.find(x=>x.uuid===selected);done.disabled=focus.disabled=!writable||!item||loading||mutating||!validResult||item.archived;done.disabled||=item?.status==='done';focus.disabled||=['done','cancelled'].includes(item?.status);edit.disabled=wiki.disabled=!selected||loading||mutating||!validResult;}
function select(id){selected=id;selection(true);grid.focus({preventScroll:true});}
async function move(delta){if(loading)return;let i=items.findIndex(x=>x.uuid===selected);if(delta>0&&i===items.length-1&&next){const keep=i;await reload(true);if(items[keep+1])select(items[keep+1].uuid);return;}i=Math.max(0,Math.min(items.length-1,i+delta));if(items[i])select(items[i].uuid);}
async function reload(append=false){
const ticket=++generation;controller?.abort();controller=new AbortController();loading=true;validResult=false;selection();$('more').disabled=true;status.textContent=t('Loading…','読み込み中…');grid.setAttribute('aria-busy','true');const oldIndex=Math.max(0,items.findIndex(x=>x.uuid===selected));
try{const q=new URLSearchParams({kind:'task',view:'index',filter:applied,sort:sortKey,order,project,limit:'100'});if(append&&next)q.set('before',next);const data=await request(api+'?'+q,{signal:AbortSignal.any([controller.signal,AbortSignal.timeout(15000)])});if(ticket!==generation)return;
if(!append)items=[];for(const item of data.items)if(!items.some(x=>x.uuid===item.uuid))items.push(item);next=data.next;app.dataset.today=data.today;validResult=true;
if(!items.some(x=>x.uuid===selected))selected=items[Math.min(oldIndex,items.length-1)]?.uuid||'';paint();reverse.textContent=order==='asc'?'↑':'↓';sort.value=sortKey;syncURL();status.textContent=items.length?`${items.length}${next?'+':''}`:t('No matching tasks.','該当するタスクはありません。');$('more').hidden=!next;
}catch(e){if(e.name!=='AbortError'&&ticket===generation)status.textContent=e.message;}finally{if(ticket===generation){loading=false;selection();$('more').disabled=!validResult;grid.removeAttribute('aria-busy');}}
}
async function act(action){const item=items.find(x=>x.uuid===selected);if(!item||loading||mutating||!validResult)return;
if(action==='edit'){open(item.uuid);return;}
if(action==='focus'){if(writable&&!item.archived&&!['done','cancelled'].includes(item.status))app.dispatchEvent(new CustomEvent('task-focus',{detail:item}));return;}
if(action==='wiki'&&!item.page_uuid){status.textContent=t('No linked Wiki page. Use task details to link one.','関連Wikiページはありません。タスク詳細から関連付けてください。');return;}
if(action==='done'&&(!writable||item.archived||item.status==='done'))return;
mutating=true;selection();try{
if(action==='wiki'){const note=await request(api+'/'+item.uuid+'/note');if(note.linked)location.assign(note.url);else status.textContent=t('No linked Wiki page. Use task details to link or create one.','関連Wikiページはありません。タスク詳細から関連付けてください。');}
else{const fresh=await request(api+'/'+item.uuid);await request(api+'/'+item.uuid,{method:'PUT',headers:{'If-Match':'"'+item.version+'"'},body:JSON.stringify({...fresh.item,status:'done'})});app.dispatchEvent(new Event('task-today-refresh'));await reload();}
}catch(e){status.textContent=e.message;}finally{mutating=false;selection();}
}
document.addEventListener('keydown',e=>{
if(e.defaultPrevented||e.isComposing||e.keyCode===229||e.altKey||e.metaKey||document.querySelector('dialog[open]'))return;
if(e.key==='Escape'&&(filterForm.contains(e.target)||e.target===projectSearch)){e.preventDefault();filter.value=applied;grid.focus();return;}
if(e.target.closest?.('input,textarea,select,[contenteditable=true]'))return;
if(e.ctrlKey){if(e.key==='j'||e.key==='k'){e.preventDefault();moveProject(e.key==='j'?1:-1);}return;}
if(['j','k','ArrowDown','ArrowUp'].includes(e.key)){e.preventDefault();move(['j','ArrowDown'].includes(e.key)?1:-1);return;}
if(e.repeat)return;
if(e.key==='Enter'&&e.target!==grid&&e.target!==document.body)return;
const commands={o:()=>sort.focus(),O:()=>reverse.click(),l:()=>{filter.focus();filter.select();},d:()=>act('done'),s:()=>act('focus'),c:()=>{if(writable&&!mutating)open('');},m:()=>act('edit'),Enter:()=>{if(e.target===grid||e.target===document.body)act('edit');},w:()=>act('wiki'),'?':showHelp};
if(commands[e.key]){e.preventDefault();commands[e.key]();}
});
setProject(project);paintProjects();loadProjects();reload();grid.focus();
return {reload};
}};
})();
+3 -3
View File
@@ -19,7 +19,7 @@
function field(key,type,container){const label=el('label'),n=el(type==='select'?'select':'input');label.append(el('span',labels[key]));if(type!=='select')n.type=type;else ['todo','doing','done','cancelled'].forEach((v,i)=>{const o=el('option',[t('To do','未着手'),t('Doing','進行中'),t('Done','完了'),t('Cancelled','取りやめ')][i]);o.value=v;n.append(o);});n.name=key;n.value=item[key]||'';n.disabled=!writable;n.ariaLabel=labels[key];if(key==='title'){n.required=true;n.maxLength=300;label.className='task-inline-title';}inputs[key]=n;label.append(n);container.append(label);
n.addEventListener('input',()=>{draft[key]=n.value;dirtyRows.add(row);});n.addEventListener('change',()=>{draft[key]=n.value;dirtyRows.add(row);flush();});
n.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();n.blur();}if(e.key==='Escape'){e.preventDefault();n.value=item[key]||'';draft[key]=n.value;flush();}});}
field('title','text',line);field('status','select',line);['planned_on','due_on','review_on','start_on','end_on'].forEach(k=>field(k,'date',dates));
field('title','text',line);const titlePreview=el('div',undefined,'task-title-preview');titlePreview.setAttribute('aria-hidden','true');inputs.title.after(titlePreview);inputs.title.addEventListener('input',()=>window.PagesTaskPresentation?.render(titlePreview,inputs.title.value,false));field('status','select',line);['planned_on','due_on','review_on','start_on','end_on'].forEach(k=>field(k,'date',dates));
const complete=el('button','○');complete.type='button';complete.title=complete.ariaLabel=t('Toggle completion','完了を切り替え');complete.disabled=!writable;complete.dataset.action='complete';complete.addEventListener('click',()=>{draft.status=item.status==='done'?'todo':'done';inputs.status.value=draft.status;dirtyRows.add(row);flush();});line.prepend(complete);
const parent=el('a','↳');parent.title=parent.ariaLabel=t('Parent task','親タスク');parent.hidden=!item.parent_uuid;if(item.parent_uuid){row.classList.add('task-is-child');parent.href='/v/plan/task/'+encodeURIComponent(item.parent_uuid);}row.append(parent,line,dates,actions,status);
function button(label,icon,fn){const b=el('button',icon);b.type='button';b.title=b.ariaLabel=label;b.addEventListener('click',fn);actions.append(b);return b;}
@@ -60,11 +60,11 @@
}
if(edit&&!data.writable){message(t('This Wiki note is read-only.','このWikiメモは読み取り専用です。'));return;}location.assign(edit?data.edit_url:data.url);
}catch(e){message(e.message);}}
button(t('View Wiki note (create if missing)','Wikiメモを表示(未作成なら新規作成)'),'▤',()=>openNote(false)).dataset.action='note-view';
const noteView=button(t('View Wiki note (create if missing)','Wikiメモを表示(未作成なら新規作成)'),'▤',()=>openNote(false));noteView.dataset.action='note-view';
const editNote=button(t('Edit / create Wiki note','Wikiメモを編集・新規作成'),'✎',()=>openNote(true));editNote.dataset.action='note-edit';editNote.disabled=!writable;
if(options.planDate&&writable){button(t('Schedule for ','取り組む日を変更:')+options.planDate,'→',()=>{if(blocked())return;draft.planned_on=options.planDate;inputs.planned_on.value=draft.planned_on;dirtyRows.add(row);flush();}).dataset.action='schedule-day';}
const estimate=el('small',undefined,'task-inline-estimate');actions.prepend(estimate);
function paint(){row.dataset.done=String(['done','cancelled'].includes(item.status));complete.textContent=item.status==='done'?'✓':'○';row.dataset.archived=String(item.archived);estimate.textContent=item.estimate_minutes?item.estimate_minutes+' min':'';}
function paint(){window.PagesTaskPresentation?.render(titlePreview,item.title,false);noteView.classList.toggle('has-wiki-note',!!item.page_uuid);noteView.textContent=item.page_uuid?'▣':'▤';noteView.title=noteView.ariaLabel=item.page_uuid?t('Open linked Wiki page','関連Wikiページを開く'):t('Create Wiki note','Wikiメモを作成');row.dataset.done=String(['done','cancelled'].includes(item.status));complete.textContent=item.status==='done'?'✓':'○';row.dataset.archived=String(item.archived);estimate.textContent=item.estimate_minutes?item.estimate_minutes+' min':'';}
async function flush(){if(saving||!writable||!Object.keys(draft).length)return;if(!inputs.title.reportValidity())return;saving=true;row.setAttribute('aria-busy','true');message(t('Saving…','保存中…'),'saving');try{while(Object.keys(draft).length){const patch={...draft};const fresh=await request(api+'/'+item.uuid);const saved=await request(api+'/'+item.uuid,{method:'PUT',headers:{'If-Match':'"'+item.version+'"'},body:JSON.stringify({...fresh.item,...patch})});item=saved.item;for(const [k,v]of Object.entries(patch)){if(draft[k]===v)delete draft[k];}paint();}dirtyRows.delete(row);message(t('Saved','保存しました'),'saved');document.getElementById('tasks-app')?.dispatchEvent(new Event('task-today-refresh'));options.onChanged?.(item,row);}catch(e){message(e.message);}finally{saving=false;row.removeAttribute('aria-busy');}}
const restoreExpanded=expandedRows.has(item.uuid);
if(options.initialChildren?.length){options.initialChildren.forEach(c=>children.append(create(c,{...options,initialChildren:[],context:false,nested:true})));showChildren(true);}
+29
View File
@@ -0,0 +1,29 @@
(() => {
'use strict';
// Small inline-only dialect: no HTML, images, macros or remote rendering.
function render(node, source, links = true, depth = 0) {
node.replaceChildren();
if (depth > 8) { node.textContent=source; return; }
const pattern=/\\([\\`*_\[\]~])|(`+)([^`]+)\2|\*\*(.+?)\*\*|__(.+?)__|~~(.+?)~~|\*([^*]+)\*|_([^_]+)_|\[([^\]]+)\]\(([^\s)]+)\)/g;
let offset=0;
for(const m of source.matchAll(pattern)) {
node.append(document.createTextNode(source.slice(offset,m.index)));
if(m[1]){node.append(document.createTextNode(m[1]));offset=m.index+m[0].length;continue;}
let tag,text;
if(m[2]) {tag='code';text=m[3];} else if(m[4]||m[5]) {tag='strong';text=m[4]||m[5];}
else if(m[6]) {tag='del';text=m[6];} else if(m[7]||m[8]) {tag='em';text=m[7]||m[8];}
else {tag='span';text=m[9];if(links&&safeReference(m[10]))tag='a';}
const child=document.createElement(tag);
if(tag==='a') {child.href=m[10];child.rel='noopener noreferrer';}
if(tag==='code')child.textContent=text;else render(child,text,false,depth+1);
node.append(child);offset=m.index+m[0].length;
}
node.append(document.createTextNode(source.slice(offset)));
}
function safeReference(ref) {
if(!ref||/[\\\s\x00-\x1f]/.test(ref))return false;
if(ref.startsWith('/')&&!ref.startsWith('//'))return true;
try {const u=new URL(ref);return ['http:','https:'].includes(u.protocol)&&!u.username&&!u.password;}catch{return false;}
}
window.PagesTaskPresentation={render,safeReference};
})();
+10 -5
View File
@@ -3,6 +3,7 @@
const app = document.getElementById('tasks-app'); if (!app) return;
const ja = document.documentElement.lang.startsWith('ja');
const words = {
index:['Keyboard task index','キーボード一覧'],
delete:['Delete','削除'],deleted:['This task has been deleted.','このタスクは削除されています。'],has_children:['Move or delete the subtasks first, including archived subtasks.','先にサブタスクを移動または削除してください(アーカイブ済みも含みます)。'],working:['Stop the running work timer or focus session before deleting this task.','作業時間の記録・集中セッションを停止してから削除してください。'],deleteConfirm:['Delete this task? This cannot be undone. Wiki notes, calendar events and recorded work time will remain. Unsaved changes will be discarded.','このタスクを削除しますか?復元できません。Wikiメモ、カレンダーの予定、記録済みの作業時間は残ります。未保存の変更は破棄されます。'],
carryover:['Carryover','持ち越し'],tomorrow:['Tomorrow','明日'],day:['Daily plan','日別の計画'],notes_subpath:['Wiki note subfolder (relative to the project Wiki page)','Wikiメモのサブ階層(プロジェクトの関連Wiki配下)'],
start_on:['Work starts','工程開始'],end_on:['Work ends','工程終了'],schedule:['Day schedule','日割り工程表'],
@@ -17,6 +18,7 @@
const view = app.dataset.view, projectID = view === 'project' ? app.dataset.id : '';
const writable = app.dataset.writable === 'true';
let today = app.dataset.today;
let indexBrowser, indexProject=null;
let selectedDate=app.dataset.selectedDate||today;
const loadedItems=new Map(),contextParents=new Map();
const nextDay=date=>{const d=new Date(date+'T12:00:00Z');d.setUTCDate(d.getUTCDate()+1);return d.toISOString().slice(0,10);};
@@ -32,7 +34,7 @@
}
const href = item => '/v/plan/' + item.kind + '/' + encodeURIComponent(item.uuid);
const routes = {today:'/v/plan/today',all:'/v/plan/tasks',projects:'/v/plan/projects'};
const icons = {carryover:'↶',today:'☀',tomorrow:'⇢',inbox:'↓',backlog:'≡',someday:'◇',review:'↻',all:'☷',projects:'▱',done:'✓',archived:'▣'};
const icons = {index:'⌨',carryover:'↶',today:'☀',tomorrow:'⇢',inbox:'↓',backlog:'≡',someday:'◇',review:'↻',all:'☷',projects:'▱',done:'✓',archived:'▣'};
Object.keys(icons).forEach(key => { const a = el('a'); a.href = routes[key] || '/v/plan/tasks/' + key; a.append(el('span',icons[key]),el('span',t(key))); if(view===key||(key==='tomorrow'&&view==='day'&&selectedDate===nextDay(today)))a.setAttribute('aria-current','page'); $('nav').append(a); });
const schedule=el('a','▦ '+t('schedule'));schedule.href='/v/plan/tasks/schedule'+(projectID?'?project='+projectID:'');$('nav').append(schedule);const workHistory=el('a',ja?'◷ 作業記録':'◷ Work history');workHistory.href='/v/plan/tasks/work';$('nav').append(workHistory);
$('date').textContent = view==='day'?selectedDate:today; $('heading').textContent = t(view === 'project' ? 'project' : view === 'detail' || view === 'new' ? 'all' : view);
@@ -56,9 +58,10 @@
if(!writable)$('help').textContent+=' '+t('readonly');
let taskDefaults={},reminderDefaults={};
async function refreshDefaults(){const data=await request('/_/api/v1/extension/organizer.tasks/preferences');taskDefaults=data.defaults;reminderDefaults=data.preferences;}
function blank(kind='task') { const defaults=kind==='task'?taskDefaults:{};const item={ ...defaults,uuid:crypto.randomUUID(),kind,title:'',notes:'',status:'todo',bucket:['inbox','backlog','someday'].includes(view)?view:'inbox',priority:1,estimate_minutes:defaults.estimate_minutes||0,project_uuid:kind==='task'?(projectID||defaults.project_uuid||''):'',page_uuid:'',due_on:defaults.due_on||'',planned_on:['today','day'].includes(view)&&kind==='task'?(view==='day'?selectedDate:today):(defaults.planned_on||''),review_on:defaults.review_on||'',archived:false,version:0 };if(kind==='task'){item.notify_due=!!(reminderDefaults.notify_due&&item.due_on);item.notify_planned=!!(reminderDefaults.notify_planned&&item.planned_on);}return item; }
function blank(kind='task') { const defaults=kind==='task'?taskDefaults:{};const item={ ...defaults,uuid:crypto.randomUUID(),kind,title:'',notes:'',status:'todo',bucket:['inbox','backlog','someday'].includes(view)?view:'inbox',priority:1,estimate_minutes:defaults.estimate_minutes||0,project_uuid:kind==='task'?(view==='index'&&indexProject!==null?indexProject:(projectID||defaults.project_uuid||'')):'',page_uuid:'',due_on:defaults.due_on||'',planned_on:['today','day'].includes(view)&&kind==='task'?(view==='day'?selectedDate:today):(defaults.planned_on||''),review_on:defaults.review_on||'',archived:false,version:0 };if(kind==='task'){item.notify_due=!!(reminderDefaults.notify_due&&item.due_on);item.notify_planned=!!(reminderDefaults.notify_planned&&item.planned_on);}return item; }
function listView(){return ['project','detail','new'].includes(view)?'all':view;}
async function load(append=false) {
if(indexBrowser)return indexBrowser.reload(append);
if(window.PagesWikiTaskRows?.hasDirty()){$('status').textContent=ja?'編集中の行を保存または再読込してください。':'Save or reload edited rows first.';return;}
const ticket=++generation; listController?.abort();listController=new AbortController();$('status').textContent=t('loading');$('more').disabled=true;
const q=new URLSearchParams({kind:view==='projects'?'project':view==='archived'?$('kind').value:'task',view:listView(),q:$('search').value,project:projectID,hierarchy:'1'});if(view==='day')q.set('date',selectedDate);if(append&&next)q.set('before',next);
@@ -86,7 +89,7 @@
if(item.kind==='task'&&window.PagesWikiTaskRows){$('list').append(window.PagesWikiTaskRows.create(item,rowOptions()));return;}
const row=el('div',undefined,'task-row');row.role='listitem';row.dataset.done=String(item.status==='done'||item.status==='cancelled');
if(item.kind==='task'&&writable){const b=el('button',item.status==='done'?'✓':'○');b.type='button';b.title=b.ariaLabel=t(item.status==='done'?'reopen':'complete');b.addEventListener('click',async()=>{b.disabled=true;try{const {item:fresh}=await request(api+'/'+item.uuid);fresh.status=fresh.status==='done'?'todo':'done';await saveItem(fresh);await load();}catch(e){$('status').textContent=e.message;}finally{b.disabled=false;}});row.append(b);}
const main=el('div',undefined,'task-row-main'), a=el('a',item.title);a.href=href(item);if(item.kind==='task')a.addEventListener('click',e=>{if(e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;e.preventDefault();open(item.uuid);});main.append(a);
const main=el('div',undefined,'task-row-main'), a=el('a',item.title);window.PagesTaskPresentation?.render(a,item.title,false);a.href=href(item);if(item.kind==='task')a.addEventListener('click',e=>{if(e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;e.preventDefault();open(item.uuid);});main.append(a);
const meta=el('div',undefined,'task-row-meta');meta.append(el('span',t(item.status)));if(item.kind==='task'){if(item.due_on)meta.append(el('span',t('due_on')+' '+item.due_on,item.due_on<today?'task-overdue':''));if(item.planned_on)meta.append(el('span',t('planned_on')+' '+item.planned_on));if(item.priority>=2)meta.append(el('span',t(item.priority===3?'urgent':'high')));if(item.estimate_minutes)meta.append(el('span',item.estimate_minutes+' min'));}main.append(meta);row.append(main);$('list').append(row);
}
const fields={};
@@ -147,6 +150,8 @@
if(!id)for(const [date,key] of [['due_on','notify_due'],['planned_on','notify_planned']]){let touched=false;fields[key].addEventListener('change',()=>{touched=true;});fields[date].addEventListener('input',()=>{if(!touched){fields[key].checked=!!(fields[date].value&&reminderDefaults[key]);requirements();}});}
}
if(editing.kind==='project'){const folder=field('notes_subpath',t('notes_subpath'),'text',editing.notes_subpath||'tasks',true);folder.maxLength=500;folder.placeholder='tasks';$('fields').append(el('small',ja?'例:関連Wikiが /projects/app、サブ階層が tasks → /projects/app/tasks/件名。Wikiの公開範囲に従います。':'Example: project Wiki /projects/app + subfolder tasks → /projects/app/tasks/title. Wiki permissions apply.','task-full'));}
const refs=field('references',ja?'URL / 添付Path(1行に1件)':'URLs / attachment Paths (one per line)','textarea',(editing.references||[]).join('\n'),true);refs.maxLength=81920;
const referenceLinks=el('div',undefined,'task-full');for(const ref of editing.references||[]){if(!window.PagesTaskPresentation.safeReference(ref))continue;const a=el('a',ref);a.href=ref;a.target='_blank';a.rel='noopener noreferrer';referenceLinks.append(a,el('br'));}$('fields').append(referenceLinks);
field('page_path',t('page'),'text',data.page_path,true).placeholder='/lab/project';
const updatePageLink=()=>{const a=$('page-open');a.hidden=!data.page_path||!editing.page_uuid||fields.page_path.value!==data.page_path;a.removeAttribute('href');if(!a.hidden)a.href='/'+data.page_path.replace(/^\/+/, '').split('/').map(encodeURIComponent).join('/');};
$('page-open').textContent=t('linked')+' ↗';$('page-open').title=ja?'関連ページを新しいタブで開く':'Open related page in a new tab';updatePageLink();
@@ -168,7 +173,7 @@
$('close').addEventListener('click',()=>closeDialog());$('dialog').addEventListener('cancel',e=>{e.preventDefault();closeDialog();});
$('form').addEventListener('input',()=>{dirty=true;});
$('form').addEventListener('invalid',event=>{const details=event.target.closest('details');if(details)details.open=true;},true);
function readForm(){const item={...editing};['title','notes','notes_subpath','status','bucket','project_uuid','assignee_uuid','due_on','planned_on','review_on','start_on','end_on','reminder_time'].forEach(k=>{if(fields[k])item[k]=fields[k].value;});['notify_due','notify_planned'].forEach(k=>{if(fields[k])item[k]=fields[k].checked;});['priority','estimate_minutes','complexity'].forEach(k=>{if(fields[k])item[k]=Number(fields[k].value);});if(fields.page_path?.dataset.changed||(!item.page_uuid&&fields.page_path?.value))item.page_path=fields.page_path.value;return item;}
function readForm(){const item={...editing};if(fields.references)item.references=fields.references.value.split('\n').map(x=>x.trim()).filter(Boolean);['title','notes','notes_subpath','status','bucket','project_uuid','assignee_uuid','due_on','planned_on','review_on','start_on','end_on','reminder_time'].forEach(k=>{if(fields[k])item[k]=fields[k].value;});['notify_due','notify_planned'].forEach(k=>{if(fields[k])item[k]=fields[k].checked;});['priority','estimate_minutes','complexity'].forEach(k=>{if(fields[k])item[k]=Number(fields[k].value);});if(fields.page_path?.dataset.changed||(!item.page_uuid&&fields.page_path?.value))item.page_path=fields.page_path.value;return item;}
async function saveItem(item){const data=await request(api+(item.version?'/'+item.uuid:''),{method:item.version?'PUT':'POST',headers:item.version?{'If-Match':'"'+item.version+'"'}:{},body:JSON.stringify(item)});app.dispatchEvent(new Event('task-today-refresh'));return data;}
async function submit(archive=false){if(!editing||saving||!writable)return;if(!$('form').reportValidity())return;const item=readForm();if(archive)item.archived=!item.archived;saving=true;Object.values(fields).forEach(f=>f.disabled=true);$('save').disabled=$('archive').disabled=$('delete').disabled=true;$('error').textContent='';try{await saveItem(item);saving=false;closeDialog(true);await load();if(projectID)await loadProject();}catch(e){$('error').textContent=e.message;}finally{saving=false;Object.values(fields).forEach(f=>f.disabled=!writable);$('save').disabled=$('archive').disabled=$('delete').disabled=false;}}
$('delete').addEventListener('click',async()=>{
@@ -194,5 +199,5 @@
$('project-edit').addEventListener('click',()=>open(projectID));
window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue='';}});
document.addEventListener('visibilitychange',()=>{if(!document.hidden&&!$('dialog').open&&!capturing)load();});
load();if(projectID)loadProject();if(view==='detail')open(app.dataset.id);if(view==='new')open('');
if(view==='index')indexBrowser=window.PagesTaskIndex.mount({app,open,setProject:id=>{indexProject=id==='none'?'':id||null;}});else load();if(projectID)loadProject();if(view==='detail')open(app.dataset.id);if(view==='new')open('');
})();
+3
View File
@@ -38953,6 +38953,9 @@
}
})
];
if (options.preserveLineEndings) {
extensions.push(EditorState.lineSeparator.of("\n"));
}
if (keymapName === "vim") {
installVimCommands();
extensions.push(vim());
+2 -2
View File
@@ -1,7 +1,7 @@
{
"version": 3,
"sources": ["../../../assets/editor/node_modules/@marijn/find-cluster-break/src/index.js", "../../../assets/editor/node_modules/@codemirror/state/dist/index.js", "../../../assets/editor/node_modules/style-mod/src/style-mod.js", "../../../assets/editor/node_modules/w3c-keyname/index.js", "../../../assets/editor/node_modules/@codemirror/view/dist/index.js", "../../../assets/editor/node_modules/@lezer/common/dist/index.js", "../../../assets/editor/node_modules/@lezer/highlight/dist/index.js", "../../../assets/editor/node_modules/@codemirror/language/dist/index.js", "../../../assets/editor/node_modules/@codemirror/commands/dist/index.js", "../../../assets/editor/node_modules/@codemirror/autocomplete/dist/index.js", "../../../assets/editor/node_modules/@lezer/lr/dist/index.js", "../../../assets/editor/node_modules/@lezer/html/dist/index.js", "../../../assets/editor/node_modules/@lezer/css/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-css/dist/index.js", "../../../assets/editor/node_modules/@lezer/javascript/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-javascript/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-html/dist/index.js", "../../../assets/editor/node_modules/@lezer/markdown/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-markdown/dist/index.js", "../../../assets/editor/node_modules/@lezer/python/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-python/dist/index.js", "../../../assets/editor/node_modules/@lezer/json/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-json/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-sql/dist/index.js", "../../../assets/editor/node_modules/@lezer/yaml/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-yaml/dist/index.js", "../../../assets/editor/node_modules/@lezer/go/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-go/dist/index.js", "../../../assets/editor/node_modules/@lezer/rust/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-rust/dist/index.js", "../../../assets/editor/node_modules/@lezer/java/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-java/dist/index.js", "../../../assets/editor/node_modules/@lezer/cpp/dist/index.js", "../../../assets/editor/node_modules/@codemirror/lang-cpp/dist/index.js", "../../../assets/editor/node_modules/@codemirror/legacy-modes/mode/shell.js", "../../../assets/editor/node_modules/@codemirror/legacy-modes/mode/toml.js", "../../../assets/editor/node_modules/@codemirror/search/dist/index.js", "../../../assets/editor/node_modules/@replit/codemirror-vim/dist/index.js", "../../../assets/editor/src/editor.js"],
"sourcesContent": ["// These are filled with ranges (rangeFrom[i] up to but not including\n// rangeTo[i]) of code points that count as extending characters.\nlet rangeFrom = [], rangeTo = []\n\n;(() => {\n // Compressed representation of the Grapheme_Cluster_Break=Extend\n // information from\n // http://www.unicode.org/Public/16.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.\n // Each pair of elements represents a range, as an offet from the\n // previous range and a length. Numbers are in base-36, with the empty\n // string being a shorthand for 1.\n let numbers = \"lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o\".split(\",\").map(s => s ? parseInt(s, 36) : 1)\n for (let i = 0, n = 0; i < numbers.length; i++)\n (i % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i])\n})()\n\nexport function isExtendingChar(code) {\n if (code < 768) return false\n for (let from = 0, to = rangeFrom.length;;) {\n let mid = (from + to) >> 1\n if (code < rangeFrom[mid]) to = mid\n else if (code >= rangeTo[mid]) from = mid + 1\n else return true\n if (from == to) return false\n }\n}\n\nfunction isRegionalIndicator(code) {\n return code >= 0x1F1E6 && code <= 0x1F1FF\n}\n\nfunction check(code) {\n for (let i = 0; i < rangeFrom.length; i++) {\n if (rangeTo[i] > code) return rangeFrom[i] <= code\n }\n return false\n}\n\nconst ZWJ = 0x200d\n\nexport function findClusterBreak(str, pos, forward = true, includeExtending = true) {\n return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending)\n}\n\nfunction nextClusterBreak(str, pos, includeExtending) {\n if (pos == str.length) return pos\n // If pos is in the middle of a surrogate pair, move to its start\n if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) pos--\n let prev = codePointAt(str, pos)\n pos += codePointSize(prev)\n while (pos < str.length) {\n let next = codePointAt(str, pos)\n if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {\n pos += codePointSize(next)\n prev = next\n } else if (isRegionalIndicator(next)) {\n let countBefore = 0, i = pos - 2\n while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { countBefore++; i -= 2 }\n if (countBefore % 2 == 0) break\n else pos += 2\n } else {\n break\n }\n }\n return pos\n}\n\nfunction prevClusterBreak(str, pos, includeExtending) {\n while (pos > 0) {\n let found = nextClusterBreak(str, pos - 2, includeExtending)\n if (found < pos) return found\n pos--\n }\n return 0\n}\n\nfunction codePointAt(str, pos) {\n let code0 = str.charCodeAt(pos)\n if (!surrogateHigh(code0) || pos + 1 == str.length) return code0\n let code1 = str.charCodeAt(pos + 1)\n if (!surrogateLow(code1)) return code0\n return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000\n}\n\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000 }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00 }\nfunction codePointSize(code) { return code < 0x10000 ? 1 : 2 }\n", "import { findClusterBreak as findClusterBreak$1 } from '@marijn/find-cluster-break';\n\n/**\nThe data structure for documents. @nonabstract\n*/\nclass Text {\n /**\n Get the line description around the given position.\n */\n lineAt(pos) {\n if (pos < 0 || pos > this.length)\n throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);\n return this.lineInner(pos, false, 1, 0);\n }\n /**\n Get the description for the given (1-based) line number.\n */\n line(n) {\n if (n < 1 || n > this.lines)\n throw new RangeError(`Invalid line number ${n}Line truncated
"mappings": ";;AAEA,MAAI,YAAY,CAAC;AAAjB,MAAoB,UAAU,CAAC;AAE9B,GAAC,MAAM;AAON,QAAI,UAAU,izCAAizC,MAAM,GAAG,EAAE,IAAI,OAAK,IAAI,SAAS,GAAG,EAAE,IAAI,CAAC;AAC12C,aAAS,IAAI,GAAG,IAAI,GAAG,IAAI,QAAQ,QAAQ;AACzC,OAAC,IAAI,IAAI,UAAU,WAAW,KAAK,IAAI,IAAI,QAAQ,CAAC,CAAC;AAAA,EACzD,GAAG;AAEI,WAAS,gBAAgB,MAAM;AACpC,QAAI,OAAO,IAAK,QAAO;AACvB,aAAS,OAAO,GAAG,KAAK,UAAU,YAAU;AAC1C,UAAI,MAAO,OAAO,MAAO;AACzB,UAAI,OAAO,UAAU,GAAG,EAAG,MAAK;AAAA,eACvB,QAAQ,QAAQ,GAAG,EAAG,QAAO,MAAM;AAAA,UACvC,QAAO;AACZ,UAAI,QAAQ,GAAI,QAAO;AAAA,IACzB;AAAA,EACF;AAEA,WAAS,oBAAoB,MAAM;AACjC,WAAO,QAAQ,UAAW,QAAQ;AAAA,EACpC;AASA,MAAM,MAAM;AAEL,WAAS,iBAAiB,KAAK,KAAK,UAAU,MAAM,mBAAmB,MAAM;AAClF,YAAQ,UAAU,mBAAmB,kBAAkB,KAAK,KAAK,gBAAgB;AAAA,EACnF;AAEA,WAAS,iBAAiB,KAAK,KAAK,kBAAkB;AACpD,QAAI,OAAO,IAAI,OAAQ,QAAO;AAE9B,QAAI,OAAO,aAAa,IAAI,WAAW,GAAG,CAAC,KAAK,cAAc,IAAI,WAAW,MAAM,CAAC,CAAC,EAAG;AACxF,QAAI,OAAO,YAAY,KAAK,GAAG;AAC/B,WAAO,cAAc,IAAI;AACzB,WAAO,MAAM,IAAI,QAAQ;AACvB,UAAI,OAAO,YAAY,KAAK,GAAG;AAC/B,UAAI,QAAQ,OAAO,QAAQ,OAAO,oBAAoB,gBAAgB,IAAI,GAAG;AAC3E,eAAO,cAAc,IAAI;AACzB,eAAO;AAAA,MACT,WAAW,oBAAoB,IAAI,GAAG;AACpC,YAAI,cAAc,GAAG,IAAI,MAAM;AAC/B,eAAO,KAAK,KAAK,oBAAoB,YAAY,KAAK,CAAC,CAAC,GAAG;AAAE;AAAe,eAAK;AAAA,QAAE;AACnF,YAAI,cAAc,KAAK,EAAG;AAAA,YACrB,QAAO;AAAA,MACd,OAAO;AACL;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,WAAS,iBAAiB,KAAK,KAAK,kBAAkB;AACpD,WAAO,MAAM,GAAG;AACd,UAAI,QAAQ,iBAAiB,KAAK,MAAM,GAAG,gBAAgB;AAC3D,UAAI,QAAQ,IAAK,QAAO;AACxB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,WAAS,YAAY,KAAK,KAAK;AAC7B,QAAI,QAAQ,IAAI,WAAW,GAAG;AAC9B,QAAI,CAAC,cAAc,KAAK,KAAK,MAAM,KAAK,IAAI,OAAQ,QAAO;AAC3D,QAAI,QAAQ,IAAI,WAAW,MAAM,CAAC;AAClC,QAAI,CAAC,aAAa,KAAK,EAAG,QAAO;AACjC,YAAS,QAAQ,SAAW,OAAO,QAAQ,SAAU;AAAA,EACvD;AAEA,WAAS,aAAa,IAAI;AAAE,WAAO,MAAM,SAAU,KAAK;AAAA,EAAO;AAC/D,WAAS,cAAc,IAAI;AAAE,WAAO,MAAM,SAAU,KAAK;AAAA,EAAO;AAChE,WAAS,cAAc,MAAM;AAAE,WAAO,OAAO,QAAU,IAAI;AAAA,EAAE;;;ACjF7D,MAAMA,QAAN,MAAM,MAAK;AAAA;AAAA;AAAA;AAAA,IAIP,OAAO,KAAK;AACR,UAAI,MAAM,KAAK,MAAM,KAAK;AACtB,cAAM,IAAI,WAAW,oBAAoB,GAAG,0BAA0B,KAAK,MAAM,EAAE;AACvF,aAAO,KAAK,UAAU,KAAK,OAAO,GAAG,CAAC;AAAA,IAC1C;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,GAAG;AACJ,UAAI,IAAI,KAAK,IAAI,KAAK;AAClB,cAAM,IAAI,WAAW,uBAAuB,CAAC,OAAO,KAAK,KAAK,gBAAgB;AAClF,aAAO,KAAK,UAAU,GAAG,MAAM,GAAG,CAAC;AAAA,IACvC;AAAA;AAAA;AAAA;AAAA,IAIA,QAAQ,MAAM,IAAI,MAAM;AACpB,OAAC,MAAM,EAAE,IAAI,KAAK,MAAM,MAAM,EAAE;AAChC,UAAI,QAAQ,CAAC;AACb,WAAK;AAAA,QAAU;AAAA,QAAG;AAAA,QAAM;AAAA,QAAO;AAAA;AAAA,MAAe;AAC9C,UAAI,KAAK;AACL,aAAK;AAAA,UAAU;AAAA,UAAG,KAAK;AAAA,UAAQ;AAAA,UAAO,IAAoB;AAAA;AAAA,QAAe;AAC7E,WAAK;AAAA,QAAU;AAAA,QAAI,KAAK;AAAA,QAAQ;AAAA,QAAO;AAAA;AAAA,MAAiB;AACxD,aAAO,SAAS,KAAK,OAAO,KAAK,UAAU,KAAK,QAAQ,KAAK,MAAM;AAAA,IACvE;AAAA;AAAA;AAAA;AAAA,IAIA,OAAO,OAAO;AACV,aAAO,KAAK,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK;AAAA,IACvD;AAAA;AAAA;AAAA;AAAA,IAIA,MAAM,MAAM,KAAK,KAAK,QAAQ;AAC1B,OAAC,MAAM,EAAE,IAAI,KAAK,MAAM,MAAM,EAAE;AAChC,UAAI,QAAQ,CAAC;AACb,WAAK,UAAU,MAAM,IAAI,OAAO,CAAC;AACjC,aAAO,SAAS,KAAK,OAAO,KAAK,IAAI;AAAA,IACzC;AAAA;AAAA;AAAA;AAAA,IAIA,GAAG,OAAO;AACN,UAAI,SAAS;AACT,eAAO;AACX,UAAI,MAAM,UAAU,KAAK,UAAU,MAAM,SAAS,KAAK;AACnD,eAAO;AACX,UAAI,QAAQ,KAAK,cAAc,OAAO,CAAC,GAAG,MAAM,KAAK,SAAS,KAAK,cAAc,OAAO,EAAE;AAC1F,UAAIC,KAAI,IAAI,cAAc,IAAI,GAAG,IAAI,IAAI,cAAc,KAAK;AAC5D,eAAS,OAAO,OAAO,MAAM,WAAS;AAClC,QAAAA,GAAE,KAAK,IAAI;AACX,UAAE,KAAK,IAAI;AACX,eAAO;AACP,YAAIA,GAAE,aAAa,EAAE,aAAaA,GAAE,QAAQ,EAAE,QAAQA,GAAE,SAAS,EAAE;AAC/D,iBAAO;AACX,eAAOA,GAAE,MAAM;AACf,YAAIA,GAAE,QAAQ,OAAO;AACjB,iBAAO;AAAA,MACf;AAAA,IACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,KAAK,MAAM,GAAG;AAAE,aAAO,IAAI,cAAc,MAAM,GAAG;AAAA,IAAG;AAAA;AAAA;AAAA;AAAA;AAAA,IAKrD,UAAU,MAAM,KAAK,KAAK,QAAQ;AAAE,aAAO,IAAI,kBAAkB,MAAM,MAAM,EAAE;AAAA,IAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQlF,UAAU,MAAM,IAAI;AAChB,UAAI;AACJ,UAAI,QAAQ,MAAM;AACd,gBAAQ,KAAK,KAAK;AAAA,MACtB,OACK;AACD,YAAI,MAAM;AACN,eAAK,KAAK,QAAQ;AACtB,YAAI,QAAQ,KAAK,KAAK,IAAI,EAAE;AAC5B,gBAAQ,KAAK,UAAU,OAAO,KAAK,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,SAAS,MAAM,IAAI,IAAI,KAAK,KAAK,KAAK,CAAC,EAAE,EAAE,CAAC;AAAA,MAC1H;AACA,aAAO,IAAI,WAAW,KAAK;AAAA,IAC/B;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,WAAW;AAAE,aAAO,KAAK,YAAY,CAAC;AAAA,IAAG;AAAA;AAAA;AAAA;AAAA;AAAA,IAKzC,SAAS;AACL,UAAI,QAAQ,CAAC;AACb,WAAK,QAAQ,KAAK;AAClB,aAAO;AAAA,IACX;AAAA;AAAA;AAAA;AAAA,IAIA,cAAc;AAAA,IAAE;AAAA;AAAA;AAAA;AAAA,IAIhB,OAAO,GAAG,MAAM;AACZ,UAAI,KAAK,UAAU;AACf,cAAM,IAAI,WAAW,wCAAwC;AACjE,UAAI,KAAK,UAAU,KAAK,CAAC,KAAK,CAAC;AAC3B,eAAO,MAAK;AAChB,aAAO,KAAK,UAAU,KAAuB,IAAI,SAAS,IAAI,IAAI,SAAS,KAAK,SAAS,MAAM,MAAM,CAAC,CAAC,CAAC;AAAA,IAC5G;AAAA,EACJ;AAIA,MAAM,WAAN,MAAM,kBAAiBD,MAAK;AAAA,IACxB,YAAY,MAAM,SAAS,WAAW,IAAI,GAAG;AACzC,YAAM;AACN,WAAK,OAAO;AACZ,WAAK,SAAS;AAAA,IAClB;AAAA,IACA,IAAI,QAAQ;AAAE,aAAO,KAAK,KAAK;AAAA,IAAQ;AAAA,IACvC,IAAI,WAAW;AAAE,aAAO;AAAA,IAAM;AAAA,IAC9B,UAAU,QAAQ,QAAQ,MAAM,QAAQ;AACpC,eAAS,IAAI,KAAI,KAAK;AAClB,YAAIE,UAAS,KAAK,KAAK,CAAC,GAAG,MAAM,SAASA,QAAO;AACjD,aAAK,SAAS,OAAO,QAAQ;AACzB,iBAAO,IAAI,KAAK,QAAQ,KAAK,MAAMA,OAAM;AAC7C,iBAAS,MAAM;AACf;AAAA,MACJ;AAAA,IACJ;AAAA,IACA,UAAU,MAAM,IAAI,QAAQ,MAAM;AAC9B,UAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,SAAS,OACtC,IAAI,UAAS,UAAU,KAAK,MAAM,MAAM,EAALine truncated
"sourcesContent": ["// These are filled with ranges (rangeFrom[i] up to but not including\n// rangeTo[i]) of code points that count as extending characters.\nlet rangeFrom = [], rangeTo = []\n\n;(() => {\n // Compressed representation of the Grapheme_Cluster_Break=Extend\n // information from\n // http://www.unicode.org/Public/16.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.\n // Each pair of elements represents a range, as an offet from the\n // previous range and a length. Numbers are in base-36, with the empty\n // string being a shorthand for 1.\n let numbers = \"lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o\".split(\",\").map(s => s ? parseInt(s, 36) : 1)\n for (let i = 0, n = 0; i < numbers.length; i++)\n (i % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i])\n})()\n\nexport function isExtendingChar(code) {\n if (code < 768) return false\n for (let from = 0, to = rangeFrom.length;;) {\n let mid = (from + to) >> 1\n if (code < rangeFrom[mid]) to = mid\n else if (code >= rangeTo[mid]) from = mid + 1\n else return true\n if (from == to) return false\n }\n}\n\nfunction isRegionalIndicator(code) {\n return code >= 0x1F1E6 && code <= 0x1F1FF\n}\n\nfunction check(code) {\n for (let i = 0; i < rangeFrom.length; i++) {\n if (rangeTo[i] > code) return rangeFrom[i] <= code\n }\n return false\n}\n\nconst ZWJ = 0x200d\n\nexport function findClusterBreak(str, pos, forward = true, includeExtending = true) {\n return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending)\n}\n\nfunction nextClusterBreak(str, pos, includeExtending) {\n if (pos == str.length) return pos\n // If pos is in the middle of a surrogate pair, move to its start\n if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) pos--\n let prev = codePointAt(str, pos)\n pos += codePointSize(prev)\n while (pos < str.length) {\n let next = codePointAt(str, pos)\n if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {\n pos += codePointSize(next)\n prev = next\n } else if (isRegionalIndicator(next)) {\n let countBefore = 0, i = pos - 2\n while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { countBefore++; i -= 2 }\n if (countBefore % 2 == 0) break\n else pos += 2\n } else {\n break\n }\n }\n return pos\n}\n\nfunction prevClusterBreak(str, pos, includeExtending) {\n while (pos > 0) {\n let found = nextClusterBreak(str, pos - 2, includeExtending)\n if (found < pos) return found\n pos--\n }\n return 0\n}\n\nfunction codePointAt(str, pos) {\n let code0 = str.charCodeAt(pos)\n if (!surrogateHigh(code0) || pos + 1 == str.length) return code0\n let code1 = str.charCodeAt(pos + 1)\n if (!surrogateLow(code1)) return code0\n return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000\n}\n\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000 }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00 }\nfunction codePointSize(code) { return code < 0x10000 ? 1 : 2 }\n", "import { findClusterBreak as findClusterBreak$1 } from '@marijn/find-cluster-break';\n\n/**\nThe data structure for documents. @nonabstract\n*/\nclass Text {\n /**\n Get the line description around the given position.\n */\n lineAt(pos) {\n if (pos < 0 || pos > this.length)\n throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);\n return this.lineInner(pos, false, 1, 0);\n }\n /**\n Get the description for the given (1-based) line number.\n */\n line(n) {\n if (n < 1 || n > this.lines)\n throw new RangeError(`Invalid line number ${n}Line truncated
"mappings": ";;AAEA,MAAI,YAAY,CAAC;AAAjB,MAAoB,UAAU,CAAC;AAE9B,GAAC,MAAM;AAON,QAAI,UAAU,izCAAizC,MAAM,GAAG,EAAE,IAAI,OAAK,IAAI,SAAS,GAAG,EAAE,IAAI,CAAC;AAC12C,aAAS,IAAI,GAAG,IAAI,GAAG,IAAI,QAAQ,QAAQ;AACzC,OAAC,IAAI,IAAI,UAAU,WAAW,KAAK,IAAI,IAAI,QAAQ,CAAC,CAAC;AAAA,EACzD,GAAG;AAEI,WAAS,gBAAgB,MAAM;AACpC,QAAI,OAAO,IAAK,QAAO;AACvB,aAAS,OAAO,GAAG,KAAK,UAAU,YAAU;AAC1C,UAAI,MAAO,OAAO,MAAO;AACzB,UAAI,OAAO,UAAU,GAAG,EAAG,MAAK;AAAA,eACvB,QAAQ,QAAQ,GAAG,EAAG,QAAO,MAAM;AAAA,UACvC,QAAO;AACZ,UAAI,QAAQ,GAAI,QAAO;AAAA,IACzB;AAAA,EACF;AAEA,WAAS,oBAAoB,MAAM;AACjC,WAAO,QAAQ,UAAW,QAAQ;AAAA,EACpC;AASA,MAAM,MAAM;AAEL,WAAS,iBAAiB,KAAK,KAAK,UAAU,MAAM,mBAAmB,MAAM;AAClF,YAAQ,UAAU,mBAAmB,kBAAkB,KAAK,KAAK,gBAAgB;AAAA,EACnF;AAEA,WAAS,iBAAiB,KAAK,KAAK,kBAAkB;AACpD,QAAI,OAAO,IAAI,OAAQ,QAAO;AAE9B,QAAI,OAAO,aAAa,IAAI,WAAW,GAAG,CAAC,KAAK,cAAc,IAAI,WAAW,MAAM,CAAC,CAAC,EAAG;AACxF,QAAI,OAAO,YAAY,KAAK,GAAG;AAC/B,WAAO,cAAc,IAAI;AACzB,WAAO,MAAM,IAAI,QAAQ;AACvB,UAAI,OAAO,YAAY,KAAK,GAAG;AAC/B,UAAI,QAAQ,OAAO,QAAQ,OAAO,oBAAoB,gBAAgB,IAAI,GAAG;AAC3E,eAAO,cAAc,IAAI;AACzB,eAAO;AAAA,MACT,WAAW,oBAAoB,IAAI,GAAG;AACpC,YAAI,cAAc,GAAG,IAAI,MAAM;AAC/B,eAAO,KAAK,KAAK,oBAAoB,YAAY,KAAK,CAAC,CAAC,GAAG;AAAE;AAAe,eAAK;AAAA,QAAE;AACnF,YAAI,cAAc,KAAK,EAAG;AAAA,YACrB,QAAO;AAAA,MACd,OAAO;AACL;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,WAAS,iBAAiB,KAAK,KAAK,kBAAkB;AACpD,WAAO,MAAM,GAAG;AACd,UAAI,QAAQ,iBAAiB,KAAK,MAAM,GAAG,gBAAgB;AAC3D,UAAI,QAAQ,IAAK,QAAO;AACxB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,WAAS,YAAY,KAAK,KAAK;AAC7B,QAAI,QAAQ,IAAI,WAAW,GAAG;AAC9B,QAAI,CAAC,cAAc,KAAK,KAAK,MAAM,KAAK,IAAI,OAAQ,QAAO;AAC3D,QAAI,QAAQ,IAAI,WAAW,MAAM,CAAC;AAClC,QAAI,CAAC,aAAa,KAAK,EAAG,QAAO;AACjC,YAAS,QAAQ,SAAW,OAAO,QAAQ,SAAU;AAAA,EACvD;AAEA,WAAS,aAAa,IAAI;AAAE,WAAO,MAAM,SAAU,KAAK;AAAA,EAAO;AAC/D,WAAS,cAAc,IAAI;AAAE,WAAO,MAAM,SAAU,KAAK;AAAA,EAAO;AAChE,WAAS,cAAc,MAAM;AAAE,WAAO,OAAO,QAAU,IAAI;AAAA,EAAE;;;ACjF7D,MAAMA,QAAN,MAAM,MAAK;AAAA;AAAA;AAAA;AAAA,IAIP,OAAO,KAAK;AACR,UAAI,MAAM,KAAK,MAAM,KAAK;AACtB,cAAM,IAAI,WAAW,oBAAoB,GAAG,0BAA0B,KAAK,MAAM,EAAE;AACvF,aAAO,KAAK,UAAU,KAAK,OAAO,GAAG,CAAC;AAAA,IAC1C;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,GAAG;AACJ,UAAI,IAAI,KAAK,IAAI,KAAK;AAClB,cAAM,IAAI,WAAW,uBAAuB,CAAC,OAAO,KAAK,KAAK,gBAAgB;AAClF,aAAO,KAAK,UAAU,GAAG,MAAM,GAAG,CAAC;AAAA,IACvC;AAAA;AAAA;AAAA;AAAA,IAIA,QAAQ,MAAM,IAAI,MAAM;AACpB,OAAC,MAAM,EAAE,IAAI,KAAK,MAAM,MAAM,EAAE;AAChC,UAAI,QAAQ,CAAC;AACb,WAAK;AAAA,QAAU;AAAA,QAAG;AAAA,QAAM;AAAA,QAAO;AAAA;AAAA,MAAe;AAC9C,UAAI,KAAK;AACL,aAAK;AAAA,UAAU;AAAA,UAAG,KAAK;AAAA,UAAQ;AAAA,UAAO,IAAoB;AAAA;AAAA,QAAe;AAC7E,WAAK;AAAA,QAAU;AAAA,QAAI,KAAK;AAAA,QAAQ;AAAA,QAAO;AAAA;AAAA,MAAiB;AACxD,aAAO,SAAS,KAAK,OAAO,KAAK,UAAU,KAAK,QAAQ,KAAK,MAAM;AAAA,IACvE;AAAA;AAAA;AAAA;AAAA,IAIA,OAAO,OAAO;AACV,aAAO,KAAK,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK;AAAA,IACvD;AAAA;AAAA;AAAA;AAAA,IAIA,MAAM,MAAM,KAAK,KAAK,QAAQ;AAC1B,OAAC,MAAM,EAAE,IAAI,KAAK,MAAM,MAAM,EAAE;AAChC,UAAI,QAAQ,CAAC;AACb,WAAK,UAAU,MAAM,IAAI,OAAO,CAAC;AACjC,aAAO,SAAS,KAAK,OAAO,KAAK,IAAI;AAAA,IACzC;AAAA;AAAA;AAAA;AAAA,IAIA,GAAG,OAAO;AACN,UAAI,SAAS;AACT,eAAO;AACX,UAAI,MAAM,UAAU,KAAK,UAAU,MAAM,SAAS,KAAK;AACnD,eAAO;AACX,UAAI,QAAQ,KAAK,cAAc,OAAO,CAAC,GAAG,MAAM,KAAK,SAAS,KAAK,cAAc,OAAO,EAAE;AAC1F,UAAIC,KAAI,IAAI,cAAc,IAAI,GAAG,IAAI,IAAI,cAAc,KAAK;AAC5D,eAAS,OAAO,OAAO,MAAM,WAAS;AAClC,QAAAA,GAAE,KAAK,IAAI;AACX,UAAE,KAAK,IAAI;AACX,eAAO;AACP,YAAIA,GAAE,aAAa,EAAE,aAAaA,GAAE,QAAQ,EAAE,QAAQA,GAAE,SAAS,EAAE;AAC/D,iBAAO;AACX,eAAOA,GAAE,MAAM;AACf,YAAIA,GAAE,QAAQ,OAAO;AACjB,iBAAO;AAAA,MACf;AAAA,IACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,KAAK,MAAM,GAAG;AAAE,aAAO,IAAI,cAAc,MAAM,GAAG;AAAA,IAAG;AAAA;AAAA;AAAA;AAAA;AAAA,IAKrD,UAAU,MAAM,KAAK,KAAK,QAAQ;AAAE,aAAO,IAAI,kBAAkB,MAAM,MAAM,EAAE;AAAA,IAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQlF,UAAU,MAAM,IAAI;AAChB,UAAI;AACJ,UAAI,QAAQ,MAAM;AACd,gBAAQ,KAAK,KAAK;AAAA,MACtB,OACK;AACD,YAAI,MAAM;AACN,eAAK,KAAK,QAAQ;AACtB,YAAI,QAAQ,KAAK,KAAK,IAAI,EAAE;AAC5B,gBAAQ,KAAK,UAAU,OAAO,KAAK,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,SAAS,MAAM,IAAI,IAAI,KAAK,KAAK,KAAK,CAAC,EAAE,EAAE,CAAC;AAAA,MAC1H;AACA,aAAO,IAAI,WAAW,KAAK;AAAA,IAC/B;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,WAAW;AAAE,aAAO,KAAK,YAAY,CAAC;AAAA,IAAG;AAAA;AAAA;AAAA;AAAA;AAAA,IAKzC,SAAS;AACL,UAAI,QAAQ,CAAC;AACb,WAAK,QAAQ,KAAK;AAClB,aAAO;AAAA,IACX;AAAA;AAAA;AAAA;AAAA,IAIA,cAAc;AAAA,IAAE;AAAA;AAAA;AAAA;AAAA,IAIhB,OAAO,GAAG,MAAM;AACZ,UAAI,KAAK,UAAU;AACf,cAAM,IAAI,WAAW,wCAAwC;AACjE,UAAI,KAAK,UAAU,KAAK,CAAC,KAAK,CAAC;AAC3B,eAAO,MAAK;AAChB,aAAO,KAAK,UAAU,KAAuB,IAAI,SAAS,IAAI,IAAI,SAAS,KAAK,SAAS,MAAM,MAAM,CAAC,CAAC,CAAC;AAAA,IAC5G;AAAA,EACJ;AAIA,MAAM,WAAN,MAAM,kBAAiBD,MAAK;AAAA,IACxB,YAAY,MAAM,SAAS,WAAW,IAAI,GAAG;AACzC,YAAM;AACN,WAAK,OAAO;AACZ,WAAK,SAAS;AAAA,IAClB;AAAA,IACA,IAAI,QAAQ;AAAE,aAAO,KAAK,KAAK;AAAA,IAAQ;AAAA,IACvC,IAAI,WAAW;AAAE,aAAO;AAAA,IAAM;AAAA,IAC9B,UAAU,QAAQ,QAAQ,MAAM,QAAQ;AACpC,eAAS,IAAI,KAAI,KAAK;AAClB,YAAIE,UAAS,KAAK,KAAK,CAAC,GAAG,MAAM,SAASA,QAAO;AACjD,aAAK,SAAS,OAAO,QAAQ;AACzB,iBAAO,IAAI,KAAK,QAAQ,KAAK,MAAMA,OAAM;AAC7C,iBAAS,MAAM;AACf;AAAA,MACJ;AAAA,IACJ;AAAA,IACA,UAAU,MAAM,IAAI,QAAQ,MAAM;AAC9B,UAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,SAAS,OACtC,IAAI,UAAS,UAAU,KAAK,MAAM,MAAM,EAALine truncated
"names": ["Text", "a", "string", "top", "number", "findClusterBreak", "surrogateLow", "surrogateHigh", "codePointAt", "codePointSize", "MapMode", "json", "doc", "process", "insert", "i", "values", "compare", "config", "_a", "id", "prec", "content", "base", "scrollIntoView", "CharCategory", "require", "name", "defaults", "cur", "spec", "a", "id", "doc", "name", "ie", "name", "a", "BlockType", "off", "elt", "doc", "cur", "top", "rect", "Direction", "replace", "type", "isNum", "_a", "findClusterBreak", "values", "t", "id", "pos", "flatten", "Text", "dist", "cache", "blockWrappers", "marks", "tile", "decorations", "from", "to", "offset", "textHeight", "i", "content", "child", "scrollIntoView", "base", "handlers", "observers", "insert", "event", "data", "_b", "QueryType", "DecorationComparator", "gap", "key", "view", "config", "shift", "meta", "command", "codePointAt", "codePointSize", "cmd", "a", "t", "_a", "i", "values", "_a", "_b", "config", "t", "space", "top", "elt", "top", "values", "config", "gutter", "cur", "gutters", "asArray", "marker", "elt", "a", "event", "number", "marks", "Range", "config", "parser", "bracketed", "name", "id", "types", "IterMode", "data", "_a", "mounted", "cur", "cache", "nodeSet", "children", "positions", "node", "buffer", "contextHash", "length", "lookAhead", "base", "pair", "nodeSize", "nodeStart", "from", "to", "off", "string", "done", "inner", "r", "pos", "a", "name", "base", "t", "a", "sameArray", "config", "tags", "cur", "hasChild", "rangeFrom", "rangeTo", "name", "values", "data", "parser", "name", "top", "base", "_a", "doc", "stringStart", "parser", "_a", "language", "name", "a", "values", "cur", "base", "lineEnd", "space", "closing", "cur", "lineEnd", "a", "_a", "from", "to", "a", "values", "config", "baseTheme$1", "baseTheme$1", "values", "from", "to", "baseTheme", "decorations", "config", "cur", "matching", "bracket", "pos", "string", "indentUnit", "_a", "parser", "data", "line", "indentation", "off", "eol", "rangeEnd", "id", "name", "t", "config", "data", "tokens", "comment", "indent", "empty", "isAdjacent", "a", "config", "json", "command", "_a", "_b", "json", "none", "a", "isAdjacent", "t", "_f", "config", "bracket", "space", "matching", "cur", "findClusterBreak", "findClusterBreak", "nextChar", "lineEnd", "Text", "findClusterBreak", "dist", "indent", "insert", "Text", "changes", "cur", "space", "types", "words", "score", "_a", "codePointAt", "codePointSize", "a", "space", "config", "content", "off", "applyCompletion", "options", "id", "scrollIntoView", "name", "compare", "cur", "none", "noAttrs", "baseTheme", "indent", "pos", "m", "snippet", "Text", "inputHandler", "insert", "codePointSize", "codePointAt", "tokens", "bracket", "doc", "config", "content", "baseTheme", "score", "_a", "parser", "base", "count", "top", "off", "i", "Type", "data", "id", "readToken", "dialect", "FragmentCursor", "nodeSet", "Parse", "a", "tokens", "insert", "name", "config", "t", "prec", "values", "name", "getAttrs", "tags", "id", "attrs", "dash", "id", "callee", "parser", "name", "tags", "identifier", "doc", "_a", "callee", "cur", "node", "parser", "newline", "space", "slash", "question", "bracketL", "spec_identifier", "parser", "id", "doc", "top", "node", "name", "parser", "_a", "name", "config", "doc", "android", "base", "empty", "insert", "a", "elementName", "doc", "name", "identifier", "elt", "_a", "base", "config", "cur", "dialect", "autoCloseTags", "selfClosers", "_b", "to", "insert", "hash", "nodeSet", "Type", "content", "Line", "indent", "elt", "space", "count", "marks", "base", "empty", "off", "parser", "FragmentCursor", "eol", "none", "top", "rangeEnd", "t", "config", "nodeTypes", "name", "id", "rm", "spec", "a", "conc", "Element", "comment", "cur", "node", "m", "next", "parser", "heading", "doc", "number", "cur", "node", "content", "space", "config", "insert", "changes", "empty", "_a", "newline", "space", "hash", "dot", "backslash", "isHex", "spaces", "Context", "indent", "topIndent", "off", "spec_identifier", "parser", "cache", "ScopeNodes", "defID", "id", "gatherCompletions", "_a", "_b", "getScope", "doc", "top", "node", "name", "Identifier", "dontComplete", "localCompletionSource", "snippets", "base", "parser", "parser", "parser", "LineComment", "BlockComment", "String$1", "Number", "Bool", "ParenL", "BraceL", "BracketL", "Punctuation", "Identifier", "Type", "isAlpha", "keywords", "types", "defaults", "dialect", "_a", "cur", "doc", "id", "name", "top", "empty", "keyword", "parser", "language", "config", "eof", "Tag", "BracketL", "BraceL", "Context", "findColumn", "indentation", "indent", "off", "newlines", "parser", "parser", "identifier", "String", "Number", "newline", "carriageReturn", "space", "tab", "slash", "semicolon", "spec_identifier", "parser", "snippets", "cache", "ScopeNodes", "cur", "gatherCompletions", "getScope", "doc", "top", "node", "name", "Identifier", "dontComplete", "localCompletionSource", "parser", "kwCompletion", "keywords", "Dot", "count", "spec_idLine truncated
}
+19
View File
@@ -0,0 +1,19 @@
Copyright (C) 2011-2026 Hakim El Hattab, http://hakim.se, and reveal.js contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+15
View File
@@ -0,0 +1,15 @@
Reveal.js 6.0.2
Source: https://github.com/hakimel/reveal.js
Distribution: https://registry.npmjs.org/reveal.js/-/reveal.js-6.0.2.tgz
License: MIT (full copyright and permission notice in LICENSE)
Package integrity: sha512-JYIg5D9aoxoaLeb84O+OvAwsKWdIavVgEDScxtYEXFCT6t6TQrhNtSgogcjdCpdLsWglhJn3zyE3fUOwiH5KEg==
Unmodified distribution files, SHA-256:
reveal.js aa1bbbf2617b23a623b23612cb3c5bdb63de512e652bf20fcfa832b045d37844
reveal.css 615ee850cbbb98a0f688b60ed37b21819a3f54c9f3e6f20e33e63693ab74a0c0
LICENSE b2883e4b610bfa1b4d8fff84c4d4b825cc7d553cbd9fec4777c04068a2859dc0
Only the runtime and base CSS are distributed. No Markdown/highlight/notes
plugins, theme fonts, remote imports, or CDN requests are used. PagesWiki's
wrapper, sanitizer and theme styles are maintained separately under static/js
and static/css. Keep this notice and LICENSE with binary/image distributions.
+1
View File
@@ -0,0 +1 @@
.reveal .stretch,.reveal .r-stretch{max-width:none;max-height:none}.reveal pre.stretch code,.reveal pre.r-stretch code{box-sizing:border-box;height:100%;max-height:100%}.reveal .r-fit-text{white-space:nowrap;display:inline-block}.reveal .r-stack{grid-template-rows:100%;display:grid}.reveal .r-stack>*{grid-area:1/1;margin:auto}.reveal .r-vstack,.reveal .r-hstack{display:flex}.reveal .r-vstack img,.reveal .r-vstack video,.reveal .r-hstack img,.reveal .r-hstack video{object-fit:contain;min-width:0;min-height:0}.reveal .r-vstack{flex-direction:column;justify-content:center;align-items:center}.reveal .r-hstack{flex-direction:row;justify-content:center;align-items:center}.reveal .items-stretch{align-items:stretch}.reveal .items-start{align-items:flex-start}.reveal .items-center{align-items:center}.reveal .items-end{align-items:flex-end}.reveal .justify-between{justify-content:space-between}.reveal .justify-around{justify-content:space-around}.reveal .justify-start{justify-content:flex-start}.reveal .justify-center{justify-content:center}.reveal .justify-end{justify-content:flex-end}html.reveal-full-page{width:100%;height:100vh;height:calc(var(--vh,1vh) * 100);height:100dvh;overflow:hidden}.reveal-viewport{color:#000;--r-controls-spacing:12px;--r-overlay-header-height:40px;--r-overlay-margin:0px;--r-overlay-padding:6px;--r-overlay-gap:5px;background-color:#fff;height:100%;margin:0;line-height:1;position:relative;overflow:hidden}@media screen and (width<=1024px),(height<=768px){.reveal-viewport{--r-overlay-header-height:26px}}.reveal-viewport:fullscreen{width:100%!important;height:100%!important;top:0!important;left:0!important;transform:none!important}.reveal .fragment{transition:all .2s}.reveal .fragment:not(.custom){opacity:0;visibility:hidden;will-change:opacity}.reveal .fragment.visible{opacity:1;visibility:inherit}.reveal .fragment.disabled{transition:none}.reveal .fragment.grow{opacity:1;visibility:inherit}.reveal .fragment.grow.visible{transform:scale(1.3)}.reveal .fragment.shrink{opacity:1;visibility:inherit}.reveal .fragment.shrink.visible{transform:scale(.7)}.reveal .fragment.zoom-in{transform:scale(.1)}.reveal .fragment.zoom-in.visible{transform:none}.reveal .fragment.fade-out{opacity:1;visibility:inherit}.reveal .fragment.fade-out.visible{opacity:0;visibility:hidden}.reveal .fragment.semi-fade-out{opacity:1;visibility:inherit}.reveal .fragment.semi-fade-out.visible{opacity:.5;visibility:inherit}.reveal .fragment.strike{opacity:1;visibility:inherit}.reveal .fragment.strike.visible{text-decoration:line-through}.reveal .fragment.fade-up{transform:translateY(40px)}.reveal .fragment.fade-up.visible{transform:translate(0)}.reveal .fragment.fade-down{transform:translateY(-40px)}.reveal .fragment.fade-down.visible{transform:translate(0)}.reveal .fragment.fade-right{transform:translate(-40px)}.reveal .fragment.fade-right.visible{transform:translate(0)}.reveal .fragment.fade-left{transform:translate(40px)}.reveal .fragment.fade-left.visible{transform:translate(0)}.reveal .fragment.fade-in-then-out,.reveal .fragment.current-visible{opacity:0;visibility:hidden}.reveal .fragment.fade-in-then-out.current-fragment,.reveal .fragment.current-visible.current-fragment{opacity:1;visibility:inherit}.reveal .fragment.fade-in-then-semi-out{opacity:0;visibility:hidden}.reveal .fragment.fade-in-then-semi-out.visible{opacity:.5;visibility:inherit}.reveal .fragment.fade-in-then-semi-out.current-fragment,.reveal .fragment.highlight-red,.reveal .fragment.highlight-current-red,.reveal .fragment.highlight-green,.reveal .fragment.highlight-current-green,.reveal .fragment.highlight-blue,.reveal .fragment.highlight-current-blue{opacity:1;visibility:inherit}.reveal .fragment.highlight-red.visible{color:#ff2c2d}.reveal .fragment.highlight-green.visible{color:#17ff2e}.reveal .fragment.highlight-blue.visible{color:#1b91ff}.reveal .fragment.highlight-current-red.current-fragment{color:#ff2c2d}.reveal .fragment.highlight-current-green.current-fragment{color:#17ff2e}.reveal .fragment.highlight-current-blue.current-fragment{color:#1b91ff}.reveal:after{content:"";font-style:italic}.reveal iframe{z-index:1}.reveal a{position:relative}@keyframes bounce-right{0%,10%,25%,40%,50%{transform:translate(0)}20%{transform:translate(10px)}30%{transform:translate(-5px)}}@keyframes bounce-left{0%,10%,25%,40%,50%{transform:translate(0)}20%{transform:translate(-10px)}30%{transform:translate(5px)}}@keyframes bounce-down{0%,10%,25%,40%,50%{transform:translateY(0)}20%{transform:translateY(10px)}30%{transform:translateY(-5px)}}.reveal .controls{top:auto;bottom:var(--r-controls-spacing);right:var(--r-controls-spacing);z-index:11;color:#000;pointer-events:none;font-size:10px;display:none;position:absolute;left:auto}.reveal .controls button{cursor:pointer;color:currentColor;z-index:2;pointer-events:auto;font-size:inherit;visibility:hidden;opacity:0;-webkit-appearance:none;-webkit-tap-highlight-color:#0000;background-color:#0000;border:0;outline:0;padding:0;transitioLine truncated
+40
View File
@@ -0,0 +1,40 @@
/*!
* reveal.js
* https://revealjs.com
* MIT licensed
*
* Copyright (C) 2011-2026 Hakim El Hattab, https://hakim.se
*/
(function(e,t){typeof exports==`object`&&typeof module<`u`?module.exports=t():typeof define==`function`&&define.amd?define([],t):(e=typeof globalThis<`u`?globalThis:e||self,e.Reveal=t())})(this,function(){var e=(e,t)=>{for(let n in t)e[n]=t[n];return e},t=(e,t)=>Array.from(e.querySelectorAll(t)),n=(e,t,n)=>{n?e.classList.add(t):e.classList.remove(t)},r=e=>{if(typeof e==`string`){if(e===`null`)return null;if(e===`true`)return!0;if(e===`false`)return!1;if(e.match(/^-?[\d\.]+$/))return parseFloat(e)}return e},i=(e,t)=>{e.style.transform=t},a=(e,t)=>{let n=e.matches||e.matchesSelector||e.msMatchesSelector;return!!(n&&n.call(e,t))},o=(e,t)=>{if(e&&typeof e.closest==`function`)return e.closest(t);for(;e;){if(a(e,t))return e;e=e.parentElement}return null},s=e=>{e=e||document.documentElement;let t=e.requestFullscreen||e.webkitRequestFullscreen||e.webkitRequestFullScreen||e.mozRequestFullScreen||e.msRequestFullscreen;t&&t.apply(e)},c=(e,t,n,r=``)=>{let i=e.querySelectorAll(`.`+n);for(let t=0;t<i.length;t++){let n=i[t];if(n.parentNode===e)return n}let a=document.createElement(t);return a.className=n,a.innerHTML=r,e.appendChild(a),a},l=e=>{let t=document.createElement(`style`);return e&&e.length>0&&t.appendChild(document.createTextNode(e)),document.head.appendChild(t),t},u=()=>{let e={};location.search.replace(/[A-Z0-9]+?=([\w\.%-]*)/gi,t=>{let n=t.split(`=`).shift(),r=t.split(`=`).pop();return n&&r!==void 0&&(e[n]=r),t});for(let t in e){let n=e[t];e[t]=r(unescape(n))}return e.dependencies!==void 0&&delete e.dependencies,e},d=(e,t=0)=>{if(e){var n;let r,i=e.style.height;return e.style.height=`0px`,e.parentElement&&(e.parentElement.style.height=`auto`),r=t-(((n=e.parentElement)==null?void 0:n.offsetHeight)||0),e.style.height=i+`px`,e.parentElement&&e.parentElement.style.removeProperty(`height`),r}return t},f={mp4:`video/mp4`,m4a:`video/mp4`,ogv:`video/ogg`,mpeg:`video/mpeg`,webm:`video/webm`},p=(e=``)=>{let t=e.split(`.`).pop();return t?f[t]:void 0},m=(e=``)=>encodeURI(e).replace(/%5B/g,`[`).replace(/%5D/g,`]`).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),h=navigator.userAgent,g=/(iphone|ipod|ipad|android)/gi.test(h)||navigator.platform===`MacIntel`&&navigator.maxTouchPoints>1;/chrome/i.test(h)&&/edge/i.test(h);var _=/android/gi.test(h),v=function(e){if(e){var t=function(e){return[].slice.call(e)},n=0,r=1,i=2,a=3,o=[],s=null,c=`requestAnimationFrame`in e?function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{sync:!1};e.cancelAnimationFrame(s);var n=function(){return u(o.filter((function(e){return e.dirty&&e.active})))};if(t.sync)return n();s=e.requestAnimationFrame(n)}:function(){},l=function(e){return function(t){o.forEach((function(t){return t.dirty=e})),c(t)}},u=function(e){e.filter((function(e){return!e.styleComputed})).forEach((function(e){e.styleComputed=m(e)})),e.filter(h).forEach(g);var t=e.filter(p);t.forEach(f),t.forEach((function(e){g(e),d(e)})),t.forEach(_)},d=function(e){return e.dirty=n},f=function(e){e.availableWidth=e.element.parentNode.clientWidth,e.currentWidth=e.element.scrollWidth,e.previousFontSize=e.currentFontSize,e.currentFontSize=Math.min(Math.max(e.minSize,e.availableWidth/e.currentWidth*e.previousFontSize),e.maxSize),e.whiteSpace=e.multiLine&&e.currentFontSize===e.minSize?`normal`:`nowrap`},p=function(e){return e.dirty!==i||e.dirty===i&&e.element.parentNode.clientWidth!==e.availableWidth},m=function(t){var n=e.getComputedStyle(t.element,null);return t.currentFontSize=parseFloat(n.getPropertyValue(`font-size`)),t.display=n.getPropertyValue(`display`),t.whiteSpace=n.getPropertyValue(`white-space`),!0},h=function(e){var t=!1;return!e.preStyleTestCompleted&&(/inline-/.test(e.display)||(t=!0,e.display=`inline-block`),e.whiteSpace!==`nowrap`&&(t=!0,e.whiteSpace=`nowrap`),e.preStyleTestCompleted=!0,t)},g=function(e){e.element.style.whiteSpace=e.whiteSpace,e.element.style.display=e.display,e.element.style.fontSize=e.currentFontSize+`px`},_=function(e){e.element.dispatchEvent(new CustomEvent(`fit`,{detail:{oldValue:e.previousFontSize,newValue:e.currentFontSize,scaleFactor:e.currentFontSize/e.previousFontSize}}))},v=function(e,t){return function(n){e.dirty=t,e.active&&c(n)}},y=function(e){return function(){o=o.filter((function(t){return t.element!==e.element})),e.observeMutations&&e.observer.disconnect(),e.element.style.whiteSpace=e.originalStyle.whiteSpace,e.element.style.display=e.originalStyle.display,e.element.style.fontSize=e.originalStyle.fontSize}},b=function(e){return function(){e.active||(e.active=!0,c())}},x=function(e){return function(){return e.active=!1}},S=function(e){e.observeMutations&&(e.observer=new MutationObserver(v(e,r)),e.observer.observe(e.element,e.observeMutations))},ee={minSize:16,maxSize:512,multiLine:!0,observeMutations:`MutationObserver`in e&&{subtree:!0,childList:!0,characterData:!0}},C=null,w=function(){e.clearTimeout(C),C=e.setTimeout(l(i),E.observeWindowDelay)},te=[`resize`,`orientationchange`];return Object.defineProperty(ELine truncated
<span class="slide-number-a">${e}</span>
<span class="slide-number-delimiter">${t}</span>
<span class="slide-number-b">${n}</span>
</a>`:`<a href="${r}">
<span class="slide-number-a">${e}</span>
</a>`}destroy(){this.element.remove()}},re=class{constructor(e){this.Reveal=e,this.onInput=this.onInput.bind(this),this.onBlur=this.onBlur.bind(this),this.onKeyDown=this.onKeyDown.bind(this)}render(){this.element=document.createElement(`div`),this.element.className=`jump-to-slide`,this.jumpInput=document.createElement(`input`),this.jumpInput.type=`text`,this.jumpInput.className=`jump-to-slide-input`,this.jumpInput.placeholder=`Jump to slide`,this.jumpInput.addEventListener(`input`,this.onInput),this.jumpInput.addEventListener(`keydown`,this.onKeyDown),this.jumpInput.addEventListener(`blur`,this.onBlur),this.element.appendChild(this.jumpInput)}show(){this.indicesOnShow=this.Reveal.getIndices(),this.Reveal.getRevealElement().appendChild(this.element),this.jumpInput.focus()}hide(){this.isVisible()&&(this.element.remove(),this.jumpInput.value=``,clearTimeout(this.jumpTimeout),delete this.jumpTimeout)}isVisible(){return!!this.element.parentNode}jump(){clearTimeout(this.jumpTimeout),delete this.jumpTimeout;let e=this.jumpInput.value.trim(``),t;if(/^\d+$/.test(e)){let n=this.Reveal.getConfig().slideNumber;if(n===`c`||n===`c/t`){let n=this.Reveal.getSlides()[parseInt(e,10)-1];n&&(t=this.Reveal.getIndices(n))}}return t||(/^\d+\.\d+$/.test(e)&&(e=e.replace(`.`,`/`)),t=this.Reveal.location.getIndicesFromHash(e,{oneBasedIndex:!0})),!t&&/\S+/i.test(e)&&e.length>1&&(t=this.search(e)),t&&e!==``?(this.Reveal.slide(t.h,t.v,t.f),!0):(this.Reveal.slide(this.indicesOnShow.h,this.indicesOnShow.v,this.indicesOnShow.f),!1)}jumpAfter(e){clearTimeout(this.jumpTimeout),this.jumpTimeout=setTimeout(()=>this.jump(),e)}search(e){let t=RegExp(`\\b`+e.trim()+`\\b`,`i`),n=this.Reveal.getSlides().find(e=>t.test(e.innerText));return n?this.Reveal.getIndices(n):null}cancel(){this.Reveal.slide(this.indicesOnShow.h,this.indicesOnShow.v,this.indicesOnShow.f),this.hide()}confirm(){this.jump(),this.hide()}destroy(){this.jumpInput.removeEventListener(`input`,this.onInput),this.jumpInput.removeEventListener(`keydown`,this.onKeyDown),this.jumpInput.removeEventListener(`blur`,this.onBlur),this.element.remove()}onKeyDown(e){e.keyCode===13?this.confirm():e.keyCode===27&&(this.cancel(),e.stopImmediatePropagation())}onInput(e){this.jumpAfter(200)}onBlur(){setTimeout(()=>this.hide(),1)}},D=e=>{let t=e.match(/^#([0-9a-f]{3})$/i);if(t&&t[1]){let e=t[1];return{r:parseInt(e.charAt(0),16)*17,g:parseInt(e.charAt(1),16)*17,b:parseInt(e.charAt(2),16)*17}}let n=e.match(/^#([0-9a-f]{6})$/i);if(n&&n[1]){let e=n[1];return{r:parseInt(e.slice(0,2),16),g:parseInt(e.slice(2,4),16),b:parseInt(e.slice(4,6),16)}}let r=e.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);if(r)return{r:parseInt(r[1],10),g:parseInt(r[2],10),b:parseInt(r[3],10)};let i=e.match(/^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i);return i?{r:parseInt(i[1],10),g:parseInt(i[2],10),b:parseInt(i[3],10),a:parseFloat(i[4])}:null},ie=e=>(typeof e==`string`&&(e=D(e)),e?(e.r*299+e.g*587+e.b*114)/1e3:null),ae=class{constructor(e){this.Reveal=e}render(){this.element=document.createElement(`div`),this.element.className=`backgrounds`,this.Reveal.getRevealElement().appendChild(this.element)}create(){this.element.innerHTML=``,this.element.classList.add(`no-transition`),this.Reveal.getHorizontalSlides().forEach(e=>{let n=this.createBackground(e,this.element);t(e,`section`).forEach(e=>{this.createBackground(e,n),n.classList.add(`stack`)})}),this.Reveal.getConfig().parallaxBackgroundImage?(this.element.style.backgroundImage=`url("`+this.Reveal.getConfig().parallaxBackgroundImage+`")`,this.element.style.backgroundSize=this.Reveal.getConfig().parallaxBackgroundSize,this.element.style.backgroundRepeat=this.Reveal.getConfig().parallaxBackgroundRepeat,this.element.style.backgroundPosition=this.Reveal.getConfig().parallaxBackgroundPosition,setTimeout(()=>{this.Reveal.getRevealElement().classList.add(`has-parallax-background`)},1)):(this.element.style.backgroundImage=``,this.Reveal.getRevealElement().classList.remove(`has-parallax-background`))}createBackground(e,t){let n=document.createElement(`div`);n.className=`slide-background `+e.className.replace(/present|past|future/,``);let r=document.createElement(`div`);return r.className=`slide-background-content`,n.appendChild(r),t.appendChild(n),e.slideBackgroundElement=n,e.slideBackgroundContentElement=r,this.sync(e),n}sync(e){let t=e.slideBackgroundElement,n=e.slideBackgroundContentElement,r={background:e.getAttribute(`data-background`),backgroundSize:e.getAttribute(`data-background-size`),backgroundImage:e.getAttribute(`data-background-image`),backgroundVideo:e.getAttribute(`data-background-video`),backgroundIframe:e.getAttribute(`data-background-iframe`),backgroundColor:e.getAttribute(`data-background-color`),backgroundGradient:e.getAttribute(`data-background-gradient`),backgroundRepeat:e.getAttribute(`data-background-repeat`),backgroundPosition:e.getAttribute(`data-background-position`),backgroundTransition:e.getAttribute(`data-back Line truncated
<button class="navigate-right" aria-label="${e?`previous slide`:`next slide`}"><div class="controls-arrow"></div></button>
<button class="navigate-up" aria-label="above slide"><div class="controls-arrow"></div></button>
<button class="navigate-down" aria-label="below slide"><div class="controls-arrow"></div></button>`,this.Reveal.getRevealElement().appendChild(this.element),this.controlsLeft=t(n,`.navigate-left`),this.controlsRight=t(n,`.navigate-right`),this.controlsUp=t(n,`.navigate-up`),this.controlsDown=t(n,`.navigate-down`),this.controlsPrev=t(n,`.navigate-prev`),this.controlsNext=t(n,`.navigate-next`),this.controlsFullscreen=t(n,`.enter-fullscreen`),this.controlsRightArrow=this.element.querySelector(`.navigate-right`),this.controlsLeftArrow=this.element.querySelector(`.navigate-left`),this.controlsDownArrow=this.element.querySelector(`.navigate-down`)}configure(e,t){let n=e.controls===`speaker`||e.controls===`speaker-only`;this.element.style.display=e.controls&&(!n||this.Reveal.isSpeakerNotes())?`block`:`none`,this.element.setAttribute(`data-controls-layout`,e.controlsLayout),this.element.setAttribute(`data-controls-back-arrows`,e.controlsBackArrows)}bind(){let e=[`touchstart`,`click`];_&&(e=[`touchend`]),e.forEach(e=>{this.controlsLeft.forEach(t=>t.addEventListener(e,this.onNavigateLeftClicked,!1)),this.controlsRight.forEach(t=>t.addEventListener(e,this.onNavigateRightClicked,!1)),this.controlsUp.forEach(t=>t.addEventListener(e,this.onNavigateUpClicked,!1)),this.controlsDown.forEach(t=>t.addEventListener(e,this.onNavigateDownClicked,!1)),this.controlsPrev.forEach(t=>t.addEventListener(e,this.onNavigatePrevClicked,!1)),this.controlsNext.forEach(t=>t.addEventListener(e,this.onNavigateNextClicked,!1)),this.controlsFullscreen.forEach(t=>t.addEventListener(e,this.onEnterFullscreen,!1))})}unbind(){[`touchstart`,`touchend`,`click`].forEach(e=>{this.controlsLeft.forEach(t=>t.removeEventListener(e,this.onNavigateLeftClicked,!1)),this.controlsRight.forEach(t=>t.removeEventListener(e,this.onNavigateRightClicked,!1)),this.controlsUp.forEach(t=>t.removeEventListener(e,this.onNavigateUpClicked,!1)),this.controlsDown.forEach(t=>t.removeEventListener(e,this.onNavigateDownClicked,!1)),this.controlsPrev.forEach(t=>t.removeEventListener(e,this.onNavigatePrevClicked,!1)),this.controlsNext.forEach(t=>t.removeEventListener(e,this.onNavigateNextClicked,!1)),this.controlsFullscreen.forEach(t=>t.removeEventListener(e,this.onEnterFullscreen,!1))})}update(){let e=this.Reveal.availableRoutes();[...this.controlsLeft,...this.controlsRight,...this.controlsUp,...this.controlsDown,...this.controlsPrev,...this.controlsNext].forEach(e=>{e.classList.remove(`enabled`,`fragmented`),e.setAttribute(`disabled`,`disabled`)}),e.left&&this.controlsLeft.forEach(e=>{e.classList.add(`enabled`),e.removeAttribute(`disabled`)}),e.right&&this.controlsRight.forEach(e=>{e.classList.add(`enabled`),e.removeAttribute(`disabled`)}),e.up&&this.controlsUp.forEach(e=>{e.classList.add(`enabled`),e.removeAttribute(`disabled`)}),e.down&&this.controlsDown.forEach(e=>{e.classList.add(`enabled`),e.removeAttribute(`disabled`)}),(e.left||e.up)&&this.controlsPrev.forEach(e=>{e.classList.add(`enabled`),e.removeAttribute(`disabled`)}),(e.right||e.down)&&this.controlsNext.forEach(e=>{e.classList.add(`enabled`),e.removeAttribute(`disabled`)});let t=this.Reveal.getCurrentSlide();if(t){let e=this.Reveal.fragments.availableRoutes();e.prev&&this.controlsPrev.forEach(e=>{e.classList.add(`fragmented`,`enabled`),e.removeAttribute(`disabled`)}),e.next&&this.controlsNext.forEach(e=>{e.classList.add(`fragmented`,`enabled`),e.removeAttribute(`disabled`)});let n=this.Reveal.isVerticalSlide(t),r=n&&t.parentElement&&t.parentElement.querySelectorAll(`:scope > section`).length>1;n&&r?(e.prev&&this.controlsUp.forEach(e=>{e.classList.add(`fragmented`,`enabled`),e.removeAttribute(`disabled`)}),e.next&&this.controlsDown.forEach(e=>{e.classList.add(`fragmented`,`enabled`),e.removeAttribute(`disabled`)})):(e.prev&&this.controlsLeft.forEach(e=>{e.classList.add(`fragmented`,`enabled`),e.removeAttribute(`disabled`)}),e.next&&this.controlsRight.forEach(e=>{e.classList.add(`fragmented`,`enabled`),e.removeAttribute(`disabled`)}))}if(this.Reveal.getConfig().controlsTutorial){let t=this.Reveal.getIndices();!this.Reveal.hasNavigatedVertically()&&e.down?this.controlsDownArrow.classList.add(`highlight`):(this.controlsDownArrow.classList.remove(`highlight`),this.Reveal.getConfig().rtl?!this.Reveal.hasNavigatedHorizontally()&&e.left&&t.v===0?this.controlsLeftArrow.classList.add(`highlight`):this.controlsLeftArrow.classList.remove(`highlight`):!this.Reveal.hasNavigatedHorizontally()&&e.right&&t.v===0?this.controlsRightArrow.classList.add(`highlight`):this.controlsRightArrow.classList.remove(`highlight`))}}destroy(){this.unbind(),this.element.remove()}onNavigateLeftClicked(e){e.preventDefault(),this.Reveal.onUserInput(),this.Reveal.getConfig().navigationMode===`linear`?this.Reveal.prev():this.Reveal.left()}onNavigateRightClicked(e){e.preventDefault(),this.Reveal.onUserInput(),this.Reveal.getConfig().navigationMode===`linear`?this.Reveal.next():this.Reveal.right()}onNavigateUpClicked(e){e.preventDefault(),this.Reveal.onULine truncated
`+e))});let r=document.querySelector(`head`);r&&r.insertBefore(n,r.lastChild)},ye=class{constructor(e){this.Reveal=e,this.state=`idle`,this.registeredPlugins={},this.asyncDependencies=[]}load(e,t){return this.state=`loading`,e.forEach(this.registerPlugin.bind(this)),new Promise(e=>{let n=[],r=0;if(t.forEach(e=>{(!e.condition||e.condition())&&(e.async?this.asyncDependencies.push(e):n.push(e))}),n.length){r=n.length;let t=t=>{t&&typeof t.callback==`function`&&t.callback(),--r===0&&this.initPlugins().then(e)};n.forEach(e=>{typeof e.id==`string`?(this.registerPlugin(e),t(e)):typeof e.src==`string`?ve(e.src,()=>t(e)):(console.warn(`Unrecognized plugin format`,e),t())})}else this.initPlugins().then(e)})}initPlugins(){return new Promise(e=>{let t=Object.values(this.registeredPlugins),n=t.length;if(n===0)this.loadAsync().then(e);else{let r,i=()=>{--n===0?this.loadAsync().then(e):r()},a=0;r=()=>{let e=t[a++];if(typeof e.init==`function`){let t=e.init(this.Reveal);t&&typeof t.then==`function`?t.then(i):i()}else i()},r()}})}loadAsync(){return this.state=`loaded`,this.asyncDependencies.length&&this.asyncDependencies.forEach(e=>{ve(e.src,e.callback)}),Promise.resolve()}registerPlugin(e){arguments.length===2&&typeof arguments[0]==`string`?(e=arguments[1],e.id=arguments[0]):typeof e==`function`&&(e=e());let t=e.id;typeof t==`string`?this.registeredPlugins[t]===void 0?(this.registeredPlugins[t]=e,this.state===`loaded`&&typeof e.init==`function`&&e.init(this.Reveal)):console.warn(`reveal.js: "`+t+`" plugin has already been registered`):console.warn(`Unrecognized plugin format; can't find plugin.id`,e)}hasPlugin(e){return!!this.registeredPlugins[e]}getPlugin(e){return this.registeredPlugins[e]}getRegisteredPlugins(){return this.registeredPlugins}destroy(){Object.values(this.registeredPlugins).forEach(e=>{typeof e.destroy==`function`&&e.destroy()}),this.registeredPlugins={},this.asyncDependencies=[]}},be=class{constructor(e){this.Reveal=e,this.onSlidesClicked=this.onSlidesClicked.bind(this),this.iframeTriggerSelector=null,this.mediaTriggerSelector=`[data-preview-image], [data-preview-video]`,this.stateProps=[`previewIframe`,`previewImage`,`previewVideo`,`previewFit`],this.state={}}update(){this.iframeTriggerSelector=this.Reveal.getConfig().previewLinks?`a[href]:not([data-preview-link=false]), [data-preview-link]:not(a):not([data-preview-link=false])`:`[data-preview-link]:not([data-preview-link=false])`;let e=this.Reveal.getSlidesElement().querySelectorAll(this.iframeTriggerSelector).length>0,t=this.Reveal.getSlidesElement().querySelectorAll(this.mediaTriggerSelector).length>0;e||t?this.Reveal.getSlidesElement().addEventListener(`click`,this.onSlidesClicked,!1):this.Reveal.getSlidesElement().removeEventListener(`click`,this.onSlidesClicked,!1)}createOverlay(e){this.dom=document.createElement(`div`),this.dom.classList.add(`r-overlay`),this.dom.classList.add(e),this.viewport=document.createElement(`div`),this.viewport.classList.add(`r-overlay-viewport`),this.dom.appendChild(this.viewport),this.Reveal.getRevealElement().appendChild(this.dom)}previewIframe(e){if(typeof e!=`string`)return;let t;try{t=new URL(e,document.baseURI)}catch(e){return}if(t.protocol===`file:`&&window.location.protocol!==`file:`||![`http:`,`https:`,`file:`].includes(t.protocol)&&t.href!==`about:blank`)return;this.close(),this.state={previewIframe:e},this.createOverlay(`r-overlay-preview`),this.dom.dataset.state=`loading`,this.viewport.innerHTML=`<header class="r-overlay-header">
<a class="r-overlay-header-button r-overlay-external" target="_blank" rel="noopener"><span class="icon"></span></a>
<button class="r-overlay-header-button r-overlay-close"><span class="icon"></span></button>
</header>
<div class="r-overlay-spinner"></div>
<div class="r-overlay-content">
<iframe></iframe>
<small class="r-overlay-content-inner">
<span class="r-overlay-error x-frame-error">Unable to load iframe. This is likely due to the site's policy (x-frame-options).</span>
</small>
</div>`;let n=this.dom.querySelector(`iframe`);n.addEventListener(`load`,e=>{this.dom.dataset.state=`loaded`},!1),n.src=t.href,this.dom.querySelector(`.r-overlay-external`).href=t.href,this.dom.querySelector(`.r-overlay-close`).addEventListener(`click`,e=>{this.close(),e.preventDefault()},!1),this.dom.querySelector(`.r-overlay-external`).addEventListener(`click`,e=>{this.close()},!1),this.Reveal.dispatchEvent({type:`previewiframe`,data:{url:e}})}previewMedia(e,t,n){if(t!==`image`&&t!==`video`){console.warn(`Please specify a valid media type to preview (image|video)`);return}this.close(),n=n||`scale-down`,this.createOverlay(`r-overlay-preview`),this.dom.dataset.state=`loading`,this.dom.dataset.previewFit=n,this.viewport.innerHTML=`<header class="r-overlay-header">
<button class="r-overlay-header-button r-overlay-close">Esc <span class="icon"></span></button>
</header>
<div class="r-overlay-spinner"></div>
<div class="r-overlay-content"></div>`;let r=this.dom.querySelector(`.r-overlay-content`);if(t===`image`){this.state={previewImage:e,previewFit:n};let t=document.createElement(`img`,{});t.src=e,r.appendChild(t),t.addEventListener(`load`,()=>{this.dom.dataset.state=`loaded`},!1),t.addEventListener(`error`,()=>{this.dom.dataset.state=`error`,r.innerHTML=`<span class="r-overlay-error">Unable to load image.</span>`},!1),this.dom.style.cursor=`zoom-out`,this.dom.addEventListener(`click`,e=>{this.close()},!1),this.Reveal.dispatchEvent({type:`previewimage`,data:{url:e}})}else if(t===`video`){this.state={previewVideo:e,previewFit:n};let t=document.createElement(`video`);t.autoplay=this.dom.dataset.previewAutoplay!==`false`,t.controls=this.dom.dataset.previewControls!==`false`,t.loop=this.dom.dataset.previewLoop===`true`,t.muted=this.dom.dataset.previewMuted===`true`,t.playsInline=!0,t.src=e,r.appendChild(t),t.addEventListener(`loadeddata`,()=>{this.dom.dataset.state=`loaded`},!1),t.addEventListener(`error`,()=>{this.dom.dataset.state=`error`,r.innerHTML=`<span class="r-overlay-error">Unable to load video.</span>`},!1),this.Reveal.dispatchEvent({type:`previewvideo`,data:{url:e}})}else throw Error(`Please specify a valid media type to preview`);this.dom.querySelector(`.r-overlay-close`).addEventListener(`click`,e=>{this.close(),e.preventDefault()},!1)}previewImage(e,t){this.previewMedia(e,`image`,t)}previewVideo(e,t){this.previewMedia(e,`video`,t)}toggleHelp(e){typeof e==`boolean`?e?this.showHelp():this.close():this.dom?this.close():this.showHelp()}showHelp(){if(this.Reveal.getConfig().help){this.close(),this.createOverlay(`r-overlay-help`);let e=`<p class="title">Keyboard Shortcuts</p>`,t=this.Reveal.keyboard.getShortcuts(),n=this.Reveal.keyboard.getBindings();e+=`<table><th>KEY</th><th>ACTION</th>`;for(let n in t)e+=`<tr><td>${n}</td><td>${t[n]}</td></tr>`;for(let t in n)n[t].key&&n[t].description&&(e+=`<tr><td>${n[t].key}</td><td>${n[t].description}</td></tr>`);e+=`</table>`,this.viewport.innerHTML=`
<header class="r-overlay-header">
<button class="r-overlay-header-button r-overlay-close">Esc <span class="icon"></span></button>
</header>
<div class="r-overlay-content">
<div class="r-overlay-help-content">${e}</div>
</div>
`,this.dom.querySelector(`.r-overlay-close`).addEventListener(`click`,e=>{this.close(),e.preventDefault()},!1),this.Reveal.dispatchEvent({type:`showhelp`})}}isOpen(){return!!this.dom}close(){return this.dom?(this.dom.remove(),this.dom=null,this.state={},this.Reveal.dispatchEvent({type:`closeoverlay`}),!0):!1}getState(){return this.state}setState(e){this.stateProps.every(t=>this.state[t]===e[t])||(e.previewIframe?this.previewIframe(e.previewIframe):e.previewImage?this.previewImage(e.previewImage,e.previewFit):e.previewVideo?this.previewVideo(e.previewVideo,e.previewFit):this.close())}onSlidesClicked(e){let t=e.target,n=t.closest(this.iframeTriggerSelector),r=t.closest(this.mediaTriggerSelector);if(n){if(e.metaKey||e.shiftKey||e.altKey)return;let t=n.getAttribute(`data-preview-link`),r=typeof t==`string`&&t.startsWith(`http`)?t:n.getAttribute(`href`);r&&(this.previewIframe(r),e.preventDefault())}else if(r){if(r.hasAttribute(`data-preview-image`)){let t=r.dataset.previewImage||r.getAttribute(`src`);t&&(this.previewImage(t,r.dataset.previewFit),e.preventDefault())}else if(r.hasAttribute(`data-preview-video`)){let t=r.dataset.previewVideo||r.getAttribute(`src`);if(!t){let e=r.querySelector(`source`);e&&(t=e.getAttribute(`src`))}t&&(this.previewVideo(t,r.dataset.previewFit),e.preventDefault())}}}destroy(){this.close()}},F=40,I=1.03,xe=class{constructor(e){this.Reveal=e,this.touchStartX=0,this.touchStartY=0,this.touchStartCount=0,this.touchCaptured=!1,this.activePointers=new Map,this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.onPointerCancel=this.onPointerCancel.bind(this),this.onTouchStart=this.onTouchStart.bind(this),this.onTouchMove=this.onTouchMove.bind(this),this.onTouchEnd=this.onTouchEnd.bind(this)}bind(){let e=this.Reveal.getRevealElement();`onpointerdown`in window?(e.addEventListener(`pointerdown`,this.onPointerDown,!1),e.addEventListener(`pointermove`,this.onPointerMove,!1),e.addEventListener(`pointerup`,this.onPointerUp,!1),e.addEventListener(`pointercancel`,this.onPointerCancel,!1)):(e.addEventListener(`touchstart`,this.onTouchStart,!1),e.addEventListener(`touchmove`,this.onTouchMove,!1),e.addEventListener(`touchend`,this.onTouchEnd,!1))}unbind(){let e=this.Reveal.getRevealElement();e.removeEventListener(`pointerdown`,this.onPointerDown,!1),e.removeEventListener(`pointermove`,this.onPointerMove,!1),e.removeEventListener(`pointerup`,this.onPointerUp,!1),e.removeEventListener(`pointercancel`,this.onPointerCancel,!1),e.removeEventListener(`touchstart`,this.onTouchStart,!1),e.removeEventListener(`touchmove`,this.onTouchMove,!1),e.removeEventListener(`touchend`,this.onTouchEnd,!1)}isSwipePrevented(e){if(a(e,`video[controls], audio[controls]`))return!0;for(;e&&typeof e.hasAttribute==`function`;){if(e.hasAttribute(`data-prevent-swipe`))return!0;e=e.parentNode}return!1}isViewportZoomed(){if(!window.visualViewport||typeof window.visualViewport.scale!=`number`)return!1;let e=window.visualViewport.scale;return this.visualViewportBaseScale=this.visualViewportBaseScale===void 0?e:Math.min(this.visualViewportBaseScale,e),e/this.visualViewportBaseScale>I}onTouchStart(e){if(this.touchCaptured=!1,this.isSwipePrevented(e.target))return!0;this.touchStartX=e.touches[0].clientX,this.touchStartY=e.touches[0].clientY,this.touchStartCount=e.touches.length}onTouchMove(e){if(this.isSwipePrevented(e.target))return!0;let t=this.Reveal.getConfig();if(this.touchCaptured)_&&e.preventDefault();else{this.Reveal.onUserInput(e);let n=e.touches[0].clientX,r=e.touches[0].clientY;if(e.touches.length===1&&this.touchStartCount!==2){let i=this.Reveal.availableRoutes({includeFragments:!0}),a=n-this.touchStartX,o=r-this.touchStartY;a>F&&Math.abs(a)>Math.abs(o)?(this.touchCaptured=!0,t.navigationMode===`linear`?t.rtl?this.Reveal.next():this.Reveal.prev():this.Reveal.left()):a<-40&&Math.abs(a)>Math.abs(o)?(this.touchCaptured=!0,t.navigationMode===`linear`?t.rtl?this.Reveal.prev():this.Reveal.next():this.Reveal.right()):o>F&&i.up?(this.touchCaptured=!0,t.navigationMode===`linear`?this.Reveal.prev():this.Reveal.up()):o<-40&&i.down&&(this.touchCaptured=!0,t.navigationMode===`linear`?this.Reveal.next():this.Reveal.down()),t.embedded?(this.touchCaptured||this.Reveal.isVerticalSlide())&&e.preventDefault():e.preventDefault()}}}onTouchEnd(e){this.touchCaptured&&!this.Reveal.slideContent.isAllowedToPlayAudio()&&this.Reveal.startEmbeddedContent(this.Reveal.getCurrentSlide()),this.touchCaptured=!1}getActiveTouches(){return Array.from(this.activePointers.values(),e=>({clientX:e.clientX,clientY:e.clientY}))}onPointerDown(e){e.pointerType===`touch`&&(this.activePointers.set(e.pointerId,e),e.touches=this.getActiveTouches(),this.onTouchStart(e))}onPointerMove(e){e.pointerType===`touch`&&(this.activePointers.set(e.pointerId,e),e.touches=this.getActiveTouches(),this.onTouchMove(e))}onPointerUp(e){e.pointerType===`touch`&&(this.activePointers.delete(e.pointerId), Line truncated
`):null}destroy(){this.element.remove()}},we=class{constructor(e,t){this.diameter=100,this.diameter2=this.diameter/2,this.thickness=6,this.playing=!1,this.progress=0,this.progressOffset=1,this.container=e,this.progressCheck=t,this.canvas=document.createElement(`canvas`),this.canvas.className=`playback`,this.canvas.width=this.diameter,this.canvas.height=this.diameter,this.canvas.style.width=this.diameter2+`px`,this.canvas.style.height=this.diameter2+`px`,this.context=this.canvas.getContext(`2d`),this.container.appendChild(this.canvas),this.render()}setPlaying(e){let t=this.playing;this.playing=e,!t&&this.playing?this.animate():this.render()}animate(){let e=this.progress;this.progress=this.progressCheck(),e>.8&&this.progress<.2&&(this.progressOffset=this.progress),this.render(),this.playing&&requestAnimationFrame(this.animate.bind(this))}render(){let e=this.playing?this.progress:0,t=this.diameter2-this.thickness,n=this.diameter2,r=this.diameter2;this.progressOffset+=(1-this.progressOffset)*.1;let i=-Math.PI/2+Math.PI*2*e,a=-Math.PI/2+this.progressOffset*(Math.PI*2);this.context.save(),this.context.clearRect(0,0,this.diameter,this.diameter),this.context.beginPath(),this.context.arc(n,r,t+4,0,Math.PI*2,!1),this.context.fillStyle=`rgba( 0, 0, 0, 0.4 )`,this.context.fill(),this.context.beginPath(),this.context.arc(n,r,t,0,Math.PI*2,!1),this.context.lineWidth=this.thickness,this.context.strokeStyle=`rgba( 255, 255, 255, 0.2 )`,this.context.stroke(),this.playing&&(this.context.beginPath(),this.context.arc(n,r,t,a,i,!1),this.context.lineWidth=this.thickness,this.context.strokeStyle=`#fff`,this.context.stroke()),this.context.translate(n-14,r-14),this.playing?(this.context.fillStyle=`#fff`,this.context.fillRect(0,0,10,28),this.context.fillRect(18,0,10,28)):(this.context.beginPath(),this.context.translate(4,0),this.context.moveTo(0,0),this.context.lineTo(24,14),this.context.lineTo(0,28),this.context.fillStyle=`#fff`,this.context.fill()),this.context.restore()}on(e,t){this.canvas.addEventListener(e,t,!1)}off(e,t){this.canvas.removeEventListener(e,t,!1)}destroy(){this.playing=!1,this.canvas.parentNode&&this.container.removeChild(this.canvas)}},Te={width:960,height:700,margin:.04,minScale:.2,maxScale:2,controls:!0,controlsTutorial:!0,controlsLayout:`bottom-right`,controlsBackArrows:`faded`,progress:!0,slideNumber:!1,showSlideNumber:`all`,hashOneBasedIndex:!1,hash:!1,respondToHashChanges:!0,jumpToSlide:!0,history:!1,keyboard:!0,keyboardCondition:null,disableLayout:!1,overview:!0,center:!0,touch:!0,loop:!1,rtl:!1,navigationMode:`default`,shuffle:!1,fragments:!0,fragmentInURL:!0,embedded:!1,help:!0,pause:!0,showNotes:!1,showHiddenSlides:!1,autoPlayMedia:null,preloadIframes:null,mouseWheel:!1,previewLinks:!1,viewDistance:3,mobileViewDistance:2,display:`block`,hideInactiveCursor:!0,hideCursorTime:5e3,sortFragmentsOnSync:!0,autoAnimate:!0,autoAnimateMatcher:null,autoAnimateEasing:`ease`,autoAnimateDuration:1,autoAnimateUnmatched:!0,autoAnimateStyles:[`opacity`,`color`,`background-color`,`padding`,`font-size`,`line-height`,`letter-spacing`,`border-width`,`border-color`,`border-radius`,`outline`,`outline-offset`],autoSlide:0,autoSlideStoppable:!0,autoSlideMethod:null,defaultTiming:null,postMessage:!0,postMessageEvents:!1,focusBodyOnPageVisibilityChange:!0,transition:`slide`,transitionSpeed:`default`,backgroundTransition:`fade`,parallaxBackgroundImage:``,parallaxBackgroundSize:``,parallaxBackgroundRepeat:``,parallaxBackgroundPosition:``,parallaxBackgroundHorizontal:null,parallaxBackgroundVertical:null,view:null,scrollLayout:`full`,scrollSnap:`mandatory`,scrollProgress:`auto`,scrollActivationWidth:435,pdfMaxPagesPerSlide:1/0,pdfSeparateFragments:!0,pdfPageHeightOffset:-1,dependencies:[],plugins:[]},Ee=`6.0.2`;function z(a,s){arguments.length<2&&(s=arguments[0],a=document.querySelector(`.reveal`));let l={},f={},p=!1,m=!1,h,_,v,y,b={hasNavigatedHorizontally:!1,hasNavigatedVertically:!1},x=[],S=1,T={layout:``,overview:``},D={},ie=`idle`,O=0,k,se=0,ce=-1,A=!1,j=new ee(l),M=new ne(l),N=new re(l),ve=new oe(l),F=new ae(l),I=new le(l),L=new ue(l),R=new de(l),z=new fe(l),B=new pe(l),V=new me(l),H=new he(l),U=new ge(l),De=new _e(l),W=new ye(l),G=new be(l),K=new Se(l),Oe=new xe(l),q=new Ce(l);function ke(e){if(!a)throw`Unable to find presentation root (<div class="reveal">).`;if(p)throw`Reveal.js has already been initialized.`;if(p=!0,D.wrapper=a,D.slides=a.querySelector(`.slides`),!D.slides)throw`Unable to find slides container (<div class="slides">).`;return f=P(P(P(P(P({},Te),f),s),e),u()),/print-pdf/gi.test(window.location.search)&&(f.view=`print`),Ae(),window.addEventListener(`load`,Y,!1),W.load(f.plugins,f.dependencies).then(je),new Promise(e=>l.on(`ready`,e))}function Ae(){f.embedded===!0?D.viewport=o(a,`.reveal-viewport`)||a:(D.viewport=document.body,document.documentElement.classList.add(`reveal-full-page`)),D.viewport.classList.add(`reveal-viewport`)}function je(){p!==!1&&(m=!0,Ne(),Pe(),Ve(),ze(),Be(),vt(),He(),F.update(!0),Me(),V Line truncated
+1
View File
@@ -102,6 +102,7 @@
<option value="blog" {{ if eq .HomeLayout "blog" }}selected{{ end }}>{{ T "periodical.blog" }}</option>
</select></label>
<label>{{ T "config.home_path" }}<input name="home_path" value="{{ .HomePath }}" placeholder="/home"></label>
<h3 class="wide">{{ T "home.domain_appearance_defaults" }} · <a href="/-/sys/config?panel=organizer#appearance">{{ T "organizer.settings" }} ↗</a></h3>
<label class="wide">{{ T "home.wallpaper_path" }}<span class="config-path-control"><input id="home-wallpaper-path" name="home_wallpaper_path" value="{{ .HomeWallpaperPath }}" placeholder="/wallpapers"><button type="button" data-path-picker data-picker-target="home-wallpaper-path" data-picker-mode="image-or-folder" aria-label="{{ T "picker.open" }}" title="{{ T "picker.open" }}">⌕</button></span></label>
<label class="wide">{{ T "home.wallpaper_opacity" }}<span class="config-range-control"><input name="home_wallpaper_opacity" type="range" min="0" max="100" step="1" value="{{ .HomeWallpaperOpacity }}" data-range-output="home-wallpaper-opacity-output"><output id="home-wallpaper-opacity-output">{{ .HomeWallpaperOpacity }}%</output></span></label>
<p class="muted wide">{{ T "home.wallpaper_help" }}</p>
+18 -8
View File
@@ -22,13 +22,15 @@
<link rel="stylesheet" href="/static/css/theme/base.css">
<link rel="stylesheet" href="/static/css/content-viewer.css">
{{ if .CSVEditor }}<link rel="stylesheet" href="/static/css/csv-editor.css?v=1">{{ end }}
{{ if .SlidesEnabled }}<link rel="stylesheet" href="/static/css/slides.css?v=1"><script defer src="/static/js/slides.js?v=1"></script>{{ end }}
<link rel="stylesheet" href="{{ .ThemeCSS }}">
<script defer src="/static/js/content-viewer.js?v=macro-projection-1"></script>
<script
type="module"
src="/static/vendor/codemirror/editor.bundle.js?v=command-ux-1"
src="/static/vendor/codemirror/editor.bundle.js?v=csv-edit-1"
></script>
@@ -39,7 +41,7 @@
</head>
<body class="mode-editor">
<body class="mode-editor{{ if .CSVEditor }} csv-editor{{ end }}">
<header class="topbar">
@@ -129,6 +131,7 @@
<div class="editor-head-right">
{{ if and (ne .EditType "code") (ne .EditType "plain") }}
{{ if .SlidesEnabled }}<button type="button" class="editor-action-icon" data-editor-action="slides" aria-pressed="false" title="{{ T "slides.preview" }}" aria-label="{{ T "slides.preview" }}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 4h18v12H3zM12 16v5m-5 0 5-5 5 5M8 8h8m-8 4h5"/></svg></button>{{ end }}
<button
type="button"
class="editor-format-icon {{ if eq .EditType "html" }}active{{ end }}"
@@ -165,8 +168,8 @@
aria-pressed="true"
aria-label="{{ T "editor.hide_preview" }}"
title="{{ T "editor.hide_preview" }}"
data-hide-label="{{ T "editor.hide_preview" }}"
data-show-label="{{ T "editor.show_preview" }}"
data-hide-label="{{ if .CSVEditor }}{{ T "editor.csv_source" }}{{ else }}{{ T "editor.hide_preview" }}{{ end }}"
data-show-label="{{ if .CSVEditor }}{{ T "editor.csv_table" }}{{ else }}{{ T "editor.show_preview" }}{{ end }}"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="3" y="4" width="18" height="16" rx="2"/>
@@ -204,6 +207,7 @@
data-base-revision="{{ .BaseRevision }}"
data-domain="{{ .Context.Domain.UUID }}"
data-owner="{{ if .AuthUser }}{{ .AuthUser.UUID }}{{ end }}"
data-csv="{{ .CSVEditor }}"
></div>
<div
@@ -215,7 +219,7 @@
MODE
</span>
<span id="editor-format-status">
{{ .EditType }}
{{ if .CSVEditor }}CSV{{ else }}{{ .EditType }}{{ end }}
</span>
</div>
@@ -272,7 +276,8 @@ Ln 1, Col 1
</main>
<script src="/static/js/editor-core.js?v=priority-ux-1"></script>
<script src="/static/js/editor.js?v=priority-ux-1"></script>
{{ if .CSVEditor }}<script>window.PagesCSVSource = {{ .Body }};</script><script src="/static/js/csv-core.js?v=2"></script><script src="/static/js/csv-editor.js?v=2"></script>{{ end }}
<script src="/static/js/editor.js?v=slides-1"></script>
<script src="/static/js/path-actions.js"></script>
@@ -295,12 +300,13 @@ window.addEventListener(
const cm =
window.PagesWikiEditor.create(
mount,
textarea.value,
window.PagesEditor?.text() ?? textarea.value,
"{{ .EditType }}",
{
keymap: mount.dataset.keymap,
syntax: mount.dataset.syntax === "true",
autocomplete: mount.dataset.autocomplete === "true",
preserveLineEndings: mount.dataset.csv === "true",
}
)
@@ -308,7 +314,11 @@ window.addEventListener(
cm
cm.focus()
setTimeout(() => cm.focus(), 0)
setTimeout(() => {
// Do not steal focus from a table cell or toolbar clicked while
// the editor was initializing.
if (document.activeElement === document.body || mount.contains(document.activeElement)) cm.focus()
}, 0)
window.PagesWikiGetEditorText =
() => window.PagesWikiCodeMirror.state.doc.toString()
+1 -1
View File
@@ -6,4 +6,4 @@
<main id="feeds-app" data-timezone="{{ .FeedTimezone }}" 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 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=11" defer></script></body></html>{{ end }}
</main><script src="/static/js/feeds.js?v=12" defer></script></body></html>{{ end }}
+2 -2
View File
@@ -1,7 +1,7 @@
{{ define "organizer_dashboard.gohtml" }}<!doctype html>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ T "organizer.dashboard" }} · {{ .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/task-productivity.css?v=3"><link rel="stylesheet" href="/static/css/organizer.css?v=1"></head>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ T "organizer.dashboard" }} · {{ .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/task-productivity.css?v=3"><link rel="stylesheet" href="/static/css/organizer.css?v=3"></head>
<body class="mode-view organizer-page"><header class="topbar"><div class="brand"><a href="/">{{ .WikiName }}</a></div>{{ template "auth-menu" . }}</header>
{{ template "organizer-nav" . }}
<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>
</main><script src="/static/js/organizer-dashboard.js?v=2" defer></script><script src="/static/js/task-productivity.js?v=8" defer></script></body></html>{{ end }}
</main><script src="/static/js/task-presentation.js?v=1" defer></script><script src="/static/js/dashboard-commands.js?v=1" defer></script><script src="/static/js/organizer-dashboard.js?v=5" defer></script><script src="/static/js/task-productivity.js?v=8" defer></script></body></html>{{ end }}
+2 -1
View File
@@ -1,8 +1,9 @@
{{ define "organizer_settings.gohtml" }}<!doctype html>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ T "organizer.settings" }} · {{ .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/config.css"><link rel="stylesheet" href="/static/css/task-productivity.css?v=3"><link rel="stylesheet" href="/static/css/organizer.css?v=1"></head>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ T "organizer.settings" }} · {{ .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/config.css"><link rel="stylesheet" href="/static/css/task-productivity.css?v=3"><link rel="stylesheet" href="/static/css/organizer.css?v=3"></head>
<body class="mode-config organizer-page"><header class="topbar"><div class="brand"><a href="/">{{ .WikiName }}</a></div>{{ template "auth-menu" . }}</header>{{ template "organizer-nav" . }}
<main class="config-main"><div class="config-layout"><aside class="config-sidebar"><nav class="sidebar-nav"><a href="/-/sys/config?panel=organizer" aria-current="page">{{ T "organizer.settings" }}</a>{{ if .TasksEnabled }}<a href="#task-productivity">{{ T "tasks.title" }}</a>{{ end }}{{ if .CalendarEnabled }}<a href="#organizer-calendar-defaults">{{ T "organizer.calendar_defaults" }}</a>{{ end }}{{ if .ContactsEnabled }}<a href="/v/plan/contacts">{{ T "organizer.contacts" }} ↗</a>{{ end }}{{ if .AuthIsAdmin }}<a href="/-/sys/config">{{ T "config.title" }} ↗</a>{{ end }}</nav></aside>
<section class="organizer-settings-content"><h1>{{ T "organizer.settings" }}</h1><p>{{ T "organizer.private" }}</p>
<section id="appearance"><h2>{{ T "home.appearance" }}</h2><form class="personal-appearance" method="post" action="/-/sys/config?panel=organizer&amp;section=appearance"><fieldset {{ if not .TaskWritable }}disabled{{ end }}><input type="hidden" name="version" value="{{ .AppearanceVersion }}">{{ template "personal-wallpaper-controls" . }}<label>{{ T "home.glass_transparency" }}<input name="home_glass_transparency" type="number" min="0" max="85" value="{{ .HomeGlassTransparency }}"></label>{{ template "home-palette-controls" . }}<button type="submit">{{ T "config.save" }}</button></fieldset></form></section>
{{ 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 .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 }}
+1
View File
@@ -80,6 +80,7 @@
</div>
{{ if .ObjectUUID }}
{{ if and .SlidesEnabled (eq .ContentView.Kind "html") }}<a class="breadcrumb-action-icon" href="/v/slides{{ .Path }}" title="{{ T "slides.title" }}" aria-label="{{ T "slides.title" }}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 4h18v12H3zM12 16v5m-5 0 5-5 5 5M8 8h8m-8 4h5"/></svg></a>{{ end }}
<a class="breadcrumb-action-icon" href="/_/view/print/uuid:{{ .ObjectUUID }}" title="{{ T "viewer.print" }}" aria-label="{{ T "viewer.print" }}">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 9V4h10v5M7 17H5a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2M7 14h10v6H7z"></path></svg>
</a>
+12
View File
@@ -0,0 +1,12 @@
{{ define "slides.gohtml" }}
<!doctype html><html lang="{{ .Locale }}"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{ .Title }} · {{ .WikiName }}</title>
<link rel="stylesheet" href="/static/css/main.css"><link rel="stylesheet" href="/static/css/theme/base.css"><link rel="stylesheet" href="{{ .ThemeCSS }}">
<link rel="stylesheet" href="/static/css/slides.css?v=1"><script defer src="/static/js/slides.js?v=1"></script>
</head><body class="slides-page">
<header class="topbar"><a href="{{ .Path }}" aria-label="{{ T "slides.close" }}" title="{{ T "slides.close" }}">←</a><span>{{ .Path }}</span><button type="button" data-slides-fullscreen title="{{ T "slides.fullscreen" }}" aria-label="{{ T "slides.fullscreen" }}">⛶</button></header>
<main data-slides-viewer data-path="{{ .Path }}" data-error="{{ T "slides.error" }}"></main>
<textarea data-slides-source hidden>{{ .SlideSource }}</textarea>
</body></html>
{{ end }}
+1 -1
View File
@@ -1,5 +1,5 @@
{{ define "task_work_history.gohtml" }}<!doctype html>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ T "task.work_history" }} · {{ .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/organizer.css?v=1"><link rel="stylesheet" href="/static/css/task-work-history.css?v=1"></head>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ T "task.work_history" }} · {{ .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/organizer.css?v=3"><link rel="stylesheet" href="/static/css/task-work-history.css?v=1"></head>
<body class="mode-view organizer-page"><header class="topbar"><div class="brand"><a href="/">{{ .WikiName }}</a></div>{{ template "auth-menu" . }}</header>{{ template "organizer-nav" . }}
<main id="task-work-history" data-writable="{{ .TaskWritable }}" data-timezone="{{ .Timezone }}"><header><h1>{{ T "task.work_history" }}</h1><a href="/v/plan/dashboard#activity">{{ T "organizer.dashboard" }}</a></header><p id="work-history-status" role="status" aria-live="polite"></p><div id="work-history-controls"></div><div id="work-history-list"></div><div id="work-history-paging"></div></main>
<script src="/static/js/task-work-history.js?v=1" defer></script></body></html>{{ end }}
+2 -2
View File
@@ -1,6 +1,6 @@
{{ define "tasks.gohtml" }}<!doctype html>
<html lang="{{ .Locale }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ T "tasks.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/tasks.css?v=11"></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/tasks.css?v=12">{{ if eq .TaskView "index" }}<link rel="stylesheet" href="/static/css/task-index.css?v=1">{{ end }}</head>
<body class="mode-view organizer-page"><header class="topbar"><div class="brand"><a href="/">{{ .WikiName }}</a></div>{{ template "auth-menu" . }}</header>{{ template "organizer-nav" . }}
<main id="tasks-app" data-view="{{ .TaskView }}" data-id="{{ .TaskID }}" data-today="{{ .TaskToday }}" data-selected-date="{{ .TaskSelectedDate }}" data-timezone="{{ .TaskTimezone }}" data-writable="{{ .TaskWritable }}">
<nav id="tasks-nav" aria-label="Tasks"></nav><section class="tasks-workspace">
@@ -11,4 +11,4 @@
<p id="tasks-status" role="status" aria-live="polite"></p><div class="tasks-list-scroll"><div id="tasks-list" role="list"></div></div><button type="button" id="tasks-more" hidden></button>
</section>
<dialog id="tasks-dialog" aria-labelledby="tasks-dialog-title"><form id="tasks-form"><header class="tasks-toolbar"><h2 id="tasks-dialog-title"></h2><button type="button" id="tasks-close">×</button></header><div id="tasks-fields"></div><p id="tasks-error" role="alert"></p><details id="tasks-history"><summary></summary><ol></ol></details><footer class="tasks-actions"><button type="button" id="tasks-archive"></button><button type="button" id="tasks-delete" class="danger" hidden></button><a id="tasks-page-open" class="task-footer-link" target="_blank" rel="noopener noreferrer" hidden></a><a id="tasks-project-open" class="task-footer-link" hidden></a><button type="submit" id="tasks-save"></button></footer></form></dialog>
</main><link rel="stylesheet" href="/static/css/dav-settings.css?v=3"><script src="/static/js/task-inline.js?v=4" defer></script><script src="/static/js/task-today.js?v=1" defer></script><script src="/static/js/task-planning.js?v=3" defer></script><script src="/static/js/task-focus.js?v=2" defer></script><script src="/static/js/task-work.js?v=1" defer></script><script src="/static/js/tasks.js?v=11" defer></script><script src="/static/js/task-dav-settings.js?v=4" defer></script></body></html>{{ end }}
</main><link rel="stylesheet" href="/static/css/dav-settings.css?v=3"><script src="/static/js/task-presentation.js?v=1" defer></script><script src="/static/js/task-inline.js?v=5" defer></script><script src="/static/js/task-today.js?v=1" defer></script><script src="/static/js/task-planning.js?v=3" defer></script><script src="/static/js/task-focus.js?v=2" defer></script><script src="/static/js/task-work.js?v=1" defer></script>{{ if eq .TaskView "index" }}<script src="/static/js/task-index.js?v=1" defer></script>{{ end }}<script src="/static/js/tasks.js?v=13" defer></script><script src="/static/js/task-dav-settings.js?v=4" defer></script></body></html>{{ end }}
+1 -1
View File
@@ -13,7 +13,7 @@
<link rel="stylesheet" href="/static/css/notifications.css?v=3">
<link rel="stylesheet" href="/static/css/notification-active.css?v=1">
<link rel="stylesheet" href="/static/css/nav-modals.css?v=3">
<link rel="stylesheet" href="/static/css/organizer.css?v=1">
<link rel="stylesheet" href="/static/css/organizer.css?v=3">
<button type="button" class="city-map-launch" data-city-map-launch aria-label="{{ T "city.map" }}" title="{{ T "city.map" }}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m3 6 5-3 8 3 5-3v15l-5 3-8-3-5 3V6Zm5-1v11m8-8v11M5 7.2v10.3l3-1.8 8 3 3-1.8V6.5l-3 1.8-8-3L5 7.2Z"/></svg></button>
<dialog class="city-map-dialog" data-city-map-dialog aria-label="{{ T "city.map" }}"><div class="city-map-dialog-head"><strong>{{ T "city.map" }}</strong><a href="/v/city">↗</a><button type="button" data-city-map-close aria-label="Close">×</button></div><iframe title="{{ T "city.map" }}" data-city-map-frame data-src="/v/city?popup=1"></iframe></dialog>
{{ if .AuthUser }}<button type="button" class="notification-launch" data-notification-launch aria-label="{{ T "notification.title" }}" title="{{ T "notification.title" }}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M18 9a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4"/></svg><span class="notification-badge" data-notification-badge hidden></span></button><dialog class="notification-dialog" data-notification-dialog data-owner="{{ .AuthUser.UUID }}" data-domain="{{ .Context.Domain.UUID }}" aria-label="{{ T "notification.title" }}"><form method="dialog"><header><h2>{{ T "notification.title" }}</h2><button type="button" data-notification-close aria-label="Close">×</button></header><div class="notifications-list" data-notifications-list></div><footer><a href="/v/notification">{{ T "notification.all" }}</a></footer></form></dialog>{{ end }}
+8 -3
View File
@@ -11,19 +11,24 @@
{{ if .CanConfigureHome }}
<button type="button" class="home-appearance-launch" data-home-appearance-open aria-label="{{ T "home.appearance" }}" title="{{ T "home.appearance" }}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m9 3-.5 3-2 .9L4 6l-2 4 2.5 1.8v2.4L2 16l2 4 2.5-.9 2 .9.5 3h6l.5-3 2-.9L20 20l2-4-2.5-1.8v-2.4L22 10l-2-4-2.5.9-2-.9-.5-3z"/><circle cx="12" cy="13" r="3"/></svg></button>
<dialog class="home-appearance-dialog" data-home-appearance-dialog aria-labelledby="home-appearance-title">
<form method="post" action="/-/sys/config" data-home-appearance-form data-saved="{{ T "config.saved" }}">
<input type="hidden" name="section" value="home-appearance">
<form method="post" action="/-/sys/config?panel=organizer&amp;section=appearance" data-home-appearance-form data-saved="{{ T "config.saved" }}">
<input type="hidden" name="version" value="{{ .AppearanceVersion }}">
<header><h2 id="home-appearance-title">{{ T "home.appearance" }}</h2><button type="button" data-home-appearance-close aria-label="{{ T "picker.cancel" }}">×</button></header>
{{ template "personal-wallpaper-controls" . }}
<label>{{ T "home.glass_transparency" }}<span class="home-appearance-range"><input name="home_glass_transparency" type="range" min="0" max="85" step="1" value="{{ .HomeGlassTransparency }}"><output>{{ .HomeGlassTransparency }}%</output></span></label>
<p class="muted">{{ T "home.glass_help" }}</p>
{{ template "home-palette-controls" . }}
<footer><span data-home-appearance-status role="status"></span><button type="button" data-home-appearance-cancel>{{ T "picker.cancel" }}</button><button type="submit">{{ T "config.save" }}</button></footer>
</form>
</dialog>
<script defer src="/static/js/home-appearance.js?v=2"></script>
<script defer src="/static/js/home-appearance.js?v=3"></script>
{{ end }}
{{ end }}
{{ end }}
{{ define "personal-wallpaper-controls" }}
<label>{{ T "home.personal_wallpaper" }}<input type="text" name="home_wallpaper_path" value="{{ .HomeWallpaperPath }}" placeholder="/wallpapers" maxlength="4096"></label>
<label>{{ T "home.personal_opacity" }}<input type="number" name="home_wallpaper_opacity" value="{{ .HomeWallpaperPercent }}" min="0" max="100"></label>
{{ end }}
{{ define "home-palette" }}
{{ if and .IsHome .HomeWallpaperURL }}
<div hidden data-home-palette data-mode="{{ .HomePalette.Mode }}" data-strength="{{ .HomePalette.Strength }}" data-brightness="{{ .HomePalette.Brightness }}" data-key="{{ .HomeWallpaperKey }}" data-domain="{{ .HomePaletteDomain }}"></div>
+1 -1
View File
@@ -1,5 +1,5 @@
{{ define "organizer-nav" }}
<link rel="stylesheet" href="/static/css/organizer.css?v=2">
<link rel="stylesheet" href="/static/css/organizer.css?v=3">
<nav class="organizer-nav" aria-label="{{ T "organizer.title" }}">
{{ if .FeedsEnabled }}<a href="/v/feeds" title="{{ T "feeds.title" }}" aria-label="{{ T "feeds.title" }}" {{ if eq .OrganizerSection "feeds" }}aria-current="page"{{ end }}>◉ <span>{{ T "feeds.title" }}</span></a>{{ end }}
{{ if .TasksEnabled }}<a href="/v/plan/dashboard" title="{{ T "organizer.dashboard" }}" aria-label="{{ T "organizer.dashboard" }}" {{ if eq .OrganizerSection "dashboard" }}aria-current="page"{{ end }}>▦ <span>{{ T "organizer.dashboard" }}</span></a><a href="/v/plan/tasks" title="{{ T "tasks.title" }}" aria-label="{{ T "tasks.title" }}" {{ if eq .OrganizerSection "tasks" }}aria-current="page"{{ end }}>✓ <span>{{ T "tasks.title" }}</span></a>{{ end }}