Trilium als Archiv: verwaltete Instanz pro Projekt, MD-Archiv und Dokument-Tab entfernt
- domain/trilium.rs: Runtime-Download (gepinnt 0.104.0), Instanz pro Projekt auf 127.0.0.1 mit FNV-Port, ETAPI (archive_note, search_notes), Token im Keyring - Setup bis aufs Passwort automatisiert: trilium_connect macht new-document (skipDemoDb), set-password und ETAPI-Login; Modul-Flag erst nach Token-Erfolg - write_panel legt direkt eine Trilium-Notiz an (text|path, folder/description/tags); noteopen-Kanal, das Terminal-Fenster öffnet die Notiz (ersetzt archive_panel) - MD-Altbestand raus: archive*/wiki*, archiveHome samt Permissions, panel_set/panel_load/ wiki_open, panel_archive*/archive_docs/*_archive_home, reveal_path, spellcheck - Dokument-Tab raus: Panel = ToDo/Befehle/Suche + Archiv-Knopf (trilium_open); panel-view/archive-form gelöscht, Markup/CSS/Messages bereinigt - Lösch-Stufe Archiv: Instanz stoppen, Trilium-Datadir und Keyring-Token löschen
This commit is contained in:
+3
-29
@@ -2,7 +2,7 @@
|
|||||||
<html lang="de">
|
<html lang="de">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<title data-i18n="panel.windowDocument">Dokument</title>
|
<title data-i18n="panel.windowPanel">Panel</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="panel-topbar" data-tauri-drag-region>
|
<div class="panel-topbar" data-tauri-drag-region>
|
||||||
@@ -21,38 +21,12 @@
|
|||||||
<svg width="12" height="12" viewBox="0 0 12 12"><path d="M3 3l6 6M9 3l-6 6" /></svg>
|
<svg width="12" height="12" viewBox="0 0 12 12"><path d="M3 3l6 6M9 3l-6 6" /></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Modul-Container (<mode>-content) reihen sich hinter der Kopfzeile ein. -->
|
||||||
<div class="panel-head">
|
<div class="panel-head">
|
||||||
<div class="panel-titlerow" data-tauri-drag-region>
|
<div class="panel-titlerow" data-tauri-drag-region>
|
||||||
<span class="panel-title" data-i18n="panel.tabDraft">Dokument</span>
|
<span class="panel-title"></span>
|
||||||
<button class="panel-btn panel-edit draft-only" id="panel-title-edit" data-i18n-title="panel.editTitle">✎</button>
|
|
||||||
</div>
|
|
||||||
<div class="panel-actions">
|
|
||||||
<select class="panel-lang draft-only" id="panel-lang" data-i18n-title="panel.spellcheckLang">
|
|
||||||
<option value="de">DE</option>
|
|
||||||
<option value="en">EN</option>
|
|
||||||
<option value="en-GB">EN-GB</option>
|
|
||||||
<option value="fr">FR</option>
|
|
||||||
<option value="es">ES</option>
|
|
||||||
<option value="it">IT</option>
|
|
||||||
<option value="nl">NL</option>
|
|
||||||
</select>
|
|
||||||
<button class="panel-btn draft-only" id="panel-wiki-jump" data-i18n-title="panel.openInWiki">
|
|
||||||
<svg width="14" height="14" viewBox="0 0 16 16"><path d="M8 3.5C6.6 2.4 4.6 2 2.5 2v11c2.1 0 4.1.4 5.5 1.5 1.4-1.1 3.4-1.5 5.5-1.5V2c-2.1 0-4.1.4-5.5 1.5z" /><path d="M8 3.5v11" /></svg>
|
|
||||||
</button>
|
|
||||||
<button class="panel-btn draft-only" id="panel-mode" data-i18n-title="panel.toggleRaw" data-i18n="panel.rendered">MD</button>
|
|
||||||
<button class="panel-btn draft-only" id="panel-content-edit" data-i18n-title="panel.editDraft">
|
|
||||||
<svg width="14" height="14" viewBox="0 0 16 16"><path d="M10.8 2.6 13.4 5.2 6 12.6l-3.1.5.5-3.1z" /><path d="M9.7 3.7 12.3 6.3" /></svg>
|
|
||||||
</button>
|
|
||||||
<button class="panel-btn draft-only" id="panel-copy" data-i18n-title="panel.copy">
|
|
||||||
<svg width="14" height="14" viewBox="0 0 16 16"><rect x="5.5" y="5.5" width="8" height="8" rx="1.5" /><path d="M10.5 3.2V3A1.5 1.5 0 0 0 9 1.5H3A1.5 1.5 0 0 0 1.5 3v6A1.5 1.5 0 0 0 3 10.5h.2" /></svg>
|
|
||||||
</button>
|
|
||||||
<button class="panel-btn draft-only" id="panel-archive" data-i18n-title="panel.archive">
|
|
||||||
<svg width="14" height="14" viewBox="0 0 16 16"><rect x="1.5" y="2.5" width="13" height="3.5" rx="1" /><path d="M2.8 6v6.5a1 1 0 0 0 1 1h8.4a1 1 0 0 0 1-1V6" /><path d="M6.3 9h3.4" /></svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- Modul-Container (<mode>-content) reihen sich hier ein. -->
|
|
||||||
<div id="panel-content" class="md"></div>
|
|
||||||
<div id="resize-grips" aria-hidden="true">
|
<div id="resize-grips" aria-hidden="true">
|
||||||
<div class="grip n" data-dir="North"></div>
|
<div class="grip n" data-dir="North"></div>
|
||||||
<div class="grip s" data-dir="South"></div>
|
<div class="grip s" data-dir="South"></div>
|
||||||
|
|||||||
Generated
+26
-75
@@ -19,18 +19,6 @@ dependencies = [
|
|||||||
"version_check",
|
"version_check",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "ahash"
|
|
||||||
version = "0.8.12"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"once_cell",
|
|
||||||
"version_check",
|
|
||||||
"zerocopy",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aho-corasick"
|
name = "aho-corasick"
|
||||||
version = "1.1.4"
|
version = "1.1.4"
|
||||||
@@ -54,8 +42,8 @@ dependencies = [
|
|||||||
"objc2-app-kit",
|
"objc2-app-kit",
|
||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
"portable-pty",
|
"portable-pty",
|
||||||
|
"pulldown-cmark",
|
||||||
"rfd 0.15.4",
|
"rfd 0.15.4",
|
||||||
"rusqlite",
|
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
@@ -1256,18 +1244,6 @@ dependencies = [
|
|||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "fallible-iterator"
|
|
||||||
version = "0.3.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "fallible-streaming-iterator"
|
|
||||||
version = "0.1.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fastrand"
|
name = "fastrand"
|
||||||
version = "2.4.1"
|
version = "2.4.1"
|
||||||
@@ -1803,16 +1779,7 @@ version = "0.12.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ahash 0.7.8",
|
"ahash",
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "hashbrown"
|
|
||||||
version = "0.14.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
|
||||||
dependencies = [
|
|
||||||
"ahash 0.8.12",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1830,15 +1797,6 @@ version = "0.17.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "hashlink"
|
|
||||||
version = "0.9.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
|
|
||||||
dependencies = [
|
|
||||||
"hashbrown 0.14.5",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "heck"
|
name = "heck"
|
||||||
version = "0.4.1"
|
version = "0.4.1"
|
||||||
@@ -2367,17 +2325,6 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "libsqlite3-sys"
|
|
||||||
version = "0.30.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
|
|
||||||
dependencies = [
|
|
||||||
"cc",
|
|
||||||
"pkg-config",
|
|
||||||
"vcpkg",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "linux-raw-sys"
|
name = "linux-raw-sys"
|
||||||
version = "0.12.1"
|
version = "0.12.1"
|
||||||
@@ -3172,6 +3119,24 @@ dependencies = [
|
|||||||
"syn 1.0.109",
|
"syn 1.0.109",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pulldown-cmark"
|
||||||
|
version = "0.12.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f86ba2052aebccc42cbbb3ed234b8b13ce76f75c3551a303cb2bcffcff12bb14"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.0",
|
||||||
|
"memchr",
|
||||||
|
"pulldown-cmark-escape",
|
||||||
|
"unicase",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pulldown-cmark-escape"
|
||||||
|
version = "0.11.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pxfm"
|
name = "pxfm"
|
||||||
version = "0.1.29"
|
version = "0.1.29"
|
||||||
@@ -3465,20 +3430,6 @@ dependencies = [
|
|||||||
"syn 1.0.109",
|
"syn 1.0.109",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rusqlite"
|
|
||||||
version = "0.32.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
|
|
||||||
dependencies = [
|
|
||||||
"bitflags 2.13.0",
|
|
||||||
"fallible-iterator",
|
|
||||||
"fallible-streaming-iterator",
|
|
||||||
"hashlink",
|
|
||||||
"libsqlite3-sys",
|
|
||||||
"smallvec",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rust_decimal"
|
name = "rust_decimal"
|
||||||
version = "1.42.1"
|
version = "1.42.1"
|
||||||
@@ -4930,6 +4881,12 @@ dependencies = [
|
|||||||
"unic-common",
|
"unic-common",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicase"
|
||||||
|
version = "2.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.24"
|
version = "1.0.24"
|
||||||
@@ -5009,12 +4966,6 @@ version = "1.12.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"
|
checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "vcpkg"
|
|
||||||
version = "0.2.15"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vec_map"
|
name = "vec_map"
|
||||||
version = "0.8.2"
|
version = "0.8.2"
|
||||||
|
|||||||
@@ -34,8 +34,8 @@ base64 = "0.22"
|
|||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
portable-pty = "0.9"
|
portable-pty = "0.9"
|
||||||
uuid = { version = "1", features = ["v4"] }
|
uuid = { version = "1", features = ["v4"] }
|
||||||
# Volltext-Suche übers Panel-Archiv (SQLite FTS5, in-memory aus dem Baum gebaut).
|
# Markdown→HTML beim Archivieren in Trilium (Notizen sind HTML).
|
||||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
pulldown-cmark = { version = "0.12", default-features = false, features = ["html"] }
|
||||||
keyring = { version = "3", features = ["apple-native", "sync-secret-service", "windows-native"] }
|
keyring = { version = "3", features = ["apple-native", "sync-secret-service", "windows-native"] }
|
||||||
|
|
||||||
[target.'cfg(target_os = "linux")'.dependencies]
|
[target.'cfg(target_os = "linux")'.dependencies]
|
||||||
|
|||||||
+5
-17
@@ -41,14 +41,11 @@ fn main() {
|
|||||||
"oauth_login",
|
"oauth_login",
|
||||||
"keychain_status",
|
"keychain_status",
|
||||||
"set_apikey",
|
"set_apikey",
|
||||||
"panel_archive_dir_cmd",
|
"trilium_status",
|
||||||
"panel_archive_cmd",
|
"trilium_setup",
|
||||||
"set_archive_home_cmd",
|
"trilium_connect",
|
||||||
"change_archive_home_cmd",
|
"trilium_open",
|
||||||
"clear_archive_home_cmd",
|
"trilium_disable",
|
||||||
"archive_docs_cmd",
|
|
||||||
"reveal_path_cmd",
|
|
||||||
"spellcheck_lang",
|
|
||||||
"open_terminal",
|
"open_terminal",
|
||||||
"term_start",
|
"term_start",
|
||||||
"term_log",
|
"term_log",
|
||||||
@@ -62,16 +59,7 @@ fn main() {
|
|||||||
"todos_delete",
|
"todos_delete",
|
||||||
"todos_add",
|
"todos_add",
|
||||||
"todos_update",
|
"todos_update",
|
||||||
"panel_set",
|
|
||||||
"search_run",
|
"search_run",
|
||||||
"panel_load",
|
|
||||||
"wiki_open",
|
|
||||||
"archive_move",
|
|
||||||
"archive_rename",
|
|
||||||
"archive_delete",
|
|
||||||
"archive_move_folder",
|
|
||||||
"archive_create_folder",
|
|
||||||
"archive_create_doc",
|
|
||||||
"open_panel_window",
|
"open_panel_window",
|
||||||
])),
|
])),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -48,14 +48,14 @@
|
|||||||
"allow-oauth-login",
|
"allow-oauth-login",
|
||||||
"allow-keychain-status",
|
"allow-keychain-status",
|
||||||
"allow-set-apikey",
|
"allow-set-apikey",
|
||||||
"allow-panel-archive-dir-cmd",
|
|
||||||
"allow-set-archive-home-cmd",
|
|
||||||
"allow-clear-archive-home-cmd",
|
|
||||||
"allow-archive-docs-cmd",
|
|
||||||
"allow-delete-preview",
|
"allow-delete-preview",
|
||||||
"allow-delete-project-scoped",
|
"allow-delete-project-scoped",
|
||||||
"allow-change-archive-home-cmd",
|
|
||||||
"allow-module-registry",
|
"allow-module-registry",
|
||||||
"allow-set-module"
|
"allow-set-module",
|
||||||
|
"allow-trilium-status",
|
||||||
|
"allow-trilium-setup",
|
||||||
|
"allow-trilium-connect",
|
||||||
|
"allow-trilium-open",
|
||||||
|
"allow-trilium-disable"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,27 +20,15 @@
|
|||||||
"autostart:default",
|
"autostart:default",
|
||||||
"dialog:default",
|
"dialog:default",
|
||||||
"clipboard-manager:allow-write-text",
|
"clipboard-manager:allow-write-text",
|
||||||
"allow-archive-create-doc",
|
|
||||||
"allow-archive-create-folder",
|
|
||||||
"allow-archive-delete",
|
|
||||||
"allow-archive-move",
|
|
||||||
"allow-archive-move-folder",
|
|
||||||
"allow-archive-rename",
|
|
||||||
"allow-buffer-read",
|
"allow-buffer-read",
|
||||||
"allow-commands-delete",
|
"allow-commands-delete",
|
||||||
"allow-enabled-modules",
|
"allow-enabled-modules",
|
||||||
"allow-list-projects",
|
"allow-list-projects",
|
||||||
"allow-panel-archive-cmd",
|
"allow-trilium-open",
|
||||||
"allow-panel-archive-dir-cmd",
|
|
||||||
"allow-panel-load",
|
|
||||||
"allow-panel-set",
|
|
||||||
"allow-reveal-path-cmd",
|
|
||||||
"allow-search-run",
|
"allow-search-run",
|
||||||
"allow-spellcheck-lang",
|
|
||||||
"allow-term-log",
|
"allow-term-log",
|
||||||
"allow-todos-add",
|
"allow-todos-add",
|
||||||
"allow-todos-delete",
|
"allow-todos-delete",
|
||||||
"allow-todos-update",
|
"allow-todos-update"
|
||||||
"allow-wiki-open"
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,27 +20,16 @@
|
|||||||
"autostart:default",
|
"autostart:default",
|
||||||
"dialog:default",
|
"dialog:default",
|
||||||
"clipboard-manager:allow-write-text",
|
"clipboard-manager:allow-write-text",
|
||||||
"allow-archive-create-doc",
|
|
||||||
"allow-archive-create-folder",
|
|
||||||
"allow-archive-delete",
|
|
||||||
"allow-archive-move",
|
|
||||||
"allow-archive-move-folder",
|
|
||||||
"allow-archive-rename",
|
|
||||||
"allow-buffer-read",
|
"allow-buffer-read",
|
||||||
"allow-commands-delete",
|
"allow-commands-delete",
|
||||||
"allow-enabled-modules",
|
"allow-enabled-modules",
|
||||||
"allow-list-projects",
|
"allow-list-projects",
|
||||||
"allow-open-panel-window",
|
"allow-open-panel-window",
|
||||||
"allow-panel-archive-cmd",
|
"allow-trilium-open",
|
||||||
"allow-panel-archive-dir-cmd",
|
|
||||||
"allow-panel-load",
|
|
||||||
"allow-panel-set",
|
|
||||||
"allow-pool-label",
|
"allow-pool-label",
|
||||||
"allow-project-icon",
|
"allow-project-icon",
|
||||||
"allow-reveal-path-cmd",
|
|
||||||
"allow-search-run",
|
"allow-search-run",
|
||||||
"allow-set-terminal-font-size",
|
"allow-set-terminal-font-size",
|
||||||
"allow-spellcheck-lang",
|
|
||||||
"allow-term-log",
|
"allow-term-log",
|
||||||
"allow-term-resize",
|
"allow-term-resize",
|
||||||
"allow-term-start",
|
"allow-term-start",
|
||||||
@@ -48,7 +37,6 @@
|
|||||||
"allow-terminal-font-size",
|
"allow-terminal-font-size",
|
||||||
"allow-todos-add",
|
"allow-todos-add",
|
||||||
"allow-todos-delete",
|
"allow-todos-delete",
|
||||||
"allow-todos-update",
|
"allow-todos-update"
|
||||||
"allow-wiki-open"
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-archive-docs-cmd"
|
|
||||||
description = "Enables the archive_docs_cmd command without any pre-configured scope."
|
|
||||||
commands.allow = ["archive_docs_cmd"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-archive-docs-cmd"
|
|
||||||
description = "Denies the archive_docs_cmd command without any pre-configured scope."
|
|
||||||
commands.deny = ["archive_docs_cmd"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-change-archive-home-cmd"
|
|
||||||
description = "Enables the change_archive_home_cmd command without any pre-configured scope."
|
|
||||||
commands.allow = ["change_archive_home_cmd"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-change-archive-home-cmd"
|
|
||||||
description = "Denies the change_archive_home_cmd command without any pre-configured scope."
|
|
||||||
commands.deny = ["change_archive_home_cmd"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-clear-archive-home-cmd"
|
|
||||||
description = "Enables the clear_archive_home_cmd command without any pre-configured scope."
|
|
||||||
commands.allow = ["clear_archive_home_cmd"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-clear-archive-home-cmd"
|
|
||||||
description = "Denies the clear_archive_home_cmd command without any pre-configured scope."
|
|
||||||
commands.deny = ["clear_archive_home_cmd"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-panel-archive-cmd"
|
|
||||||
description = "Enables the panel_archive_cmd command without any pre-configured scope."
|
|
||||||
commands.allow = ["panel_archive_cmd"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-panel-archive-cmd"
|
|
||||||
description = "Denies the panel_archive_cmd command without any pre-configured scope."
|
|
||||||
commands.deny = ["panel_archive_cmd"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-panel-archive-dir-cmd"
|
|
||||||
description = "Enables the panel_archive_dir_cmd command without any pre-configured scope."
|
|
||||||
commands.allow = ["panel_archive_dir_cmd"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-panel-archive-dir-cmd"
|
|
||||||
description = "Denies the panel_archive_dir_cmd command without any pre-configured scope."
|
|
||||||
commands.deny = ["panel_archive_dir_cmd"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-panel-load"
|
|
||||||
description = "Enables the panel_load command without any pre-configured scope."
|
|
||||||
commands.allow = ["panel_load"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-panel-load"
|
|
||||||
description = "Denies the panel_load command without any pre-configured scope."
|
|
||||||
commands.deny = ["panel_load"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-panel-set"
|
|
||||||
description = "Enables the panel_set command without any pre-configured scope."
|
|
||||||
commands.allow = ["panel_set"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-panel-set"
|
|
||||||
description = "Denies the panel_set command without any pre-configured scope."
|
|
||||||
commands.deny = ["panel_set"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-reveal-path-cmd"
|
|
||||||
description = "Enables the reveal_path_cmd command without any pre-configured scope."
|
|
||||||
commands.allow = ["reveal_path_cmd"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-reveal-path-cmd"
|
|
||||||
description = "Denies the reveal_path_cmd command without any pre-configured scope."
|
|
||||||
commands.deny = ["reveal_path_cmd"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-set-archive-home-cmd"
|
|
||||||
description = "Enables the set_archive_home_cmd command without any pre-configured scope."
|
|
||||||
commands.allow = ["set_archive_home_cmd"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-set-archive-home-cmd"
|
|
||||||
description = "Denies the set_archive_home_cmd command without any pre-configured scope."
|
|
||||||
commands.deny = ["set_archive_home_cmd"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-spellcheck-lang"
|
|
||||||
description = "Enables the spellcheck_lang command without any pre-configured scope."
|
|
||||||
commands.allow = ["spellcheck_lang"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-spellcheck-lang"
|
|
||||||
description = "Denies the spellcheck_lang command without any pre-configured scope."
|
|
||||||
commands.deny = ["spellcheck_lang"]
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-trilium-connect"
|
||||||
|
description = "Enables the trilium_connect command without any pre-configured scope."
|
||||||
|
commands.allow = ["trilium_connect"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-trilium-connect"
|
||||||
|
description = "Denies the trilium_connect command without any pre-configured scope."
|
||||||
|
commands.deny = ["trilium_connect"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-trilium-disable"
|
||||||
|
description = "Enables the trilium_disable command without any pre-configured scope."
|
||||||
|
commands.allow = ["trilium_disable"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-trilium-disable"
|
||||||
|
description = "Denies the trilium_disable command without any pre-configured scope."
|
||||||
|
commands.deny = ["trilium_disable"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-trilium-open"
|
||||||
|
description = "Enables the trilium_open command without any pre-configured scope."
|
||||||
|
commands.allow = ["trilium_open"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-trilium-open"
|
||||||
|
description = "Denies the trilium_open command without any pre-configured scope."
|
||||||
|
commands.deny = ["trilium_open"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-trilium-setup"
|
||||||
|
description = "Enables the trilium_setup command without any pre-configured scope."
|
||||||
|
commands.allow = ["trilium_setup"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-trilium-setup"
|
||||||
|
description = "Denies the trilium_setup command without any pre-configured scope."
|
||||||
|
commands.deny = ["trilium_setup"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-trilium-status"
|
||||||
|
description = "Enables the trilium_status command without any pre-configured scope."
|
||||||
|
commands.allow = ["trilium_status"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-trilium-status"
|
||||||
|
description = "Denies the trilium_status command without any pre-configured scope."
|
||||||
|
commands.deny = ["trilium_status"]
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-wiki-open"
|
|
||||||
description = "Enables the wiki_open command without any pre-configured scope."
|
|
||||||
commands.allow = ["wiki_open"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-wiki-open"
|
|
||||||
description = "Denies the wiki_open command without any pre-configured scope."
|
|
||||||
commands.deny = ["wiki_open"]
|
|
||||||
+5
-17
@@ -286,14 +286,11 @@ fn invoke_handlers() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send +
|
|||||||
commands::oauth_login,
|
commands::oauth_login,
|
||||||
commands::keychain_status,
|
commands::keychain_status,
|
||||||
commands::set_apikey,
|
commands::set_apikey,
|
||||||
commands::panel_archive_dir_cmd,
|
commands::trilium_status,
|
||||||
commands::panel_archive_cmd,
|
commands::trilium_setup,
|
||||||
commands::set_archive_home_cmd,
|
commands::trilium_connect,
|
||||||
commands::change_archive_home_cmd,
|
commands::trilium_open,
|
||||||
commands::clear_archive_home_cmd,
|
commands::trilium_disable,
|
||||||
commands::archive_docs_cmd,
|
|
||||||
commands::reveal_path_cmd,
|
|
||||||
commands::spellcheck_lang,
|
|
||||||
commands::enabled_modules,
|
commands::enabled_modules,
|
||||||
commands::module_registry,
|
commands::module_registry,
|
||||||
commands::set_module,
|
commands::set_module,
|
||||||
@@ -307,16 +304,7 @@ fn invoke_handlers() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send +
|
|||||||
terminal::todos_delete,
|
terminal::todos_delete,
|
||||||
terminal::todos_add,
|
terminal::todos_add,
|
||||||
terminal::todos_update,
|
terminal::todos_update,
|
||||||
terminal::panel_set,
|
|
||||||
terminal::search_run,
|
terminal::search_run,
|
||||||
terminal::panel_load,
|
|
||||||
terminal::wiki_open,
|
|
||||||
terminal::archive_move,
|
|
||||||
terminal::archive_rename,
|
|
||||||
terminal::archive_delete,
|
|
||||||
terminal::archive_move_folder,
|
|
||||||
terminal::archive_create_folder,
|
|
||||||
terminal::archive_create_doc,
|
|
||||||
terminal::open_panel_window
|
terminal::open_panel_window
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
+104
-72
@@ -3,9 +3,6 @@
|
|||||||
|
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use crate::domain::archive::{
|
|
||||||
archive_panel_content, project_archive_home, require_archive_home, ArchiveMeta,
|
|
||||||
};
|
|
||||||
use crate::domain::credentials::keychain_service;
|
use crate::domain::credentials::keychain_service;
|
||||||
use crate::domain::paths::Paths;
|
use crate::domain::paths::Paths;
|
||||||
use crate::domain::pool::{
|
use crate::domain::pool::{
|
||||||
@@ -350,11 +347,6 @@ pub(crate) fn set_terminal_font_size(size: u32) -> Result<(), String> {
|
|||||||
settings::set_terminal_font_size_in(&Paths::real(), size)
|
settings::set_terminal_font_size_in(&Paths::real(), size)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub(crate) fn spellcheck_lang() -> String {
|
|
||||||
settings::spellcheck_lang(&Paths::real())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- Verbrauch ----------
|
// ---------- Verbrauch ----------
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -362,15 +354,6 @@ pub(crate) fn usage_stats(days: u32) -> Result<Vec<UsageRow>, String> {
|
|||||||
usage_stats_in(&Paths::real(), days)
|
usage_stats_in(&Paths::real(), days)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- Panel-Archiv ----------
|
|
||||||
|
|
||||||
/// Konfiguriertes Archiv-Home des Projekts (für den Panel-Button: entscheidet,
|
|
||||||
/// ob der Ordner-Dialog nötig ist).
|
|
||||||
#[tauri::command]
|
|
||||||
pub(crate) fn panel_archive_dir_cmd(project: String) -> Option<String> {
|
|
||||||
project_archive_home(&project).map(|p| p.display().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Modul-Registry für den Settings-Dialog (Checkbox-Gruppe „Module").
|
/// Modul-Registry für den Settings-Dialog (Checkbox-Gruppe „Module").
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub(crate) fn module_registry(project: String) -> Result<Vec<crate::domain::modules::ModuleInfo>, String> {
|
pub(crate) fn module_registry(project: String) -> Result<Vec<crate::domain::modules::ModuleInfo>, String> {
|
||||||
@@ -383,78 +366,127 @@ pub(crate) fn set_module(project: String, module: String, enabled: bool) -> Resu
|
|||||||
crate::domain::modules::set_module_in(&Paths::real(), &project, &module, enabled)
|
crate::domain::modules::set_module_in(&Paths::real(), &project, &module, enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Aktive Module fürs Frontend: Registry-Enablement der Projekt-Config plus
|
/// Aktive Module fürs Frontend (Registry-Enablement der Projekt-Config).
|
||||||
/// `requires_archive` — ohne konfiguriertes Archiv-Home fallen Archiv-Module
|
|
||||||
/// weg, ihre Tabs erscheinen nicht.
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub(crate) fn enabled_modules(project: String) -> Result<Vec<String>, String> {
|
pub(crate) fn enabled_modules(project: String) -> Result<Vec<String>, String> {
|
||||||
let paths = Paths::real();
|
|
||||||
let has_archive = read_project_config_in(&paths, &project)?.archive_home.is_some();
|
|
||||||
Ok(
|
Ok(
|
||||||
crate::domain::modules::active_in(&paths, &project)?
|
crate::domain::modules::active_in(&Paths::real(), &project)?
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|m| !m.requires_archive || has_archive)
|
|
||||||
.map(|m| m.id.to_string())
|
.map(|m| m.id.to_string())
|
||||||
.collect(),
|
.collect(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Setzt das Archiv-Home eines Projekts (Einstellungsdialog) — inklusive
|
// ---------- Trilium ----------
|
||||||
/// Permissions-Eintrag in der Projekt-settings.json.
|
|
||||||
#[tauri::command]
|
/// Wizard-Status: Runtime da, Instanz erreichbar, Token gültig. Reine
|
||||||
pub(crate) fn set_archive_home_cmd(project: String, dir: String) -> Result<(), String> {
|
/// Checks, keine Schreiber.
|
||||||
crate::domain::archive::set_project_archive_home(&project, &dir)
|
#[derive(serde::Serialize)]
|
||||||
|
pub(crate) struct TriliumStatus {
|
||||||
|
version: &'static str,
|
||||||
|
port: u16,
|
||||||
|
data_dir: String,
|
||||||
|
runtime_ready: bool,
|
||||||
|
instance_running: bool,
|
||||||
|
token_ok: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trilium_status_for(project: &str) -> TriliumStatus {
|
||||||
|
let paths = Paths::real();
|
||||||
|
let instance_running = crate::domain::trilium::instance_running(project);
|
||||||
|
TriliumStatus {
|
||||||
|
version: crate::domain::trilium::VERSION,
|
||||||
|
port: crate::domain::trilium::port_for(project),
|
||||||
|
data_dir: crate::domain::paths::contract_home(
|
||||||
|
&paths,
|
||||||
|
&crate::domain::trilium::data_dir(&paths, project),
|
||||||
|
),
|
||||||
|
runtime_ready: crate::domain::trilium::runtime_ready(&paths),
|
||||||
|
instance_running,
|
||||||
|
token_ok: instance_running && crate::domain::trilium::token_ok(project),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wechselt das Archiv-Home (Einstellungsdialog, wenn schon eins gesetzt
|
|
||||||
/// ist): optional ziehen die Dokumente mit um; die Rechte des alten Ordners
|
|
||||||
/// werden zurückgenommen.
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub(crate) fn change_archive_home_cmd(
|
pub(crate) async fn trilium_status(project: String) -> TriliumStatus {
|
||||||
|
trilium_status_for(&project)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Richtet die Projekt-Instanz ein: Runtime laden (gepinnt, Checksum),
|
||||||
|
/// Instanz starten. Schreibt KEINE Config — das Modul-Flag setzt erst
|
||||||
|
/// trilium_connect nach erfolgreichem Token-Login.
|
||||||
|
#[tauri::command]
|
||||||
|
pub(crate) async fn trilium_setup(project: String) -> Result<TriliumStatus, String> {
|
||||||
|
crate::domain::trilium::ensure_instance(&Paths::real(), &project)?;
|
||||||
|
Ok(trilium_status_for(&project))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Richtet die Instanz mit dem Passwort aus dem Wizard vollständig ein:
|
||||||
|
/// Erstlauf legt das Dokument an und setzt das Passwort, dann ETAPI-Token
|
||||||
|
/// holen, im Keyring ablegen und ERST DANN das Modul in der Projekt-Config
|
||||||
|
/// freischalten. Das Passwort wird nicht gespeichert.
|
||||||
|
#[tauri::command]
|
||||||
|
pub(crate) async fn trilium_connect(
|
||||||
project: String,
|
project: String,
|
||||||
dir: String,
|
password: String,
|
||||||
migrate: bool,
|
) -> Result<TriliumStatus, String> {
|
||||||
|
let paths = Paths::real();
|
||||||
|
crate::domain::trilium::ensure_instance(&paths, &project)?;
|
||||||
|
if !crate::domain::trilium::initialized(&project)? {
|
||||||
|
crate::domain::trilium::setup_new_document(&project)?;
|
||||||
|
crate::domain::trilium::set_password(&project, &password)?;
|
||||||
|
}
|
||||||
|
let token = crate::domain::trilium::login(&project, &password)?;
|
||||||
|
crate::domain::trilium::store_token(&project, &token)?;
|
||||||
|
if !crate::domain::trilium::token_ok(&project) {
|
||||||
|
crate::domain::trilium::delete_token(&project);
|
||||||
|
return Err("Token angenommen, aber ETAPI-Zugriff scheitert".into());
|
||||||
|
}
|
||||||
|
crate::domain::modules::set_module_in(&paths, &project, "trilium", true)?;
|
||||||
|
Ok(trilium_status_for(&project))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Öffnet das Trilium-Fenster des Projekts (startet die Instanz bei Bedarf);
|
||||||
|
/// `note_id` springt zur Notiz. Async wie open_panel_window (Fenster-Erzeugung
|
||||||
|
/// aus synchronen Commands klemmt auf dem GTK-Mainloop).
|
||||||
|
#[tauri::command]
|
||||||
|
pub(crate) async fn trilium_open(
|
||||||
|
app: tauri::AppHandle,
|
||||||
|
project: String,
|
||||||
|
note_id: Option<String>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
crate::domain::archive::change_project_archive_home(&project, &dir, migrate)
|
use tauri::Manager;
|
||||||
|
crate::domain::trilium::ensure_instance(&Paths::real(), &project)?;
|
||||||
|
let mut url = crate::domain::trilium::base_url(&project);
|
||||||
|
if let Some(id) = ¬e_id {
|
||||||
|
url.push_str(&format!("/#root/{id}"));
|
||||||
|
}
|
||||||
|
let label = format!("trilium-{project}");
|
||||||
|
if let Some(win) = app.get_webview_window(&label) {
|
||||||
|
if note_id.is_some() {
|
||||||
|
win
|
||||||
|
.eval(&format!("window.location.href = {}", serde_json::json!(url)))
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
win.set_focus().map_err(|e| e.to_string())?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let parsed: tauri::Url = url.parse().map_err(|e| format!("{url}: {e}"))?;
|
||||||
|
tauri::WebviewWindowBuilder::new(&app, &label, tauri::WebviewUrl::External(parsed))
|
||||||
|
.title(format!("Trilium — {}", crate::domain::project::display_name_in(&Paths::real(), &project)?))
|
||||||
|
.inner_size(1100.0, 780.0)
|
||||||
|
.build()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wählt das Archiv ab (Einstellungsdialog): Config-Eintrag und Permissions
|
/// Wählt das Modul ab und stoppt die Projekt-Instanz. Daten und Token
|
||||||
/// weg, der Ordner bleibt liegen.
|
/// bleiben — erneutes Aktivieren verbindet sich wieder.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub(crate) fn clear_archive_home_cmd(project: String) -> Result<(), String> {
|
pub(crate) async fn trilium_disable(project: String) -> Result<(), String> {
|
||||||
crate::domain::archive::clear_project_archive_home(&project)
|
crate::domain::modules::set_module_in(&Paths::real(), &project, "trilium", false)?;
|
||||||
|
crate::domain::trilium::stop_instance(&project);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Archiviert den aktuellen Panel-Entwurf. `dir` (aus dem Ordner-Dialog) setzt
|
|
||||||
/// das Archiv-Home zugleich; ohne `dir` muss es konfiguriert sein. Ordner,
|
|
||||||
/// Beschreibung und Schlagwörter kommen aus dem Archiv-Formular im Panel.
|
|
||||||
#[tauri::command]
|
|
||||||
pub(crate) fn panel_archive_cmd(
|
|
||||||
project: String,
|
|
||||||
dir: Option<String>,
|
|
||||||
folder: Option<String>,
|
|
||||||
description: Option<String>,
|
|
||||||
tags: Option<Vec<String>>,
|
|
||||||
) -> Result<String, String> {
|
|
||||||
let meta = ArchiveMeta {
|
|
||||||
folder: folder.filter(|f| !f.trim().is_empty()),
|
|
||||||
description: description.filter(|d| !d.trim().is_empty()),
|
|
||||||
tags: tags.unwrap_or_default(),
|
|
||||||
};
|
|
||||||
archive_panel_content(&project, dir.as_deref(), &meta).map(|p| p.display().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dokumentliste des Archiv-Index (frisch gescannt) fürs Panel.
|
|
||||||
#[tauri::command]
|
|
||||||
pub(crate) fn archive_docs_cmd(
|
|
||||||
project: String,
|
|
||||||
) -> Result<Vec<crate::domain::archive_index::Doc>, String> {
|
|
||||||
let home = require_archive_home(&project)?;
|
|
||||||
crate::domain::archive_index::scan_archive(&home)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Zeigt einen Pfad im Dateimanager (nach dem Archivieren „im Finder zeigen").
|
|
||||||
#[tauri::command]
|
|
||||||
pub(crate) fn reveal_path_cmd(path: String) {
|
|
||||||
crate::platform::reveal_path(std::path::Path::new(&path));
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,565 +0,0 @@
|
|||||||
//! Archiv: Panel-Entwürfe als Markdown-Dateien mit Frontmatter im
|
|
||||||
//! konfigurierten Archiv-Ordner des Projekts persistieren.
|
|
||||||
|
|
||||||
use std::fs;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
use crate::domain::paths::{contract_home, expand_home, panel_file, Paths};
|
|
||||||
use crate::domain::project::{
|
|
||||||
read_project_config_in, settings_path, write_project_config_in,
|
|
||||||
};
|
|
||||||
use crate::domain::registry::project_dir;
|
|
||||||
|
|
||||||
/// Konfiguriertes Archiv-Home des Projekts (config.json: archiveHome),
|
|
||||||
/// Home-expandiert; None, wenn nicht gesetzt.
|
|
||||||
pub(crate) fn project_archive_home(project: &str) -> Option<PathBuf> {
|
|
||||||
let paths = Paths::real();
|
|
||||||
let dir = read_project_config_in(&paths, project).ok()?.archive_home?;
|
|
||||||
Some(expand_home(&paths, &dir))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Archiv-Home als Result — die gemeinsame Vorbedingung aller Archiv-Tools.
|
|
||||||
/// Legt den konfigurierten Ordner an, falls er (noch) nicht existiert.
|
|
||||||
pub(crate) fn require_archive_home(project: &str) -> Result<PathBuf, String> {
|
|
||||||
let home = project_archive_home(project).ok_or("kein Archiv-Ordner gesetzt")?;
|
|
||||||
fs::create_dir_all(&home).map_err(|e| format!("{}: {e}", home.display()))?;
|
|
||||||
Ok(home)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Setzt das Archiv-Home: config.json (~-relativ) und ein Eintrag in
|
|
||||||
/// permissions.additionalDirectories + Edit der Projekt-settings.json, damit
|
|
||||||
/// claude das Archiv später lesen/scannen darf.
|
|
||||||
pub(crate) fn set_project_archive_home(project: &str, dir: &str) -> Result<(), String> {
|
|
||||||
let paths = Paths::real();
|
|
||||||
let expanded = expand_home(&paths, dir);
|
|
||||||
if !expanded.is_absolute() {
|
|
||||||
return Err(format!("Archiv-Ordner muss ein absoluter Pfad sein: {}", expanded.display()));
|
|
||||||
}
|
|
||||||
// Zu weit gefasst? Ein Vorfahre des Home (inkl. Home selbst und Root) würde
|
|
||||||
// claude über additionalDirectories weiten Zugriff geben — das lehnen wir ab.
|
|
||||||
if paths.home.starts_with(&expanded) {
|
|
||||||
return Err(format!(
|
|
||||||
"Archiv-Ordner zu weit gefasst: {}. Bitte einen spezifischen Unterordner wählen.",
|
|
||||||
expanded.display()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
fs::create_dir_all(&expanded).map_err(|e| format!("{}: {e}", expanded.display()))?;
|
|
||||||
let contracted = contract_home(&paths, &expanded);
|
|
||||||
let mut cfg = read_project_config_in(&paths, project)?;
|
|
||||||
cfg.archive_home = Some(contracted.clone());
|
|
||||||
write_project_config_in(&paths, project, &cfg)?;
|
|
||||||
add_archive_permission(&paths, project, &contracted)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Trägt den Archiv-Ordner idempotent in additionalDirectories + Edit-Allow ein.
|
|
||||||
/// Auch beim Projekt-Import im Einsatz (mitgebrachtes archiveHome).
|
|
||||||
pub(crate) fn add_archive_permission(
|
|
||||||
paths: &Paths,
|
|
||||||
project: &str,
|
|
||||||
dir: &str,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let sp = settings_path(&project_dir(paths, project)?);
|
|
||||||
crate::domain::update_settings_permissions(&sp, true, |perms| {
|
|
||||||
let dirs = crate::domain::perm_array(perms, "additionalDirectories")?;
|
|
||||||
if !dirs.iter().any(|d| d.as_str() == Some(dir)) {
|
|
||||||
dirs.push(serde_json::json!(dir));
|
|
||||||
}
|
|
||||||
let edit = format!("Edit({dir}/**)");
|
|
||||||
let allow = crate::domain::perm_array(perms, "allow")?;
|
|
||||||
if !allow.iter().any(|p| p.as_str() == Some(&edit)) {
|
|
||||||
allow.push(serde_json::json!(edit));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wechselt das Archiv-Home: neues Home setzen (validieren, anlegen, Rechte,
|
|
||||||
/// Config), auf Wunsch die Dokumente aus dem alten Home hinüberziehen, dann
|
|
||||||
/// die Rechte des alten zurücknehmen. Ohne `migrate` bleibt das alte Archiv
|
|
||||||
/// unverändert liegen — nichts wird implizit verschoben; der Umzug ist eine
|
|
||||||
/// bewusste Option im Dialog.
|
|
||||||
pub(crate) fn change_project_archive_home(
|
|
||||||
project: &str,
|
|
||||||
dir: &str,
|
|
||||||
migrate: bool,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let paths = Paths::real();
|
|
||||||
let old = read_project_config_in(&paths, project)?.archive_home;
|
|
||||||
set_project_archive_home(project, dir)?;
|
|
||||||
let new_home = expand_home(&paths, dir);
|
|
||||||
if let Some(old_c) = old {
|
|
||||||
let old_home = expand_home(&paths, &old_c);
|
|
||||||
if old_home == new_home {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
if migrate && old_home.is_dir() {
|
|
||||||
move_dir_contents(&old_home, &new_home)?;
|
|
||||||
}
|
|
||||||
remove_archive_permission(&paths, project, &old_c)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Zieht alle Einträge von `from` nach `to` um. Gleiche Platte per rename,
|
|
||||||
/// über Dateisystemgrenzen als Kopie + Löschen. Ein im Ziel schon vorhandener
|
|
||||||
/// Name bricht laut ab — nichts wird überschrieben.
|
|
||||||
fn move_dir_contents(from: &std::path::Path, to: &std::path::Path) -> Result<(), String> {
|
|
||||||
for entry in fs::read_dir(from).map_err(|e| format!("{}: {e}", from.display()))? {
|
|
||||||
let entry = entry.map_err(|e| format!("{}: {e}", from.display()))?;
|
|
||||||
let src = entry.path();
|
|
||||||
let dest = to.join(entry.file_name());
|
|
||||||
if dest.exists() {
|
|
||||||
return Err(format!("existiert schon im neuen Archiv: {}", dest.display()));
|
|
||||||
}
|
|
||||||
match fs::rename(&src, &dest) {
|
|
||||||
Ok(()) => {}
|
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => {
|
|
||||||
copy_recursive(&src, &dest)?;
|
|
||||||
if src.is_dir() {
|
|
||||||
fs::remove_dir_all(&src).map_err(|e| format!("{}: {e}", src.display()))?;
|
|
||||||
} else {
|
|
||||||
fs::remove_file(&src).map_err(|e| format!("{}: {e}", src.display()))?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => return Err(format!("{}: {e}", src.display())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn copy_recursive(src: &std::path::Path, dest: &std::path::Path) -> Result<(), String> {
|
|
||||||
if src.is_dir() {
|
|
||||||
fs::create_dir_all(dest).map_err(|e| format!("{}: {e}", dest.display()))?;
|
|
||||||
for entry in fs::read_dir(src).map_err(|e| format!("{}: {e}", src.display()))? {
|
|
||||||
let entry = entry.map_err(|e| format!("{}: {e}", src.display()))?;
|
|
||||||
copy_recursive(&entry.path(), &dest.join(entry.file_name()))?;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
fs::copy(src, dest).map_err(|e| format!("{}: {e}", src.display()))?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wählt das Archiv ab: archiveHome aus der config.json entfernen und die
|
|
||||||
/// beim Setzen eingetragenen Rechte (additionalDirectories + Edit-Allow) aus
|
|
||||||
/// der Projekt-settings.json zurücknehmen. Der Ordner selbst bleibt liegen.
|
|
||||||
pub(crate) fn clear_project_archive_home(project: &str) -> Result<(), String> {
|
|
||||||
let paths = Paths::real();
|
|
||||||
let mut cfg = read_project_config_in(&paths, project)?;
|
|
||||||
let Some(dir) = cfg.archive_home.take() else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
write_project_config_in(&paths, project, &cfg)?;
|
|
||||||
remove_archive_permission(&paths, project, &dir)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gegenstück zu add_archive_permission; auch der Lösch-Dialog (Stufe „nur
|
|
||||||
/// Integration") nimmt darüber die Archiv-Rechte zurück.
|
|
||||||
pub(crate) fn remove_archive_permission(
|
|
||||||
paths: &Paths,
|
|
||||||
project: &str,
|
|
||||||
dir: &str,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let sp = settings_path(&project_dir(paths, project)?);
|
|
||||||
if !sp.is_file() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
crate::domain::update_settings_permissions(&sp, false, |perms| {
|
|
||||||
if let Some(dirs) = perms.get_mut("additionalDirectories").and_then(|d| d.as_array_mut()) {
|
|
||||||
dirs.retain(|d| d.as_str() != Some(dir));
|
|
||||||
}
|
|
||||||
let edit = format!("Edit({dir}/**)");
|
|
||||||
if let Some(allow) = perms.get_mut("allow").and_then(|a| a.as_array_mut()) {
|
|
||||||
allow.retain(|p| p.as_str() != Some(&edit));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Metadaten beim Archivieren: Unterordner im Archiv-Home plus Frontmatter-Felder.
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(crate) struct ArchiveMeta {
|
|
||||||
/// Unterordner relativ zum Archiv-Home (wird angelegt).
|
|
||||||
pub(crate) folder: Option<String>,
|
|
||||||
/// Einzeiler fürs Frontmatter.
|
|
||||||
pub(crate) description: Option<String>,
|
|
||||||
/// Schlagwörter fürs Frontmatter.
|
|
||||||
pub(crate) tags: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Archiviert den aktuellen Panel-Inhalt des Projekts als Markdown-Datei mit
|
|
||||||
/// Frontmatter im Archiv-Home. `dir_override` setzt das Home zugleich
|
|
||||||
/// (Terminal-Fallback ohne Dialog). Liefert den geschriebenen Pfad.
|
|
||||||
pub(crate) fn archive_panel_content(
|
|
||||||
project: &str,
|
|
||||||
dir_override: Option<&str>,
|
|
||||||
meta: &ArchiveMeta,
|
|
||||||
) -> Result<PathBuf, String> {
|
|
||||||
// Erst prüfen, dann konfigurieren: `set_project_archive_home` legt Ordner an
|
|
||||||
// und trägt eine Berechtigung in die settings.json des Projekts ein. Käme das
|
|
||||||
// vor der Leer-Prüfung, hinterließe ein Archivieren mit leerem Panel die
|
|
||||||
// Meldung „nicht archiviert“ — und ein dauerhaft umgestelltes Archiv-Home.
|
|
||||||
let text = fs::read_to_string(panel_file(project)).unwrap_or_default();
|
|
||||||
if text.trim().is_empty() {
|
|
||||||
return Err("Panel ist leer — nichts zu archivieren".into());
|
|
||||||
}
|
|
||||||
let folder = meta.folder.as_deref().map(check_folder).transpose()?;
|
|
||||||
if let Some(d) = dir_override {
|
|
||||||
set_project_archive_home(project, d)?;
|
|
||||||
}
|
|
||||||
let home = require_archive_home(project)?;
|
|
||||||
let dir = match folder {
|
|
||||||
Some(f) => home.join(f),
|
|
||||||
None => home,
|
|
||||||
};
|
|
||||||
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
|
||||||
|
|
||||||
let secs = SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.map_err(|e| e.to_string())?
|
|
||||||
.as_secs();
|
|
||||||
let (stamp, iso) = utc_stamp(secs);
|
|
||||||
let title = first_line(&text);
|
|
||||||
let (path, mut file) = create_unique(&dir, &stamp, &slugify(&title))?;
|
|
||||||
// Frontmatter trägt den Anzeigenamen, nicht die Projekt-ID.
|
|
||||||
let name = crate::domain::project::display_name_in(&Paths::real(), project)?;
|
|
||||||
let doc = format!("{}{}\n", frontmatter(&title, &name, &iso, meta), text.trim_end());
|
|
||||||
std::io::Write::write_all(&mut file, doc.as_bytes())
|
|
||||||
.map_err(|e| format!("{}: {e}", path.display()))?;
|
|
||||||
Ok(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Archiv-Dokument kollisionsfrei anlegen.
|
|
||||||
///
|
|
||||||
/// Der Zeitstempel hat Minutenauflösung; zweimal Archivieren innerhalb einer
|
|
||||||
/// Minute mit derselben Titelzeile ergäbe denselben Namen — bei Kollision
|
|
||||||
/// wird `-2`, `-3`, … angehängt. Die Garantie kommt vom Dateisystem
|
|
||||||
/// (`create_new`), nicht von einem `exists()`-Vorabblick: Beim Archiv-Sync
|
|
||||||
/// über zwei Maschinen wäre der Vorabblick ein TOCTOU-Fenster, und stiller
|
|
||||||
/// Datenverlust träfe ausgerechnet die dauerhafte Ablage.
|
|
||||||
fn create_unique(
|
|
||||||
dir: &std::path::Path,
|
|
||||||
stamp: &str,
|
|
||||||
slug: &str,
|
|
||||||
) -> Result<(PathBuf, fs::File), String> {
|
|
||||||
for n in 1.. {
|
|
||||||
let name = if n == 1 {
|
|
||||||
format!("{stamp}-{slug}.md")
|
|
||||||
} else {
|
|
||||||
format!("{stamp}-{slug}-{n}.md")
|
|
||||||
};
|
|
||||||
let path = dir.join(name);
|
|
||||||
match fs::OpenOptions::new().write(true).create_new(true).open(&path) {
|
|
||||||
Ok(file) => return Ok((path, file)),
|
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
|
||||||
Err(e) => return Err(format!("{}: {e}", path.display())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Unterordner-Pfad: relativ, nur normale Komponenten (kein `..`, kein Root).
|
|
||||||
fn check_folder(folder: &str) -> Result<&std::path::Path, String> {
|
|
||||||
let p = std::path::Path::new(folder);
|
|
||||||
let normal = p
|
|
||||||
.components()
|
|
||||||
.all(|c| matches!(c, std::path::Component::Normal(_)));
|
|
||||||
if p.components().next().is_some() && normal {
|
|
||||||
Ok(p)
|
|
||||||
} else {
|
|
||||||
Err(format!("Unterordner muss ein relativer Pfad ohne '..' sein: {folder}"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// YAML-Frontmatter des Archiv-Dokuments inklusive optionaler
|
|
||||||
/// description/tags aus den Metadaten. Gegenstück: `parse_frontmatter` unten —
|
|
||||||
/// Schreiber und Leser des Formats leben bewusst im selben Modul.
|
|
||||||
pub(crate) fn frontmatter(
|
|
||||||
title: &str,
|
|
||||||
project: &str,
|
|
||||||
iso: &str,
|
|
||||||
meta: &ArchiveMeta,
|
|
||||||
) -> String {
|
|
||||||
let mut fm = format!(
|
|
||||||
"---\ntitle: \"{}\"\nproject: {project}\ncreated: {iso}\nsource: ai-control\n",
|
|
||||||
title.replace('"', "'"),
|
|
||||||
);
|
|
||||||
if let Some(d) = &meta.description {
|
|
||||||
fm.push_str(&format!("description: \"{}\"\n", d.replace('"', "'")));
|
|
||||||
}
|
|
||||||
if !meta.tags.is_empty() {
|
|
||||||
let quoted: Vec<String> =
|
|
||||||
meta.tags.iter().map(|t| format!("\"{}\"", t.replace('"', "'"))).collect();
|
|
||||||
fm.push_str(&format!("tags: [{}]\n", quoted.join(", ")));
|
|
||||||
}
|
|
||||||
fm.push_str("---\n\n");
|
|
||||||
fm
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Minimaler Frontmatter-Parser für die selbst geschriebenen Dokumente:
|
|
||||||
/// `key: value`-Zeilen zwischen den beiden `---`-Markern, Anführungszeichen
|
|
||||||
/// um Werte werden entfernt.
|
|
||||||
pub(crate) fn parse_frontmatter(text: &str) -> std::collections::HashMap<String, String> {
|
|
||||||
let mut map = std::collections::HashMap::new();
|
|
||||||
let Some(rest) = text.strip_prefix("---\n") else {
|
|
||||||
return map;
|
|
||||||
};
|
|
||||||
let Some(end) = rest.find("\n---") else {
|
|
||||||
return map;
|
|
||||||
};
|
|
||||||
for line in rest[..end].lines() {
|
|
||||||
let Some((key, value)) = line.split_once(':') else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
map.insert(key.trim().to_string(), unquote(value.trim()).to_string());
|
|
||||||
}
|
|
||||||
map
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dokument-Rumpf ohne den Frontmatter-Block; führende Leerzeilen entfernt.
|
|
||||||
pub(crate) fn strip_frontmatter(text: &str) -> &str {
|
|
||||||
let Some(rest) = text.strip_prefix("---\n") else {
|
|
||||||
return text;
|
|
||||||
};
|
|
||||||
match rest.find("\n---\n") {
|
|
||||||
Some(end) => rest[end + 5..].trim_start_matches('\n'),
|
|
||||||
None => text,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unquote(s: &str) -> &str {
|
|
||||||
s.strip_prefix('"')
|
|
||||||
.and_then(|s| s.strip_suffix('"'))
|
|
||||||
.unwrap_or(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Inline-Liste `["a", "b"]` bzw. `[a, b]` in Einzel-Tags zerlegen.
|
|
||||||
pub(crate) fn parse_tag_list(raw: &str) -> Vec<String> {
|
|
||||||
raw
|
|
||||||
.trim_start_matches('[')
|
|
||||||
.trim_end_matches(']')
|
|
||||||
.split(',')
|
|
||||||
.map(|t| unquote(t.trim()).to_string())
|
|
||||||
.filter(|t| !t.is_empty())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Datei-Stem ohne führenden `YYYY-MM-DD_HHMM-`-Zeitstempel — das Gegenstück
|
|
||||||
/// zum Dateinamen aus `utc_stamp` + `slugify`.
|
|
||||||
pub(crate) fn strip_stamp(stem: &str) -> &str {
|
|
||||||
let bytes = stem.as_bytes();
|
|
||||||
let stamped = bytes.len() > 16
|
|
||||||
&& bytes[..16].iter().enumerate().all(|(i, b)| match i {
|
|
||||||
4 | 7 => *b == b'-',
|
|
||||||
10 => *b == b'_',
|
|
||||||
15 => *b == b'-',
|
|
||||||
_ => b.is_ascii_digit(),
|
|
||||||
});
|
|
||||||
if stamped {
|
|
||||||
&stem[16..]
|
|
||||||
} else {
|
|
||||||
stem
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Titelzeile: erste Überschrift (## …) oder sonst erste nicht-leere Zeile.
|
|
||||||
fn first_line(text: &str) -> String {
|
|
||||||
let mut fallback: Option<&str> = None;
|
|
||||||
for line in text.lines() {
|
|
||||||
let t = line.trim();
|
|
||||||
if t.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let h = t.trim_start_matches('#').trim();
|
|
||||||
if t.starts_with('#') && !h.is_empty() {
|
|
||||||
return h.to_string();
|
|
||||||
}
|
|
||||||
fallback.get_or_insert(t);
|
|
||||||
}
|
|
||||||
fallback.unwrap_or("entwurf").to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dateinamen-tauglicher Slug (ascii, klein, Bindestriche, max. 60 Zeichen).
|
|
||||||
pub(crate) fn slugify(s: &str) -> String {
|
|
||||||
let mut out = String::new();
|
|
||||||
for c in s.chars() {
|
|
||||||
// Umlaute/ß transliterieren statt verschlucken („für's" → fuer-s).
|
|
||||||
match c {
|
|
||||||
'ä' | 'Ä' => out.push_str("ae"),
|
|
||||||
'ö' | 'Ö' => out.push_str("oe"),
|
|
||||||
'ü' | 'Ü' => out.push_str("ue"),
|
|
||||||
'ß' => out.push_str("ss"),
|
|
||||||
_ if c.is_ascii_alphanumeric() => out.push(c.to_ascii_lowercase()),
|
|
||||||
_ if !out.ends_with('-') => out.push('-'),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let out: String = out.trim_matches('-').chars().take(60).collect();
|
|
||||||
if out.is_empty() {
|
|
||||||
"entwurf".into()
|
|
||||||
} else {
|
|
||||||
out
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Aktuelle UTC-Zeit als ISO-String — Frontmatter-`created` neu angelegter
|
|
||||||
/// Dokumente.
|
|
||||||
pub(crate) fn utc_now_iso() -> Result<String, String> {
|
|
||||||
let secs = SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.map_err(|e| e.to_string())?
|
|
||||||
.as_secs();
|
|
||||||
Ok(utc_stamp(secs).1)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// UTC aus Epoch-Sekunden: (Dateistempel `YYYY-MM-DD_HHMM`, ISO `…Z`).
|
|
||||||
fn utc_stamp(secs: u64) -> (String, String) {
|
|
||||||
let (h, mi, s) = (secs / 3600 % 24, secs / 60 % 60, secs % 60);
|
|
||||||
let (y, m, d) = civil_from_days((secs / 86400) as i64);
|
|
||||||
(
|
|
||||||
format!("{y:04}-{m:02}-{d:02}_{h:02}{mi:02}"),
|
|
||||||
format!("{y:04}-{m:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Kalenderdatum aus Tagen seit 1970-01-01 (Howard-Hinnant-Algorithmus).
|
|
||||||
fn civil_from_days(z: i64) -> (i64, u32, u32) {
|
|
||||||
let z = z + 719468;
|
|
||||||
let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
|
|
||||||
let doe = z - era * 146097;
|
|
||||||
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
|
|
||||||
let y = yoe + era * 400;
|
|
||||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
|
||||||
let mp = (5 * doy + 2) / 153;
|
|
||||||
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
|
||||||
let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
|
|
||||||
(if m <= 2 { y + 1 } else { y }, m, d)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn utc_stamp_bekannte_zeit() {
|
|
||||||
// 2026-07-11 (20645 Tage seit Epoch) um 11:14:15 UTC.
|
|
||||||
let secs = 20_645u64 * 86400 + 11 * 3600 + 14 * 60 + 15;
|
|
||||||
let (stamp, iso) = utc_stamp(secs);
|
|
||||||
assert_eq!(stamp, "2026-07-11_1114");
|
|
||||||
assert_eq!(iso, "2026-07-11T11:14:15Z");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Zweimal Archivieren in derselben Minute mit gleichem Titel darf die erste
|
|
||||||
/// Datei nicht überschreiben — der Stempel hat nur Minutenauflösung, und
|
|
||||||
/// die Datei entsteht bereits beim Anlegen (create_new), nicht erst beim
|
|
||||||
/// Schreiben.
|
|
||||||
#[test]
|
|
||||||
fn gleicher_stempel_und_titel_kollidiert_nicht() {
|
|
||||||
let dir = crate::domain::testutil::tmp_paths().home.join("archiv");
|
|
||||||
fs::create_dir_all(&dir).unwrap();
|
|
||||||
let (erste, mut f1) = create_unique(&dir, "2026-07-19_2118", "notiz").unwrap();
|
|
||||||
assert_eq!(erste.file_name().unwrap(), "2026-07-19_2118-notiz.md");
|
|
||||||
std::io::Write::write_all(&mut f1, b"alt").unwrap();
|
|
||||||
|
|
||||||
let (zweite, _f2) = create_unique(&dir, "2026-07-19_2118", "notiz").unwrap();
|
|
||||||
assert_eq!(zweite.file_name().unwrap(), "2026-07-19_2118-notiz-2.md");
|
|
||||||
|
|
||||||
assert_eq!(fs::read_to_string(&erste).unwrap(), "alt");
|
|
||||||
let (dritte, _f3) = create_unique(&dir, "2026-07-19_2118", "notiz").unwrap();
|
|
||||||
assert_eq!(dritte.file_name().unwrap(), "2026-07-19_2118-notiz-3.md");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn civil_from_days_referenz() {
|
|
||||||
assert_eq!(civil_from_days(0), (1970, 1, 1));
|
|
||||||
assert_eq!(civil_from_days(20_645), (2026, 7, 11));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn slugify_grenzen() {
|
|
||||||
assert_eq!(slugify("ADR: Logging vereinheitlichen"), "adr-logging-vereinheitlichen");
|
|
||||||
assert_eq!(slugify(" "), "entwurf");
|
|
||||||
assert_eq!(slugify("###"), "entwurf");
|
|
||||||
assert_eq!(slugify("Ein Test für's Archiv"), "ein-test-fuer-s-archiv");
|
|
||||||
assert_eq!(slugify("Größe ÄÖÜ"), "groesse-aeoeue");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stamp_und_strip_roundtrip() {
|
|
||||||
let (stamp, _) = utc_stamp(20_645u64 * 86400);
|
|
||||||
assert_eq!(strip_stamp(&format!("{stamp}-adr-logging")), "adr-logging");
|
|
||||||
assert_eq!(strip_stamp("adr-logging"), "adr-logging");
|
|
||||||
assert_eq!(strip_stamp("2026-07-19-adr"), "2026-07-19-adr");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn frontmatter_und_parser_roundtrip() {
|
|
||||||
let meta = ArchiveMeta {
|
|
||||||
folder: None,
|
|
||||||
description: Some("Kurz".into()),
|
|
||||||
tags: vec!["adr".into(), "infra".into()],
|
|
||||||
};
|
|
||||||
let fm = frontmatter("Titel", "proj", "2026-07-19T10:00:00Z", &meta);
|
|
||||||
let map = parse_frontmatter(&fm);
|
|
||||||
assert_eq!(map.get("title").map(String::as_str), Some("Titel"));
|
|
||||||
assert_eq!(map.get("description").map(String::as_str), Some("Kurz"));
|
|
||||||
assert_eq!(parse_tag_list(&map["tags"]), vec!["adr", "infra"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Umzug: Einträge wandern komplett, Namenskollision bricht laut ab.
|
|
||||||
#[test]
|
|
||||||
fn archiv_umzug_verschiebt_und_kollidiert_laut() {
|
|
||||||
let home = crate::domain::testutil::tmp_paths().home;
|
|
||||||
let (alt, neu) = (home.join("alt"), home.join("neu"));
|
|
||||||
fs::create_dir_all(alt.join("ordner")).unwrap();
|
|
||||||
fs::write(alt.join("doc.md"), "inhalt").unwrap();
|
|
||||||
fs::write(alt.join("ordner/tief.md"), "tief").unwrap();
|
|
||||||
fs::create_dir_all(&neu).unwrap();
|
|
||||||
|
|
||||||
move_dir_contents(&alt, &neu).unwrap();
|
|
||||||
assert_eq!(fs::read_to_string(neu.join("doc.md")).unwrap(), "inhalt");
|
|
||||||
assert_eq!(fs::read_to_string(neu.join("ordner/tief.md")).unwrap(), "tief");
|
|
||||||
assert!(fs::read_dir(&alt).unwrap().next().is_none());
|
|
||||||
|
|
||||||
// Kollision: gleicher Name im Ziel → Fehler, nichts überschrieben
|
|
||||||
fs::write(alt.join("doc.md"), "neuer").unwrap();
|
|
||||||
let err = move_dir_contents(&alt, &neu).unwrap_err();
|
|
||||||
assert!(err.contains("existiert schon"));
|
|
||||||
assert_eq!(fs::read_to_string(neu.join("doc.md")).unwrap(), "inhalt");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn check_folder_relativ_ohne_punktpunkt() {
|
|
||||||
assert!(check_folder("konzepte/panel").is_ok());
|
|
||||||
assert!(check_folder("../raus").is_err());
|
|
||||||
assert!(check_folder("a/../b").is_err());
|
|
||||||
assert!(check_folder("/absolut").is_err());
|
|
||||||
assert!(check_folder("").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn frontmatter_mit_und_ohne_meta() {
|
|
||||||
let leer = ArchiveMeta::default();
|
|
||||||
let fm = frontmatter("Titel", "proj", "2026-07-19T10:00:00Z", &leer);
|
|
||||||
assert!(fm.starts_with("---\ntitle: \"Titel\"\n"));
|
|
||||||
assert!(!fm.contains("description:"));
|
|
||||||
assert!(!fm.contains("tags:"));
|
|
||||||
|
|
||||||
let voll = ArchiveMeta {
|
|
||||||
folder: None,
|
|
||||||
description: Some("Kurz \"zitiert\"".into()),
|
|
||||||
tags: vec!["archiv".into(), "wiki".into()],
|
|
||||||
};
|
|
||||||
let fm = frontmatter("Titel", "proj", "2026-07-19T10:00:00Z", &voll);
|
|
||||||
assert!(fm.contains("description: \"Kurz 'zitiert'\"\n"));
|
|
||||||
assert!(fm.contains("tags: [\"archiv\", \"wiki\"]\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn first_line_ueberschrift_oder_erste_zeile() {
|
|
||||||
assert_eq!(first_line("\n\n# Titel\n\nText"), "Titel");
|
|
||||||
assert_eq!(first_line("Kein Heading\nzweite"), "Kein Heading");
|
|
||||||
assert_eq!(first_line(" \n"), "entwurf");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,427 +0,0 @@
|
|||||||
//! Archiv-Index: reproduzierbare Sicht über den Archiv-Baum eines Projekts —
|
|
||||||
//! pro Markdown-Dokument Name, Frontmatter-Metadaten und Wikilinks; Backlinks
|
|
||||||
//! fallen beim Scan als Nebenprodukt ab. Der Index ist abgeleitete Information
|
|
||||||
//! und wird bei Bedarf frisch aus dem Baum gebaut (nichts davon wird gesynct).
|
|
||||||
//! Das Dateiformat (Frontmatter, Zeitstempel-Stem) definiert archive.rs.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::fs;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use crate::domain::archive::{parse_frontmatter, parse_tag_list, slugify, strip_stamp};
|
|
||||||
|
|
||||||
#[derive(serde::Serialize, Clone)]
|
|
||||||
pub(crate) struct Doc {
|
|
||||||
/// Pfad relativ zum Archiv-Home.
|
|
||||||
pub(crate) relpath: String,
|
|
||||||
/// Wikilink-Name: Datei-Stem ohne führenden Zeitstempel.
|
|
||||||
pub(crate) name: String,
|
|
||||||
/// Frontmatter-Titel, sonst der Name.
|
|
||||||
pub(crate) title: String,
|
|
||||||
pub(crate) description: Option<String>,
|
|
||||||
pub(crate) tags: Vec<String>,
|
|
||||||
/// Frontmatter-`created` (ISO) — Datumsquelle für Dokumente ohne
|
|
||||||
/// Zeitstempel im Dateinamen.
|
|
||||||
pub(crate) created: Option<String>,
|
|
||||||
/// Wikilink-Ziele im Dokumenttext (`[[ziel]]`/`[[ziel|label]]`, nur das Ziel).
|
|
||||||
pub(crate) links: Vec<String>,
|
|
||||||
/// Namen der Dokumente, die per Wikilink hierher zeigen.
|
|
||||||
pub(crate) backlinks: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Scannt den Archiv-Baum rekursiv über alle Markdown-Dateien; versteckte
|
|
||||||
/// Einträge (Punkt-Präfix) bleiben außen vor. Reihenfolge: relpath sortiert;
|
|
||||||
/// Backlinks sind nach dem Scan gefüllt.
|
|
||||||
pub(crate) fn scan_archive(home: &Path) -> Result<Vec<Doc>, String> {
|
|
||||||
Ok(scan_with_bodies(home)?.into_iter().map(|(doc, _)| doc).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wie `scan_archive`, liefert zu jedem Dokument den bereits gelesenen
|
|
||||||
/// Volltext mit — die Suche indexiert damit ohne zweite Lesung pro Datei.
|
|
||||||
pub(crate) fn scan_with_bodies(home: &Path) -> Result<Vec<(Doc, String)>, String> {
|
|
||||||
let mut docs = Vec::new();
|
|
||||||
walk(home, home, &mut docs)?;
|
|
||||||
docs.sort_by(|a, b| a.0.relpath.cmp(&b.0.relpath));
|
|
||||||
fill_backlinks(&mut docs);
|
|
||||||
Ok(docs)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Backlinks in einem Durchlauf: Slug → Doc-Index einmal aufbauen, jeden Link
|
|
||||||
/// genau einmal auflösen und zu Backlinks invertieren.
|
|
||||||
fn fill_backlinks(docs: &mut [(Doc, String)]) {
|
|
||||||
let mut lookup: HashMap<String, usize> = HashMap::new();
|
|
||||||
for (i, (doc, _)) in docs.iter().enumerate() {
|
|
||||||
let stem = Path::new(&doc.relpath).file_stem().unwrap_or_default().to_string_lossy();
|
|
||||||
for key in [slugify(&doc.name), slugify(&doc.title), slugify(&stem)] {
|
|
||||||
lookup.entry(key).or_insert(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut back: Vec<Vec<String>> = vec![Vec::new(); docs.len()];
|
|
||||||
for (i, (doc, _)) in docs.iter().enumerate() {
|
|
||||||
let mut targets: std::collections::BTreeSet<usize> = docs[i]
|
|
||||||
.0
|
|
||||||
.links
|
|
||||||
.iter()
|
|
||||||
.filter_map(|l| lookup.get(&slugify(l)).copied())
|
|
||||||
.collect();
|
|
||||||
targets.remove(&i);
|
|
||||||
for t in targets {
|
|
||||||
back[t].push(doc.name.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for ((doc, _), b) in docs.iter_mut().zip(back) {
|
|
||||||
doc.backlinks = b;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn walk(home: &Path, dir: &Path, docs: &mut Vec<(Doc, String)>) -> Result<(), String> {
|
|
||||||
let entries = fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
|
||||||
for entry in entries {
|
|
||||||
let entry = entry.map_err(|e| format!("{}: {e}", dir.display()))?;
|
|
||||||
let path = entry.path();
|
|
||||||
let file_name = entry.file_name();
|
|
||||||
let fname = file_name.to_string_lossy();
|
|
||||||
if fname.starts_with('.') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if path.is_dir() {
|
|
||||||
walk(home, &path, docs)?;
|
|
||||||
} else if fname.ends_with(".md") {
|
|
||||||
docs.push(read_doc(home, &path)?);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_doc(home: &Path, path: &Path) -> Result<(Doc, String), String> {
|
|
||||||
let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
|
||||||
let stem = path.file_stem().unwrap_or_default().to_string_lossy().to_string();
|
|
||||||
let name = strip_stamp(&stem).to_string();
|
|
||||||
let fm = parse_frontmatter(&text);
|
|
||||||
let relpath = path
|
|
||||||
.strip_prefix(home)
|
|
||||||
.map_err(|e| format!("{}: {e}", path.display()))?
|
|
||||||
.display()
|
|
||||||
.to_string();
|
|
||||||
let doc = Doc {
|
|
||||||
relpath,
|
|
||||||
title: fm.get("title").unwrap_or(&name).clone(),
|
|
||||||
description: fm.get("description").cloned(),
|
|
||||||
tags: fm.get("tags").map(|t| parse_tag_list(t)).unwrap_or_default(),
|
|
||||||
created: fm.get("created").cloned(),
|
|
||||||
links: wikilinks(&text),
|
|
||||||
backlinks: Vec::new(),
|
|
||||||
name,
|
|
||||||
};
|
|
||||||
Ok((doc, text))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Slug-Vergleich eines Wikilink-Ziels gegen Name, Titel und Datei-Stem.
|
|
||||||
fn matches(doc: &Doc, want: &str) -> bool {
|
|
||||||
slugify(&doc.name) == want
|
|
||||||
|| slugify(&doc.title) == want
|
|
||||||
|| Path::new(&doc.relpath)
|
|
||||||
.file_stem()
|
|
||||||
.is_some_and(|s| slugify(&s.to_string_lossy()) == want)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Übersichts- bzw. Schlagwort-Seite als strukturierte Wiki-Daten: Dokumente
|
|
||||||
/// nach Ordnern gruppiert (neueste zuerst), Schlagwort-Leiste mit Zählern.
|
|
||||||
/// Das Panel rendert daraus die Wiki-Ansicht; `kind` unterscheidet im
|
|
||||||
/// Wiki-Puffer Seite und Dokument.
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
pub(crate) struct WikiPage {
|
|
||||||
pub(crate) kind: &'static str,
|
|
||||||
pub(crate) home: String,
|
|
||||||
pub(crate) tag: Option<String>,
|
|
||||||
pub(crate) total: usize,
|
|
||||||
pub(crate) tags: Vec<TagCount>,
|
|
||||||
pub(crate) folders: Vec<WikiFolder>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
pub(crate) struct TagCount {
|
|
||||||
pub(crate) name: String,
|
|
||||||
pub(crate) count: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
pub(crate) struct WikiFolder {
|
|
||||||
/// Ordner relativ zum Archiv-Home; leer für die Wurzel.
|
|
||||||
pub(crate) name: String,
|
|
||||||
pub(crate) docs: Vec<WikiDocEntry>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
pub(crate) struct WikiDocEntry {
|
|
||||||
/// Pfad relativ zum Archiv-Home — Sprung ins Dokument und Adressat der
|
|
||||||
/// Zeilen-Aktionen (umbenennen, löschen).
|
|
||||||
pub(crate) relpath: String,
|
|
||||||
pub(crate) name: String,
|
|
||||||
pub(crate) title: String,
|
|
||||||
pub(crate) description: Option<String>,
|
|
||||||
pub(crate) tags: Vec<String>,
|
|
||||||
/// Archivierungsdatum aus dem Zeitstempel-Stem (`YYYY-MM-DD`).
|
|
||||||
pub(crate) date: Option<String>,
|
|
||||||
/// Zahl der Dokumente, die per Wikilink hierher zeigen.
|
|
||||||
pub(crate) backlinks: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn archive_page(home: &Path, tag: Option<&str>) -> Result<WikiPage, String> {
|
|
||||||
let docs = scan_archive(home)?;
|
|
||||||
let mut counts: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
|
|
||||||
for doc in &docs {
|
|
||||||
for t in &doc.tags {
|
|
||||||
*counts.entry(t).or_default() += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let selected: Vec<&Doc> = match tag {
|
|
||||||
Some(t) => docs.iter().filter(|d| d.tags.iter().any(|x| x == t)).collect(),
|
|
||||||
None => docs.iter().collect(),
|
|
||||||
};
|
|
||||||
let mut folders: std::collections::BTreeMap<String, Vec<&Doc>> =
|
|
||||||
std::collections::BTreeMap::new();
|
|
||||||
// Die Übersicht führt alle Ordner, auch dokumentlose — der Navigator zeigt
|
|
||||||
// frisch angelegte Ordner sonst nicht. Schlagwort-Seiten bleiben auf die
|
|
||||||
// Treffer-Ordner beschränkt.
|
|
||||||
if tag.is_none() {
|
|
||||||
let mut dirs = Vec::new();
|
|
||||||
folder_paths(home, home, &mut dirs)?;
|
|
||||||
for d in dirs {
|
|
||||||
folders.entry(d).or_default();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for doc in &selected {
|
|
||||||
let folder = Path::new(&doc.relpath)
|
|
||||||
.parent()
|
|
||||||
.map(|p| p.display().to_string())
|
|
||||||
.unwrap_or_default();
|
|
||||||
folders.entry(folder).or_default().push(doc);
|
|
||||||
}
|
|
||||||
Ok(WikiPage {
|
|
||||||
kind: "page",
|
|
||||||
home: home.display().to_string(),
|
|
||||||
tag: tag.map(str::to_string),
|
|
||||||
total: selected.len(),
|
|
||||||
tags: counts
|
|
||||||
.into_iter()
|
|
||||||
.map(|(name, count)| TagCount { name: name.to_string(), count })
|
|
||||||
.collect(),
|
|
||||||
folders: folders
|
|
||||||
.into_iter()
|
|
||||||
.map(|(name, mut list)| {
|
|
||||||
// Zeitstempel-Stems sortieren chronologisch — absteigend = neueste oben.
|
|
||||||
list.sort_by(|a, b| b.relpath.cmp(&a.relpath));
|
|
||||||
WikiFolder { name, docs: list.into_iter().map(doc_entry).collect() }
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Alle Ordner-Relpaths unterhalb von `dir`, rekursiv; versteckte Einträge
|
|
||||||
/// (Punkt-Präfix) bleiben außen vor — wie beim Dokument-Scan.
|
|
||||||
fn folder_paths(home: &Path, dir: &Path, out: &mut Vec<String>) -> Result<(), String> {
|
|
||||||
let entries = fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
|
||||||
for entry in entries {
|
|
||||||
let entry = entry.map_err(|e| format!("{}: {e}", dir.display()))?;
|
|
||||||
let path = entry.path();
|
|
||||||
if entry.file_name().to_string_lossy().starts_with('.') || !path.is_dir() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
out.push(path.strip_prefix(home).unwrap().display().to_string());
|
|
||||||
folder_paths(home, &path, out)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn doc_entry(doc: &Doc) -> WikiDocEntry {
|
|
||||||
let stem = Path::new(&doc.relpath)
|
|
||||||
.file_stem()
|
|
||||||
.unwrap_or_default()
|
|
||||||
.to_string_lossy()
|
|
||||||
.to_string();
|
|
||||||
// Zeitstempel im Dateinamen, sonst der Frontmatter-`created`-Tag —
|
|
||||||
// im Navigator angelegte Dokumente tragen das Datum nur dort.
|
|
||||||
let date = (stem != doc.name)
|
|
||||||
.then(|| stem[..10].to_string())
|
|
||||||
.or_else(|| {
|
|
||||||
doc
|
|
||||||
.created
|
|
||||||
.as_ref()
|
|
||||||
.filter(|c| c.len() >= 10)
|
|
||||||
.map(|c| c[..10].to_string())
|
|
||||||
});
|
|
||||||
WikiDocEntry {
|
|
||||||
relpath: doc.relpath.clone(),
|
|
||||||
name: doc.name.clone(),
|
|
||||||
title: doc.title.clone(),
|
|
||||||
description: doc.description.clone(),
|
|
||||||
tags: doc.tags.clone(),
|
|
||||||
date,
|
|
||||||
backlinks: doc.backlinks.len(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Löst ein Wikilink-Ziel (Name, Titel oder Datei-Stem) gegen das Archiv auf
|
|
||||||
/// und liefert den relpath des Dokuments.
|
|
||||||
pub(crate) fn resolve_doc(home: &Path, target: &str) -> Result<String, String> {
|
|
||||||
let docs = scan_archive(home)?;
|
|
||||||
let want = slugify(target);
|
|
||||||
docs
|
|
||||||
.iter()
|
|
||||||
.find(|d| matches(d, &want))
|
|
||||||
.map(|d| d.relpath.clone())
|
|
||||||
.ok_or_else(|| format!("kein Archiv-Dokument zu „{target}“ gefunden"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Alle `[[ziel]]`-Vorkommen im Text, in Dokumentreihenfolge; bei
|
|
||||||
/// `[[ziel|label]]` zählt nur das Ziel.
|
|
||||||
fn wikilinks(text: &str) -> Vec<String> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
let mut rest = text;
|
|
||||||
while let Some(start) = rest.find("[[") {
|
|
||||||
rest = &rest[start + 2..];
|
|
||||||
let Some(end) = rest.find("]]") else {
|
|
||||||
break;
|
|
||||||
};
|
|
||||||
let inner = &rest[..end];
|
|
||||||
let target = inner.split('|').next().unwrap_or(inner).trim();
|
|
||||||
if !target.is_empty() {
|
|
||||||
out.push(target.to_string());
|
|
||||||
}
|
|
||||||
rest = &rest[end + 2..];
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::domain::testutil::tmp_paths;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
fn write(home: &Path, rel: &str, content: &str) {
|
|
||||||
let path = home.join(rel);
|
|
||||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
|
||||||
fs::write(path, content).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn archiv() -> PathBuf {
|
|
||||||
let home = tmp_paths().home.join("archiv");
|
|
||||||
fs::create_dir_all(&home).unwrap();
|
|
||||||
write(
|
|
||||||
&home,
|
|
||||||
"2026-07-19_1000-adr-logging.md",
|
|
||||||
"---\ntitle: \"ADR Logging\"\ndescription: \"Logging vereinheitlichen\"\ntags: [\"adr\", \"infra\"]\n---\n\nSiehe [[notiz-deploy|die Deploy-Notiz]].\n",
|
|
||||||
);
|
|
||||||
write(
|
|
||||||
&home,
|
|
||||||
"konzepte/2026-07-19_1005-notiz-deploy.md",
|
|
||||||
"---\ntitle: \"Notiz Deploy\"\n---\n\nText ohne Links.\n",
|
|
||||||
);
|
|
||||||
write(&home, ".versteckt/ignoriert.md", "unsichtbar");
|
|
||||||
home
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_liest_baum_frontmatter_und_links() {
|
|
||||||
let home = archiv();
|
|
||||||
let docs = scan_archive(&home).unwrap();
|
|
||||||
assert_eq!(docs.len(), 2);
|
|
||||||
let adr = &docs[0];
|
|
||||||
assert_eq!(adr.name, "adr-logging");
|
|
||||||
assert_eq!(adr.title, "ADR Logging");
|
|
||||||
assert_eq!(adr.description.as_deref(), Some("Logging vereinheitlichen"));
|
|
||||||
assert_eq!(adr.tags, vec!["adr", "infra"]);
|
|
||||||
assert_eq!(adr.links, vec!["notiz-deploy"]);
|
|
||||||
assert_eq!(docs[1].relpath, "konzepte/2026-07-19_1005-notiz-deploy.md");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn backlinks_aus_wikilinks() {
|
|
||||||
let home = archiv();
|
|
||||||
let docs = scan_archive(&home).unwrap();
|
|
||||||
let deploy = docs.iter().find(|d| d.name == "notiz-deploy").unwrap();
|
|
||||||
assert_eq!(deploy.backlinks, vec!["adr-logging"]);
|
|
||||||
let adr = docs.iter().find(|d| d.name == "adr-logging").unwrap();
|
|
||||||
assert!(adr.backlinks.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn startseite_gruppiert_und_zaehlt() {
|
|
||||||
let home = archiv();
|
|
||||||
let page = archive_page(&home, None).unwrap();
|
|
||||||
assert_eq!(page.kind, "page");
|
|
||||||
assert_eq!(page.tag, None);
|
|
||||||
assert_eq!(page.total, 2);
|
|
||||||
let tags: Vec<(&str, usize)> =
|
|
||||||
page.tags.iter().map(|t| (t.name.as_str(), t.count)).collect();
|
|
||||||
assert_eq!(tags, vec![("adr", 1), ("infra", 1)]);
|
|
||||||
assert_eq!(page.folders.len(), 2);
|
|
||||||
assert_eq!(page.folders[0].name, "");
|
|
||||||
let adr = &page.folders[0].docs[0];
|
|
||||||
assert_eq!(adr.name, "adr-logging");
|
|
||||||
assert_eq!(adr.title, "ADR Logging");
|
|
||||||
assert_eq!(adr.description.as_deref(), Some("Logging vereinheitlichen"));
|
|
||||||
assert_eq!(adr.date.as_deref(), Some("2026-07-19"));
|
|
||||||
assert_eq!(adr.relpath, "2026-07-19_1000-adr-logging.md");
|
|
||||||
assert_eq!(page.folders[1].name, "konzepte");
|
|
||||||
assert_eq!(page.folders[1].docs[0].name, "notiz-deploy");
|
|
||||||
assert_eq!(page.folders[1].docs[0].backlinks, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn leere_ordner_und_created_datum() {
|
|
||||||
let home = archiv();
|
|
||||||
fs::create_dir_all(home.join("leer/unter")).unwrap();
|
|
||||||
write(
|
|
||||||
&home,
|
|
||||||
"notiz-plain.md",
|
|
||||||
"---\ntitle: \"Plain\"\ncreated: 2026-07-23T10:00:00Z\n---\n\nText.\n",
|
|
||||||
);
|
|
||||||
let page = archive_page(&home, None).unwrap();
|
|
||||||
let names: Vec<&str> = page.folders.iter().map(|f| f.name.as_str()).collect();
|
|
||||||
// Dokumentlose Ordner erscheinen (Navigator), versteckte weiterhin nicht.
|
|
||||||
assert!(names.contains(&"leer"));
|
|
||||||
assert!(names.contains(&"leer/unter"));
|
|
||||||
assert!(!names.iter().any(|n| n.starts_with(".versteckt")));
|
|
||||||
// Ohne Zeitstempel im Namen kommt das Datum aus dem Frontmatter-created.
|
|
||||||
let plain = page
|
|
||||||
.folders
|
|
||||||
.iter()
|
|
||||||
.find(|f| f.name.is_empty())
|
|
||||||
.unwrap()
|
|
||||||
.docs
|
|
||||||
.iter()
|
|
||||||
.find(|d| d.name == "notiz-plain")
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(plain.date.as_deref(), Some("2026-07-23"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tag_seite_filtert() {
|
|
||||||
let home = archiv();
|
|
||||||
let page = archive_page(&home, Some("adr")).unwrap();
|
|
||||||
assert_eq!(page.tag.as_deref(), Some("adr"));
|
|
||||||
assert_eq!(page.total, 1);
|
|
||||||
assert_eq!(page.folders.len(), 1);
|
|
||||||
assert_eq!(page.folders[0].docs[0].name, "adr-logging");
|
|
||||||
// Die Schlagwort-Leiste bleibt vollständig — sie ist die Navigation.
|
|
||||||
assert_eq!(page.tags.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_ueber_name_titel_und_stem() {
|
|
||||||
let home = archiv();
|
|
||||||
// Auflösung über Titel; Name und Stem gehen über dieselben Slug-Vergleiche.
|
|
||||||
assert_eq!(
|
|
||||||
resolve_doc(&home, "Notiz Deploy").unwrap(),
|
|
||||||
"konzepte/2026-07-19_1005-notiz-deploy.md"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
resolve_doc(&home, "2026-07-19_1000-adr-logging").unwrap(),
|
|
||||||
"2026-07-19_1000-adr-logging.md"
|
|
||||||
);
|
|
||||||
assert!(resolve_doc(&home, "fehlt").is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,275 +0,0 @@
|
|||||||
//! Dokument- und Ordner-Operationen im Archiv-Baum (Baum-Navigation im
|
|
||||||
//! Panel): verschieben, umbenennen, löschen. Alle Pfade sind relativ zum
|
|
||||||
//! Archiv-Home und strikt darauf begrenzt — die relpaths kommen aus dem
|
|
||||||
//! Webview, ein Traversal-Bestandteil bricht laut ab.
|
|
||||||
|
|
||||||
use std::fs;
|
|
||||||
use std::path::{Component, Path, PathBuf};
|
|
||||||
|
|
||||||
use crate::domain::archive::{
|
|
||||||
frontmatter, slugify, strip_frontmatter, strip_stamp, utc_now_iso, ArchiveMeta,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Relativer Pfad ohne Traversal: nur normale Komponenten, nichts Absolutes.
|
|
||||||
fn checked_rel(rel: &str) -> Result<(), String> {
|
|
||||||
if rel.is_empty() {
|
|
||||||
return Err("leerer Pfad".into());
|
|
||||||
}
|
|
||||||
for c in Path::new(rel).components() {
|
|
||||||
match c {
|
|
||||||
Component::Normal(_) => {}
|
|
||||||
_ => return Err(format!("unzulässiger Pfad: {rel}")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Vorhandenes Archiv-Dokument zum relpath.
|
|
||||||
fn doc_path(home: &Path, relpath: &str) -> Result<PathBuf, String> {
|
|
||||||
checked_rel(relpath)?;
|
|
||||||
if !relpath.ends_with(".md") {
|
|
||||||
return Err(format!("kein Markdown-Dokument: {relpath}"));
|
|
||||||
}
|
|
||||||
let path = home.join(relpath);
|
|
||||||
if !path.is_file() {
|
|
||||||
return Err(format!("Dokument nicht gefunden: {relpath}"));
|
|
||||||
}
|
|
||||||
Ok(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ziel für rename: darf noch nicht existieren — stilles Überschreiben wäre
|
|
||||||
/// Datenverlust.
|
|
||||||
fn fresh_target(target: &Path, home: &Path) -> Result<(), String> {
|
|
||||||
if target.exists() {
|
|
||||||
return Err(format!(
|
|
||||||
"Ziel existiert bereits: {}",
|
|
||||||
target.strip_prefix(home).unwrap_or(target).display()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Verschiebt ein Dokument in einen anderen Ordner (leer = Wurzel); der
|
|
||||||
/// Zielordner entsteht bei Bedarf. Liefert den neuen relpath.
|
|
||||||
pub(crate) fn move_doc(home: &Path, relpath: &str, folder: &str) -> Result<String, String> {
|
|
||||||
let src = doc_path(home, relpath)?;
|
|
||||||
if !folder.is_empty() {
|
|
||||||
checked_rel(folder)?;
|
|
||||||
}
|
|
||||||
let file_name = src.file_name().unwrap();
|
|
||||||
let dir = home.join(folder);
|
|
||||||
let target = dir.join(file_name);
|
|
||||||
if target == src {
|
|
||||||
return Ok(relpath.to_string());
|
|
||||||
}
|
|
||||||
fresh_target(&target, home)?;
|
|
||||||
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
|
||||||
fs::rename(&src, &target).map_err(|e| format!("{}: {e}", src.display()))?;
|
|
||||||
Ok(target.strip_prefix(home).unwrap().display().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Benennt ein Dokument um: neuer Name als Slug hinter dem (erhaltenen)
|
|
||||||
/// Zeitstempel. Liefert den neuen relpath.
|
|
||||||
pub(crate) fn rename_doc(home: &Path, relpath: &str, name: &str) -> Result<String, String> {
|
|
||||||
let src = doc_path(home, relpath)?;
|
|
||||||
let stem = src.file_stem().unwrap().to_string_lossy().to_string();
|
|
||||||
let stamp = &stem[..stem.len() - strip_stamp(&stem).len()];
|
|
||||||
let target = src.with_file_name(format!("{stamp}{}.md", slugify(name)));
|
|
||||||
if target == src {
|
|
||||||
return Ok(relpath.to_string());
|
|
||||||
}
|
|
||||||
fresh_target(&target, home)?;
|
|
||||||
fs::rename(&src, &target).map_err(|e| format!("{}: {e}", src.display()))?;
|
|
||||||
Ok(target.strip_prefix(home).unwrap().display().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn delete_doc(home: &Path, relpath: &str) -> Result<(), String> {
|
|
||||||
let path = doc_path(home, relpath)?;
|
|
||||||
fs::remove_file(&path).map_err(|e| format!("{}: {e}", path.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Legt einen (auch leeren) Ordner unterhalb des Archiv-Home an.
|
|
||||||
pub(crate) fn create_folder(home: &Path, folder: &str) -> Result<(), String> {
|
|
||||||
checked_rel(folder)?;
|
|
||||||
let dir = home.join(folder);
|
|
||||||
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Legt ein leeres Dokument an: `<slug>.md` im Ordner (leer = Wurzel), das
|
|
||||||
/// Datum steht in der Frontmatter (`created`), nicht im Dateinamen. Liefert
|
|
||||||
/// den relpath.
|
|
||||||
pub(crate) fn create_doc(
|
|
||||||
home: &Path,
|
|
||||||
folder: &str,
|
|
||||||
name: &str,
|
|
||||||
project_name: &str,
|
|
||||||
) -> Result<String, String> {
|
|
||||||
let name = name.trim();
|
|
||||||
if name.is_empty() {
|
|
||||||
return Err("Dokumentname fehlt".into());
|
|
||||||
}
|
|
||||||
if !folder.is_empty() {
|
|
||||||
checked_rel(folder)?;
|
|
||||||
}
|
|
||||||
let dir = home.join(folder);
|
|
||||||
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
|
||||||
let target = dir.join(format!("{}.md", slugify(name)));
|
|
||||||
let fm = frontmatter(name, project_name, &utc_now_iso()?, &ArchiveMeta::default());
|
|
||||||
let mut file = match fs::OpenOptions::new().write(true).create_new(true).open(&target) {
|
|
||||||
Ok(f) => f,
|
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
|
|
||||||
return Err(format!(
|
|
||||||
"Ziel existiert bereits: {}",
|
|
||||||
target.strip_prefix(home).unwrap_or(&target).display()
|
|
||||||
))
|
|
||||||
}
|
|
||||||
Err(e) => return Err(format!("{}: {e}", target.display())),
|
|
||||||
};
|
|
||||||
std::io::Write::write_all(&mut file, fm.as_bytes())
|
|
||||||
.map_err(|e| format!("{}: {e}", target.display()))?;
|
|
||||||
Ok(target.strip_prefix(home).unwrap().display().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Schreibt den Panel-Body zurück in ein Archiv-Dokument (Quell-Verknüpfung
|
|
||||||
/// des Dokument-Tabs): der Frontmatter-Block der Datei bleibt, der Rumpf wird
|
|
||||||
/// ersetzt.
|
|
||||||
pub(crate) fn write_body(path: &Path, text: &str) -> Result<(), String> {
|
|
||||||
let doc = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
|
||||||
let head = doc.len() - strip_frontmatter(&doc).len();
|
|
||||||
let out = format!("{}{}\n", &doc[..head], text.trim_end());
|
|
||||||
fs::write(path, out).map_err(|e| format!("{}: {e}", path.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Verschiebt bzw. benennt einen ganzen Ordner um (fs::rename des
|
|
||||||
/// Verzeichnisses); Eltern des Ziels entstehen bei Bedarf.
|
|
||||||
pub(crate) fn move_folder(home: &Path, folder: &str, to: &str) -> Result<(), String> {
|
|
||||||
checked_rel(folder)?;
|
|
||||||
checked_rel(to)?;
|
|
||||||
let src = home.join(folder);
|
|
||||||
if !src.is_dir() {
|
|
||||||
return Err(format!("Ordner nicht gefunden: {folder}"));
|
|
||||||
}
|
|
||||||
let target = home.join(to);
|
|
||||||
if target == src {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
fresh_target(&target, home)?;
|
|
||||||
if let Some(parent) = target.parent() {
|
|
||||||
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
|
||||||
}
|
|
||||||
fs::rename(&src, &target).map_err(|e| format!("{}: {e}", src.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::domain::testutil::tmp_paths;
|
|
||||||
|
|
||||||
fn archiv() -> PathBuf {
|
|
||||||
let home = tmp_paths().home.join("archiv");
|
|
||||||
fs::create_dir_all(home.join("konzepte")).unwrap();
|
|
||||||
fs::write(home.join("2026-07-19_1000-adr-logging.md"), "a").unwrap();
|
|
||||||
fs::write(home.join("konzepte/2026-07-19_1005-notiz-deploy.md"), "b").unwrap();
|
|
||||||
home
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn verschieben_legt_ordner_an_und_liefert_relpath() {
|
|
||||||
let home = archiv();
|
|
||||||
let rel = move_doc(&home, "2026-07-19_1000-adr-logging.md", "adr/2026").unwrap();
|
|
||||||
assert_eq!(rel, "adr/2026/2026-07-19_1000-adr-logging.md");
|
|
||||||
assert!(home.join(&rel).is_file());
|
|
||||||
|
|
||||||
// In die Wurzel zurück: leerer Zielordner.
|
|
||||||
let rel = move_doc(&home, &rel, "").unwrap();
|
|
||||||
assert_eq!(rel, "2026-07-19_1000-adr-logging.md");
|
|
||||||
|
|
||||||
// Gleiches Ziel ist ein No-Op, kein Fehler.
|
|
||||||
assert_eq!(move_doc(&home, &rel, "").unwrap(), rel);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn verschieben_ueberschreibt_nicht() {
|
|
||||||
let home = archiv();
|
|
||||||
fs::write(home.join("konzepte/2026-07-19_1000-adr-logging.md"), "alt").unwrap();
|
|
||||||
let err = move_doc(&home, "2026-07-19_1000-adr-logging.md", "konzepte").unwrap_err();
|
|
||||||
assert!(err.contains("existiert bereits"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn traversal_und_fremde_pfade_brechen_ab() {
|
|
||||||
let home = archiv();
|
|
||||||
assert!(move_doc(&home, "../2026-07-19_1000-adr-logging.md", "x").is_err());
|
|
||||||
assert!(move_doc(&home, "2026-07-19_1000-adr-logging.md", "../raus").is_err());
|
|
||||||
assert!(move_doc(&home, "/etc/passwd.md", "x").is_err());
|
|
||||||
assert!(delete_doc(&home, "konzepte").is_err()); // kein .md
|
|
||||||
assert!(move_folder(&home, "konzepte", "../raus").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn umbenennen_erhaelt_stempel_und_sluggt() {
|
|
||||||
let home = archiv();
|
|
||||||
let rel =
|
|
||||||
rename_doc(&home, "konzepte/2026-07-19_1005-notiz-deploy.md", "Deploy Nötiz!").unwrap();
|
|
||||||
assert_eq!(rel, "konzepte/2026-07-19_1005-deploy-noetiz.md");
|
|
||||||
assert!(home.join(&rel).is_file());
|
|
||||||
|
|
||||||
// Ohne Stempel bleibt der Name pur.
|
|
||||||
fs::write(home.join("plain.md"), "c").unwrap();
|
|
||||||
assert_eq!(rename_doc(&home, "plain.md", "Neu").unwrap(), "neu.md");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn anlegen_ordner_und_dokument() {
|
|
||||||
let home = archiv();
|
|
||||||
create_folder(&home, "notizen/2026").unwrap();
|
|
||||||
assert!(home.join("notizen/2026").is_dir());
|
|
||||||
assert!(create_folder(&home, "../raus").is_err());
|
|
||||||
|
|
||||||
let rel = create_doc(&home, "notizen/2026", "Deploy Nötiz!", "proj").unwrap();
|
|
||||||
assert_eq!(rel, "notizen/2026/deploy-noetiz.md");
|
|
||||||
let text = fs::read_to_string(home.join(&rel)).unwrap();
|
|
||||||
assert!(text.starts_with("---\ntitle: \"Deploy Nötiz!\"\n"));
|
|
||||||
assert!(text.contains("created: "));
|
|
||||||
|
|
||||||
// In der Wurzel, gleicher Name kollidiert laut, leerer Name bricht ab.
|
|
||||||
assert_eq!(create_doc(&home, "", "Plain", "proj").unwrap(), "plain.md");
|
|
||||||
let err = create_doc(&home, "notizen/2026", "Deploy Nötiz!", "proj").unwrap_err();
|
|
||||||
assert!(err.contains("existiert bereits"));
|
|
||||||
assert!(create_doc(&home, "", " ", "proj").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn write_body_ersetzt_rumpf_und_erhaelt_frontmatter() {
|
|
||||||
let home = archiv();
|
|
||||||
let path = home.join("mit-fm.md");
|
|
||||||
fs::write(&path, "---\ntitle: \"T\"\n---\n\nalter Text\n").unwrap();
|
|
||||||
write_body(&path, "neuer Text").unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
fs::read_to_string(&path).unwrap(),
|
|
||||||
"---\ntitle: \"T\"\n---\n\nneuer Text\n"
|
|
||||||
);
|
|
||||||
|
|
||||||
// Ohne Frontmatter wird die Datei komplett ersetzt.
|
|
||||||
let plain = home.join("ohne-fm.md");
|
|
||||||
fs::write(&plain, "alt").unwrap();
|
|
||||||
write_body(&plain, "neu").unwrap();
|
|
||||||
assert_eq!(fs::read_to_string(&plain).unwrap(), "neu\n");
|
|
||||||
|
|
||||||
assert!(write_body(&home.join("fehlt.md"), "x").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn loeschen_und_ordner_verschieben() {
|
|
||||||
let home = archiv();
|
|
||||||
delete_doc(&home, "2026-07-19_1000-adr-logging.md").unwrap();
|
|
||||||
assert!(!home.join("2026-07-19_1000-adr-logging.md").exists());
|
|
||||||
|
|
||||||
move_folder(&home, "konzepte", "notizen/2026").unwrap();
|
|
||||||
assert!(home.join("notizen/2026/2026-07-19_1005-notiz-deploy.md").is_file());
|
|
||||||
assert!(!home.join("konzepte").exists());
|
|
||||||
|
|
||||||
let err = move_folder(&home, "fehlt", "x").unwrap_err();
|
|
||||||
assert!(err.contains("nicht gefunden"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,227 +0,0 @@
|
|||||||
//! Volltext-Suche übers Panel-Archiv: SQLite-FTS5-Index, bei jeder Anfrage
|
|
||||||
//! frisch in-memory aus dem Archiv-Baum gebaut. Bei den Archiv-Größen dieser
|
|
||||||
//! App ist der Aufbau Millisekundensache; damit gibt es keinen persistierten
|
|
||||||
//! Index, keine Staleness und nichts, was gesynct werden könnte. Die
|
|
||||||
//! Tool-Schnittstelle bleibt engine-unabhängig.
|
|
||||||
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use rusqlite::Connection;
|
|
||||||
|
|
||||||
use crate::domain::archive_index::scan_with_bodies;
|
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
pub(crate) struct Hit {
|
|
||||||
/// Pfad relativ zum Archiv-Home.
|
|
||||||
pub(crate) relpath: String,
|
|
||||||
pub(crate) title: String,
|
|
||||||
/// Textausschnitt um die Fundstelle, Treffer in `**…**`.
|
|
||||||
pub(crate) snippet: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Durchsucht das Archiv unter `home`. `query` ist FTS5-Syntax (Wörter,
|
|
||||||
/// "Phrasen", Präfix*); `tag` engt auf ein Schlagwort ein. Treffer nach
|
|
||||||
/// BM25-Rang, höchstens `limit`.
|
|
||||||
pub(crate) fn search(
|
|
||||||
home: &Path,
|
|
||||||
query: &str,
|
|
||||||
tag: Option<&str>,
|
|
||||||
limit: usize,
|
|
||||||
) -> Result<Vec<Hit>, String> {
|
|
||||||
let q = sanitize_query(query);
|
|
||||||
let t = tag.and_then(|t| quote_phrase(t, false)).map(|t| format!("tags:{t}"));
|
|
||||||
let expr = match (q.is_empty(), t) {
|
|
||||||
(false, Some(t)) => format!("({q}) AND {t}"),
|
|
||||||
(false, None) => q,
|
|
||||||
(true, Some(t)) => t,
|
|
||||||
// Von vornherein leere Anfrage ist ein Bedienfehler. Eine Eingabe, die nur
|
|
||||||
// aus Satzzeichen bestand (`!?`, ein einzelnes `"`, das angetippte `#`),
|
|
||||||
// findet dagegen schlicht nichts — und spart sich den Index-Aufbau.
|
|
||||||
(true, None) if query.trim().is_empty() && tag.is_none() => {
|
|
||||||
return Err("leere Suchanfrage".into())
|
|
||||||
}
|
|
||||||
(true, None) => return Ok(Vec::new()),
|
|
||||||
};
|
|
||||||
let conn = build_index(home)?;
|
|
||||||
let mut stmt = conn
|
|
||||||
.prepare(
|
|
||||||
"SELECT relpath, title, snippet(docs, 5, '**', '**', ' … ', 12) \
|
|
||||||
FROM docs WHERE docs MATCH ?1 ORDER BY rank LIMIT ?2",
|
|
||||||
)
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
let rows = stmt
|
|
||||||
.query_map(rusqlite::params![expr, limit as i64], |row| {
|
|
||||||
Ok(Hit { relpath: row.get(0)?, title: row.get(1)?, snippet: row.get(2)? })
|
|
||||||
})
|
|
||||||
.map_err(|e| format!("Suchausdruck „{query}“: {e}"))?;
|
|
||||||
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Übersetzt die Nutzereingabe in einen FTS5-Ausdruck, der nicht scheitern kann.
|
|
||||||
///
|
|
||||||
/// Roh durchgereicht ist fast jede natürliche Eingabe ein Syntaxfehler: `ai-control`
|
|
||||||
/// liest FTS5 als Spaltenfilter (`no such column: control`), `C++` und eine offene
|
|
||||||
/// Klammer brechen den Parser. Die Live-Suche schickt zudem jeden Zwischenstand beim
|
|
||||||
/// Tippen ab, also auch das halbe `"Phrase`. Darum wird jedes Wort als Phrase
|
|
||||||
/// gequotet — die Tokenizer-Regeln bleiben dieselben, nur die Operatorzeichen
|
|
||||||
/// verlieren ihre Sonderbedeutung. Erhalten bleiben die zwei Formen, die Nutzer
|
|
||||||
/// bewusst tippen: "Phrasen in Anführungszeichen" und Präfix*.
|
|
||||||
fn sanitize_query(query: &str) -> String {
|
|
||||||
let mut out: Vec<String> = Vec::new();
|
|
||||||
// An `"` aufteilen: ungerade Segmente standen in Anführungszeichen und
|
|
||||||
// bleiben als Ganzes eine Phrase, gerade zerfallen in Wörter. Ein fehlendes
|
|
||||||
// schließendes Anführungszeichen (Tippzwischenstand) fällt damit von selbst
|
|
||||||
// richtig heraus — der Rest der Eingabe ist das letzte ungerade Segment.
|
|
||||||
for (i, teil) in query.split('"').enumerate() {
|
|
||||||
if i % 2 == 1 {
|
|
||||||
out.extend(quote_phrase(teil, false));
|
|
||||||
} else {
|
|
||||||
out.extend(
|
|
||||||
teil
|
|
||||||
.split_whitespace()
|
|
||||||
.filter_map(|w| quote_phrase(w.trim_end_matches('*'), w.ends_with('*'))),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out.join(" ")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `term` als gequotete FTS5-Phrase, sofern überhaupt etwas Indexierbares darin
|
|
||||||
/// steht. Reine Satzzeichen ergäben die leere Phrase `""` — für FTS5 ein
|
|
||||||
/// Syntaxfehler. Gilt auch für den Tag-Filter: Das angetippte `#` liefert über
|
|
||||||
/// `panel-wiring.ts` den leeren Tag.
|
|
||||||
fn quote_phrase(term: &str, prefix: bool) -> Option<String> {
|
|
||||||
if !term.chars().any(char::is_alphanumeric) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let quoted = term.replace('"', "");
|
|
||||||
Some(if prefix { format!("\"{quoted}\"*") } else { format!("\"{quoted}\"") })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Baut den FTS5-Index in-memory aus dem Archiv-Baum.
|
|
||||||
fn build_index(home: &Path) -> Result<Connection, String> {
|
|
||||||
let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
|
|
||||||
conn
|
|
||||||
.execute_batch(
|
|
||||||
"CREATE VIRTUAL TABLE docs USING fts5(relpath UNINDEXED, name, title, description, tags, body)",
|
|
||||||
)
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
let docs = scan_with_bodies(home)?;
|
|
||||||
let mut insert = conn
|
|
||||||
.prepare("INSERT INTO docs (relpath, name, title, description, tags, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
for (doc, body) in &docs {
|
|
||||||
insert
|
|
||||||
.execute(rusqlite::params![
|
|
||||||
doc.relpath,
|
|
||||||
doc.name,
|
|
||||||
doc.title,
|
|
||||||
doc.description.as_deref().unwrap_or(""),
|
|
||||||
doc.tags.join(" "),
|
|
||||||
body,
|
|
||||||
])
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
}
|
|
||||||
drop(insert);
|
|
||||||
Ok(conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::domain::testutil::tmp_paths;
|
|
||||||
use std::fs;
|
|
||||||
|
|
||||||
fn archiv() -> std::path::PathBuf {
|
|
||||||
let home = tmp_paths().home.join("archiv");
|
|
||||||
fs::create_dir_all(home.join("konzepte")).unwrap();
|
|
||||||
fs::write(
|
|
||||||
home.join("2026-07-19_1000-adr-logging.md"),
|
|
||||||
"---\ntitle: \"ADR Logging\"\ntags: [\"adr\", \"infra\"]\n---\n\nStrukturiertes Logging mit tracing vereinheitlichen.\n",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
fs::write(
|
|
||||||
home.join("konzepte/2026-07-19_1005-notiz-deploy.md"),
|
|
||||||
"---\ntitle: \"Notiz Deploy\"\ntags: [\"infra\"]\n---\n\nDeploy braucht lsregister auf macOS.\n",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
home
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn findet_nach_inhaltswort() {
|
|
||||||
let home = archiv();
|
|
||||||
let hits = search(&home, "tracing", None, 10).unwrap();
|
|
||||||
assert_eq!(hits.len(), 1);
|
|
||||||
assert_eq!(hits[0].title, "ADR Logging");
|
|
||||||
assert!(hits[0].snippet.contains("**tracing**"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tag_filter_engt_ein() {
|
|
||||||
let home = archiv();
|
|
||||||
assert_eq!(search(&home, "", Some("infra"), 10).unwrap().len(), 2);
|
|
||||||
assert_eq!(search(&home, "", Some("adr"), 10).unwrap().len(), 1);
|
|
||||||
let hits = search(&home, "deploy", Some("adr"), 10).unwrap();
|
|
||||||
assert!(hits.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn phrase_und_praefix() {
|
|
||||||
let home = archiv();
|
|
||||||
assert_eq!(search(&home, "\"Strukturiertes Logging\"", None, 10).unwrap().len(), 1);
|
|
||||||
assert_eq!(search(&home, "lsregist*", None, 10).unwrap().len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn leere_anfrage_scheitert() {
|
|
||||||
let home = archiv();
|
|
||||||
assert!(search(&home, " ", None, 10).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Eingaben, die roh durchgereicht einen FTS5-Syntaxfehler warfen. Die
|
|
||||||
/// Bindestrich-Fälle sind die wichtigsten: Archiv-Dokumente heißen selbst so.
|
|
||||||
/// Die angefangenen Phrasen stehen für die Tippzwischenstände, die die
|
|
||||||
/// Live-Suche abschickt.
|
|
||||||
#[test]
|
|
||||||
fn sonderzeichen_werfen_keinen_syntaxfehler() {
|
|
||||||
let home = archiv();
|
|
||||||
let eingaben = [
|
|
||||||
"ai-control",
|
|
||||||
"adr-log",
|
|
||||||
"TODO: fix",
|
|
||||||
"C++",
|
|
||||||
"wiki (",
|
|
||||||
"\"",
|
|
||||||
"\"Strukturiertes",
|
|
||||||
"\"Strukturiertes Logging",
|
|
||||||
"!?",
|
|
||||||
];
|
|
||||||
for q in eingaben {
|
|
||||||
assert!(search(&home, q, None, 10).is_ok(), "Suche scheiterte an „{q}“");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Der Tag-Filter lief früher an der Quoting-Regel vorbei. `#` allein ist der
|
|
||||||
/// erste Tastendruck jeder Tag-Suche und kommt als leerer Tag an.
|
|
||||||
#[test]
|
|
||||||
fn leerer_tag_wirft_keinen_syntaxfehler() {
|
|
||||||
let home = archiv();
|
|
||||||
// Das angetippte `#`: kein Fehler-Toast, sondern schlicht kein Treffer.
|
|
||||||
assert_eq!(search(&home, "", Some(""), 10).unwrap().len(), 0);
|
|
||||||
assert_eq!(search(&home, "", Some("!?"), 10).unwrap().len(), 0);
|
|
||||||
// Mit Volltext daneben zählt nur dieser, der leere Tag engt nichts ein.
|
|
||||||
assert_eq!(search(&home, "tracing", Some(""), 10).unwrap().len(), 1);
|
|
||||||
// Fehler bleibt allein die komplett leere Anfrage ohne jeden Tag.
|
|
||||||
assert!(search(&home, "", None, 10).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn bindestrich_wort_findet_dokument() {
|
|
||||||
let home = archiv();
|
|
||||||
let hits = search(&home, "adr-logging", None, 10).unwrap();
|
|
||||||
assert_eq!(hits.len(), 1);
|
|
||||||
assert_eq!(hits[0].title, "ADR Logging");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -2,13 +2,10 @@
|
|||||||
//! (injizierbares Home) und den `ApikeyStore`-Trait testbar; OS-Aufrufe
|
//! (injizierbares Home) und den `ApikeyStore`-Trait testbar; OS-Aufrufe
|
||||||
//! laufen ausschließlich über crate::platform.
|
//! laufen ausschließlich über crate::platform.
|
||||||
|
|
||||||
pub(crate) mod archive;
|
|
||||||
pub(crate) mod archive_index;
|
|
||||||
pub(crate) mod archive_ops;
|
|
||||||
pub(crate) mod archive_search;
|
|
||||||
pub(crate) mod credentials;
|
pub(crate) mod credentials;
|
||||||
pub(crate) mod modules;
|
pub(crate) mod modules;
|
||||||
pub(crate) mod paths;
|
pub(crate) mod paths;
|
||||||
|
pub(crate) mod trilium;
|
||||||
pub(crate) mod pool;
|
pub(crate) mod pool;
|
||||||
pub(crate) mod project;
|
pub(crate) mod project;
|
||||||
pub(crate) mod registry;
|
pub(crate) mod registry;
|
||||||
|
|||||||
@@ -36,36 +36,15 @@ pub(crate) struct ModuleDesc {
|
|||||||
pub(crate) core: bool,
|
pub(crate) core: bool,
|
||||||
/// Aktiv ohne Eintrag in der Projekt-Config.
|
/// Aktiv ohne Eintrag in der Projekt-Config.
|
||||||
pub(crate) default_enabled: bool,
|
pub(crate) default_enabled: bool,
|
||||||
/// Modul setzt ein konfiguriertes Archiv-Home voraus — ohne Home fallen
|
|
||||||
/// seine Tabs im Frontend weg. Seine MCP-Tools bleiben absichtlich
|
|
||||||
/// gelistet: Das Home kann mitten in der Session gesetzt werden, und die
|
|
||||||
/// Tools melden das fehlende Home selbst verständlich zurück.
|
|
||||||
pub(crate) requires_archive: bool,
|
|
||||||
pub(crate) mcp_tools: &'static [&'static str],
|
pub(crate) mcp_tools: &'static [&'static str],
|
||||||
pub(crate) buffers: &'static [BufferDesc],
|
pub(crate) buffers: &'static [BufferDesc],
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) const MODULES: &[ModuleDesc] = &[
|
pub(crate) const MODULES: &[ModuleDesc] = &[
|
||||||
ModuleDesc {
|
|
||||||
id: "draft",
|
|
||||||
core: true,
|
|
||||||
default_enabled: true,
|
|
||||||
requires_archive: false,
|
|
||||||
mcp_tools: &["write_panel"],
|
|
||||||
buffers: &[BufferDesc {
|
|
||||||
id: "panel",
|
|
||||||
env: "AI_CONTROL_PANEL",
|
|
||||||
event: "panel-update",
|
|
||||||
file: crate::domain::paths::panel_file,
|
|
||||||
suffix: "md",
|
|
||||||
persistent: false,
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
ModuleDesc {
|
ModuleDesc {
|
||||||
id: "commands",
|
id: "commands",
|
||||||
core: false,
|
core: false,
|
||||||
default_enabled: true,
|
default_enabled: true,
|
||||||
requires_archive: false,
|
|
||||||
mcp_tools: &["write_commands", "show_commands"],
|
mcp_tools: &["write_commands", "show_commands"],
|
||||||
buffers: &[BufferDesc {
|
buffers: &[BufferDesc {
|
||||||
id: "commands",
|
id: "commands",
|
||||||
@@ -81,7 +60,6 @@ pub(crate) const MODULES: &[ModuleDesc] = &[
|
|||||||
core: false,
|
core: false,
|
||||||
// Opt-in: der Tab erscheint erst, wenn das Modul im Projekt gewählt ist.
|
// Opt-in: der Tab erscheint erst, wenn das Modul im Projekt gewählt ist.
|
||||||
default_enabled: false,
|
default_enabled: false,
|
||||||
requires_archive: false,
|
|
||||||
mcp_tools: &["write_todos", "show_todos"],
|
mcp_tools: &["write_todos", "show_todos"],
|
||||||
buffers: &[BufferDesc {
|
buffers: &[BufferDesc {
|
||||||
id: "todos",
|
id: "todos",
|
||||||
@@ -93,11 +71,14 @@ pub(crate) const MODULES: &[ModuleDesc] = &[
|
|||||||
}],
|
}],
|
||||||
},
|
},
|
||||||
ModuleDesc {
|
ModuleDesc {
|
||||||
id: "archive",
|
id: "trilium",
|
||||||
core: false,
|
core: false,
|
||||||
default_enabled: true,
|
// Opt-in: das Anwählen öffnet im Settings-Dialog den Einricht-Wizard;
|
||||||
requires_archive: true,
|
// das Modul-Flag schreibt erst der erfolgreiche Setup (Erst-nach-Erfolg).
|
||||||
mcp_tools: &["archive_panel", "show_archive", "search_archive"],
|
// Das Modul IST das Archiv: Archivieren und Volltextsuche laufen über
|
||||||
|
// die ETAPI der projekteigenen Trilium-Instanz.
|
||||||
|
default_enabled: false,
|
||||||
|
mcp_tools: &["write_panel", "search_archive"],
|
||||||
buffers: &[
|
buffers: &[
|
||||||
BufferDesc {
|
BufferDesc {
|
||||||
id: "search",
|
id: "search",
|
||||||
@@ -107,12 +88,14 @@ pub(crate) const MODULES: &[ModuleDesc] = &[
|
|||||||
suffix: "search.json",
|
suffix: "search.json",
|
||||||
persistent: false,
|
persistent: false,
|
||||||
},
|
},
|
||||||
|
// Signal-Kanal „Notiz öffnen": write_panel legt die Notiz per ETAPI an
|
||||||
|
// und schreibt hier die noteId; die Fenster reagieren mit trilium_open.
|
||||||
BufferDesc {
|
BufferDesc {
|
||||||
id: "wiki",
|
id: "noteopen",
|
||||||
env: "AI_CONTROL_WIKI",
|
env: "AI_CONTROL_NOTEOPEN",
|
||||||
event: "wiki-update",
|
event: "noteopen-update",
|
||||||
file: crate::domain::paths::wiki_file,
|
file: crate::domain::paths::noteopen_file,
|
||||||
suffix: "wiki.json",
|
suffix: "noteopen.json",
|
||||||
persistent: false,
|
persistent: false,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -142,8 +125,7 @@ pub(crate) fn by_tool(tool: &str) -> Option<&'static ModuleDesc> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Registry-Zeile für den Settings-Dialog: `enabled` ist der effektive
|
/// Registry-Zeile für den Settings-Dialog: `enabled` ist der effektive
|
||||||
/// Config-Schalter (ohne `requires_archive` — die Pfadfrage zeigt der
|
/// Config-Schalter.
|
||||||
/// Dialog daneben an).
|
|
||||||
#[derive(serde::Serialize)]
|
#[derive(serde::Serialize)]
|
||||||
pub(crate) struct ModuleInfo {
|
pub(crate) struct ModuleInfo {
|
||||||
pub(crate) id: &'static str,
|
pub(crate) id: &'static str,
|
||||||
@@ -207,7 +189,7 @@ mod tests {
|
|||||||
create_project(&p, "proj").unwrap();
|
create_project(&p, "proj").unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
ids(&active_in(&p, "proj").unwrap()),
|
ids(&active_in(&p, "proj").unwrap()),
|
||||||
vec!["draft", "commands", "archive"]
|
vec!["commands"]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,11 +204,10 @@ mod tests {
|
|||||||
.join("config.json");
|
.join("config.json");
|
||||||
std::fs::write(
|
std::fs::write(
|
||||||
&cfg,
|
&cfg,
|
||||||
r#"{"id": "proj", "name": "proj", "modules": {"commands": false, "draft": false}}"#,
|
r#"{"id": "proj", "name": "proj", "modules": {"commands": false}}"#,
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
// commands ist ab; draft ignoriert den Eintrag (Kern-Modul).
|
assert!(active_in(&p, "proj").unwrap().is_empty());
|
||||||
assert_eq!(ids(&active_in(&p, "proj").unwrap()), vec!["draft", "archive"]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -242,7 +223,7 @@ mod tests {
|
|||||||
set_module_in(&p, "proj", "todo", true).unwrap();
|
set_module_in(&p, "proj", "todo", true).unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
ids(&active_in(&p, "proj").unwrap()),
|
ids(&active_in(&p, "proj").unwrap()),
|
||||||
vec!["draft", "commands", "todo", "archive"]
|
vec!["commands", "todo"]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -260,21 +241,20 @@ mod tests {
|
|||||||
let p = tmp_paths();
|
let p = tmp_paths();
|
||||||
create_project(&p, "proj").unwrap();
|
create_project(&p, "proj").unwrap();
|
||||||
set_module_in(&p, "proj", "commands", false).unwrap();
|
set_module_in(&p, "proj", "commands", false).unwrap();
|
||||||
assert_eq!(ids(&active_in(&p, "proj").unwrap()), vec!["draft", "archive"]);
|
assert!(active_in(&p, "proj").unwrap().is_empty());
|
||||||
assert!(!module_infos_in(&p, "proj").unwrap()[1].enabled);
|
assert!(!module_infos_in(&p, "proj").unwrap()[0].enabled);
|
||||||
// Zurück auf den Default löscht den Eintrag statt `true` zu speichern.
|
// Zurück auf den Default löscht den Eintrag statt `true` zu speichern.
|
||||||
set_module_in(&p, "proj", "commands", true).unwrap();
|
set_module_in(&p, "proj", "commands", true).unwrap();
|
||||||
let cfg = crate::domain::project::read_project_config_in(&p, "proj").unwrap();
|
let cfg = crate::domain::project::read_project_config_in(&p, "proj").unwrap();
|
||||||
assert!(cfg.modules.is_empty());
|
assert!(cfg.modules.is_empty());
|
||||||
// Kern-Modul und unbekannte ID scheitern laut.
|
// Unbekannte ID scheitert laut.
|
||||||
assert!(set_module_in(&p, "proj", "draft", false).is_err());
|
|
||||||
assert!(set_module_in(&p, "proj", "gibtsnicht", true).is_err());
|
assert!(set_module_in(&p, "proj", "gibtsnicht", true).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn tool_zuordnung() {
|
fn tool_zuordnung() {
|
||||||
assert_eq!(by_tool("write_panel").unwrap().id, "draft");
|
assert_eq!(by_tool("write_panel").unwrap().id, "trilium");
|
||||||
assert_eq!(by_tool("search_archive").unwrap().id, "archive");
|
assert_eq!(by_tool("search_archive").unwrap().id, "trilium");
|
||||||
assert!(by_tool("unbekannt").is_none());
|
assert!(by_tool("unbekannt").is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -65,22 +65,13 @@ fn checked(project: &str) -> &str {
|
|||||||
project
|
project
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Panel-Datei eines Projekts (Kanal Skill -> Panel). Der Pfad landet als
|
/// Signal-Datei „Notiz öffnen": write_panel (MCP) schreibt die noteId der
|
||||||
/// AI_CONTROL_PANEL in der PTY-Umgebung.
|
/// frisch angelegten Trilium-Notiz, die Fenster öffnen sie daraufhin. Der
|
||||||
pub(crate) fn panel_file(project: &str) -> PathBuf {
|
/// Pfad landet als AI_CONTROL_NOTEOPEN in der PTY-Umgebung.
|
||||||
Paths::real().panels_dir().join(format!("{}.md", checked(project)))
|
pub(crate) fn noteopen_file(project: &str) -> PathBuf {
|
||||||
}
|
|
||||||
|
|
||||||
/// Quell-Verknüpfung des Panel-Inhalts: absoluter Pfad des Archiv-Dokuments,
|
|
||||||
/// aus dem der Dokument-Tab gerade geladen ist. Solange sie existiert,
|
|
||||||
/// schreibt jeder Editor-Commit den Body dorthin zurück; ein frischer Entwurf
|
|
||||||
/// (write_panel, Session-Start) entfernt sie. Liegt neben der Panel-Datei als
|
|
||||||
/// `<panel>.source`, damit der MCP-Server sie aus AI_CONTROL_PANEL ableiten
|
|
||||||
/// kann.
|
|
||||||
pub(crate) fn panel_source_file(project: &str) -> PathBuf {
|
|
||||||
Paths::real()
|
Paths::real()
|
||||||
.panels_dir()
|
.panels_dir()
|
||||||
.join(format!("{}.md.source", checked(project)))
|
.join(format!("{}.noteopen.json", checked(project)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Command-History eines Projekts (JSONL, anhängend — flüchtig, wird beim
|
/// Command-History eines Projekts (JSONL, anhängend — flüchtig, wird beim
|
||||||
@@ -101,15 +92,6 @@ pub(crate) fn search_file(project: &str) -> PathBuf {
|
|||||||
.join(format!("{}.search.json", checked(project)))
|
.join(format!("{}.search.json", checked(project)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wiki-Puffer eines Projekts (JSON, jeweils letzte Wiki-Seite bzw. letztes
|
|
||||||
/// geöffnetes Dokument — flüchtig, wird beim Session-Start geleert). Der Pfad
|
|
||||||
/// landet als AI_CONTROL_WIKI in der PTY-Umgebung.
|
|
||||||
pub(crate) fn wiki_file(project: &str) -> PathBuf {
|
|
||||||
Paths::real()
|
|
||||||
.panels_dir()
|
|
||||||
.join(format!("{}.wiki.json", checked(project)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Persistente ToDo-Liste eines Projekts (JSONL, anhängend — überlebt
|
/// Persistente ToDo-Liste eines Projekts (JSONL, anhängend — überlebt
|
||||||
/// Sessions; write_todos hängt an, Kachel-Löschen entfernt Zeilen). Der Pfad
|
/// Sessions; write_todos hängt an, Kachel-Löschen entfernt Zeilen). Der Pfad
|
||||||
/// landet als AI_CONTROL_TODOS in der PTY-Umgebung.
|
/// landet als AI_CONTROL_TODOS in der PTY-Umgebung.
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ pub(crate) struct Project {
|
|||||||
pub(crate) pool: Option<String>,
|
pub(crate) pool: Option<String>,
|
||||||
pub(crate) running: bool,
|
pub(crate) running: bool,
|
||||||
pub(crate) terminal: TerminalConfig,
|
pub(crate) terminal: TerminalConfig,
|
||||||
|
/// Trilium-Modul aktiv — die Projektliste zeigt dann den Archiv-Knopf.
|
||||||
|
pub(crate) archive: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Default)]
|
#[derive(Serialize, Deserialize, Default)]
|
||||||
@@ -51,16 +53,6 @@ pub(crate) struct ProjectConfig {
|
|||||||
pub(crate) name: Option<String>,
|
pub(crate) name: Option<String>,
|
||||||
#[serde(default, skip_serializing_if = "TerminalConfig::is_empty")]
|
#[serde(default, skip_serializing_if = "TerminalConfig::is_empty")]
|
||||||
pub(crate) terminal: TerminalConfig,
|
pub(crate) terminal: TerminalConfig,
|
||||||
/// Archiv-Home des Projekts: Zielordner fürs Archivieren von Panel-Entwürfen
|
|
||||||
/// (~-relativ gespeichert). Liest den früheren Key `archiveDir` weiterhin ein,
|
|
||||||
/// geschrieben wird nur noch `archiveHome`.
|
|
||||||
#[serde(
|
|
||||||
default,
|
|
||||||
rename = "archiveHome",
|
|
||||||
alias = "archiveDir",
|
|
||||||
skip_serializing_if = "Option::is_none"
|
|
||||||
)]
|
|
||||||
pub(crate) archive_home: Option<String>,
|
|
||||||
/// Modul-Abweichungen vom Default (`"commands": false`); fehlender Key =
|
/// Modul-Abweichungen vom Default (`"commands": false`); fehlender Key =
|
||||||
/// Default aus der Registry (domain/modules.rs). Kern-Module ignorieren
|
/// Default aus der Registry (domain/modules.rs). Kern-Module ignorieren
|
||||||
/// den Eintrag.
|
/// den Eintrag.
|
||||||
@@ -174,6 +166,7 @@ pub(crate) fn list_projects_in(paths: &Paths) -> Result<Vec<Project>, String> {
|
|||||||
path: contract_home(paths, &entry.dir),
|
path: contract_home(paths, &entry.dir),
|
||||||
pool: entry.pool,
|
pool: entry.pool,
|
||||||
name: cfg.name.unwrap_or_else(|| id.clone()),
|
name: cfg.name.unwrap_or_else(|| id.clone()),
|
||||||
|
archive: cfg.modules.get("trilium").copied().unwrap_or(false),
|
||||||
terminal: cfg.terminal,
|
terminal: cfg.terminal,
|
||||||
id,
|
id,
|
||||||
});
|
});
|
||||||
@@ -314,7 +307,6 @@ pub(crate) fn create_project_full_in(
|
|||||||
id: Some(id.clone()),
|
id: Some(id.clone()),
|
||||||
name: Some(name.to_string()),
|
name: Some(name.to_string()),
|
||||||
terminal,
|
terminal,
|
||||||
archive_home: None,
|
|
||||||
modules: Default::default(),
|
modules: Default::default(),
|
||||||
rest: Default::default(),
|
rest: Default::default(),
|
||||||
};
|
};
|
||||||
@@ -403,11 +395,6 @@ pub(crate) fn add_project_in(paths: &Paths, path: &str) -> Result<(), String> {
|
|||||||
let wd_path = expand_home(paths, &wd);
|
let wd_path = expand_home(paths, &wd);
|
||||||
fs::create_dir_all(&wd_path).map_err(|e| format!("{}: {e}", wd_path.display()))?;
|
fs::create_dir_all(&wd_path).map_err(|e| format!("{}: {e}", wd_path.display()))?;
|
||||||
}
|
}
|
||||||
if let Some(archive) = cfg.archive_home.as_deref() {
|
|
||||||
let expanded = expand_home(paths, archive);
|
|
||||||
fs::create_dir_all(&expanded).map_err(|e| format!("{}: {e}", expanded.display()))?;
|
|
||||||
crate::domain::archive::add_archive_permission(paths, &id, archive)?;
|
|
||||||
}
|
|
||||||
crate::platform::write_terminal_desktop(paths, &id, &cfg);
|
crate::platform::write_terminal_desktop(paths, &id, &cfg);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -484,10 +471,10 @@ pub(crate) struct DeletePreview {
|
|||||||
pub(crate) name: String,
|
pub(crate) name: String,
|
||||||
pub(crate) project_dir: String,
|
pub(crate) project_dir: String,
|
||||||
pub(crate) ai_control_dir: bool,
|
pub(crate) ai_control_dir: bool,
|
||||||
pub(crate) archive_permission: bool,
|
|
||||||
pub(crate) panel_files: usize,
|
pub(crate) panel_files: usize,
|
||||||
pub(crate) archive_home: Option<String>,
|
/// Trilium-Datenverzeichnis der Projekt-Instanz (~-relativ), sofern es
|
||||||
pub(crate) archive_docs: usize,
|
/// existiert — das Archiv der Lösch-Stufe "archive".
|
||||||
|
pub(crate) trilium_data: Option<String>,
|
||||||
pub(crate) work_dirs: Vec<String>,
|
pub(crate) work_dirs: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -495,25 +482,13 @@ pub(crate) fn delete_preview_in(paths: &Paths, project: &str) -> Result<DeletePr
|
|||||||
check_name(project)?;
|
check_name(project)?;
|
||||||
let dir = project_dir(paths, project)?;
|
let dir = project_dir(paths, project)?;
|
||||||
let cfg = read_project_config_in(paths, project)?;
|
let cfg = read_project_config_in(paths, project)?;
|
||||||
let archive_docs = match cfg.archive_home.as_deref() {
|
let tri = crate::domain::trilium::data_dir(paths, project);
|
||||||
Some(a) => {
|
|
||||||
let home = expand_home(paths, a);
|
|
||||||
if home.is_dir() {
|
|
||||||
crate::domain::archive_index::scan_archive(&home)?.len()
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => 0,
|
|
||||||
};
|
|
||||||
Ok(DeletePreview {
|
Ok(DeletePreview {
|
||||||
name: cfg.name.clone().unwrap_or_else(|| project.to_string()),
|
name: cfg.name.clone().unwrap_or_else(|| project.to_string()),
|
||||||
project_dir: contract_home(paths, &dir),
|
project_dir: contract_home(paths, &dir),
|
||||||
ai_control_dir: dir.join(PROJECT_CONFIG_DIR).is_dir(),
|
ai_control_dir: dir.join(PROJECT_CONFIG_DIR).is_dir(),
|
||||||
archive_permission: cfg.archive_home.is_some(),
|
|
||||||
panel_files: session_files(paths, project).iter().filter(|f| f.is_file()).count(),
|
panel_files: session_files(paths, project).iter().filter(|f| f.is_file()).count(),
|
||||||
archive_home: cfg.archive_home.clone(),
|
trilium_data: tri.is_dir().then(|| contract_home(paths, &tri)),
|
||||||
archive_docs,
|
|
||||||
work_dirs: project_work_dirs_in(paths, project)?,
|
work_dirs: project_work_dirs_in(paths, project)?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -533,9 +508,10 @@ fn session_files(paths: &Paths, project: &str) -> Vec<PathBuf> {
|
|||||||
/// Löscht ein Projekt in drei Stufen (Eskalationsleiter, jede schließt die
|
/// Löscht ein Projekt in drei Stufen (Eskalationsleiter, jede schließt die
|
||||||
/// vorige ein):
|
/// vorige ein):
|
||||||
/// - "integration": nur die ai-control-Spuren — Registry, .ai-control/,
|
/// - "integration": nur die ai-control-Spuren — Registry, .ai-control/,
|
||||||
/// Archiv-Rechte in der settings.json, Panel-Dateien, .desktop. Ordner,
|
/// Panel-Dateien, .desktop. Ordner, memory/ und das Claude-Code-Grundgerüst
|
||||||
/// memory/ und das Claude-Code-Grundgerüst der settings.json bleiben.
|
/// der settings.json bleiben.
|
||||||
/// - "archive": zusätzlich der Archiv-Ordner samt Dokumenten.
|
/// - "archive": zusätzlich das Trilium-Archiv der Projekt-Instanz
|
||||||
|
/// (Datenverzeichnis + Keyring-Token; die Instanz wird vorher gestoppt).
|
||||||
/// - "full": zusätzlich der Projektordner; Arbeitsordner per Flag.
|
/// - "full": zusätzlich der Projektordner; Arbeitsordner per Flag.
|
||||||
pub(crate) fn delete_project_scoped_in(
|
pub(crate) fn delete_project_scoped_in(
|
||||||
paths: &Paths,
|
paths: &Paths,
|
||||||
@@ -548,24 +524,17 @@ pub(crate) fn delete_project_scoped_in(
|
|||||||
if !dir.is_dir() {
|
if !dir.is_dir() {
|
||||||
return Err(format!("Projektordner nicht gefunden: {}", dir.display()));
|
return Err(format!("Projektordner nicht gefunden: {}", dir.display()));
|
||||||
}
|
}
|
||||||
let cfg = read_project_config_in(paths, project)?;
|
|
||||||
|
|
||||||
// Archiv vor der Integration räumen — Stufe 1 löscht die Config, die den
|
|
||||||
// Pfad kennt.
|
|
||||||
if scope == "archive" || scope == "full" {
|
if scope == "archive" || scope == "full" {
|
||||||
if let Some(a) = cfg.archive_home.as_deref() {
|
crate::domain::trilium::stop_instance(project);
|
||||||
let home = expand_home(paths, a);
|
let tri = crate::domain::trilium::data_dir(paths, project);
|
||||||
if home.is_dir() {
|
if tri.is_dir() {
|
||||||
fs::remove_dir_all(&home).map_err(|e| format!("{}: {e}", home.display()))?;
|
fs::remove_dir_all(&tri).map_err(|e| format!("{}: {e}", tri.display()))?;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
crate::domain::trilium::delete_token(project);
|
||||||
}
|
}
|
||||||
|
|
||||||
match scope {
|
match scope {
|
||||||
"integration" | "archive" => {
|
"integration" | "archive" => {
|
||||||
if let Some(a) = cfg.archive_home.as_deref() {
|
|
||||||
crate::domain::archive::remove_archive_permission(paths, project, a)?;
|
|
||||||
}
|
|
||||||
let ac = dir.join(PROJECT_CONFIG_DIR);
|
let ac = dir.join(PROJECT_CONFIG_DIR);
|
||||||
if ac.is_dir() {
|
if ac.is_dir() {
|
||||||
fs::remove_dir_all(&ac).map_err(|e| format!("{}: {e}", ac.display()))?;
|
fs::remove_dir_all(&ac).map_err(|e| format!("{}: {e}", ac.display()))?;
|
||||||
@@ -664,7 +633,7 @@ pub(crate) fn resolve_icon_path(
|
|||||||
|
|
||||||
/// Liest eine Datei für `write_panel(path)` — den promptfreien MCP-Weg.
|
/// Liest eine Datei für `write_panel(path)` — den promptfreien MCP-Weg.
|
||||||
/// Erlaubt ist genau, was die Session über ihre Permissions ohnehin promptfrei
|
/// Erlaubt ist genau, was die Session über ihre Permissions ohnehin promptfrei
|
||||||
/// liest: Projektordner, Arbeitsordner und Archiv-Home. Geprüft wird nach
|
/// liest: Projektordner und Arbeitsordner. Geprüft wird nach
|
||||||
/// `canonicalize` (symlink-fest), nur reguläre Dateien bis 2 MB — sonst
|
/// `canonicalize` (symlink-fest), nur reguläre Dateien bis 2 MB — sonst
|
||||||
/// umginge das Tool das Read-Permission-Modell von Claude Code, und ein
|
/// umginge das Tool das Read-Permission-Modell von Claude Code, und ein
|
||||||
/// Device wie /dev/zero hinge den Prozess.
|
/// Device wie /dev/zero hinge den Prozess.
|
||||||
@@ -679,16 +648,13 @@ pub(crate) fn read_for_panel_in(
|
|||||||
for d in project_work_dirs_in(paths, project)? {
|
for d in project_work_dirs_in(paths, project)? {
|
||||||
roots.push(expand_home(paths, &d));
|
roots.push(expand_home(paths, &d));
|
||||||
}
|
}
|
||||||
if let Some(a) = read_project_config_in(paths, project)?.archive_home {
|
|
||||||
roots.push(expand_home(paths, &a));
|
|
||||||
}
|
|
||||||
let allowed = roots
|
let allowed = roots
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|r| fs::canonicalize(r).ok())
|
.filter_map(|r| fs::canonicalize(r).ok())
|
||||||
.any(|r| canon.starts_with(&r));
|
.any(|r| canon.starts_with(&r));
|
||||||
if !allowed {
|
if !allowed {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"{src}: liegt außerhalb von Projekt-, Arbeits- und Archiv-Ordnern"
|
"{src}: liegt außerhalb von Projekt- und Arbeitsordnern"
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let f = fs::File::open(&canon).map_err(|e| format!("{src}: {e}"))?;
|
let f = fs::File::open(&canon).map_err(|e| format!("{src}: {e}"))?;
|
||||||
@@ -1088,7 +1054,8 @@ mod tests {
|
|||||||
let cfg = read_project_config_in(&p, &id).unwrap();
|
let cfg = read_project_config_in(&p, &id).unwrap();
|
||||||
assert_eq!(cfg.id.as_deref(), Some(id.as_str()));
|
assert_eq!(cfg.id.as_deref(), Some(id.as_str()));
|
||||||
assert_eq!(cfg.name.as_deref(), Some("proj"));
|
assert_eq!(cfg.name.as_deref(), Some("proj"));
|
||||||
assert_eq!(cfg.archive_home.as_deref(), Some("~/archiv"));
|
// Unbekannte Alt-Keys (archiveHome) wandern unverändert mit.
|
||||||
|
assert_eq!(cfg.rest["archiveHome"], "~/archiv");
|
||||||
// Icon liegt jetzt im Projekt, das zentrale Verzeichnis ist geräumt.
|
// Icon liegt jetzt im Projekt, das zentrale Verzeichnis ist geräumt.
|
||||||
assert_eq!(cfg.terminal.icon.as_deref(), Some("icon.png"));
|
assert_eq!(cfg.terminal.icon.as_deref(), Some("icon.png"));
|
||||||
assert!(dir.join(PROJECT_CONFIG_DIR).join("icon.png").is_file());
|
assert!(dir.join(PROJECT_CONFIG_DIR).join("icon.png").is_file());
|
||||||
@@ -1143,8 +1110,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Import eines Ordners mit mitgebrachter Config: die ID wird übernommen
|
/// Import eines Ordners mit mitgebrachter Config: die ID wird übernommen
|
||||||
/// (Sync-Fall), Arbeitsordner und Archiv-Home werden angelegt, die
|
/// (Sync-Fall), Arbeitsordner werden angelegt.
|
||||||
/// Archiv-Permission nachgezogen.
|
|
||||||
#[test]
|
#[test]
|
||||||
fn projekt_import_uebernimmt_id_und_legt_pfade_an() {
|
fn projekt_import_uebernimmt_id_und_legt_pfade_an() {
|
||||||
let p = tmp_paths();
|
let p = tmp_paths();
|
||||||
@@ -1152,7 +1118,7 @@ mod tests {
|
|||||||
fs::create_dir_all(dir.join(PROJECT_CONFIG_DIR)).unwrap();
|
fs::create_dir_all(dir.join(PROJECT_CONFIG_DIR)).unwrap();
|
||||||
fs::write(
|
fs::write(
|
||||||
dir.join(PROJECT_CONFIG_DIR).join(PROJECT_FILE),
|
dir.join(PROJECT_CONFIG_DIR).join(PROJECT_FILE),
|
||||||
r#"{"id": "sync-id", "name": "Mein Projekt", "archiveHome": "~/archiv/proj"}"#,
|
r#"{"id": "sync-id", "name": "Mein Projekt"}"#,
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
fs::create_dir_all(dir.join(".claude")).unwrap();
|
fs::create_dir_all(dir.join(".claude")).unwrap();
|
||||||
@@ -1167,10 +1133,6 @@ mod tests {
|
|||||||
assert_eq!(project_dir(&p, "sync-id").unwrap(), dir);
|
assert_eq!(project_dir(&p, "sync-id").unwrap(), dir);
|
||||||
assert_eq!(display_name_in(&p, "sync-id").unwrap(), "Mein Projekt");
|
assert_eq!(display_name_in(&p, "sync-id").unwrap(), "Mein Projekt");
|
||||||
assert!(p.home.join("work/proj").is_dir());
|
assert!(p.home.join("work/proj").is_dir());
|
||||||
assert!(p.home.join("archiv/proj").is_dir());
|
|
||||||
let raw = fs::read_to_string(settings_path(&dir)).unwrap();
|
|
||||||
assert!(raw.contains("~/archiv/proj"));
|
|
||||||
assert!(raw.contains("Edit(~/archiv/proj/**)"));
|
|
||||||
|
|
||||||
// Doppelt aufnehmen scheitert an der ID.
|
// Doppelt aufnehmen scheitert an der ID.
|
||||||
let err = add_project_in(&p, &dir.display().to_string()).unwrap_err();
|
let err = add_project_in(&p, &dir.display().to_string()).unwrap_err();
|
||||||
@@ -1300,7 +1262,7 @@ mod tests {
|
|||||||
// -- write_panel(path): promptfreier Lese-Weg --
|
// -- write_panel(path): promptfreier Lese-Weg --
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn panel_lesen_nur_aus_projekt_arbeits_und_archivordnern() {
|
fn panel_lesen_nur_aus_projekt_und_arbeitsordnern() {
|
||||||
let p = tmp_paths();
|
let p = tmp_paths();
|
||||||
create_project(&p, "proj").unwrap();
|
create_project(&p, "proj").unwrap();
|
||||||
let dir = p.projects_dir().join("proj");
|
let dir = p.projects_dir().join("proj");
|
||||||
@@ -1339,49 +1301,45 @@ mod tests {
|
|||||||
let id = create_project_full_in(&p, "proj", None, None, None, false, TerminalConfig::default())
|
let id = create_project_full_in(&p, "proj", None, None, None, false, TerminalConfig::default())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let dir = p.projects_dir().join("proj");
|
let dir = p.projects_dir().join("proj");
|
||||||
// Archiv-Home samt Permission wie über die UI gesetzt
|
// flüchtige Panel-Datei + Trilium-Datenverzeichnis
|
||||||
let mut cfg = read_project_config_in(&p, &id).unwrap();
|
|
||||||
cfg.archive_home = Some("~/archiv/proj".into());
|
|
||||||
write_project_config_in(&p, &id, &cfg).unwrap();
|
|
||||||
crate::domain::archive::add_archive_permission(&p, &id, "~/archiv/proj").unwrap();
|
|
||||||
fs::create_dir_all(p.home.join("archiv/proj")).unwrap();
|
|
||||||
fs::write(p.home.join("archiv/proj/doc.md"), "inhalt").unwrap();
|
|
||||||
// flüchtige Panel-Datei
|
|
||||||
fs::create_dir_all(p.config_dir().join("panels")).unwrap();
|
fs::create_dir_all(p.config_dir().join("panels")).unwrap();
|
||||||
fs::write(p.config_dir().join("panels").join(format!("{id}.md")), "x").unwrap();
|
fs::write(
|
||||||
|
p.config_dir().join("panels").join(format!("{id}.commands.jsonl")),
|
||||||
|
"x",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let tri = crate::domain::trilium::data_dir(&p, &id);
|
||||||
|
fs::create_dir_all(&tri).unwrap();
|
||||||
|
|
||||||
let preview = delete_preview_in(&p, &id).unwrap();
|
let preview = delete_preview_in(&p, &id).unwrap();
|
||||||
assert!(preview.ai_control_dir && preview.archive_permission);
|
assert!(preview.ai_control_dir);
|
||||||
assert_eq!(preview.panel_files, 1);
|
assert_eq!(preview.panel_files, 1);
|
||||||
assert_eq!(preview.archive_docs, 1);
|
assert!(preview.trilium_data.is_some());
|
||||||
|
|
||||||
delete_project_scoped_in(&p, &id, "integration", false).unwrap();
|
delete_project_scoped_in(&p, &id, "integration", false).unwrap();
|
||||||
|
|
||||||
assert!(dir.is_dir());
|
assert!(dir.is_dir());
|
||||||
assert!(!dir.join(PROJECT_CONFIG_DIR).exists());
|
assert!(!dir.join(PROJECT_CONFIG_DIR).exists());
|
||||||
let sp = fs::read_to_string(settings_path(&dir)).unwrap();
|
let sp = fs::read_to_string(settings_path(&dir)).unwrap();
|
||||||
assert!(!sp.contains("archiv/proj"));
|
|
||||||
assert!(sp.contains("autoMemoryDirectory")); // Claude-Code-Bestand bleibt
|
assert!(sp.contains("autoMemoryDirectory")); // Claude-Code-Bestand bleibt
|
||||||
assert!(p.home.join("archiv/proj/doc.md").is_file()); // Archiv bleibt
|
assert!(tri.is_dir()); // Archiv bleibt
|
||||||
assert!(!p.config_dir().join("panels").join(format!("{id}.md")).exists());
|
assert!(!p.config_dir().join("panels").join(format!("{id}.commands.jsonl")).exists());
|
||||||
assert!(load_registry(&p).unwrap().is_empty());
|
assert!(load_registry(&p).unwrap().is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stufe „Integration & Archiv": zusätzlich stirbt der Archiv-Ordner.
|
/// Stufe „Integration & Archiv": zusätzlich stirbt das Trilium-Datadir.
|
||||||
#[test]
|
#[test]
|
||||||
fn loeschen_integration_und_archiv() {
|
fn loeschen_integration_und_archiv() {
|
||||||
let p = tmp_paths();
|
let p = tmp_paths();
|
||||||
let id = create_project_full_in(&p, "proj", None, None, None, false, TerminalConfig::default())
|
let id = create_project_full_in(&p, "proj", None, None, None, false, TerminalConfig::default())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let mut cfg = read_project_config_in(&p, &id).unwrap();
|
let tri = crate::domain::trilium::data_dir(&p, &id);
|
||||||
cfg.archive_home = Some("~/archiv/proj".into());
|
fs::create_dir_all(&tri).unwrap();
|
||||||
write_project_config_in(&p, &id, &cfg).unwrap();
|
|
||||||
fs::create_dir_all(p.home.join("archiv/proj")).unwrap();
|
|
||||||
|
|
||||||
delete_project_scoped_in(&p, &id, "archive", false).unwrap();
|
delete_project_scoped_in(&p, &id, "archive", false).unwrap();
|
||||||
|
|
||||||
assert!(p.projects_dir().join("proj").is_dir());
|
assert!(p.projects_dir().join("proj").is_dir());
|
||||||
assert!(!p.home.join("archiv/proj").exists());
|
assert!(!tri.exists());
|
||||||
assert!(load_registry(&p).unwrap().is_empty());
|
assert!(load_registry(&p).unwrap().is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
//! App-eigene settings.json unter ~/.config/ai-control (nicht pool-/projektbezogen):
|
//! App-eigene settings.json unter ~/.config/ai-control (nicht pool-/projektbezogen):
|
||||||
//! claudeCommand, syncOnSessionEnd, poolSyncDir, terminalFontSize, spellcheckLang.
|
//! claudeCommand, syncOnSessionEnd, poolSyncDir, terminalFontSize.
|
||||||
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@@ -53,14 +53,6 @@ pub(crate) fn set_terminal_font_size_in(paths: &Paths, size: u32) -> Result<(),
|
|||||||
write_app_setting(paths, "terminalFontSize", serde_json::json!(size))
|
write_app_setting(paths, "terminalFontSize", serde_json::json!(size))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Standard-Sprache der Rechtschreibprüfung (settings.json: spellcheckLang),
|
|
||||||
/// Default „de". Pro Text im Panel überschreibbar.
|
|
||||||
pub(crate) fn spellcheck_lang(paths: &Paths) -> String {
|
|
||||||
read_app_settings(paths)
|
|
||||||
.and_then(|v| v["spellcheckLang"].as_str().map(str::to_string))
|
|
||||||
.unwrap_or_else(|| "de".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Hat der Nutzer das Angebot, die App nach ~/Applications zu holen, schon
|
/// Hat der Nutzer das Angebot, die App nach ~/Applications zu holen, schon
|
||||||
/// abgelehnt? (settings.json: moveOfferDismissed, nur macOS)
|
/// abgelehnt? (settings.json: moveOfferDismissed, nur macOS)
|
||||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||||
|
|||||||
@@ -0,0 +1,555 @@
|
|||||||
|
//! Trilium-Integration: das Archiv eines Projekts ist eine eigene, von
|
||||||
|
//! ai-control verwaltete Trilium-Instanz — Archivieren und Volltextsuche
|
||||||
|
//! laufen über die dokumentierte ETAPI, die Oberfläche kommt aus dem lokalen
|
||||||
|
//! Server-Prozess und wird in einem eigenen Tauri-Fenster angezeigt.
|
||||||
|
//!
|
||||||
|
//! Verwaltung komplett bei uns: versionsgepinnter Runtime-Download (Checksum),
|
||||||
|
//! ein Server-Prozess pro Projekt mit eigenem Datenverzeichnis und
|
||||||
|
//! deterministischem Port (nur 127.0.0.1) — parallele Projekte und ein
|
||||||
|
//! privates Trilium des Nutzers kollidieren nicht. Es werden ausschließlich
|
||||||
|
//! dokumentierte Schnittstellen benutzt: TRILIUM_DATA_DIR, TRILIUM_PORT,
|
||||||
|
//! ETAPI (Token über /etapi/auth/login).
|
||||||
|
//!
|
||||||
|
//! Erst-nach-Erfolg-Muster: Config-Einträge (Modul-Flag) schreibt der Wizard
|
||||||
|
//! erst, wenn Setup und Token-Login durch sind; Datei-Arbeit rollt bei
|
||||||
|
//! Fehlern zurück.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::{Child, Command, Stdio};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
|
use crate::domain::paths::Paths;
|
||||||
|
|
||||||
|
/// Gepinntes Release; Update = Konstanten anheben (der Update-Check beim
|
||||||
|
/// App-Start vergleicht gegen diese Version, nicht gegen GitHub).
|
||||||
|
pub(crate) const VERSION: &str = "0.104.0";
|
||||||
|
|
||||||
|
/// Download-URL und SHA-256 des Server-Builds je Plattform. macOS/Windows
|
||||||
|
/// folgen, sobald unsere Pipeline eigene Server-Bundles baut (offizielle
|
||||||
|
/// Server-Builds gibt es nur für Linux).
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
const ASSET: (&str, &str) = (
|
||||||
|
"https://github.com/TriliumNext/Trilium/releases/download/v0.104.0/TriliumNotes-Server-v0.104.0-linux-x64.tar.xz",
|
||||||
|
"96b64bd1cf628ef8d851094de813750611d1d8a69c146ea1e8acc896420a2c69",
|
||||||
|
);
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
const ASSET: (&str, &str) = ("", "");
|
||||||
|
|
||||||
|
/// Wurzel der Trilium-Verwaltung: Runtime und Projekt-Datenverzeichnisse.
|
||||||
|
pub(crate) fn trilium_root(paths: &Paths) -> PathBuf {
|
||||||
|
paths.config_dir().join("trilium")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Entpackte Runtime der gepinnten Version.
|
||||||
|
pub(crate) fn runtime_dir(paths: &Paths) -> PathBuf {
|
||||||
|
trilium_root(paths).join(format!("runtime-{VERSION}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn runtime_binary(paths: &Paths) -> PathBuf {
|
||||||
|
runtime_dir(paths).join("node").join("bin").join("node")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn runtime_main(paths: &Paths) -> PathBuf {
|
||||||
|
runtime_dir(paths).join("main.cjs")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Datenverzeichnis der Projekt-Instanz (TRILIUM_DATA_DIR) — maschinenlokal,
|
||||||
|
/// unter der Projekt-UUID.
|
||||||
|
pub(crate) fn data_dir(paths: &Paths, project: &str) -> PathBuf {
|
||||||
|
// Zweite Linie wie bei den Panel-Kanälen: eine Projekt-ID mit
|
||||||
|
// Pfad-Bestandteilen bricht laut ab, statt einen Pfad zu bilden.
|
||||||
|
crate::domain::check_name(project).unwrap();
|
||||||
|
trilium_root(paths).join("data").join(project)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deterministischer Port pro Projekt (FNV-1a über die Projekt-ID) im
|
||||||
|
/// Bereich 27200–27981 — dasselbe Schema wie die übrigen Projekt-Ports.
|
||||||
|
pub(crate) fn port_for(project: &str) -> u16 {
|
||||||
|
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||||
|
for b in project.bytes() {
|
||||||
|
h ^= b as u64;
|
||||||
|
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||||
|
}
|
||||||
|
27200 + (h % 782) as u16
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn base_url(project: &str) -> String {
|
||||||
|
format!("http://127.0.0.1:{}", port_for(project))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lädt und entpackt die gepinnte Runtime, falls sie fehlt. Download in eine
|
||||||
|
/// Temp-Datei, SHA-256-Prüfung, Entpacken neben das Ziel, atomares Umbenennen
|
||||||
|
/// — ein Abbruch lässt keinen halben Runtime-Ordner zurück.
|
||||||
|
pub(crate) fn ensure_runtime(paths: &Paths) -> Result<(), String> {
|
||||||
|
if runtime_binary(paths).is_file() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let (url, sha) = ASSET;
|
||||||
|
if url.is_empty() {
|
||||||
|
return Err("Trilium-Runtime für dieses Betriebssystem noch nicht verfügbar".into());
|
||||||
|
}
|
||||||
|
let root = trilium_root(paths);
|
||||||
|
fs::create_dir_all(&root).map_err(|e| format!("{}: {e}", root.display()))?;
|
||||||
|
let tarball = root.join(format!("download-{VERSION}.tar.xz"));
|
||||||
|
|
||||||
|
let status = Command::new("curl")
|
||||||
|
.args(["-fsSL", "--retry", "2", "-o"])
|
||||||
|
.arg(&tarball)
|
||||||
|
.arg(url)
|
||||||
|
.status()
|
||||||
|
.map_err(|e| format!("curl: {e}"))?;
|
||||||
|
if !status.success() {
|
||||||
|
let _ = fs::remove_file(&tarball);
|
||||||
|
return Err(format!("Download fehlgeschlagen ({status}): {url}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let bytes = fs::read(&tarball).map_err(|e| format!("{}: {e}", tarball.display()))?;
|
||||||
|
let digest = {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
let mut h = Sha256::new();
|
||||||
|
h.update(&bytes);
|
||||||
|
format!("{:x}", h.finalize())
|
||||||
|
};
|
||||||
|
if digest != sha {
|
||||||
|
let _ = fs::remove_file(&tarball);
|
||||||
|
return Err(format!("Checksum-Abweichung beim Trilium-Download: {digest} statt {sha}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ins Temp-Verzeichnis entpacken, dann den inneren Ordner atomar an den
|
||||||
|
// Zielnamen heben.
|
||||||
|
let unpack = root.join(format!("unpack-{VERSION}"));
|
||||||
|
let _ = fs::remove_dir_all(&unpack);
|
||||||
|
fs::create_dir_all(&unpack).map_err(|e| format!("{}: {e}", unpack.display()))?;
|
||||||
|
let status = Command::new("tar")
|
||||||
|
.arg("-xJf")
|
||||||
|
.arg(&tarball)
|
||||||
|
.arg("-C")
|
||||||
|
.arg(&unpack)
|
||||||
|
.arg("--strip-components=1")
|
||||||
|
.status()
|
||||||
|
.map_err(|e| format!("tar: {e}"))?;
|
||||||
|
let _ = fs::remove_file(&tarball);
|
||||||
|
if !status.success() {
|
||||||
|
let _ = fs::remove_dir_all(&unpack);
|
||||||
|
return Err(format!("Entpacken fehlgeschlagen ({status})"));
|
||||||
|
}
|
||||||
|
fs::rename(&unpack, runtime_dir(paths))
|
||||||
|
.map_err(|e| format!("{}: {e}", runtime_dir(paths).display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Laufende Projekt-Instanzen dieses App-Prozesses.
|
||||||
|
static INSTANCES: Mutex<Option<HashMap<String, Child>>> = Mutex::new(None);
|
||||||
|
|
||||||
|
/// Startet die Projekt-Instanz, falls sie nicht läuft, und wartet bis der
|
||||||
|
/// Port antwortet. Läuft der Port schon (z. B. Instanz aus einem früheren
|
||||||
|
/// App-Lauf), wird nichts gestartet.
|
||||||
|
pub(crate) fn ensure_instance(paths: &Paths, project: &str) -> Result<(), String> {
|
||||||
|
if http_ok(project, "/", 1) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
ensure_runtime(paths)?;
|
||||||
|
let dd = data_dir(paths, project);
|
||||||
|
fs::create_dir_all(&dd).map_err(|e| format!("{}: {e}", dd.display()))?;
|
||||||
|
|
||||||
|
let mut guard = INSTANCES.lock().unwrap();
|
||||||
|
let map = guard.get_or_insert_with(HashMap::new);
|
||||||
|
// Toter Eintrag (Prozess beendet) fliegt raus, bevor neu gestartet wird.
|
||||||
|
if let Some(child) = map.get_mut(project) {
|
||||||
|
match child.try_wait() {
|
||||||
|
Ok(None) => {}
|
||||||
|
_ => {
|
||||||
|
map.remove(project);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !map.contains_key(project) {
|
||||||
|
let child = Command::new(runtime_binary(paths))
|
||||||
|
.arg(runtime_main(paths))
|
||||||
|
.current_dir(runtime_dir(paths))
|
||||||
|
.env("TRILIUM_DATA_DIR", &dd)
|
||||||
|
.env("TRILIUM_PORT", port_for(project).to_string())
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| format!("Trilium-Start: {e}"))?;
|
||||||
|
map.insert(project.to_string(), child);
|
||||||
|
}
|
||||||
|
drop(guard);
|
||||||
|
|
||||||
|
if http_ok(project, "/", 20) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(format!("Trilium antwortet nicht auf Port {}", port_for(project)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Beendet die Projekt-Instanz dieses App-Prozesses (falls von uns gestartet).
|
||||||
|
pub(crate) fn stop_instance(project: &str) {
|
||||||
|
let mut guard = INSTANCES.lock().unwrap();
|
||||||
|
if let Some(map) = guard.as_mut() {
|
||||||
|
if let Some(mut child) = map.remove(project) {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Beendet alle von uns gestarteten Instanzen (App-Ende).
|
||||||
|
pub(crate) fn stop_all() {
|
||||||
|
let mut guard = INSTANCES.lock().unwrap();
|
||||||
|
if let Some(map) = guard.as_mut() {
|
||||||
|
for (_, mut child) in map.drain() {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wartet bis zu `tries` Sekunden darauf, dass GET auf `path` antwortet.
|
||||||
|
fn http_ok(project: &str, path: &str, tries: u32) -> bool {
|
||||||
|
for i in 0..tries {
|
||||||
|
if i > 0 {
|
||||||
|
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||||
|
}
|
||||||
|
let ok = Command::new("curl")
|
||||||
|
.args(["-fsS", "-m", "2", "-o", "/dev/null"])
|
||||||
|
.arg(format!("{}{}", base_url(project), path))
|
||||||
|
.status()
|
||||||
|
.map(|s| s.success())
|
||||||
|
.unwrap_or(false);
|
||||||
|
if ok {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ist die Datenbank der Instanz schon initialisiert? (Vor dem ersten Setup
|
||||||
|
/// liefert Trilium die Setup-Seite aus; der dokumentierte ETAPI-Login
|
||||||
|
/// existiert erst danach sinnvoll.) Erkennung über die App-Info der ETAPI:
|
||||||
|
/// 401 = initialisiert (Auth nötig), Verbindung da; die Setup-Seite selbst
|
||||||
|
/// beantwortet /etapi/… nicht mit 401.
|
||||||
|
pub(crate) fn etapi(
|
||||||
|
project: &str,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
token: Option<&str>,
|
||||||
|
body: Option<&Value>,
|
||||||
|
) -> Result<(u16, Value), String> {
|
||||||
|
let mut cmd = Command::new("curl");
|
||||||
|
cmd.args(["-sS", "-m", "10", "-X", method, "-w", "\n%{http_code}"]);
|
||||||
|
if let Some(token) = token {
|
||||||
|
cmd.arg("-H").arg(format!("Authorization: {token}"));
|
||||||
|
}
|
||||||
|
if let Some(body) = body {
|
||||||
|
cmd.args(["-H", "Content-Type: application/json", "--data-binary", &body.to_string()]);
|
||||||
|
}
|
||||||
|
cmd.arg(format!("{}{}", base_url(project), path));
|
||||||
|
let out = cmd.output().map_err(|e| format!("curl: {e}"))?;
|
||||||
|
if !out.status.success() && out.stdout.is_empty() {
|
||||||
|
return Err(format!("ETAPI {path}: {}", String::from_utf8_lossy(&out.stderr)));
|
||||||
|
}
|
||||||
|
let text = String::from_utf8_lossy(&out.stdout);
|
||||||
|
let (payload, code) = text.rsplit_once('\n').ok_or_else(|| format!("ETAPI {path}: leere Antwort"))?;
|
||||||
|
let code: u16 = code.trim().parse().map_err(|_| format!("ETAPI {path}: Statuszeile fehlt"))?;
|
||||||
|
let value = if payload.trim().is_empty() {
|
||||||
|
Value::Null
|
||||||
|
} else {
|
||||||
|
serde_json::from_str(payload).unwrap_or(Value::String(payload.to_string()))
|
||||||
|
};
|
||||||
|
Ok((code, value))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ist die Datenbank der Instanz schon initialisiert? (GET /api/setup/status,
|
||||||
|
/// erreichbar ohne Auth.)
|
||||||
|
pub(crate) fn initialized(project: &str) -> Result<bool, String> {
|
||||||
|
let (code, value) = etapi(project, "GET", "/api/setup/status", None, None)?;
|
||||||
|
if code != 200 {
|
||||||
|
return Err(format!("Setup-Status fehlgeschlagen (HTTP {code})"));
|
||||||
|
}
|
||||||
|
Ok(value["isInitialized"].as_bool() == Some(true))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Legt das Initial-Dokument an (ohne Demo-Notizen). Die Route ist nur
|
||||||
|
/// erreichbar, solange die Instanz uninitialisiert ist, und antwortet erst
|
||||||
|
/// nach abgeschlossener Datenbank-Anlage.
|
||||||
|
pub(crate) fn setup_new_document(project: &str) -> Result<(), String> {
|
||||||
|
let code = http_post(project, "/api/setup/new-document?skipDemoDb", None, 120)?;
|
||||||
|
if code >= 300 {
|
||||||
|
return Err(format!("Dokument-Anlage fehlgeschlagen (HTTP {code})"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Setzt das Passwort der frischen Instanz (Route nur erreichbar, solange
|
||||||
|
/// keins gesetzt ist); Trilium antwortet mit Redirect auf die Login-Seite.
|
||||||
|
pub(crate) fn set_password(project: &str, password: &str) -> Result<(), String> {
|
||||||
|
let form = format!("password1={0}&password2={0}", uri_encode(password));
|
||||||
|
let code = http_post(project, "/set-password", Some(&form), 30)?;
|
||||||
|
if code != 302 {
|
||||||
|
return Err(format!("Passwort setzen fehlgeschlagen (HTTP {code})"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Formular-/Setup-POST außerhalb der ETAPI; liefert den Statuscode.
|
||||||
|
fn http_post(
|
||||||
|
project: &str,
|
||||||
|
path: &str,
|
||||||
|
form: Option<&str>,
|
||||||
|
timeout_s: u32,
|
||||||
|
) -> Result<u16, String> {
|
||||||
|
let mut cmd = Command::new("curl");
|
||||||
|
cmd.args(["-sS", "-m", &timeout_s.to_string(), "-o", "/dev/null", "-w", "%{http_code}", "-X", "POST"]);
|
||||||
|
if let Some(form) = form {
|
||||||
|
cmd.args(["--data", form]);
|
||||||
|
}
|
||||||
|
cmd.arg(format!("{}{}", base_url(project), path));
|
||||||
|
let out = cmd.output().map_err(|e| format!("curl: {e}"))?;
|
||||||
|
String::from_utf8_lossy(&out.stdout)
|
||||||
|
.trim()
|
||||||
|
.parse()
|
||||||
|
.map_err(|_| format!("POST {path}: {}", String::from_utf8_lossy(&out.stderr)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Holt per dokumentiertem Login einen ETAPI-Token (Passwort kommt aus dem
|
||||||
|
/// Wizard und wird nicht gespeichert).
|
||||||
|
pub(crate) fn login(project: &str, password: &str) -> Result<String, String> {
|
||||||
|
let (code, value) = etapi(
|
||||||
|
project,
|
||||||
|
"POST",
|
||||||
|
"/etapi/auth/login",
|
||||||
|
None,
|
||||||
|
Some(&json!({ "password": password })),
|
||||||
|
)?;
|
||||||
|
if code != 201 {
|
||||||
|
return Err(format!("ETAPI-Login fehlgeschlagen (HTTP {code})"));
|
||||||
|
}
|
||||||
|
value["authToken"]
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_string)
|
||||||
|
.ok_or_else(|| "ETAPI-Login ohne authToken".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keyring-Ablage des ETAPI-Tokens (Service wie die übrigen ai-control-Keys).
|
||||||
|
const TOKEN_SERVICE: &str = "ai-control-trilium";
|
||||||
|
|
||||||
|
pub(crate) fn store_token(project: &str, token: &str) -> Result<(), String> {
|
||||||
|
keyring::Entry::new(TOKEN_SERVICE, project)
|
||||||
|
.and_then(|e| e.set_password(token))
|
||||||
|
.map_err(|e| format!("Keyring: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn read_token(project: &str) -> Result<String, String> {
|
||||||
|
keyring::Entry::new(TOKEN_SERVICE, project)
|
||||||
|
.and_then(|e| e.get_password())
|
||||||
|
.map_err(|e| format!("Keyring: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn delete_token(project: &str) {
|
||||||
|
if let Ok(entry) = keyring::Entry::new(TOKEN_SERVICE, project) {
|
||||||
|
let _ = entry.delete_credential();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Percent-Encoding für Query-Parameter (ETAPI-Suche).
|
||||||
|
pub(crate) fn uri_encode(s: &str) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
for b in s.bytes() {
|
||||||
|
match b {
|
||||||
|
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
|
||||||
|
out.push(b as char)
|
||||||
|
}
|
||||||
|
_ => out.push_str(&format!("%{b:02X}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runtime der gepinnten Version liegt entpackt da.
|
||||||
|
pub(crate) fn runtime_ready(paths: &Paths) -> bool {
|
||||||
|
runtime_binary(paths).is_file()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Antwortet die Projekt-Instanz gerade? (Ein Versuch, ohne Warten.)
|
||||||
|
pub(crate) fn instance_running(project: &str) -> bool {
|
||||||
|
http_ok(project, "/", 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prüft den gespeicherten Token gegen die Instanz (GET /etapi/app-info).
|
||||||
|
pub(crate) fn token_ok(project: &str) -> bool {
|
||||||
|
let Ok(token) = read_token(project) else { return false };
|
||||||
|
matches!(etapi(project, "GET", "/etapi/app-info", Some(&token), None), Ok((200, _)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Findet unter `parent` das Kind mit diesem Titel oder legt es als
|
||||||
|
/// Buch-Notiz an (Triliums Ordner-Äquivalent: Notiz mit Kindern).
|
||||||
|
fn find_or_create_child(
|
||||||
|
project: &str,
|
||||||
|
token: &str,
|
||||||
|
parent: &str,
|
||||||
|
title: &str,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let (code, parent_note) =
|
||||||
|
etapi(project, "GET", &format!("/etapi/notes/{parent}"), Some(token), None)?;
|
||||||
|
if code != 200 {
|
||||||
|
return Err(format!("ETAPI: Notiz {parent} nicht lesbar (HTTP {code})"));
|
||||||
|
}
|
||||||
|
for child in parent_note["childNoteIds"].as_array().into_iter().flatten() {
|
||||||
|
let Some(id) = child.as_str() else { continue };
|
||||||
|
let (code, note) =
|
||||||
|
etapi(project, "GET", &format!("/etapi/notes/{id}"), Some(token), None)?;
|
||||||
|
if code == 200 && note["title"].as_str() == Some(title) {
|
||||||
|
return Ok(id.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (code, created) = etapi(
|
||||||
|
project,
|
||||||
|
"POST",
|
||||||
|
"/etapi/create-note",
|
||||||
|
Some(token),
|
||||||
|
Some(&json!({ "parentNoteId": parent, "title": title, "type": "book", "content": "" })),
|
||||||
|
)?;
|
||||||
|
if code != 201 {
|
||||||
|
return Err(format!("ETAPI: Ordner-Notiz „{title}“ nicht anlegbar (HTTP {code})"));
|
||||||
|
}
|
||||||
|
created["note"]["noteId"]
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_string)
|
||||||
|
.ok_or_else(|| "ETAPI: create-note ohne noteId".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Archiviert einen Markdown-Text als Trilium-Notiz: HTML-Konvertierung,
|
||||||
|
/// Ordner-Pfad als Notiz-Hierarchie unter root, Beschreibung und Schlagwörter
|
||||||
|
/// als Labels. Liefert die noteId.
|
||||||
|
pub(crate) fn archive_note(
|
||||||
|
project: &str,
|
||||||
|
title: &str,
|
||||||
|
markdown: &str,
|
||||||
|
folder: Option<&str>,
|
||||||
|
description: Option<&str>,
|
||||||
|
tags: &[String],
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let token = read_token(project)?;
|
||||||
|
let html = {
|
||||||
|
let parser = pulldown_cmark::Parser::new_ext(markdown, pulldown_cmark::Options::all());
|
||||||
|
let mut html = String::new();
|
||||||
|
pulldown_cmark::html::push_html(&mut html, parser);
|
||||||
|
html
|
||||||
|
};
|
||||||
|
let mut parent = "root".to_string();
|
||||||
|
if let Some(folder) = folder {
|
||||||
|
for segment in folder.split('/').map(str::trim).filter(|s| !s.is_empty()) {
|
||||||
|
parent = find_or_create_child(project, &token, &parent, segment)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (code, created) = etapi(
|
||||||
|
project,
|
||||||
|
"POST",
|
||||||
|
"/etapi/create-note",
|
||||||
|
Some(&token),
|
||||||
|
Some(&json!({
|
||||||
|
"parentNoteId": parent,
|
||||||
|
"title": title,
|
||||||
|
"type": "text",
|
||||||
|
"content": html,
|
||||||
|
})),
|
||||||
|
)?;
|
||||||
|
if code != 201 {
|
||||||
|
return Err(format!("ETAPI: Notiz nicht anlegbar (HTTP {code})"));
|
||||||
|
}
|
||||||
|
let note_id = created["note"]["noteId"]
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_string)
|
||||||
|
.ok_or_else(|| String::from("ETAPI: create-note ohne noteId"))?;
|
||||||
|
|
||||||
|
let mut labels: Vec<(&str, String)> = Vec::new();
|
||||||
|
if let Some(d) = description {
|
||||||
|
labels.push(("description", d.to_string()));
|
||||||
|
}
|
||||||
|
for tag in tags {
|
||||||
|
labels.push(("tag", tag.clone()));
|
||||||
|
}
|
||||||
|
for (name, value) in labels {
|
||||||
|
let (code, _) = etapi(
|
||||||
|
project,
|
||||||
|
"POST",
|
||||||
|
"/etapi/attributes",
|
||||||
|
Some(&token),
|
||||||
|
Some(&json!({ "noteId": note_id, "type": "label", "name": name, "value": value })),
|
||||||
|
)?;
|
||||||
|
if code != 201 {
|
||||||
|
return Err(format!("ETAPI: Label {name} nicht setzbar (HTTP {code})"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(note_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
pub(crate) struct Hit {
|
||||||
|
pub(crate) note_id: String,
|
||||||
|
pub(crate) title: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Volltextsuche über die Projekt-Instanz; `tag` engt auf das Label
|
||||||
|
/// `#tag=<wert>` ein (so setzt archive_note Schlagwörter).
|
||||||
|
pub(crate) fn search_notes(
|
||||||
|
project: &str,
|
||||||
|
query: &str,
|
||||||
|
tag: Option<&str>,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<Vec<Hit>, String> {
|
||||||
|
let token = read_token(project)?;
|
||||||
|
let mut q = query.trim().to_string();
|
||||||
|
if let Some(tag) = tag {
|
||||||
|
q = format!("{q} #tag=\"{}\"", tag.replace('"', "")).trim().to_string();
|
||||||
|
}
|
||||||
|
let (code, value) = etapi(
|
||||||
|
project,
|
||||||
|
"GET",
|
||||||
|
&format!("/etapi/notes?search={}&limit={limit}", uri_encode(&q)),
|
||||||
|
Some(&token),
|
||||||
|
None,
|
||||||
|
)?;
|
||||||
|
if code != 200 {
|
||||||
|
return Err(format!("ETAPI-Suche fehlgeschlagen (HTTP {code})"));
|
||||||
|
}
|
||||||
|
Ok(
|
||||||
|
value["results"]
|
||||||
|
.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|n| {
|
||||||
|
Some(Hit {
|
||||||
|
note_id: n["noteId"].as_str()?.to_string(),
|
||||||
|
title: n["title"].as_str().unwrap_or("(ohne Titel)").to_string(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn port_stabil_und_im_bereich() {
|
||||||
|
let a = port_for("projekt-a");
|
||||||
|
assert_eq!(a, port_for("projekt-a"));
|
||||||
|
assert!((27200..27982).contains(&a));
|
||||||
|
assert_ne!(a, port_for("projekt-b"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pfade_unter_config_dir() {
|
||||||
|
let p = crate::domain::testutil::tmp_paths();
|
||||||
|
assert!(runtime_dir(&p).starts_with(p.config_dir()));
|
||||||
|
assert!(data_dir(&p, "proj").starts_with(trilium_root(&p)));
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
-6
@@ -95,11 +95,16 @@ pub fn run() {
|
|||||||
// Das Dock-Icon erst nach dem App-Start setzen: in setup() gesetzt
|
// Das Dock-Icon erst nach dem App-Start setzen: in setup() gesetzt
|
||||||
// überschreibt macOS es beim Anlegen des Dock-Tiles wieder.
|
// überschreibt macOS es beim Anlegen des Dock-Tiles wieder.
|
||||||
.run(move |app, event| {
|
.run(move |app, event| {
|
||||||
if let tauri::RunEvent::Ready = event {
|
match event {
|
||||||
if let Some(icon) = icon.as_deref() {
|
tauri::RunEvent::Ready => {
|
||||||
platform::set_dock_icon(icon);
|
if let Some(icon) = icon.as_deref() {
|
||||||
|
platform::set_dock_icon(icon);
|
||||||
|
}
|
||||||
|
platform::activate_self(app);
|
||||||
}
|
}
|
||||||
platform::activate_self(app);
|
// Von diesem Prozess gestartete Trilium-Instanzen enden mit ihm.
|
||||||
|
tauri::RunEvent::Exit => domain::trilium::stop_all(),
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -108,8 +113,14 @@ pub fn run() {
|
|||||||
// dem offenen Fenster über ai-control.desktop das App-Icon zu.
|
// dem offenen Fenster über ai-control.desktop das App-Icon zu.
|
||||||
platform::set_app_id("ai-control");
|
platform::set_app_id("ai-control");
|
||||||
app::main_builder()
|
app::main_builder()
|
||||||
.run(context)
|
.build(context)
|
||||||
.expect("error while running tauri application");
|
.expect("error while building tauri application")
|
||||||
|
.run(|_, event| {
|
||||||
|
// Von diesem Prozess gestartete Trilium-Instanzen enden mit ihm.
|
||||||
|
if let tauri::RunEvent::Exit = event {
|
||||||
|
domain::trilium::stop_all();
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+94
-154
@@ -1,8 +1,9 @@
|
|||||||
//! Minimaler MCP-stdio-Server (`app --mcp-panel`), den claude als Tool-Server
|
//! Minimaler MCP-stdio-Server (`app --mcp-panel`), den claude als Tool-Server
|
||||||
//! startet. Er stellt genau ein Tool bereit: `write_panel(text)` schreibt den
|
//! startet. Die Tools kommen aus der Modul-Registry (domain/modules.rs);
|
||||||
//! Text in die Panel-Datei aus `AI_CONTROL_PANEL` (dieselbe Env, die der
|
//! Puffer-Kanäle laufen über die AI_CONTROL_*-Dateipfade, die der
|
||||||
//! Terminal-Prozess der PTY mitgibt und die claude an seine MCP-Kinder vererbt).
|
//! Terminal-Prozess der PTY mitgibt und die claude an seine MCP-Kinder
|
||||||
//! Der bestehende Datei-Watcher im Terminal-Prozess zieht den Inhalt ins Panel.
|
//! vererbt. Der Datei-Watcher im Terminal-Prozess zieht Änderungen als
|
||||||
|
//! Events in die Panel-Fenster.
|
||||||
//!
|
//!
|
||||||
//! Protokoll: JSON-RPC 2.0, newline-getrennt (ein Objekt pro Zeile).
|
//! Protokoll: JSON-RPC 2.0, newline-getrennt (ein Objekt pro Zeile).
|
||||||
|
|
||||||
@@ -97,14 +98,16 @@ fn tool_def(name: &str) -> Value {
|
|||||||
"name": "write_panel",
|
"name": "write_panel",
|
||||||
"description":
|
"description":
|
||||||
"Legt einen längeren Entwurf (ADR, E-Mail, Dokument, Spezifikation, \
|
"Legt einen längeren Entwurf (ADR, E-Mail, Dokument, Spezifikation, \
|
||||||
Commit-Message, Textbaustein) im ai-control-Panel neben dem Terminal \
|
Commit-Message, Textbaustein) als Notiz im Trilium-Archiv des \
|
||||||
ab, wo er mit der Maus selektierbar und über einen Button kopierbar \
|
Projekts an und öffnet sie im Trilium-Fenster neben dem Terminal. \
|
||||||
ist. Statt den Text zusätzlich als Fließtext auszugeben, dieses Tool \
|
Statt den Text zusätzlich als Fließtext auszugeben, dieses Tool \
|
||||||
aufrufen und im Chat nur kurz bestätigen. Für eine bestehende Datei \
|
aufrufen und im Chat nur kurz bestätigen. Für eine bestehende Datei \
|
||||||
IMMER `path` statt `text` übergeben — der Server liest die Datei \
|
IMMER `path` statt `text` übergeben — der Server liest die Datei \
|
||||||
selbst von der Platte, ohne dass ihr Inhalt generiert werden muss. \
|
selbst von der Platte, ohne dass ihr Inhalt generiert werden muss. \
|
||||||
`path` muss im Projekt-, Arbeits- oder Archiv-Ordner liegen \
|
`path` muss im Projekt- oder Arbeitsordner liegen (reguläre Datei, \
|
||||||
(reguläre Datei, max. 2 MB).",
|
max. 2 MB). `folder`, `description` und `tags` kuratieren die \
|
||||||
|
Notiz: Ordner werden zur Notiz-Hierarchie, Beschreibung und \
|
||||||
|
Schlagwörter zu Labels.",
|
||||||
"inputSchema": {
|
"inputSchema": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -115,8 +118,23 @@ fn tool_def(name: &str) -> Value {
|
|||||||
"path": {
|
"path": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description":
|
"description":
|
||||||
"Statt `text`: Pfad einer vorhandenen Datei, deren Inhalt ins \
|
"Statt `text`: Pfad einer vorhandenen Datei, deren Inhalt \
|
||||||
Panel geladen wird. Genau eines von beiden angeben.",
|
die Notiz wird. Genau eines von beiden angeben.",
|
||||||
|
},
|
||||||
|
"folder": {
|
||||||
|
"type": "string",
|
||||||
|
"description":
|
||||||
|
"Optionaler Ordner-Pfad im Archiv (z. B. `konzepte/panel`). \
|
||||||
|
Wird als Notiz-Hierarchie angelegt.",
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Einzeiler zum Inhalt (Label `description`).",
|
||||||
|
},
|
||||||
|
"tags": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"description": "Schlagwörter (Labels `tag`, kurze Slugs).",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -210,69 +228,20 @@ fn tool_def(name: &str) -> Value {
|
|||||||
(„zeig die ToDos“).",
|
(„zeig die ToDos“).",
|
||||||
"inputSchema": { "type": "object", "properties": {} },
|
"inputSchema": { "type": "object", "properties": {} },
|
||||||
}),
|
}),
|
||||||
"archive_panel" => json!({
|
|
||||||
"name": "archive_panel",
|
|
||||||
"description":
|
|
||||||
"Archiviert den aktuell im Panel liegenden Entwurf dauerhaft als \
|
|
||||||
Markdown-Datei im Archiv-Home des Projekts. Auf Wunsch nutzen \
|
|
||||||
(Nutzer sagt etwa „archiviere das“). Beim Archivieren `folder`, \
|
|
||||||
`description` und `tags` mitgeben — einmalige Kuratierung im Moment \
|
|
||||||
des Archivierens, landet im Frontmatter. Ist kein Archiv-Home \
|
|
||||||
konfiguriert, meldet das Tool das zurück; gesetzt wird es in den \
|
|
||||||
Projekt-Einstellungen oder im Panel.",
|
|
||||||
"inputSchema": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"folder": {
|
|
||||||
"type": "string",
|
|
||||||
"description":
|
|
||||||
"Optionaler Unterordner im Archiv-Home, relativ (z. B. \
|
|
||||||
`konzepte/panel`). Wird angelegt.",
|
|
||||||
},
|
|
||||||
"description": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "Einzeiler zum Inhalt fürs Frontmatter.",
|
|
||||||
},
|
|
||||||
"tags": {
|
|
||||||
"type": "array",
|
|
||||||
"items": { "type": "string" },
|
|
||||||
"description": "Schlagwörter fürs Frontmatter (kurze Slugs).",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
"show_archive" => json!({
|
|
||||||
"name": "show_archive",
|
|
||||||
"description":
|
|
||||||
"Zeigt die Archiv-Übersicht des Projekts als Wiki-Seite im Panel: \
|
|
||||||
Dokumente nach Ordnern gruppiert, mit Beschreibungen und \
|
|
||||||
klickbaren Schlagwort-Links. Mit `tag` stattdessen die Seite eines \
|
|
||||||
Schlagworts. Nutzen, wenn der Nutzer das Archiv sehen will \
|
|
||||||
(„zeig das Archiv“).",
|
|
||||||
"inputSchema": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"tag": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "Optional: Seite dieses Schlagworts statt der Übersicht.",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
"search_archive" => json!({
|
"search_archive" => json!({
|
||||||
"name": "search_archive",
|
"name": "search_archive",
|
||||||
"description":
|
"description":
|
||||||
"Volltext-Suche über das Panel-Archiv des Projekts (FTS5-Syntax: \
|
"Volltext-Suche über das Trilium-Archiv des Projekts (Triliums \
|
||||||
Wörter, \"Phrasen\", Präfix*). Die Treffer erscheinen als Kacheln \
|
Suchsyntax: Wörter, \"Phrasen\", Operatoren). Die Treffer \
|
||||||
im Panel; das Tool liefert sie zusätzlich mit Pfad und Snippet \
|
erscheinen als Kacheln im Panel; das Tool liefert sie zusätzlich \
|
||||||
zurück. Nutzen, wenn der Nutzer im Archiv suchen will („such im \
|
mit Titel und noteId zurück. Nutzen, wenn der Nutzer im Archiv \
|
||||||
Archiv nach …“).",
|
suchen will („such im Archiv nach …“).",
|
||||||
"inputSchema": {
|
"inputSchema": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"query": {
|
"query": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Suchanfrage (FTS5-Syntax).",
|
"description": "Suchanfrage (Trilium-Suchsyntax).",
|
||||||
},
|
},
|
||||||
"tag": {
|
"tag": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
@@ -300,9 +269,7 @@ fn call_tool(req: &Value) -> Value {
|
|||||||
"show_commands" => call_show_commands(),
|
"show_commands" => call_show_commands(),
|
||||||
"write_todos" => call_write_todos(req),
|
"write_todos" => call_write_todos(req),
|
||||||
"show_todos" => call_show_todos(),
|
"show_todos" => call_show_todos(),
|
||||||
"archive_panel" => call_archive(req),
|
|
||||||
"search_archive" => call_search(req),
|
"search_archive" => call_search(req),
|
||||||
"show_archive" => call_show_archive(req),
|
|
||||||
other => err(format!("Unbekanntes Tool: {other}")),
|
other => err(format!("Unbekanntes Tool: {other}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -324,44 +291,75 @@ fn env_path(var: &str) -> Result<String, Value> {
|
|||||||
.map_err(|_| err(format!("{var} nicht gesetzt (Terminal außerhalb ai-control).")))
|
.map_err(|_| err(format!("{var} nicht gesetzt (Terminal außerhalb ai-control).")))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Schreibt Text in die Panel-Datei aus AI_CONTROL_PANEL. Ein frischer
|
/// Titelzeile: erste Überschrift (## …) oder sonst erste nicht-leere Zeile —
|
||||||
/// Entwurf löst die Quell-Verknüpfung des Dokument-Tabs (`<panel>.source`,
|
/// wird der Notiz-Titel von write_panel.
|
||||||
/// gesetzt beim Öffnen eines Archiv-Dokuments) — Edits gehören danach wieder
|
fn first_line(text: &str) -> String {
|
||||||
/// nur dem Panel, nicht der zuletzt geöffneten Archiv-Datei.
|
let mut fallback: Option<&str> = None;
|
||||||
fn write_panel_text(text: &str) -> Result<(), Value> {
|
for line in text.lines() {
|
||||||
let path = env_path("AI_CONTROL_PANEL")?;
|
let t = line.trim();
|
||||||
std::fs::write(&path, text).map_err(|e| err(format!("Panel-Datei nicht schreibbar: {e}")))?;
|
if t.is_empty() {
|
||||||
match std::fs::remove_file(format!("{path}.source")) {
|
continue;
|
||||||
Ok(()) => Ok(()),
|
}
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
let h = t.trim_start_matches('#').trim();
|
||||||
Err(e) => Err(err(format!("Quell-Verknüpfung nicht gelöst: {e}"))),
|
if t.starts_with('#') && !h.is_empty() {
|
||||||
|
return h.to_string();
|
||||||
|
}
|
||||||
|
fallback.get_or_insert(t);
|
||||||
}
|
}
|
||||||
|
fallback.unwrap_or("entwurf").to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Legt den Entwurf als Trilium-Notiz an (ETAPI der Projekt-Instanz; Token
|
||||||
|
/// aus dem Keyring) und meldet die noteId über den noteopen-Kanal — die
|
||||||
|
/// Fenster öffnen die Notiz daraufhin im Trilium-Fenster.
|
||||||
fn call_write(req: &Value) -> Value {
|
fn call_write(req: &Value) -> Value {
|
||||||
|
let project = std::env::var("AI_CONTROL_PROJECT").unwrap_or_default();
|
||||||
let args = &req["params"]["arguments"];
|
let args = &req["params"]["arguments"];
|
||||||
// `path` lädt eine vorhandene Datei serverseitig — der schnelle Weg, ohne
|
// `path` lädt eine vorhandene Datei serverseitig — der schnelle Weg, ohne
|
||||||
// dass das Modell den Inhalt Token für Token als `text` generieren muss.
|
// dass das Modell den Inhalt Token für Token als `text` generieren muss.
|
||||||
// Der Zugriff ist auf Projekt-, Arbeits- und Archiv-Ordner begrenzt
|
// Der Zugriff ist auf Projekt- und Arbeitsordner begrenzt
|
||||||
// (read_for_panel_in): das Tool ist promptfrei freigegeben und darf das
|
// (read_for_panel_in): das Tool ist promptfrei freigegeben und darf das
|
||||||
// Read-Permission-Modell von Claude Code nicht umgehen.
|
// Read-Permission-Modell von Claude Code nicht umgehen.
|
||||||
let (text, ok_msg) = match args["path"].as_str() {
|
let text = match args["path"].as_str() {
|
||||||
Some(src) => {
|
Some(src) => {
|
||||||
let project = std::env::var("AI_CONTROL_PROJECT").unwrap_or_default();
|
|
||||||
let paths = crate::domain::paths::Paths::real();
|
let paths = crate::domain::paths::Paths::real();
|
||||||
match crate::domain::project::read_for_panel_in(&paths, &project, src) {
|
match crate::domain::project::read_for_panel_in(&paths, &project, src) {
|
||||||
Ok(content) => (content, "Datei ins Panel geladen."),
|
Ok(content) => content,
|
||||||
Err(e) => return err(format!("Datei nicht geladen: {e}")),
|
Err(e) => return err(format!("Datei nicht geladen: {e}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => (
|
None => args["text"].as_str().unwrap_or("").to_string(),
|
||||||
args["text"].as_str().unwrap_or("").to_string(),
|
|
||||||
"Entwurf ins Panel geschrieben.",
|
|
||||||
),
|
|
||||||
};
|
};
|
||||||
match write_panel_text(&text) {
|
if text.trim().is_empty() {
|
||||||
Ok(()) => ok(ok_msg.into()),
|
return err("Kein Inhalt — `text` oder `path` angeben.".into());
|
||||||
Err(e) => e,
|
}
|
||||||
|
let title = first_line(&text);
|
||||||
|
let tags: Vec<String> = args["tags"]
|
||||||
|
.as_array()
|
||||||
|
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let note_id = match crate::domain::trilium::archive_note(
|
||||||
|
&project,
|
||||||
|
&title,
|
||||||
|
&text,
|
||||||
|
args["folder"].as_str().filter(|f| !f.trim().is_empty()),
|
||||||
|
args["description"].as_str().filter(|d| !d.trim().is_empty()),
|
||||||
|
&tags,
|
||||||
|
) {
|
||||||
|
Ok(note_id) => note_id,
|
||||||
|
Err(e) => {
|
||||||
|
return err(format!(
|
||||||
|
"Notiz nicht angelegt: {e}. Läuft die Trilium-Instanz? (Trilium-Modul in den Projekt-Einstellungen)"
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let noteopen = match env_path("AI_CONTROL_NOTEOPEN") {
|
||||||
|
Ok(path) => path,
|
||||||
|
Err(e) => return e,
|
||||||
|
};
|
||||||
|
match std::fs::write(¬eopen, json!({ "noteId": note_id }).to_string()) {
|
||||||
|
Ok(()) => ok(format!("Notiz {note_id} („{title}“) im Archiv angelegt.")),
|
||||||
|
Err(e) => err(format!("Notiz {note_id} angelegt, aber Fenster nicht benachrichtigt: {e}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -508,71 +506,15 @@ fn call_write_todos(req: &Value) -> Value {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `dir` gibt es hier bewusst nicht mehr: Das Setzen des Archiv-Homes vergibt
|
/// Volltext-Suche übers Trilium-Archiv: Treffer als JSON in die
|
||||||
/// über `add_archive_permission` dauerhafte Rechte in der settings.json des
|
/// Suchtreffer-Datei (der Watcher zieht sie als Kacheln ins Panel) und als
|
||||||
/// Projekts (additionalDirectories + Edit-Allow) — das bleibt der UI mit
|
/// Text zurück an claude.
|
||||||
/// Nutzer-Dialog vorbehalten, nicht einem Tool-Argument des Modells.
|
|
||||||
fn call_archive(req: &Value) -> Value {
|
|
||||||
let project = std::env::var("AI_CONTROL_PROJECT").unwrap_or_default();
|
|
||||||
let args = &req["params"]["arguments"];
|
|
||||||
let meta = crate::domain::archive::ArchiveMeta {
|
|
||||||
folder: args["folder"].as_str().map(str::to_string),
|
|
||||||
description: args["description"].as_str().map(str::to_string),
|
|
||||||
tags: args["tags"]
|
|
||||||
.as_array()
|
|
||||||
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect())
|
|
||||||
.unwrap_or_default(),
|
|
||||||
};
|
|
||||||
match crate::domain::archive::archive_panel_content(&project, None, &meta) {
|
|
||||||
Ok(path) => ok(format!("Archiviert: {}", path.display())),
|
|
||||||
Err(e) => err(format!(
|
|
||||||
"Nicht archiviert: {e}. Archiv-Ordner im Panel oder in den Projekt-Einstellungen wählen."
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Archiv-Übersicht bzw. Schlagwort-Seite generieren und in den Wiki-Puffer
|
|
||||||
/// schreiben — der Watcher zieht sie als Wiki-Ansicht ins Panel.
|
|
||||||
fn call_show_archive(req: &Value) -> Value {
|
|
||||||
let project = std::env::var("AI_CONTROL_PROJECT").unwrap_or_default();
|
|
||||||
let home = match crate::domain::archive::require_archive_home(&project) {
|
|
||||||
Ok(home) => home,
|
|
||||||
Err(e) => return err(e),
|
|
||||||
};
|
|
||||||
let tag = req["params"]["arguments"]["tag"].as_str();
|
|
||||||
let page = match crate::domain::archive_index::archive_page(&home, tag) {
|
|
||||||
Ok(page) => page,
|
|
||||||
Err(e) => return err(e),
|
|
||||||
};
|
|
||||||
let path = match env_path("AI_CONTROL_WIKI") {
|
|
||||||
Ok(path) => path,
|
|
||||||
Err(e) => return e,
|
|
||||||
};
|
|
||||||
let json = match serde_json::to_string(&page) {
|
|
||||||
Ok(json) => json,
|
|
||||||
Err(e) => return err(e.to_string()),
|
|
||||||
};
|
|
||||||
match std::fs::write(&path, json) {
|
|
||||||
Ok(()) => ok(match tag {
|
|
||||||
Some(t) => format!("Schlagwort-Seite #{t} im Panel."),
|
|
||||||
None => "Archiv-Übersicht im Panel.".to_string(),
|
|
||||||
}),
|
|
||||||
Err(e) => err(format!("Wiki-Datei nicht schreibbar: {e}")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Volltext-Suche übers Archiv: Treffer als JSON in die Suchtreffer-Datei
|
|
||||||
/// (der Watcher zieht sie als Kacheln ins Panel) und als Text zurück an claude.
|
|
||||||
fn call_search(req: &Value) -> Value {
|
fn call_search(req: &Value) -> Value {
|
||||||
let project = std::env::var("AI_CONTROL_PROJECT").unwrap_or_default();
|
let project = std::env::var("AI_CONTROL_PROJECT").unwrap_or_default();
|
||||||
let home = match crate::domain::archive::require_archive_home(&project) {
|
|
||||||
Ok(home) => home,
|
|
||||||
Err(e) => return err(e),
|
|
||||||
};
|
|
||||||
let args = &req["params"]["arguments"];
|
let args = &req["params"]["arguments"];
|
||||||
let query = args["query"].as_str().unwrap_or("");
|
let query = args["query"].as_str().unwrap_or("");
|
||||||
let tag = args["tag"].as_str();
|
let tag = args["tag"].as_str();
|
||||||
let hits = match crate::domain::archive_search::search(&home, query, tag, 20) {
|
let hits = match crate::domain::trilium::search_notes(&project, query, tag, 20) {
|
||||||
Ok(hits) => hits,
|
Ok(hits) => hits,
|
||||||
Err(e) => return err(format!("Suche fehlgeschlagen: {e}")),
|
Err(e) => return err(format!("Suche fehlgeschlagen: {e}")),
|
||||||
};
|
};
|
||||||
@@ -583,7 +525,6 @@ fn call_search(req: &Value) -> Value {
|
|||||||
let payload = json!({
|
let payload = json!({
|
||||||
"query": query,
|
"query": query,
|
||||||
"tag": tag,
|
"tag": tag,
|
||||||
"home": home.display().to_string(),
|
|
||||||
"hits": hits,
|
"hits": hits,
|
||||||
});
|
});
|
||||||
if let Err(e) = std::fs::write(&search_path, payload.to_string()) {
|
if let Err(e) = std::fs::write(&search_path, payload.to_string()) {
|
||||||
@@ -591,12 +532,11 @@ fn call_search(req: &Value) -> Value {
|
|||||||
}
|
}
|
||||||
let list: Vec<String> = hits
|
let list: Vec<String> = hits
|
||||||
.iter()
|
.iter()
|
||||||
.map(|h| format!("- {} — {} ({})", h.relpath, h.title, h.snippet))
|
.map(|h| format!("- {} ({})", h.title, h.note_id))
|
||||||
.collect();
|
.collect();
|
||||||
ok(format!(
|
ok(format!(
|
||||||
"{} Treffer, als Kacheln im Panel. Archiv: {}\n{}",
|
"{} Treffer, als Kacheln im Panel.\n{}",
|
||||||
hits.len(),
|
hits.len(),
|
||||||
home.display(),
|
|
||||||
list.join("\n")
|
list.join("\n")
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,11 +44,6 @@ pub(crate) fn set_app_id(name: &str) {
|
|||||||
glib::set_prgname(Some(name));
|
glib::set_prgname(Some(name));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn reveal_path(path: &Path) {
|
|
||||||
let target = path.parent().unwrap_or(path);
|
|
||||||
let _ = Command::new("xdg-open").arg(target).spawn();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Selbstinstallation gibt es nur unter macOS — hier installieren deb/rpm.
|
/// Selbstinstallation gibt es nur unter macOS — hier installieren deb/rpm.
|
||||||
pub(crate) fn offer_move_to_applications(_paths: &crate::domain::paths::Paths) {}
|
pub(crate) fn offer_move_to_applications(_paths: &crate::domain::paths::Paths) {}
|
||||||
|
|
||||||
|
|||||||
@@ -78,10 +78,6 @@ pub(crate) fn focus_terminal(pid: u32) {
|
|||||||
/// Wayland-app_id gibt es nur unter Linux.
|
/// Wayland-app_id gibt es nur unter Linux.
|
||||||
pub(crate) fn set_app_id(_name: &str) {}
|
pub(crate) fn set_app_id(_name: &str) {}
|
||||||
|
|
||||||
pub(crate) fn reveal_path(path: &Path) {
|
|
||||||
let _ = Command::new("open").arg("-R").arg(path).spawn();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- Selbstinstallation ----------
|
// ---------- Selbstinstallation ----------
|
||||||
|
|
||||||
/// App-Bundle zum Programmpfad: …/ai-control.app/Contents/MacOS/ai-control.
|
/// App-Bundle zum Programmpfad: …/ai-control.app/Contents/MacOS/ai-control.
|
||||||
@@ -322,3 +318,4 @@ pub(crate) fn init_tray(app: &tauri::AppHandle, cb: TrayCallbacks) -> Result<(),
|
|||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
//! Prozesse terminal_pids, kill_terminal
|
//! Prozesse terminal_pids, kill_terminal
|
||||||
//! Fokus/Aktivierung focus_terminal, activate_self, yield_activation
|
//! Fokus/Aktivierung focus_terminal, activate_self, yield_activation
|
||||||
//! Fenster/Icons set_dock_icon, set_app_id
|
//! Fenster/Icons set_dock_icon, set_app_id
|
||||||
//! Dateisystem home_dir, write_secret_file, symlink, reveal_path
|
//! Dateisystem home_dir, write_secret_file, symlink
|
||||||
//! Shell shell_command
|
//! Shell shell_command
|
||||||
//! Secrets KeychainStore (impl ApikeyStore), apikey_helper_command,
|
//! Secrets KeychainStore (impl ApikeyStore), apikey_helper_command,
|
||||||
//! oauth_keychain_exists, oauth_keychain_delete
|
//! oauth_keychain_exists, oauth_keychain_delete
|
||||||
|
|||||||
@@ -47,12 +47,6 @@ pub(crate) fn set_app_id(_name: &str) {}
|
|||||||
/// Selbstinstallation gibt es nur unter macOS — hier installiert der NSIS-Setup.
|
/// Selbstinstallation gibt es nur unter macOS — hier installiert der NSIS-Setup.
|
||||||
pub(crate) fn offer_move_to_applications(_paths: &crate::domain::paths::Paths) {}
|
pub(crate) fn offer_move_to_applications(_paths: &crate::domain::paths::Paths) {}
|
||||||
|
|
||||||
pub(crate) fn reveal_path(path: &Path) {
|
|
||||||
let _ = Command::new("explorer")
|
|
||||||
.arg(format!("/select,{}", path.display()))
|
|
||||||
.spawn();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- Dateisystem / Shell ----------
|
// ---------- Dateisystem / Shell ----------
|
||||||
|
|
||||||
pub(crate) fn home_dir() -> PathBuf {
|
pub(crate) fn home_dir() -> PathBuf {
|
||||||
@@ -125,3 +119,4 @@ pub(crate) fn init_tray(app: &tauri::AppHandle, cb: TrayCallbacks) -> Result<(),
|
|||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+23
-185
@@ -5,9 +5,7 @@ use std::io::{Read, Write};
|
|||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder};
|
use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder};
|
||||||
|
|
||||||
use crate::domain::paths::{
|
use crate::domain::paths::{commands_file, search_file, Paths};
|
||||||
commands_file, panel_file, panel_source_file, search_file, wiki_file, Paths,
|
|
||||||
};
|
|
||||||
use crate::domain::project::{
|
use crate::domain::project::{
|
||||||
project_config, project_pool_dir, verify_project_dir_in, ProjectConfig,
|
project_config, project_pool_dir, verify_project_dir_in, ProjectConfig,
|
||||||
};
|
};
|
||||||
@@ -147,12 +145,19 @@ pub fn term_start(
|
|||||||
let _ = std::fs::write(path, "");
|
let _ = std::fs::write(path, "");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Quell-Verknüpfung der Vorsession lösen — der Dokument-Puffer startet leer,
|
// Trilium-Modul an: Projekt-Instanz zur Session hochfahren (im Thread —
|
||||||
// Edits dürfen nicht in die zuletzt geöffnete Archiv-Datei laufen.
|
// der Start wartet bis zu 20 s auf den Port). Fehler landen im Dev-Log;
|
||||||
match std::fs::remove_file(panel_source_file(&project)) {
|
// die Tools melden eine fehlende Instanz ohnehin laut.
|
||||||
Ok(()) => {}
|
if crate::domain::modules::active_in(&paths, &project)?
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
.iter()
|
||||||
Err(e) => return Err(e.to_string()),
|
.any(|m| m.id == "trilium")
|
||||||
|
{
|
||||||
|
let proj = project.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
if let Err(e) = crate::domain::trilium::ensure_instance(&Paths::real(), &proj) {
|
||||||
|
log::warn!("Trilium-Start ({proj}): {e}");
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut cmd = crate::platform::shell_command(&claude_command(&paths));
|
let mut cmd = crate::platform::shell_command(&claude_command(&paths));
|
||||||
@@ -429,191 +434,24 @@ pub fn todos_update(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Quell-Verknüpfung des Dokument-Tabs setzen: ab jetzt schreibt jeder
|
/// Quell-Verknüpfung des Dokument-Tabs setzen: ab jetzt schreibt jeder
|
||||||
/// Editor-Commit den Body in diese Archiv-Datei zurück.
|
/// Suche aus dem Panel-Suchfeld: läuft wie das MCP-Tool search_archive über
|
||||||
fn link_panel_source(project: &str, path: &std::path::Path) -> Result<(), String> {
|
/// die ETAPI der Projekt-Instanz und schreibt die Treffer-Datei; der Watcher
|
||||||
std::fs::write(panel_source_file(project), path.display().to_string())
|
/// zieht sie in die Ansicht (beide Fenster).
|
||||||
.map_err(|e| e.to_string())
|
#[tauri::command]
|
||||||
}
|
pub async fn search_run(
|
||||||
|
project: String,
|
||||||
/// Aktuelle Quell-Verknüpfung, falls gesetzt.
|
query: String,
|
||||||
fn panel_source(project: &str) -> Option<std::path::PathBuf> {
|
tag: Option<String>,
|
||||||
std::fs::read_to_string(panel_source_file(project))
|
|
||||||
.ok()
|
|
||||||
.map(|s| std::path::PathBuf::from(s.trim()))
|
|
||||||
.filter(|p| !p.as_os_str().is_empty())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Verknüpfung nach einer Dokument-Operation nachziehen: zeigt sie auf den
|
|
||||||
/// alten Pfad, wandert sie mit; `None` löst sie (gelöschtes Dokument).
|
|
||||||
fn relink(
|
|
||||||
project: &str,
|
|
||||||
old: &std::path::Path,
|
|
||||||
new: Option<&std::path::Path>,
|
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
if panel_source(project).as_deref() != Some(old) {
|
let hits = crate::domain::trilium::search_notes(&project, &query, tag.as_deref(), 20)?;
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
match new {
|
|
||||||
Some(p) => link_panel_source(project, p),
|
|
||||||
None => std::fs::remove_file(panel_source_file(project)).map_err(|e| e.to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wie `relink`, für einen verschobenen Ordner: eine Verknüpfung auf ein
|
|
||||||
/// Dokument darin wandert mit.
|
|
||||||
fn relink_folder(
|
|
||||||
project: &str,
|
|
||||||
old: &std::path::Path,
|
|
||||||
new: &std::path::Path,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let Some(cur) = panel_source(project) else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
match cur.strip_prefix(old) {
|
|
||||||
Ok(rest) => link_panel_source(project, &new.join(rest)),
|
|
||||||
Err(_) => Ok(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Schreibt den Panel-Inhalt (Titel-Edit im Panel). Der Watcher meldet die
|
|
||||||
/// Änderung als `panel-update` an alle Fenster. Zeigt der Dokument-Tab ein
|
|
||||||
/// Archiv-Dokument (Quell-Verknüpfung), wandert der Body implizit in die
|
|
||||||
/// Archiv-Datei zurück; ihre Frontmatter bleibt.
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn panel_set(project: String, text: String) -> Result<(), String> {
|
|
||||||
std::fs::write(panel_file(&project), &text).map_err(|e| e.to_string())?;
|
|
||||||
match panel_source(&project) {
|
|
||||||
Some(src) => crate::domain::archive_ops::write_body(&src, &text),
|
|
||||||
None => Ok(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Lädt ein Archiv-Dokument in den Dokument-Puffer (Treffer-Klick in der
|
|
||||||
/// Suche) — ohne Frontmatter-Block, wie ein frischer Entwurf — und setzt die
|
|
||||||
/// Quell-Verknüpfung fürs Zurückschreiben. Der Watcher meldet den neuen
|
|
||||||
/// Inhalt als `panel-update`.
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn panel_load(project: String, path: String) -> Result<(), String> {
|
|
||||||
let text = std::fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?;
|
|
||||||
let body = crate::domain::archive::strip_frontmatter(&text);
|
|
||||||
std::fs::write(panel_file(&project), body).map_err(|e| e.to_string())?;
|
|
||||||
link_panel_source(&project, std::path::Path::new(&path))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Suche aus dem Panel-Suchfeld: läuft wie das MCP-Tool search_archive und
|
|
||||||
/// schreibt die Treffer-Datei; der Watcher zieht sie in die Ansicht (beide
|
|
||||||
/// Fenster).
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn search_run(project: String, query: String, tag: Option<String>) -> Result<(), String> {
|
|
||||||
let home = crate::domain::archive::require_archive_home(&project)?;
|
|
||||||
let hits = crate::domain::archive_search::search(&home, &query, tag.as_deref(), 20)?;
|
|
||||||
let payload = serde_json::json!({
|
let payload = serde_json::json!({
|
||||||
"query": query,
|
"query": query,
|
||||||
"tag": tag,
|
"tag": tag,
|
||||||
"home": home.display().to_string(),
|
|
||||||
"hits": hits,
|
"hits": hits,
|
||||||
});
|
});
|
||||||
std::fs::write(search_file(&project), payload.to_string()).map_err(|e| e.to_string())
|
std::fs::write(search_file(&project), payload.to_string()).map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Öffnet ein Wiki-Ziel: `tag:x` → Schlagwort-Seite, `tag:` →
|
|
||||||
/// Archiv-Übersicht in den Wiki-Puffer (`wiki-update`); ein Dokumentname
|
|
||||||
/// (Wikilink, Backlink) wird über den Index aufgelöst und wie ein
|
|
||||||
/// Suchtreffer in den Dokument-Puffer geladen (`panel-update`).
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn wiki_open(project: String, name: String) -> Result<(), String> {
|
|
||||||
let home = crate::domain::archive::require_archive_home(&project)?;
|
|
||||||
match name.strip_prefix("tag:") {
|
|
||||||
Some(tag) => {
|
|
||||||
let json = serde_json::to_string(&crate::domain::archive_index::archive_page(
|
|
||||||
&home,
|
|
||||||
(!tag.is_empty()).then_some(tag),
|
|
||||||
)?)
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
std::fs::write(wiki_file(&project), json).map_err(|e| e.to_string())
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
let rel = crate::domain::archive_index::resolve_doc(&home, &name)?;
|
|
||||||
let path = home.join(rel);
|
|
||||||
let text =
|
|
||||||
std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
|
|
||||||
let body = crate::domain::archive::strip_frontmatter(&text);
|
|
||||||
std::fs::write(panel_file(&project), body).map_err(|e| e.to_string())?;
|
|
||||||
link_panel_source(&project, &path)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Frische Archiv-Übersicht in den Wiki-Puffer — Abschluss der
|
|
||||||
/// Dokument-/Ordner-Operationen; der Watcher meldet `wiki-update`.
|
|
||||||
fn wiki_refresh_page(project: &str, home: &std::path::Path) -> Result<(), String> {
|
|
||||||
let json = serde_json::to_string(&crate::domain::archive_index::archive_page(home, None)?)
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
std::fs::write(wiki_file(project), json).map_err(|e| e.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Verschiebt ein Archiv-Dokument in einen anderen Ordner (leer = Wurzel).
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn archive_move(project: String, relpath: String, folder: String) -> Result<(), String> {
|
|
||||||
let home = crate::domain::archive::require_archive_home(&project)?;
|
|
||||||
let old = home.join(&relpath);
|
|
||||||
let new_rel = crate::domain::archive_ops::move_doc(&home, &relpath, &folder)?;
|
|
||||||
relink(&project, &old, Some(&home.join(new_rel)))?;
|
|
||||||
wiki_refresh_page(&project, &home)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Benennt ein Archiv-Dokument um (Slug hinter erhaltenem Zeitstempel).
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn archive_rename(project: String, relpath: String, name: String) -> Result<(), String> {
|
|
||||||
let home = crate::domain::archive::require_archive_home(&project)?;
|
|
||||||
let old = home.join(&relpath);
|
|
||||||
let new_rel = crate::domain::archive_ops::rename_doc(&home, &relpath, &name)?;
|
|
||||||
relink(&project, &old, Some(&home.join(new_rel)))?;
|
|
||||||
wiki_refresh_page(&project, &home)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Löscht ein Archiv-Dokument; danach zeigt das Wiki die Übersicht.
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn archive_delete(project: String, relpath: String) -> Result<(), String> {
|
|
||||||
let home = crate::domain::archive::require_archive_home(&project)?;
|
|
||||||
crate::domain::archive_ops::delete_doc(&home, &relpath)?;
|
|
||||||
relink(&project, &home.join(&relpath), None)?;
|
|
||||||
wiki_refresh_page(&project, &home)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Verschiebt/benennt einen Archiv-Ordner um; danach Übersicht.
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn archive_move_folder(project: String, folder: String, to: String) -> Result<(), String> {
|
|
||||||
let home = crate::domain::archive::require_archive_home(&project)?;
|
|
||||||
crate::domain::archive_ops::move_folder(&home, &folder, &to)?;
|
|
||||||
relink_folder(&project, &home.join(&folder), &home.join(&to))?;
|
|
||||||
wiki_refresh_page(&project, &home)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Legt einen Ordner im Archiv an (Plus im Baum); danach Übersicht.
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn archive_create_folder(project: String, folder: String) -> Result<(), String> {
|
|
||||||
let home = crate::domain::archive::require_archive_home(&project)?;
|
|
||||||
crate::domain::archive_ops::create_folder(&home, &folder)?;
|
|
||||||
wiki_refresh_page(&project, &home)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Legt ein leeres Dokument an (Plus im Listenkopf) und öffnet es im
|
|
||||||
/// Dokument-Tab: leerer Dokument-Puffer plus Quell-Verknüpfung — das
|
|
||||||
/// Getippte landet über `panel_set` in der Archiv-Datei. Die Übersicht
|
|
||||||
/// bleibt hier unangetastet; der Wiki-Tab lädt sie beim nächsten Aktivieren
|
|
||||||
/// frisch (zwei konkurrierende Puffer-Events würden sonst um den aktiven Tab
|
|
||||||
/// rennen).
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn archive_create_doc(project: String, folder: String, name: String) -> Result<(), String> {
|
|
||||||
let home = crate::domain::archive::require_archive_home(&project)?;
|
|
||||||
let display = crate::domain::project::display_name_in(&Paths::real(), &project)?;
|
|
||||||
let rel = crate::domain::archive_ops::create_doc(&home, &folder, &name, &display)?;
|
|
||||||
let path = home.join(rel);
|
|
||||||
std::fs::write(panel_file(&project), "").map_err(|e| e.to_string())?;
|
|
||||||
link_panel_source(&project, &path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Löst das Panel in ein eigenes Fenster ab. Existiert es schon, kommt es nach
|
/// Löst das Panel in ein eigenes Fenster ab. Existiert es schon, kommt es nach
|
||||||
/// vorn. `panel-detached` blendet das angedockte Panel im Terminal-Fenster aus.
|
/// vorn. `panel-detached` blendet das angedockte Panel im Terminal-Fenster aus.
|
||||||
/// Async, weil Fenster-Erzeugung aus einem synchronen Command auf dem
|
/// Async, weil Fenster-Erzeugung aus einem synchronen Command auf dem
|
||||||
|
|||||||
@@ -1,74 +0,0 @@
|
|||||||
// Archiv-Formular: Aufklappen, Meta-Aufbereitung, Tastatur.
|
|
||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
||||||
import { initArchiveForm } from "./archive-form";
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
document.body.innerHTML = `<button id="btn">Archiv</button>`;
|
|
||||||
const onSubmit = vi.fn();
|
|
||||||
const form = initArchiveForm(document.getElementById("btn")!, onSubmit);
|
|
||||||
const root = document.querySelector<HTMLElement>(".archive-form")!;
|
|
||||||
const inputs = [...root.querySelectorAll("input")];
|
|
||||||
return { form, onSubmit, root, inputs };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("initArchiveForm", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
document.body.innerHTML = "";
|
|
||||||
});
|
|
||||||
|
|
||||||
it("klappt auf und zu", () => {
|
|
||||||
const { form, root } = setup();
|
|
||||||
expect(root.hidden).toBe(true);
|
|
||||||
form.toggle();
|
|
||||||
expect(root.hidden).toBe(false);
|
|
||||||
form.toggle();
|
|
||||||
expect(root.hidden).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("liefert getrimmte Meta; Leeres wird undefined, Tags gesplittet", () => {
|
|
||||||
const { form, onSubmit, root, inputs } = setup();
|
|
||||||
form.toggle();
|
|
||||||
inputs[0].value = " konzepte/panel ";
|
|
||||||
inputs[1].value = "";
|
|
||||||
inputs[2].value = " adr, infra ,, ";
|
|
||||||
root.querySelector<HTMLElement>(".archive-form-submit")!.click();
|
|
||||||
expect(onSubmit).toHaveBeenCalledWith({
|
|
||||||
folder: "konzepte/panel",
|
|
||||||
description: undefined,
|
|
||||||
tags: ["adr", "infra"],
|
|
||||||
});
|
|
||||||
expect(root.hidden).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Sonst gelten Ordner und Schlagwörter des vorigen Dokuments unbemerkt für
|
|
||||||
/// das nächste — wer direkt Enter drückt, archiviert es falsch einsortiert.
|
|
||||||
it("startet nach dem Archivieren wieder leer", () => {
|
|
||||||
const { form, onSubmit, root, inputs } = setup();
|
|
||||||
form.toggle();
|
|
||||||
inputs[0].value = "konzepte/panel";
|
|
||||||
inputs[1].value = "Beschreibung A";
|
|
||||||
inputs[2].value = "panel, wiki";
|
|
||||||
root.querySelector<HTMLElement>(".archive-form-submit")!.click();
|
|
||||||
|
|
||||||
form.toggle();
|
|
||||||
expect(inputs.map((i) => i.value)).toEqual(["", "", ""]);
|
|
||||||
root.querySelector<HTMLElement>(".archive-form-submit")!.click();
|
|
||||||
expect(onSubmit).toHaveBeenLastCalledWith({
|
|
||||||
folder: undefined,
|
|
||||||
description: undefined,
|
|
||||||
tags: [],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Enter schickt ab, Escape schließt ohne Abschicken", () => {
|
|
||||||
const { form, onSubmit, root } = setup();
|
|
||||||
form.toggle();
|
|
||||||
root.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
|
||||||
expect(root.hidden).toBe(true);
|
|
||||||
expect(onSubmit).not.toHaveBeenCalled();
|
|
||||||
form.toggle();
|
|
||||||
root.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
|
||||||
expect(onSubmit).toHaveBeenCalledOnce();
|
|
||||||
expect(root.hidden).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
/// Archiv-Formular: klappt unter dem Archiv-Button auf und fragt Ordner,
|
|
||||||
/// Beschreibung und Schlagwörter ab (alles optional); Enter oder der Button
|
|
||||||
/// archivieren, Escape schließt. Gemeinsam für das angedockte Panel und das
|
|
||||||
/// abgelöste Fenster.
|
|
||||||
|
|
||||||
import { t } from "./messages";
|
|
||||||
|
|
||||||
export interface ArchiveFormMeta {
|
|
||||||
folder?: string;
|
|
||||||
description?: string;
|
|
||||||
tags: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function initArchiveForm(
|
|
||||||
anchor: HTMLElement,
|
|
||||||
onSubmit: (meta: ArchiveFormMeta) => void,
|
|
||||||
): { toggle(): void } {
|
|
||||||
function field(placeholder: string): HTMLInputElement {
|
|
||||||
const i = document.createElement("input");
|
|
||||||
i.type = "text";
|
|
||||||
i.placeholder = placeholder;
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
|
|
||||||
const form = document.createElement("div");
|
|
||||||
form.className = "archive-form";
|
|
||||||
form.hidden = true;
|
|
||||||
const folder = field(t("archiveForm.folder"));
|
|
||||||
const desc = field(t("archiveForm.description"));
|
|
||||||
const tags = field(t("archiveForm.tags"));
|
|
||||||
const submit = document.createElement("button");
|
|
||||||
submit.className = "archive-form-submit";
|
|
||||||
submit.textContent = t("archiveForm.submit");
|
|
||||||
form.append(folder, desc, tags, submit);
|
|
||||||
document.body.append(form);
|
|
||||||
|
|
||||||
const meta = (): ArchiveFormMeta => ({
|
|
||||||
folder: folder.value.trim() || undefined,
|
|
||||||
description: desc.value.trim() || undefined,
|
|
||||||
tags: tags.value
|
|
||||||
.split(",")
|
|
||||||
.map((t) => t.trim())
|
|
||||||
.filter(Boolean),
|
|
||||||
});
|
|
||||||
// Leeren, weil das Formular zum Fenster gehört und nicht zum Dokument.
|
|
||||||
const close = () => {
|
|
||||||
form.hidden = true;
|
|
||||||
folder.value = "";
|
|
||||||
desc.value = "";
|
|
||||||
tags.value = "";
|
|
||||||
};
|
|
||||||
const open = () => {
|
|
||||||
const r = anchor.getBoundingClientRect();
|
|
||||||
form.style.top = `${r.bottom + 6}px`;
|
|
||||||
form.style.right = `${Math.max(8, window.innerWidth - r.right - 4)}px`;
|
|
||||||
form.hidden = false;
|
|
||||||
folder.focus();
|
|
||||||
};
|
|
||||||
const fire = () => {
|
|
||||||
onSubmit(meta());
|
|
||||||
close();
|
|
||||||
};
|
|
||||||
submit.addEventListener("click", fire);
|
|
||||||
form.addEventListener("keydown", (e) => {
|
|
||||||
if (e.key === "Enter") {
|
|
||||||
e.preventDefault();
|
|
||||||
fire();
|
|
||||||
} else if (e.key === "Escape") {
|
|
||||||
close();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return { toggle: () => (form.hidden ? open() : close()) };
|
|
||||||
}
|
|
||||||
+25
-28
@@ -6,69 +6,66 @@ function modeSetup() {
|
|||||||
document.body.innerHTML = `
|
document.body.innerHTML = `
|
||||||
<div id="tabs">
|
<div id="tabs">
|
||||||
<button data-mode="commands">Befehle</button>
|
<button data-mode="commands">Befehle</button>
|
||||||
<button data-mode="draft">Dokument</button>
|
<button data-mode="todo">ToDo</button>
|
||||||
<button data-mode="wiki">Wiki</button>
|
|
||||||
<button data-mode="search">Suche</button>
|
<button data-mode="search">Suche</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="title">Mein Titel</div>
|
<div id="title"></div>
|
||||||
<div id="draft-el"></div>
|
|
||||||
<div id="cc" hidden></div>
|
<div id="cc" hidden></div>
|
||||||
<div id="sc" hidden></div>
|
<div id="tc" hidden></div>
|
||||||
<div id="wc" hidden></div>`;
|
<div id="sc" hidden></div>`;
|
||||||
const el = (id: string) => document.getElementById(id)!;
|
const el = (id: string) => document.getElementById(id)!;
|
||||||
const tab = (m: string) =>
|
const tab = (m: string) =>
|
||||||
document.querySelector<HTMLElement>(`[data-mode="${m}"]`)!;
|
document.querySelector<HTMLElement>(`[data-mode="${m}"]`)!;
|
||||||
const flush = vi.fn();
|
|
||||||
const mode = initPanelMode({
|
const mode = initPanelMode({
|
||||||
tabs: [
|
tabs: [
|
||||||
{ mode: "commands", btn: tab("commands"), content: el("cc"), label: "Befehle" },
|
{ mode: "commands", btn: tab("commands"), content: el("cc"), label: "Befehle" },
|
||||||
{ mode: "draft", btn: tab("draft"), content: null, label: "Dokument" },
|
{ mode: "todo", btn: tab("todo"), content: el("tc"), label: "ToDo" },
|
||||||
{ mode: "wiki", btn: tab("wiki"), content: el("wc"), label: "Wiki" },
|
|
||||||
{ mode: "search", btn: tab("search"), content: el("sc"), label: "Suche" },
|
{ mode: "search", btn: tab("search"), content: el("sc"), label: "Suche" },
|
||||||
],
|
],
|
||||||
draftEls: [el("draft-el")],
|
|
||||||
titleEl: el("title"),
|
titleEl: el("title"),
|
||||||
flush,
|
|
||||||
});
|
});
|
||||||
return { mode, flush, el, tab };
|
return { mode, el, tab };
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("initPanelMode", () => {
|
describe("initPanelMode", () => {
|
||||||
it("startet im Dokument-Modus mit aktivem Tab", () => {
|
it("startet ohne aktiven Tab", () => {
|
||||||
const { el, tab } = modeSetup();
|
const { mode, el } = modeSetup();
|
||||||
expect(el("draft-el").hidden).toBe(false);
|
expect(mode.current()).toBe(null);
|
||||||
expect(el("cc").hidden).toBe(true);
|
expect(el("cc").hidden).toBe(true);
|
||||||
expect(tab("draft").classList.contains("active")).toBe(true);
|
expect(document.querySelectorAll(".active").length).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("wechselt Sichtbarkeit, Titel und aktive Markierung", () => {
|
it("wechselt Sichtbarkeit, Titel und aktive Markierung", () => {
|
||||||
const { mode, flush, el, tab } = modeSetup();
|
const { mode, el, tab } = modeSetup();
|
||||||
mode.to("commands");
|
mode.to("commands");
|
||||||
expect(flush).toHaveBeenCalledOnce();
|
|
||||||
expect(el("cc").hidden).toBe(false);
|
expect(el("cc").hidden).toBe(false);
|
||||||
expect(el("draft-el").hidden).toBe(true);
|
expect(el("tc").hidden).toBe(true);
|
||||||
expect(el("title").textContent).toBe("Befehle");
|
expect(el("title").textContent).toBe("Befehle");
|
||||||
expect(tab("commands").classList.contains("active")).toBe(true);
|
expect(tab("commands").classList.contains("active")).toBe(true);
|
||||||
expect(tab("draft").classList.contains("active")).toBe(false);
|
mode.to("todo");
|
||||||
mode.to("draft");
|
expect(el("cc").hidden).toBe(true);
|
||||||
expect(el("title").textContent).toBe("Mein Titel");
|
expect(el("tc").hidden).toBe(false);
|
||||||
|
expect(el("title").textContent).toBe("ToDo");
|
||||||
|
expect(tab("commands").classList.contains("active")).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("Tab-Klick wechselt den Modus", () => {
|
it("Tab-Klick wechselt den Modus", () => {
|
||||||
const { el, tab } = modeSetup();
|
const { el, tab } = modeSetup();
|
||||||
tab("wiki").click();
|
tab("search").click();
|
||||||
expect(el("wc").hidden).toBe(false);
|
expect(el("sc").hidden).toBe(false);
|
||||||
expect(el("draft-el").hidden).toBe(true);
|
expect(el("cc").hidden).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("clear hebt die Auswahl auf; danach wählt to() wieder aus", () => {
|
it("clear hebt die Auswahl auf; danach wählt to() wieder aus", () => {
|
||||||
const { mode, el, tab } = modeSetup();
|
const { mode, el, tab } = modeSetup();
|
||||||
|
mode.to("commands");
|
||||||
mode.clear();
|
mode.clear();
|
||||||
expect(document.querySelectorAll(".active").length).toBe(0);
|
expect(document.querySelectorAll(".active").length).toBe(0);
|
||||||
|
expect(el("cc").hidden).toBe(true);
|
||||||
expect(mode.current()).toBe(null);
|
expect(mode.current()).toBe(null);
|
||||||
mode.to("draft");
|
mode.to("commands");
|
||||||
expect(tab("draft").classList.contains("active")).toBe(true);
|
expect(tab("commands").classList.contains("active")).toBe(true);
|
||||||
expect(el("title").textContent).toBe("Mein Titel");
|
expect(el("cc").hidden).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+13
-25
@@ -123,54 +123,42 @@ export type PanelMode = string;
|
|||||||
export interface ModeTab {
|
export interface ModeTab {
|
||||||
mode: PanelMode;
|
mode: PanelMode;
|
||||||
btn: HTMLElement;
|
btn: HTMLElement;
|
||||||
/// Content-Container des Tabs; null für den Entwurfs-Tab, dessen
|
/// Content-Container des Tabs.
|
||||||
/// Sichtbarkeit über draftEls läuft.
|
content: HTMLElement;
|
||||||
content: HTMLElement | null;
|
/// Titelzeilen-Text, wenn der Tab aktiv ist.
|
||||||
/// Titelzeilen-Text, wenn der Tab aktiv ist (der Entwurfs-Tab behält
|
|
||||||
/// seinen Dokument-Titel).
|
|
||||||
label: string;
|
label: string;
|
||||||
onActivate?: () => void;
|
onActivate?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Modus-Umschalter über die Tabs der Registry: blendet Entwurfs-Inhalt samt
|
/// Modus-Umschalter über die Tabs der Registry: blendet die Ansichten
|
||||||
/// zugehöriger Kopf-Controls gegen die jeweilige Ansicht aus. Ein Wechsel bei
|
/// gegeneinander aus; die Titelzeile trägt das Label des aktiven Tabs.
|
||||||
/// offener Inhalts-Bearbeitung speichert den Entwurf (flush) statt zu
|
export function initPanelMode(opts: { tabs: ModeTab[]; titleEl: HTMLElement }) {
|
||||||
/// blockieren.
|
|
||||||
export function initPanelMode(opts: {
|
|
||||||
tabs: ModeTab[];
|
|
||||||
draftEls: HTMLElement[];
|
|
||||||
titleEl: HTMLElement;
|
|
||||||
flush: () => void;
|
|
||||||
}) {
|
|
||||||
// `null` = kein Tab aktiv (Panel zugeklappt).
|
// `null` = kein Tab aktiv (Panel zugeklappt).
|
||||||
let mode: PanelMode | null = "draft";
|
let mode: PanelMode | null = null;
|
||||||
let draftTitle = "";
|
|
||||||
|
|
||||||
function apply() {
|
function apply() {
|
||||||
for (const tab of opts.tabs) {
|
for (const tab of opts.tabs) {
|
||||||
if (tab.content) tab.content.hidden = mode !== tab.mode;
|
tab.content.hidden = mode !== tab.mode;
|
||||||
tab.btn.classList.toggle("active", tab.mode === mode);
|
tab.btn.classList.toggle("active", tab.mode === mode);
|
||||||
}
|
}
|
||||||
for (const el of opts.draftEls) el.hidden = mode !== "draft";
|
|
||||||
const active = opts.tabs.find((tab) => tab.mode === mode);
|
const active = opts.tabs.find((tab) => tab.mode === mode);
|
||||||
if (mode && mode !== "draft" && active) opts.titleEl.textContent = active.label;
|
if (active) opts.titleEl.textContent = active.label;
|
||||||
}
|
}
|
||||||
|
|
||||||
function to(m: PanelMode) {
|
function to(m: PanelMode) {
|
||||||
if (m === mode) return;
|
if (m === mode) return;
|
||||||
opts.flush();
|
|
||||||
if (mode === "draft") draftTitle = opts.titleEl.textContent || t("panel.tabDraft");
|
|
||||||
mode = m;
|
mode = m;
|
||||||
apply();
|
apply();
|
||||||
if (m === "draft") opts.titleEl.textContent = draftTitle;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Auswahl aufheben (Panel zugeklappt) — der nächste to()-Aufruf oder
|
/// Auswahl aufheben (Panel zugeklappt) — der nächste to()-Aufruf oder
|
||||||
/// Tab-Klick wählt wieder aus.
|
/// Tab-Klick wählt wieder aus.
|
||||||
function clear() {
|
function clear() {
|
||||||
if (mode === "draft") draftTitle = opts.titleEl.textContent || t("panel.tabDraft");
|
|
||||||
mode = null;
|
mode = null;
|
||||||
for (const tab of opts.tabs) tab.btn.classList.remove("active");
|
for (const tab of opts.tabs) {
|
||||||
|
tab.content.hidden = true;
|
||||||
|
tab.btn.classList.remove("active");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const tab of opts.tabs) {
|
for (const tab of opts.tabs) {
|
||||||
|
|||||||
+273
-107
@@ -10,6 +10,7 @@ interface Project {
|
|||||||
pool: string | null;
|
pool: string | null;
|
||||||
running: boolean;
|
running: boolean;
|
||||||
terminal: { theme: string | null; icon: string | null; title: string | null };
|
terminal: { theme: string | null; icon: string | null; title: string | null };
|
||||||
|
archive: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Pool {
|
interface Pool {
|
||||||
@@ -98,6 +99,15 @@ async function openTerminal(project: Project) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Archiv-Zugang aus der Projektliste: öffnet das Trilium-Fenster des Projekts.
|
||||||
|
async function openArchive(project: Project) {
|
||||||
|
try {
|
||||||
|
await invoke("trilium_open", { project: project.id, noteId: null });
|
||||||
|
} catch (e) {
|
||||||
|
error.value = String(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
interface PendingRestart {
|
interface PendingRestart {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -171,7 +181,6 @@ interface TerminalSettings {
|
|||||||
icon: string | null;
|
icon: string | null;
|
||||||
title: string;
|
title: string;
|
||||||
workDirs: string[];
|
workDirs: string[];
|
||||||
archiveHome: string | null;
|
|
||||||
modules: ModuleState[];
|
modules: ModuleState[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,9 +191,6 @@ async function openSettings(p: Project) {
|
|||||||
const workDirs = await invoke<string[]>("project_work_dirs", {
|
const workDirs = await invoke<string[]>("project_work_dirs", {
|
||||||
project: p.id,
|
project: p.id,
|
||||||
});
|
});
|
||||||
const archiveHome = await invoke<string | null>("panel_archive_dir_cmd", {
|
|
||||||
project: p.id,
|
|
||||||
});
|
|
||||||
const modules = await invoke<ModuleState[]>("module_registry", {
|
const modules = await invoke<ModuleState[]>("module_registry", {
|
||||||
project: p.id,
|
project: p.id,
|
||||||
});
|
});
|
||||||
@@ -196,7 +202,6 @@ async function openSettings(p: Project) {
|
|||||||
icon: p.terminal.icon,
|
icon: p.terminal.icon,
|
||||||
title: p.terminal.title ?? "",
|
title: p.terminal.title ?? "",
|
||||||
workDirs,
|
workDirs,
|
||||||
archiveHome,
|
|
||||||
modules,
|
modules,
|
||||||
};
|
};
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -205,10 +210,22 @@ async function openSettings(p: Project) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Modul-Schalter schreiben sofort in die Projekt-Config (nur Abweichungen
|
// Modul-Schalter schreiben sofort in die Projekt-Config (nur Abweichungen
|
||||||
// vom Default); ein Fehler stellt die Checkbox zurück.
|
// vom Default); ein Fehler stellt die Checkbox zurück. Ausnahme Trilium:
|
||||||
|
// Anhaken öffnet nur den Wizard — das Modul-Flag schreibt erst der
|
||||||
|
// erfolgreiche Setup (trilium_connect im Backend); Abwählen stoppt die
|
||||||
|
// Instanz mit.
|
||||||
async function toggleModule(m: ModuleState) {
|
async function toggleModule(m: ModuleState) {
|
||||||
const s = settings.value!;
|
const s = settings.value!;
|
||||||
try {
|
try {
|
||||||
|
if (m.id === "trilium") {
|
||||||
|
if (m.enabled) {
|
||||||
|
m.enabled = false; // folgt erst dem Setup-Erfolg
|
||||||
|
await openTriliumWizard();
|
||||||
|
} else {
|
||||||
|
await invoke("trilium_disable", { project: s.id });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
await invoke("set_module", { project: s.id, module: m.id, enabled: m.enabled });
|
await invoke("set_module", { project: s.id, module: m.id, enabled: m.enabled });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
m.enabled = !m.enabled;
|
m.enabled = !m.enabled;
|
||||||
@@ -216,6 +233,83 @@ async function toggleModule(m: ModuleState) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Trilium-Wizard: Runtime laden, Instanz starten, per Passwort den
|
||||||
|
// ETAPI-Token holen. Reine Checks beim Öffnen; geschrieben wird erst nach
|
||||||
|
// Erfolg (Backend-Muster), das Passwort wird nicht gespeichert.
|
||||||
|
interface TriliumStatus {
|
||||||
|
version: string;
|
||||||
|
port: number;
|
||||||
|
data_dir: string;
|
||||||
|
runtime_ready: boolean;
|
||||||
|
instance_running: boolean;
|
||||||
|
token_ok: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TriliumWizard {
|
||||||
|
status: TriliumStatus | null;
|
||||||
|
password: string;
|
||||||
|
busy: boolean;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const triWizard = ref<TriliumWizard | null>(null);
|
||||||
|
|
||||||
|
async function openTriliumWizard() {
|
||||||
|
const s = settings.value!;
|
||||||
|
triWizard.value = { status: null, password: "", busy: false, error: null };
|
||||||
|
try {
|
||||||
|
triWizard.value.status = await invoke<TriliumStatus>("trilium_status", {
|
||||||
|
project: s.id,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
triWizard.value.error = String(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function triliumSetup() {
|
||||||
|
const s = settings.value!;
|
||||||
|
const w = triWizard.value!;
|
||||||
|
w.busy = true;
|
||||||
|
w.error = null;
|
||||||
|
try {
|
||||||
|
w.status = await invoke<TriliumStatus>("trilium_setup", { project: s.id });
|
||||||
|
} catch (e) {
|
||||||
|
w.error = String(e);
|
||||||
|
}
|
||||||
|
w.busy = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function triliumConnect() {
|
||||||
|
const s = settings.value!;
|
||||||
|
const w = triWizard.value!;
|
||||||
|
w.busy = true;
|
||||||
|
w.error = null;
|
||||||
|
try {
|
||||||
|
w.status = await invoke<TriliumStatus>("trilium_connect", {
|
||||||
|
project: s.id,
|
||||||
|
password: w.password,
|
||||||
|
});
|
||||||
|
w.password = "";
|
||||||
|
// Modul-Flag hat das Backend gesetzt — Checkbox nachziehen.
|
||||||
|
s.modules = await invoke<ModuleState[]>("module_registry", { project: s.id });
|
||||||
|
} catch (e) {
|
||||||
|
w.error = String(e);
|
||||||
|
}
|
||||||
|
w.busy = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function triliumOpen() {
|
||||||
|
const s = settings.value!;
|
||||||
|
const w = triWizard.value!;
|
||||||
|
w.error = null;
|
||||||
|
try {
|
||||||
|
await invoke("trilium_open", { project: s.id, noteId: null });
|
||||||
|
w.status = await invoke<TriliumStatus>("trilium_status", { project: s.id });
|
||||||
|
} catch (e) {
|
||||||
|
w.error = String(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Projektordner neu zuordnen (Root, in dem die Session startet); verschoben
|
// Projektordner neu zuordnen (Root, in dem die Session startet); verschoben
|
||||||
// wird nichts — der gewählte Ordner ist der neue Ort des Projekts.
|
// wird nichts — der gewählte Ordner ist der neue Ort des Projekts.
|
||||||
async function changeProjectDir() {
|
async function changeProjectDir() {
|
||||||
@@ -256,59 +350,6 @@ async function removeWorkDir(dir: string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Archiv-Home schreibt wie die Arbeitsordner direkt (Config + Permissions);
|
|
||||||
// ohne Archiv zeigt das Panel nur Befehle und Dokument. Greift ab dem
|
|
||||||
// nächsten Session-Start. Ist schon eins gesetzt, fragt ein Dialog nach —
|
|
||||||
// mit der Option, die Dokumente mitzunehmen (nichts wird implizit verschoben).
|
|
||||||
interface PendingArchiveChange {
|
|
||||||
dir: string;
|
|
||||||
migrate: boolean;
|
|
||||||
}
|
|
||||||
const pendingArchive = ref<PendingArchiveChange | null>(null);
|
|
||||||
|
|
||||||
async function chooseArchive() {
|
|
||||||
const s = settings.value!;
|
|
||||||
const dir = await open({ directory: true, multiple: false });
|
|
||||||
if (typeof dir !== "string") return;
|
|
||||||
if (s.archiveHome && s.archiveHome !== dir) {
|
|
||||||
pendingArchive.value = { dir, migrate: false };
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await invoke("set_archive_home_cmd", { project: s.id, dir });
|
|
||||||
s.archiveHome = await invoke<string | null>("panel_archive_dir_cmd", {
|
|
||||||
project: s.id,
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
error.value = String(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function confirmArchiveChange() {
|
|
||||||
const s = settings.value!;
|
|
||||||
const a = pendingArchive.value!;
|
|
||||||
try {
|
|
||||||
await invoke("change_archive_home_cmd", { project: s.id, dir: a.dir, migrate: a.migrate });
|
|
||||||
s.archiveHome = await invoke<string | null>("panel_archive_dir_cmd", {
|
|
||||||
project: s.id,
|
|
||||||
});
|
|
||||||
pendingArchive.value = null;
|
|
||||||
} catch (e) {
|
|
||||||
error.value = String(e);
|
|
||||||
pendingArchive.value = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function clearArchive() {
|
|
||||||
const s = settings.value!;
|
|
||||||
try {
|
|
||||||
await invoke("clear_archive_home_cmd", { project: s.id });
|
|
||||||
s.archiveHome = null;
|
|
||||||
} catch (e) {
|
|
||||||
error.value = String(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pickIcon() {
|
async function pickIcon() {
|
||||||
const file = await open({
|
const file = await open({
|
||||||
multiple: false,
|
multiple: false,
|
||||||
@@ -425,10 +466,8 @@ interface DeletePreview {
|
|||||||
name: string;
|
name: string;
|
||||||
projectDir: string;
|
projectDir: string;
|
||||||
aiControlDir: boolean;
|
aiControlDir: boolean;
|
||||||
archivePermission: boolean;
|
|
||||||
panelFiles: number;
|
panelFiles: number;
|
||||||
archiveHome: string | null;
|
triliumData: string | null;
|
||||||
archiveDocs: number;
|
|
||||||
workDirs: string[];
|
workDirs: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,6 +566,14 @@ onUnmounted(() => window.clearInterval(timer));
|
|||||||
</td>
|
</td>
|
||||||
<td class="cell-actions">
|
<td class="cell-actions">
|
||||||
<span class="row-actions">
|
<span class="row-actions">
|
||||||
|
<button
|
||||||
|
v-if="p.archive"
|
||||||
|
class="gear"
|
||||||
|
:title="$t('projects.openArchive')"
|
||||||
|
@click="openArchive(p)"
|
||||||
|
>
|
||||||
|
🗃
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
class="gear"
|
class="gear"
|
||||||
:title="$t('projects.terminalSettings')"
|
:title="$t('projects.terminalSettings')"
|
||||||
@@ -665,20 +712,13 @@ onUnmounted(() => window.clearInterval(timer));
|
|||||||
<small>{{ $t("projects.scopeIntegrationDesc") }}</small>
|
<small>{{ $t("projects.scopeIntegrationDesc") }}</small>
|
||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
<label class="scope">
|
<label v-if="pendingDelete.preview.triliumData" class="scope">
|
||||||
<input
|
<input v-model="pendingDelete.scope" type="radio" value="archive" />
|
||||||
v-model="pendingDelete.scope"
|
|
||||||
type="radio"
|
|
||||||
value="archive"
|
|
||||||
:disabled="!pendingDelete.preview.archiveHome"
|
|
||||||
/>
|
|
||||||
<span>
|
<span>
|
||||||
<strong>{{ $t("projects.scopeArchive") }}</strong>
|
<strong>{{ $t("projects.scopeArchive") }}</strong>
|
||||||
<small v-if="pendingDelete.preview.archiveHome">
|
<small>
|
||||||
{{ $t("projects.scopeArchiveDesc", { path: pendingDelete.preview.archiveHome }) }}
|
{{ $t("projects.scopeArchiveDesc", { path: pendingDelete.preview.triliumData }) }}
|
||||||
({{ $t("projects.docCount", pendingDelete.preview.archiveDocs) }})
|
|
||||||
</small>
|
</small>
|
||||||
<small v-else>{{ $t("projects.archiveNone") }}</small>
|
|
||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
<label class="scope">
|
<label class="scope">
|
||||||
@@ -700,14 +740,12 @@ onUnmounted(() => window.clearInterval(timer));
|
|||||||
<ul class="affected">
|
<ul class="affected">
|
||||||
<li>{{ $t("projects.artRegistry") }}</li>
|
<li>{{ $t("projects.artRegistry") }}</li>
|
||||||
<li v-if="pendingDelete.preview.aiControlDir">{{ $t("projects.artAiControl") }}</li>
|
<li v-if="pendingDelete.preview.aiControlDir">{{ $t("projects.artAiControl") }}</li>
|
||||||
<li v-if="pendingDelete.preview.archivePermission">{{ $t("projects.artArchivePerm") }}</li>
|
|
||||||
<li v-if="pendingDelete.preview.panelFiles">
|
<li v-if="pendingDelete.preview.panelFiles">
|
||||||
{{ $t("projects.artPanelFiles", pendingDelete.preview.panelFiles) }}
|
{{ $t("projects.artPanelFiles", pendingDelete.preview.panelFiles) }}
|
||||||
</li>
|
</li>
|
||||||
<li>{{ $t("projects.artDesktop") }}</li>
|
<li>{{ $t("projects.artDesktop") }}</li>
|
||||||
<li v-if="pendingDelete.scope !== 'integration' && pendingDelete.preview.archiveHome">
|
<li v-if="pendingDelete.scope !== 'integration' && pendingDelete.preview.triliumData">
|
||||||
{{ $t("projects.artArchive", { path: pendingDelete.preview.archiveHome }) }}
|
{{ $t("projects.artArchive", { path: pendingDelete.preview.triliumData }) }}
|
||||||
({{ $t("projects.docCount", pendingDelete.preview.archiveDocs) }})
|
|
||||||
</li>
|
</li>
|
||||||
<li v-if="pendingDelete.scope === 'full'">
|
<li v-if="pendingDelete.scope === 'full'">
|
||||||
{{ $t("projects.artProjectDir", { path: pendingDelete.preview.projectDir }) }}
|
{{ $t("projects.artProjectDir", { path: pendingDelete.preview.projectDir }) }}
|
||||||
@@ -818,20 +856,11 @@ onUnmounted(() => window.clearInterval(timer));
|
|||||||
<input v-model="m.enabled" type="checkbox" @change="toggleModule(m)" />
|
<input v-model="m.enabled" type="checkbox" @change="toggleModule(m)" />
|
||||||
<span>{{ $t(`modules.${m.id}`) }} — {{ $t(`modules.${m.id}Desc`) }}</span>
|
<span>{{ $t(`modules.${m.id}`) }} — {{ $t(`modules.${m.id}Desc`) }}</span>
|
||||||
</label>
|
</label>
|
||||||
<div v-if="m.id === 'archive'" class="srow">
|
<div v-if="m.id === 'trilium'" class="srow">
|
||||||
<span class="slbl">{{ $t("projects.archive") }}</span>
|
<span class="slbl"></span>
|
||||||
<span class="sval">
|
<span class="sval"></span>
|
||||||
<span v-if="settings.archiveHome" class="spath hover-pop">
|
|
||||||
{{ contractHome(settings.archiveHome) }}
|
|
||||||
<span class="pop pop-path">{{ settings.archiveHome }}</span>
|
|
||||||
</span>
|
|
||||||
<span v-else class="spath muted">{{ $t("projects.archiveNone") }}</span>
|
|
||||||
</span>
|
|
||||||
<span class="sacts">
|
<span class="sacts">
|
||||||
<button @click="chooseArchive">{{ $t("projects.changeDir") }}</button>
|
<button @click="openTriliumWizard">{{ $t("trilium.wizard") }}</button>
|
||||||
<button v-if="settings.archiveHome" @click="clearArchive">
|
|
||||||
{{ $t("projects.remove") }}
|
|
||||||
</button>
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -849,27 +878,63 @@ onUnmounted(() => window.clearInterval(timer));
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="pendingArchive && settings" class="overlay" @click.self="pendingArchive = null">
|
<div v-if="triWizard" class="overlay" @click.self="triWizard = null">
|
||||||
<div class="dialog">
|
<div class="dialog tri-dialog">
|
||||||
<h3>{{ $t("projects.archiveChangeTitle") }}</h3>
|
<h3>{{ $t("trilium.wizardTitle") }}</h3>
|
||||||
<p>
|
<p class="hint">{{ $t("trilium.wizardIntro") }}</p>
|
||||||
{{ $t("projects.archiveChangeText", {
|
<p v-if="triWizard.error" class="error">{{ triWizard.error }}</p>
|
||||||
old: contractHome(settings.archiveHome ?? ""),
|
|
||||||
neu: contractHome(pendingArchive.dir),
|
<ul v-if="triWizard.status" class="tri-steps">
|
||||||
}) }}
|
<li>
|
||||||
|
<span class="mark" :class="{ ok: triWizard.status.runtime_ready }">{{ triWizard.status.runtime_ready ? "✓" : "✗" }}</span>
|
||||||
|
<span>
|
||||||
|
{{ $t("trilium.stepRuntime") }}
|
||||||
|
<small>Trilium {{ triWizard.status.version }}</small>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<span class="mark" :class="{ ok: triWizard.status.instance_running }">{{ triWizard.status.instance_running ? "✓" : "✗" }}</span>
|
||||||
|
<span>
|
||||||
|
{{ $t("trilium.stepInstance") }}
|
||||||
|
<small>{{ $t("trilium.port", { port: triWizard.status.port }) }}</small>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<span class="mark" :class="{ ok: triWizard.status.token_ok }">{{ triWizard.status.token_ok ? "✓" : "✗" }}</span>
|
||||||
|
<span>{{ $t("trilium.stepToken") }}</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p v-if="triWizard.status" class="tri-meta">
|
||||||
|
{{ $t("trilium.dataDir") }}: <code>{{ triWizard.status.data_dir }}</code>
|
||||||
|
· http://127.0.0.1:{{ triWizard.status.port }}
|
||||||
</p>
|
</p>
|
||||||
<label class="checkline">
|
|
||||||
<input v-model="pendingArchive.migrate" type="checkbox" />
|
<p class="hint">{{ $t("trilium.firstRunHint") }}</p>
|
||||||
{{ $t("projects.archiveMigrate") }}
|
|
||||||
</label>
|
<div v-if="triWizard.status && triWizard.status.instance_running && !triWizard.status.token_ok" class="tri-connect">
|
||||||
<p class="hint">{{ $t("projects.archiveMigrateHint") }}</p>
|
<span class="tri-lbl">{{ $t("trilium.password") }}</span>
|
||||||
|
<input
|
||||||
|
v-model="triWizard.password"
|
||||||
|
type="password"
|
||||||
|
@keydown.enter="triWizard.password && triliumConnect()"
|
||||||
|
/>
|
||||||
|
<button :disabled="triWizard.busy || !triWizard.password" @click="triliumConnect">
|
||||||
|
{{ $t("trilium.connect") }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button type="button" @click="pendingArchive = null">
|
<button :disabled="triWizard.busy" @click="triliumSetup">
|
||||||
{{ $t("projects.cancel") }}
|
{{ triWizard.busy ? $t("trilium.working") : $t("trilium.setup") }}
|
||||||
</button>
|
</button>
|
||||||
<button class="primary" @click="confirmArchiveChange">
|
<button
|
||||||
{{ $t("projects.archiveChangeConfirm") }}
|
:disabled="triWizard.busy || !triWizard.status?.instance_running"
|
||||||
|
@click="triliumOpen"
|
||||||
|
>
|
||||||
|
{{ $t("trilium.open") }}
|
||||||
</button>
|
</button>
|
||||||
|
<button class="primary" @click="triWizard = null">{{ $t("trilium.close") }}</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1050,4 +1115,105 @@ onUnmounted(() => window.clearInterval(timer));
|
|||||||
.settings-dialog .actions {
|
.settings-dialog .actions {
|
||||||
margin-top: 0.25rem;
|
margin-top: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Trilium-Wizard. Maße nach UI-Guideline (px statt rem): 14 px Basis für
|
||||||
|
Interaktives, Meta-Zeilen 12 px, Zeilen mindestens 28 px, 4-px-Skala. */
|
||||||
|
.tri-dialog {
|
||||||
|
width: min(40rem, 94vw);
|
||||||
|
max-width: none;
|
||||||
|
padding: 24px;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-dialog h3 {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-dialog .hint,
|
||||||
|
.tri-dialog .error {
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-steps {
|
||||||
|
list-style: none;
|
||||||
|
margin: 4px 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-steps li {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: flex-start;
|
||||||
|
min-height: 28px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-steps li > span:last-child {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
min-width: 0;
|
||||||
|
padding-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-steps small {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--subtext);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-steps .mark {
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
flex: none;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 14px;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--surface0);
|
||||||
|
color: var(--overlay);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-steps .mark.ok {
|
||||||
|
color: var(--green, #a6e3a1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-meta {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--overlay);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-meta code {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--subtext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Verbinden-Zeile: Label | Passwort | Knopf. */
|
||||||
|
.tri-connect {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 8rem 1fr auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
min-height: 32px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--subtext);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-connect input {
|
||||||
|
min-height: 28px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tri-dialog .actions button {
|
||||||
|
min-height: 28px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ describe("Nachrichtentabellen", () => {
|
|||||||
const erlaubt = new Set([
|
const erlaubt = new Set([
|
||||||
"Pool",
|
"Pool",
|
||||||
"Pools",
|
"Pools",
|
||||||
|
"Panel",
|
||||||
"Name",
|
"Name",
|
||||||
"Theme",
|
"Theme",
|
||||||
"Wiki",
|
"Wiki",
|
||||||
@@ -47,6 +48,7 @@ describe("Nachrichtentabellen", () => {
|
|||||||
"+ apiKey",
|
"+ apiKey",
|
||||||
"+ ToDo",
|
"+ ToDo",
|
||||||
"System",
|
"System",
|
||||||
|
"Trilium",
|
||||||
"Terminal",
|
"Terminal",
|
||||||
"Terminal — {name}",
|
"Terminal — {name}",
|
||||||
".desktop-Starter",
|
".desktop-Starter",
|
||||||
@@ -69,7 +71,7 @@ function pick(obj: object, key: string): string {
|
|||||||
|
|
||||||
describe("t()", () => {
|
describe("t()", () => {
|
||||||
it("löst Punkt-Pfade auf", () => {
|
it("löst Punkt-Pfade auf", () => {
|
||||||
expect(t("panel.tabDraft")).toBe("Dokument");
|
expect(t("panel.tabSearch")).toBe("Suche");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("setzt Platzhalter ein", () => {
|
it("setzt Platzhalter ein", () => {
|
||||||
@@ -88,7 +90,7 @@ describe("t()", () => {
|
|||||||
it("folgt der gespeicherten Sprache", () => {
|
it("folgt der gespeicherten Sprache", () => {
|
||||||
window.localStorage.setItem("lang", "en");
|
window.localStorage.setItem("lang", "en");
|
||||||
expect(storedLocale()).toBe("en");
|
expect(storedLocale()).toBe("en");
|
||||||
expect(t("panel.tabDraft")).toBe("Document");
|
expect(t("panel.tabSearch")).toBe("Search");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("fällt bei unbekannter Sprache auf die Browsersprache zurück", () => {
|
it("fällt bei unbekannter Sprache auf die Browsersprache zurück", () => {
|
||||||
@@ -100,13 +102,13 @@ describe("t()", () => {
|
|||||||
describe("applyI18n()", () => {
|
describe("applyI18n()", () => {
|
||||||
it("beschriftet Text und Attribute", () => {
|
it("beschriftet Text und Attribute", () => {
|
||||||
document.body.innerHTML = `
|
document.body.innerHTML = `
|
||||||
<button data-i18n="panel.tabWiki" data-i18n-title="panel.tabWikiTitle">alt</button>
|
<button data-i18n="panel.tabSearch" data-i18n-title="panel.tabSearchTitle">alt</button>
|
||||||
<button data-i18n-aria="panel.close"></button>
|
<button data-i18n-aria="panel.close"></button>
|
||||||
<input data-i18n-placeholder="search.placeholder" />`;
|
<input data-i18n-placeholder="search.placeholder" />`;
|
||||||
applyI18n();
|
applyI18n();
|
||||||
const btn = document.querySelector("button")!;
|
const btn = document.querySelector("button")!;
|
||||||
expect(btn.textContent).toBe("Wiki");
|
expect(btn.textContent).toBe("Suche");
|
||||||
expect(btn.title).toBe("Archiv-Wiki");
|
expect(btn.title).toBe("Suchtreffer");
|
||||||
expect(document.querySelectorAll("button")[1].getAttribute("aria-label")).toBe(
|
expect(document.querySelectorAll("button")[1].getAttribute("aria-label")).toBe(
|
||||||
"Schließen",
|
"Schließen",
|
||||||
);
|
);
|
||||||
|
|||||||
+57
-113
@@ -34,6 +34,7 @@ const de = {
|
|||||||
start: "Starten",
|
start: "Starten",
|
||||||
stop: "Beenden",
|
stop: "Beenden",
|
||||||
terminalSettings: "Terminal-Einstellungen",
|
terminalSettings: "Terminal-Einstellungen",
|
||||||
|
openArchive: "Archiv öffnen (Trilium)",
|
||||||
stillRunning: "{name} läuft noch",
|
stillRunning: "{name} läuft noch",
|
||||||
poolChangeSaved:
|
poolChangeSaved:
|
||||||
"Der Pool-Wechsel ist gespeichert. Die laufende Session arbeitet aber weiter im alten Pool — der neue gilt erst ab dem nächsten Start.",
|
"Der Pool-Wechsel ist gespeichert. Die laufende Session arbeitet aber weiter im alten Pool — der neue gilt erst ab dem nächsten Start.",
|
||||||
@@ -59,8 +60,6 @@ const de = {
|
|||||||
addFolder: "Projekt importieren …",
|
addFolder: "Projekt importieren …",
|
||||||
addFolderTitle: "Bestehenden Ordner als Projekt aufnehmen",
|
addFolderTitle: "Bestehenden Ordner als Projekt aufnehmen",
|
||||||
addWorkDir: "Ordner hinzufügen …",
|
addWorkDir: "Ordner hinzufügen …",
|
||||||
archive: "Archiv",
|
|
||||||
archiveNone: "kein Archiv — Panel ohne Wiki und Suche",
|
|
||||||
changeDir: "Ändern …",
|
changeDir: "Ändern …",
|
||||||
wizardTitle: "Neues Projekt",
|
wizardTitle: "Neues Projekt",
|
||||||
name: "Name",
|
name: "Name",
|
||||||
@@ -82,25 +81,17 @@ const de = {
|
|||||||
scopeIntegrationDesc:
|
scopeIntegrationDesc:
|
||||||
"ai-control-Spuren werden entfernt; Projektordner, memory/ und Todoliste bleiben.",
|
"ai-control-Spuren werden entfernt; Projektordner, memory/ und Todoliste bleiben.",
|
||||||
scopeArchive: "Integration & Archiv",
|
scopeArchive: "Integration & Archiv",
|
||||||
scopeArchiveDesc: "zusätzlich {path} — endgültig.",
|
scopeArchiveDesc: "zusätzlich das Trilium-Archiv {path} — endgültig.",
|
||||||
scopeFull: "Projekt komplett löschen",
|
scopeFull: "Projekt komplett löschen",
|
||||||
scopeFullDesc: "zusätzlich der Projektordner {path} — endgültig.",
|
scopeFullDesc: "zusätzlich der Projektordner {path} — endgültig.",
|
||||||
deletePreviewTitle: "Wird entfernt:",
|
deletePreviewTitle: "Wird entfernt:",
|
||||||
docCount: "kein Dokument | 1 Dokument | {count} Dokumente",
|
|
||||||
artRegistry: "Registry-Eintrag",
|
artRegistry: "Registry-Eintrag",
|
||||||
artAiControl: ".ai-control/ (Config + Icon)",
|
artAiControl: ".ai-control/ (Config + Icon)",
|
||||||
artArchivePerm: "Archiv-Berechtigung in .claude/settings.json",
|
|
||||||
artPanelFiles: "Panel-Kanaldatei | {count} Panel-Kanaldateien",
|
artPanelFiles: "Panel-Kanaldatei | {count} Panel-Kanaldateien",
|
||||||
artDesktop: ".desktop-Starter",
|
artDesktop: ".desktop-Starter",
|
||||||
artArchive: "Archiv {path}",
|
artArchive: "Trilium-Archiv {path}",
|
||||||
artProjectDir: "Projektordner {path}",
|
artProjectDir: "Projektordner {path}",
|
||||||
artWorkDir: "Arbeitsordner {path}",
|
artWorkDir: "Arbeitsordner {path}",
|
||||||
archiveChangeTitle: "Archiv wechseln",
|
|
||||||
archiveChangeText: "Das Archiv wechselt von {old} nach {neu}.",
|
|
||||||
archiveMigrate: "Dokumente ins neue Archiv verschieben",
|
|
||||||
archiveMigrateHint:
|
|
||||||
"Ohne Haken bleibt das bisherige Archiv unverändert liegen; die App verweist künftig nur noch auf das neue.",
|
|
||||||
archiveChangeConfirm: "Wechseln",
|
|
||||||
groupAppearance: "Darstellung",
|
groupAppearance: "Darstellung",
|
||||||
groupFolders: "Ordner",
|
groupFolders: "Ordner",
|
||||||
groupModules: "Module",
|
groupModules: "Module",
|
||||||
@@ -111,8 +102,28 @@ const de = {
|
|||||||
commandsDesc: "Befehls-Kacheln im Panel (write_commands)",
|
commandsDesc: "Befehls-Kacheln im Panel (write_commands)",
|
||||||
todo: "ToDo-Liste",
|
todo: "ToDo-Liste",
|
||||||
todoDesc: "persistente Aufgaben-Kacheln mit Fälligkeits-Ampel; öffnet beim Sessionstart",
|
todoDesc: "persistente Aufgaben-Kacheln mit Fälligkeits-Ampel; öffnet beim Sessionstart",
|
||||||
archive: "Archiv",
|
trilium: "Trilium",
|
||||||
archiveDesc: "Archivieren, Wiki und Suche",
|
triliumDesc:
|
||||||
|
"Archiv als eigene Trilium-Instanz — Archivieren, Suche und Notizen laufen über Trilium",
|
||||||
|
},
|
||||||
|
trilium: {
|
||||||
|
wizardTitle: "Trilium einrichten",
|
||||||
|
wizardIntro:
|
||||||
|
"Richtet das Projekt-Archiv als eigene Trilium-Instanz ein: Runtime versionsgepinnt geladen, Instanz nur auf 127.0.0.1 mit eigenem Datenverzeichnis und Port. Das Modul wird erst nach erfolgreicher Verbindung aktiviert.",
|
||||||
|
stepRuntime: "Runtime vorhanden",
|
||||||
|
stepInstance: "Instanz läuft",
|
||||||
|
stepToken: "Verbunden (ETAPI-Token)",
|
||||||
|
port: "Port {port}",
|
||||||
|
dataDir: "Daten",
|
||||||
|
firstRunHint:
|
||||||
|
"Beim ersten Verbinden legt die App das Dokument an und setzt das gewählte Passwort. Gespeichert wird nur der ETAPI-Token (Keyring), nie das Passwort.",
|
||||||
|
password: "Passwort",
|
||||||
|
connect: "Verbinden",
|
||||||
|
setup: "Einrichten / Starten",
|
||||||
|
working: "Läuft …",
|
||||||
|
open: "Trilium öffnen",
|
||||||
|
close: "Schließen",
|
||||||
|
wizard: "Einrichtung / Status",
|
||||||
},
|
},
|
||||||
todos: {
|
todos: {
|
||||||
copyOne: "Aufgabe kopieren",
|
copyOne: "Aufgabe kopieren",
|
||||||
@@ -178,17 +189,15 @@ const de = {
|
|||||||
},
|
},
|
||||||
panel: {
|
panel: {
|
||||||
windowTerminal: "Terminal",
|
windowTerminal: "Terminal",
|
||||||
windowDocument: "Dokument",
|
windowPanel: "Panel",
|
||||||
windowProjects: "Projekte",
|
windowProjects: "Projekte",
|
||||||
tabCommands: "Befehle",
|
tabCommands: "Befehle",
|
||||||
tabCommandsTitle: "Befehls-History",
|
tabCommandsTitle: "Befehls-History",
|
||||||
tabTodo: "ToDo",
|
tabTodo: "ToDo",
|
||||||
tabTodoTitle: "ToDo-Liste des Projekts",
|
tabTodoTitle: "ToDo-Liste des Projekts",
|
||||||
tabDraft: "Dokument",
|
|
||||||
tabDraftTitle: "Dokument",
|
|
||||||
tabWiki: "Wiki",
|
|
||||||
tabWikiTitle: "Archiv-Wiki",
|
|
||||||
tabSearch: "Suche",
|
tabSearch: "Suche",
|
||||||
|
archiveOpen: "Archiv",
|
||||||
|
archiveOpenTitle: "Archiv in Trilium öffnen",
|
||||||
tabSearchTitle: "Suchtreffer",
|
tabSearchTitle: "Suchtreffer",
|
||||||
minimize: "Minimieren",
|
minimize: "Minimieren",
|
||||||
maximize: "Maximieren",
|
maximize: "Maximieren",
|
||||||
@@ -197,16 +206,6 @@ const de = {
|
|||||||
hidePanel: "Panel ausblenden",
|
hidePanel: "Panel ausblenden",
|
||||||
detach: "In eigenes Fenster ablösen",
|
detach: "In eigenes Fenster ablösen",
|
||||||
dock: "Wieder andocken",
|
dock: "Wieder andocken",
|
||||||
editTitle: "Titel bearbeiten",
|
|
||||||
spellcheckLang: "Sprache der Rechtschreibprüfung",
|
|
||||||
openInWiki: "Im Wiki öffnen",
|
|
||||||
toggleRaw: "Rohtext / gerendert",
|
|
||||||
rendered: "MD",
|
|
||||||
raw: "Roh",
|
|
||||||
editDraft: "Entwurf bearbeiten (Cmd/Ctrl+Enter speichert, Esc verwirft)",
|
|
||||||
copy: "In die Zwischenablage kopieren",
|
|
||||||
archive: "In den Archiv-Ordner speichern",
|
|
||||||
chooseArchiveDir: "Archiv-Ordner wählen",
|
|
||||||
processEnded: "[Prozess beendet]",
|
processEnded: "[Prozess beendet]",
|
||||||
},
|
},
|
||||||
popup: {
|
popup: {
|
||||||
@@ -219,39 +218,12 @@ const de = {
|
|||||||
copyAll: "Alle kopieren",
|
copyAll: "Alle kopieren",
|
||||||
session: "Session",
|
session: "Session",
|
||||||
},
|
},
|
||||||
archiveForm: {
|
|
||||||
folder: "Ordner — z. B. konzepte/panel",
|
|
||||||
description: "Beschreibung",
|
|
||||||
tags: "Schlagwörter, kommagetrennt",
|
|
||||||
submit: "Archivieren",
|
|
||||||
},
|
|
||||||
search: {
|
search: {
|
||||||
placeholder: "Archiv durchsuchen — #tag filtert",
|
placeholder: "Archiv durchsuchen — #tag filtert",
|
||||||
minChars: "Mindestens 3 Zeichen — oder Enter.",
|
minChars: "Mindestens 3 Zeichen — oder Enter.",
|
||||||
hits: "{count} Treffer {scope}",
|
hits: "{count} Treffer {scope}",
|
||||||
noHits: "Keine Treffer für {scope}",
|
noHits: "Keine Treffer für {scope}",
|
||||||
},
|
},
|
||||||
wiki: {
|
|
||||||
archive: "Archiv",
|
|
||||||
docOne: "{count} Dokument",
|
|
||||||
docMany: "{count} Dokumente",
|
|
||||||
backlinks: "Verweise hierher",
|
|
||||||
emptyArchive: "Das Archiv ist leer.",
|
|
||||||
emptyFolder: "Keine Dokumente in diesem Ordner.",
|
|
||||||
emptyHint:
|
|
||||||
"Archivieren: Archiv-Button im Entwurf oder „archiviere das“ im Chat — mit Ordner, Beschreibung und Schlagwörtern.",
|
|
||||||
noPage: "Keine Wiki-Seite geladen.",
|
|
||||||
openOverview: "Archiv-Übersicht öffnen",
|
|
||||||
folderRename: "Ordner umbenennen",
|
|
||||||
renameDoc: "Dokument umbenennen",
|
|
||||||
deleteDoc: "Dokument löschen",
|
|
||||||
newFolder: "Neuer Ordner",
|
|
||||||
newDoc: "Neues Dokument",
|
|
||||||
create: "Anlegen",
|
|
||||||
cancel: "Abbrechen",
|
|
||||||
folderPath: "ordner/unterordner",
|
|
||||||
docName: "Name des Dokuments",
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const en: typeof de = {
|
const en: typeof de = {
|
||||||
@@ -283,6 +255,7 @@ const en: typeof de = {
|
|||||||
start: "Start",
|
start: "Start",
|
||||||
stop: "Stop",
|
stop: "Stop",
|
||||||
terminalSettings: "Terminal settings",
|
terminalSettings: "Terminal settings",
|
||||||
|
openArchive: "Open archive (Trilium)",
|
||||||
stillRunning: "{name} is still running",
|
stillRunning: "{name} is still running",
|
||||||
poolChangeSaved:
|
poolChangeSaved:
|
||||||
"The pool change is saved. The running session keeps working in the old pool — the new one applies from the next start.",
|
"The pool change is saved. The running session keeps working in the old pool — the new one applies from the next start.",
|
||||||
@@ -308,8 +281,6 @@ const en: typeof de = {
|
|||||||
addFolder: "Import project …",
|
addFolder: "Import project …",
|
||||||
addFolderTitle: "Add an existing folder as a project",
|
addFolderTitle: "Add an existing folder as a project",
|
||||||
addWorkDir: "Add folder …",
|
addWorkDir: "Add folder …",
|
||||||
archive: "Archive",
|
|
||||||
archiveNone: "no archive — panel without wiki and search",
|
|
||||||
changeDir: "Change …",
|
changeDir: "Change …",
|
||||||
wizardTitle: "New project",
|
wizardTitle: "New project",
|
||||||
name: "Name",
|
name: "Name",
|
||||||
@@ -331,25 +302,17 @@ const en: typeof de = {
|
|||||||
scopeIntegrationDesc:
|
scopeIntegrationDesc:
|
||||||
"ai-control traces are removed; project folder, memory/ and todo list stay.",
|
"ai-control traces are removed; project folder, memory/ and todo list stay.",
|
||||||
scopeArchive: "Integration & archive",
|
scopeArchive: "Integration & archive",
|
||||||
scopeArchiveDesc: "additionally {path} — permanent.",
|
scopeArchiveDesc: "additionally the Trilium archive {path} — permanent.",
|
||||||
scopeFull: "Delete project completely",
|
scopeFull: "Delete project completely",
|
||||||
scopeFullDesc: "additionally the project folder {path} — permanent.",
|
scopeFullDesc: "additionally the project folder {path} — permanent.",
|
||||||
deletePreviewTitle: "Will be removed:",
|
deletePreviewTitle: "Will be removed:",
|
||||||
docCount: "no documents | 1 document | {count} documents",
|
|
||||||
artRegistry: "registry entry",
|
artRegistry: "registry entry",
|
||||||
artAiControl: ".ai-control/ (config + icon)",
|
artAiControl: ".ai-control/ (config + icon)",
|
||||||
artArchivePerm: "archive permission in .claude/settings.json",
|
|
||||||
artPanelFiles: "panel channel file | {count} panel channel files",
|
artPanelFiles: "panel channel file | {count} panel channel files",
|
||||||
artDesktop: ".desktop launcher",
|
artDesktop: ".desktop launcher",
|
||||||
artArchive: "archive {path}",
|
artArchive: "Trilium archive {path}",
|
||||||
artProjectDir: "project folder {path}",
|
artProjectDir: "project folder {path}",
|
||||||
artWorkDir: "working folder {path}",
|
artWorkDir: "working folder {path}",
|
||||||
archiveChangeTitle: "Change archive",
|
|
||||||
archiveChangeText: "The archive changes from {old} to {neu}.",
|
|
||||||
archiveMigrate: "Move documents to the new archive",
|
|
||||||
archiveMigrateHint:
|
|
||||||
"Unchecked, the previous archive stays untouched; the app just points to the new one.",
|
|
||||||
archiveChangeConfirm: "Change",
|
|
||||||
groupAppearance: "Appearance",
|
groupAppearance: "Appearance",
|
||||||
groupFolders: "Folders",
|
groupFolders: "Folders",
|
||||||
groupModules: "Modules",
|
groupModules: "Modules",
|
||||||
@@ -360,8 +323,28 @@ const en: typeof de = {
|
|||||||
commandsDesc: "command tiles in the panel (write_commands)",
|
commandsDesc: "command tiles in the panel (write_commands)",
|
||||||
todo: "ToDo list",
|
todo: "ToDo list",
|
||||||
todoDesc: "persistent task tiles with due-date signal; opens at session start",
|
todoDesc: "persistent task tiles with due-date signal; opens at session start",
|
||||||
archive: "Archive",
|
trilium: "Trilium",
|
||||||
archiveDesc: "archiving, wiki and search",
|
triliumDesc:
|
||||||
|
"archive as a dedicated Trilium instance — archiving, search and notes run through Trilium",
|
||||||
|
},
|
||||||
|
trilium: {
|
||||||
|
wizardTitle: "Set up Trilium",
|
||||||
|
wizardIntro:
|
||||||
|
"Sets up the project archive as its own Trilium instance: version-pinned runtime download, instance on 127.0.0.1 only with its own data directory and port. The module is enabled only after a successful connection.",
|
||||||
|
stepRuntime: "Runtime present",
|
||||||
|
stepInstance: "Instance running",
|
||||||
|
stepToken: "Connected (ETAPI token)",
|
||||||
|
port: "port {port}",
|
||||||
|
dataDir: "Data",
|
||||||
|
firstRunHint:
|
||||||
|
"On first connect the app creates the document and sets the chosen password. Only the ETAPI token is stored (keyring), never the password.",
|
||||||
|
password: "Password",
|
||||||
|
connect: "Connect",
|
||||||
|
setup: "Set up / start",
|
||||||
|
working: "Working …",
|
||||||
|
open: "Open Trilium",
|
||||||
|
close: "Close",
|
||||||
|
wizard: "Setup / status",
|
||||||
},
|
},
|
||||||
todos: {
|
todos: {
|
||||||
copyOne: "Copy task",
|
copyOne: "Copy task",
|
||||||
@@ -427,17 +410,15 @@ const en: typeof de = {
|
|||||||
},
|
},
|
||||||
panel: {
|
panel: {
|
||||||
windowTerminal: "Terminal",
|
windowTerminal: "Terminal",
|
||||||
windowDocument: "Document",
|
windowPanel: "Panel",
|
||||||
windowProjects: "Projects",
|
windowProjects: "Projects",
|
||||||
tabCommands: "Commands",
|
tabCommands: "Commands",
|
||||||
tabCommandsTitle: "Command history",
|
tabCommandsTitle: "Command history",
|
||||||
tabTodo: "ToDo",
|
tabTodo: "ToDo",
|
||||||
tabTodoTitle: "Project to-do list",
|
tabTodoTitle: "Project to-do list",
|
||||||
tabDraft: "Document",
|
|
||||||
tabDraftTitle: "Document",
|
|
||||||
tabWiki: "Wiki",
|
|
||||||
tabWikiTitle: "Archive wiki",
|
|
||||||
tabSearch: "Search",
|
tabSearch: "Search",
|
||||||
|
archiveOpen: "Archive",
|
||||||
|
archiveOpenTitle: "Open the archive in Trilium",
|
||||||
tabSearchTitle: "Search hits",
|
tabSearchTitle: "Search hits",
|
||||||
minimize: "Minimize",
|
minimize: "Minimize",
|
||||||
maximize: "Maximize",
|
maximize: "Maximize",
|
||||||
@@ -446,16 +427,6 @@ const en: typeof de = {
|
|||||||
hidePanel: "Hide panel",
|
hidePanel: "Hide panel",
|
||||||
detach: "Detach into its own window",
|
detach: "Detach into its own window",
|
||||||
dock: "Dock again",
|
dock: "Dock again",
|
||||||
editTitle: "Edit title",
|
|
||||||
spellcheckLang: "Spell-check language",
|
|
||||||
openInWiki: "Open in wiki",
|
|
||||||
toggleRaw: "Raw text / rendered",
|
|
||||||
rendered: "MD",
|
|
||||||
raw: "Raw",
|
|
||||||
editDraft: "Edit draft (Cmd/Ctrl+Enter saves, Esc discards)",
|
|
||||||
copy: "Copy to clipboard",
|
|
||||||
archive: "Save to the archive folder",
|
|
||||||
chooseArchiveDir: "Choose archive folder",
|
|
||||||
processEnded: "[process ended]",
|
processEnded: "[process ended]",
|
||||||
},
|
},
|
||||||
popup: {
|
popup: {
|
||||||
@@ -468,39 +439,12 @@ const en: typeof de = {
|
|||||||
copyAll: "Copy all",
|
copyAll: "Copy all",
|
||||||
session: "Session",
|
session: "Session",
|
||||||
},
|
},
|
||||||
archiveForm: {
|
|
||||||
folder: "Folder — e.g. concepts/panel",
|
|
||||||
description: "Description",
|
|
||||||
tags: "Tags, comma-separated",
|
|
||||||
submit: "Archive",
|
|
||||||
},
|
|
||||||
search: {
|
search: {
|
||||||
placeholder: "Search the archive — #tag filters",
|
placeholder: "Search the archive — #tag filters",
|
||||||
minChars: "At least 3 characters — or press Enter.",
|
minChars: "At least 3 characters — or press Enter.",
|
||||||
hits: "{count} hits {scope}",
|
hits: "{count} hits {scope}",
|
||||||
noHits: "No hits for {scope}",
|
noHits: "No hits for {scope}",
|
||||||
},
|
},
|
||||||
wiki: {
|
|
||||||
archive: "Archive",
|
|
||||||
docOne: "{count} document",
|
|
||||||
docMany: "{count} documents",
|
|
||||||
backlinks: "Links here",
|
|
||||||
emptyArchive: "The archive is empty.",
|
|
||||||
emptyFolder: "No documents in this folder.",
|
|
||||||
emptyHint:
|
|
||||||
"To archive: the archive button in the draft, or “archive this” in the chat — with folder, description and tags.",
|
|
||||||
noPage: "No wiki page loaded.",
|
|
||||||
openOverview: "Open archive overview",
|
|
||||||
folderRename: "Rename folder",
|
|
||||||
renameDoc: "Rename document",
|
|
||||||
deleteDoc: "Delete document",
|
|
||||||
newFolder: "New folder",
|
|
||||||
newDoc: "New document",
|
|
||||||
create: "Create",
|
|
||||||
cancel: "Cancel",
|
|
||||||
folderPath: "folder/subfolder",
|
|
||||||
docName: "Document name",
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const messages = { de, en };
|
export const messages = { de, en };
|
||||||
@@ -522,7 +466,7 @@ export function storedLocale(): Locale {
|
|||||||
return navigator.language.startsWith("de") ? "de" : "en";
|
return navigator.language.startsWith("de") ? "de" : "en";
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Übersetzt einen Punkt-Pfad (`panel.tabDraft`) und setzt `{platzhalter}` ein.
|
/// Übersetzt einen Punkt-Pfad (`panel.tabSearch`) und setzt `{platzhalter}` ein.
|
||||||
/// Fehlt der Schlüssel, kommt der Pfad selbst zurück — im UI sichtbar statt
|
/// Fehlt der Schlüssel, kommt der Pfad selbst zurück — im UI sichtbar statt
|
||||||
/// still leer.
|
/// still leer.
|
||||||
export function t(key: string, params?: Record<string, string | number>): string {
|
export function t(key: string, params?: Record<string, string | number>): string {
|
||||||
|
|||||||
+18
-45
@@ -1,57 +1,30 @@
|
|||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
import { initSearchView } from "../search-view";
|
import { initSearchView } from "../search-view";
|
||||||
import { initWikiView } from "../wiki-view";
|
|
||||||
import type { PanelTab } from "./index";
|
import type { PanelTab } from "./index";
|
||||||
|
|
||||||
export const wikiTab: PanelTab = {
|
|
||||||
mode: "wiki",
|
|
||||||
module: "archive",
|
|
||||||
buffer: "wiki",
|
|
||||||
labelKey: "panel.tabWiki",
|
|
||||||
titleKey: "panel.tabWikiTitle",
|
|
||||||
// Dokument-/Ordner-Operationen laufen als Commands; der neue Stand kommt
|
|
||||||
// über den Wiki-Puffer (wiki-update) zurück, Fehler als Toast. Der
|
|
||||||
// Dokument-Sprung lädt wie ein Suchtreffer in den Dokument-Tab.
|
|
||||||
init: (container, ctx) => {
|
|
||||||
const run = (cmd: string, args: Record<string, string>) =>
|
|
||||||
void invoke(cmd, { project: ctx.project, ...args }).catch((e) =>
|
|
||||||
ctx.toast(String(e)),
|
|
||||||
);
|
|
||||||
return initWikiView(container, {
|
|
||||||
openDoc: ctx.openDoc,
|
|
||||||
openWiki: ctx.openWiki,
|
|
||||||
actions: {
|
|
||||||
rename: (relpath, name) => run("archive_rename", { relpath, name }),
|
|
||||||
remove: (relpath) => run("archive_delete", { relpath }),
|
|
||||||
moveFolder: (folder, to) => run("archive_move_folder", { folder, to }),
|
|
||||||
createFolder: (folder) => run("archive_create_folder", { folder }),
|
|
||||||
createDoc: (folder, name) => run("archive_create_doc", { folder, name }),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
// Beim Aktivieren die Übersicht frisch laden: das Anlegen eines Dokuments
|
|
||||||
// öffnet den Dokument-Tab, ohne den Wiki-Puffer anzufassen — und auch
|
|
||||||
// direkt archivierte oder von Hand abgelegte Dateien erscheinen so.
|
|
||||||
onActivate: (_view, ctx) => ctx.openWiki("tag:"),
|
|
||||||
};
|
|
||||||
|
|
||||||
export const searchTab: PanelTab = {
|
export const searchTab: PanelTab = {
|
||||||
mode: "search",
|
mode: "search",
|
||||||
module: "archive",
|
module: "trilium",
|
||||||
buffer: "search",
|
buffer: "search",
|
||||||
labelKey: "panel.tabSearch",
|
labelKey: "panel.tabSearch",
|
||||||
titleKey: "panel.tabSearchTitle",
|
titleKey: "panel.tabSearchTitle",
|
||||||
sepAfter: true,
|
sepAfter: true,
|
||||||
// Treffer-Klick lädt das Dokument in den Dokument-Tab (dort editier- und
|
// Treffer-Klick öffnet die Notiz im Trilium-Fenster des Projekts.
|
||||||
// archivierbar); der Sprung ins Wiki geht von dort aus.
|
|
||||||
init: (container, ctx) =>
|
init: (container, ctx) =>
|
||||||
initSearchView(container, ctx.openDoc, (raw) => {
|
initSearchView(
|
||||||
// `#tag`-Tokens filtern aufs Schlagwort, der Rest ist die Volltext-Query.
|
container,
|
||||||
const words = raw.split(/\s+/).filter(Boolean);
|
(noteId) =>
|
||||||
const tag = words.find((w) => w.startsWith("#"))?.slice(1) ?? null;
|
void invoke("trilium_open", { project: ctx.project, noteId }).catch((e) =>
|
||||||
const query = words.filter((w) => !w.startsWith("#")).join(" ");
|
ctx.toast(String(e)),
|
||||||
void invoke("search_run", { project: ctx.project, query, tag }).catch((e) =>
|
),
|
||||||
ctx.toast(`Suche fehlgeschlagen: ${e}`),
|
(raw) => {
|
||||||
);
|
// `#tag`-Tokens filtern aufs Schlagwort, der Rest ist die Volltext-Query.
|
||||||
}),
|
const words = raw.split(/\s+/).filter(Boolean);
|
||||||
|
const tag = words.find((w) => w.startsWith("#"))?.slice(1) ?? null;
|
||||||
|
const query = words.filter((w) => !w.startsWith("#")).join(" ");
|
||||||
|
void invoke("search_run", { project: ctx.project, query, tag }).catch((e) =>
|
||||||
|
ctx.toast(`Suche fehlgeschlagen: ${e}`),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
|||||||
+5
-22
@@ -6,7 +6,7 @@
|
|||||||
/// `<buffer>-update`-Event.
|
/// `<buffer>-update`-Event.
|
||||||
|
|
||||||
import { commandsTab } from "./commands";
|
import { commandsTab } from "./commands";
|
||||||
import { searchTab, wikiTab } from "./archive";
|
import { searchTab } from "./archive";
|
||||||
import { todoTab } from "./todo";
|
import { todoTab } from "./todo";
|
||||||
|
|
||||||
export interface ModuleView {
|
export interface ModuleView {
|
||||||
@@ -19,10 +19,6 @@ export interface ModuleView {
|
|||||||
export interface ModuleCtx {
|
export interface ModuleCtx {
|
||||||
project: string;
|
project: string;
|
||||||
toast(msg: string): void;
|
toast(msg: string): void;
|
||||||
/// Dokument in den Entwurfs-Tab laden (Treffer-Klick).
|
|
||||||
openDoc(path: string): void;
|
|
||||||
/// Wiki-Ziel öffnen (Wikilink, Chip, `tag:`-Namensraum).
|
|
||||||
openWiki(name: string): void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PanelTab {
|
export interface PanelTab {
|
||||||
@@ -37,23 +33,10 @@ export interface PanelTab {
|
|||||||
titleKey: string;
|
titleKey: string;
|
||||||
/// Visueller Trenner hinter dem Tab.
|
/// Visueller Trenner hinter dem Tab.
|
||||||
sepAfter?: boolean;
|
sepAfter?: boolean;
|
||||||
/// Baut die Ansicht des Tabs. Ohne init verdrahtet panel-wiring die
|
/// Baut die Ansicht des Tabs.
|
||||||
/// Ansicht selbst (Entwurfs-Tab — Kern mit eigenem Markup).
|
init(container: HTMLElement, ctx: ModuleCtx): ModuleView;
|
||||||
init?(container: HTMLElement, ctx: ModuleCtx): ModuleView;
|
/// Nach Tab-Klick.
|
||||||
/// Nach Tab-Klick (z. B. Wiki: leere Ansicht lädt die Übersicht).
|
|
||||||
onActivate?(view: ModuleView, ctx: ModuleCtx): void;
|
onActivate?(view: ModuleView, ctx: ModuleCtx): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PANEL_TABS: PanelTab[] = [
|
export const PANEL_TABS: PanelTab[] = [todoTab, commandsTab, searchTab];
|
||||||
todoTab,
|
|
||||||
commandsTab,
|
|
||||||
{
|
|
||||||
mode: "draft",
|
|
||||||
module: "draft",
|
|
||||||
buffer: "panel",
|
|
||||||
labelKey: "panel.tabDraft",
|
|
||||||
titleKey: "panel.tabDraftTitle",
|
|
||||||
},
|
|
||||||
wikiTab,
|
|
||||||
searchTab,
|
|
||||||
];
|
|
||||||
|
|||||||
+1
-359
@@ -139,7 +139,7 @@
|
|||||||
border: 1px solid var(--ok);
|
border: 1px solid var(--ok);
|
||||||
}
|
}
|
||||||
/* Kopfzeile mit Anlegen-Knopf und das ToDo-Formular (Anlegen/Bearbeiten),
|
/* Kopfzeile mit Anlegen-Knopf und das ToDo-Formular (Anlegen/Bearbeiten),
|
||||||
in-flow über der Liste; Input-Stil wie im Archiv-Formular. */
|
in-flow über der Liste. */
|
||||||
.todo-head {
|
.todo-head {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
@@ -311,364 +311,6 @@
|
|||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Wiki-Ansicht: Ordner-Baum links, flache Inhaltsliste rechts. */
|
|
||||||
#wiki-content {
|
|
||||||
flex: 1;
|
|
||||||
min-height: 0;
|
|
||||||
overflow: auto;
|
|
||||||
padding: 14px 16px;
|
|
||||||
}
|
|
||||||
#wiki-content::-webkit-scrollbar {
|
|
||||||
width: 8px;
|
|
||||||
}
|
|
||||||
#wiki-content::-webkit-scrollbar-thumb {
|
|
||||||
background: var(--line);
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
/* Baum links, Seite rechts; beide scrollen gemeinsam im Tab. */
|
|
||||||
.wiki-layout {
|
|
||||||
display: flex;
|
|
||||||
align-items: flex-start;
|
|
||||||
gap: 12px;
|
|
||||||
}
|
|
||||||
.wiki-tree {
|
|
||||||
flex: 0 0 150px;
|
|
||||||
min-width: 0;
|
|
||||||
border-right: 1px solid var(--line);
|
|
||||||
padding-right: 8px;
|
|
||||||
position: sticky;
|
|
||||||
top: 0;
|
|
||||||
}
|
|
||||||
.wiki-main {
|
|
||||||
flex: 1;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
.wiki-tree details > .wiki-tree-children {
|
|
||||||
margin-left: 10px;
|
|
||||||
}
|
|
||||||
.wiki-tree summary {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 2px;
|
|
||||||
list-style: none;
|
|
||||||
cursor: pointer;
|
|
||||||
padding: 2px 2px;
|
|
||||||
color: var(--muted);
|
|
||||||
font:
|
|
||||||
500 11px/1.4 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
user-select: none;
|
|
||||||
-webkit-user-select: none;
|
|
||||||
}
|
|
||||||
.wiki-tree summary::-webkit-details-marker {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.wiki-tree summary::before {
|
|
||||||
content: "▸";
|
|
||||||
color: var(--faint);
|
|
||||||
font-size: 9px;
|
|
||||||
margin-right: 3px;
|
|
||||||
}
|
|
||||||
.wiki-tree details[open] > summary::before {
|
|
||||||
content: "▾";
|
|
||||||
}
|
|
||||||
.wiki-tree-name {
|
|
||||||
flex: 1;
|
|
||||||
min-width: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
.wiki-tree summary .panel-btn {
|
|
||||||
visibility: hidden;
|
|
||||||
}
|
|
||||||
.wiki-tree summary:hover .panel-btn {
|
|
||||||
visibility: visible;
|
|
||||||
}
|
|
||||||
.wiki-tree summary:hover,
|
|
||||||
.wiki-tree-root:hover {
|
|
||||||
background: var(--tile);
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
.wiki-tree summary.active,
|
|
||||||
.wiki-tree-root.active {
|
|
||||||
color: var(--accent);
|
|
||||||
}
|
|
||||||
.wiki-tree-root {
|
|
||||||
display: block;
|
|
||||||
width: 100%;
|
|
||||||
text-align: left;
|
|
||||||
border: none;
|
|
||||||
background: none;
|
|
||||||
color: var(--muted);
|
|
||||||
border-radius: 4px;
|
|
||||||
padding: 2px 4px;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
font:
|
|
||||||
500 11px/1.5 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
}
|
|
||||||
.wiki-tree-input {
|
|
||||||
box-sizing: border-box;
|
|
||||||
width: 100%;
|
|
||||||
background: var(--surface);
|
|
||||||
border: 1px solid var(--line-strong);
|
|
||||||
border-radius: 4px;
|
|
||||||
padding: 2px 4px;
|
|
||||||
color: var(--text);
|
|
||||||
font:
|
|
||||||
400 11px/1.4 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
/* Zeilen-Aktionen erst beim Überfahren der Zeile. */
|
|
||||||
.wiki-doc-actions {
|
|
||||||
display: flex;
|
|
||||||
gap: 2px;
|
|
||||||
visibility: hidden;
|
|
||||||
}
|
|
||||||
.wiki-doc:hover .wiki-doc-actions {
|
|
||||||
visibility: visible;
|
|
||||||
}
|
|
||||||
/* Kopfzeile des Baums: Wurzel-Knopf + Ordner anlegen. */
|
|
||||||
.wiki-tree-head {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 2px;
|
|
||||||
}
|
|
||||||
.wiki-tree-head .wiki-tree-root {
|
|
||||||
flex: 1;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
.wiki-add {
|
|
||||||
border: none;
|
|
||||||
background: none;
|
|
||||||
color: var(--muted);
|
|
||||||
border-radius: 4px;
|
|
||||||
padding: 0 5px;
|
|
||||||
font:
|
|
||||||
500 13px/1.4 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.wiki-add:hover {
|
|
||||||
background: var(--tile);
|
|
||||||
color: var(--text);
|
|
||||||
}
|
|
||||||
/* Anlege-Formular (Ordner/Dokument) oben in der Liste. */
|
|
||||||
.wiki-form {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
background: var(--surface);
|
|
||||||
border: 1px solid var(--line-strong);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 8px 10px;
|
|
||||||
margin: 10px 0 4px;
|
|
||||||
}
|
|
||||||
.wiki-form-title {
|
|
||||||
color: var(--muted);
|
|
||||||
font:
|
|
||||||
500 11px/1.4 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
.wiki-form .wiki-tree-input {
|
|
||||||
flex: 1;
|
|
||||||
width: auto;
|
|
||||||
padding: 4px 8px;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
.wiki-form-submit,
|
|
||||||
.wiki-form-cancel {
|
|
||||||
border: none;
|
|
||||||
background: var(--line);
|
|
||||||
color: var(--text);
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 4px 10px;
|
|
||||||
font:
|
|
||||||
500 11px/1.4 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
}
|
|
||||||
.wiki-form-submit:hover {
|
|
||||||
background: var(--line-strong);
|
|
||||||
}
|
|
||||||
.wiki-form-cancel {
|
|
||||||
background: none;
|
|
||||||
color: var(--muted);
|
|
||||||
}
|
|
||||||
.wiki-form-cancel:hover {
|
|
||||||
background: var(--tile);
|
|
||||||
}
|
|
||||||
.wiki-head {
|
|
||||||
display: flex;
|
|
||||||
align-items: baseline;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
.wiki-head-left {
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
.wiki-head-title {
|
|
||||||
color: var(--text);
|
|
||||||
font:
|
|
||||||
600 13px/1.3 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
}
|
|
||||||
.wiki-head-sub {
|
|
||||||
margin-top: 2px;
|
|
||||||
color: var(--faint);
|
|
||||||
font-family: "JetBrains Mono", Menlo, monospace;
|
|
||||||
font-size: 10px;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
.wiki-head-right {
|
|
||||||
color: var(--faint);
|
|
||||||
font:
|
|
||||||
500 11px/1 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
/* Einstiegs-Knopf im Leerzustand. */
|
|
||||||
.wiki-chip {
|
|
||||||
border: 1px solid var(--line);
|
|
||||||
background: transparent;
|
|
||||||
color: var(--muted);
|
|
||||||
border-radius: 999px;
|
|
||||||
padding: 2px 8px;
|
|
||||||
font:
|
|
||||||
500 10.5px/1.5 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
}
|
|
||||||
.wiki-chip:hover {
|
|
||||||
background: var(--line);
|
|
||||||
color: var(--text);
|
|
||||||
}
|
|
||||||
.wiki-doc {
|
|
||||||
padding: 7px 8px;
|
|
||||||
margin: 4px -8px 0;
|
|
||||||
border-radius: 8px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.wiki-doc:hover {
|
|
||||||
background: var(--tile);
|
|
||||||
}
|
|
||||||
.wiki-doc-line {
|
|
||||||
display: flex;
|
|
||||||
align-items: baseline;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
.wiki-doc-title {
|
|
||||||
flex: 1;
|
|
||||||
min-width: 0;
|
|
||||||
color: var(--accent);
|
|
||||||
font:
|
|
||||||
600 12px/1.4 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
}
|
|
||||||
.wiki-doc-date {
|
|
||||||
color: var(--faint);
|
|
||||||
font-family: "JetBrains Mono", Menlo, monospace;
|
|
||||||
font-size: 10px;
|
|
||||||
}
|
|
||||||
.wiki-doc-desc {
|
|
||||||
margin-top: 2px;
|
|
||||||
color: var(--muted);
|
|
||||||
font:
|
|
||||||
400 11px/1.5 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
}
|
|
||||||
.wiki-empty {
|
|
||||||
margin-top: 18px;
|
|
||||||
color: var(--muted);
|
|
||||||
font:
|
|
||||||
400 12px/1.6 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
}
|
|
||||||
.wiki-empty strong {
|
|
||||||
display: block;
|
|
||||||
margin-bottom: 6px;
|
|
||||||
color: var(--text);
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
/* Backlink-Zähler in der Dokumentzeile. */
|
|
||||||
.wiki-doc-back {
|
|
||||||
color: var(--faint);
|
|
||||||
font:
|
|
||||||
500 10px/1 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Archiv-Formular: klappt unter dem Archiv-Button auf. */
|
|
||||||
.archive-form {
|
|
||||||
position: fixed;
|
|
||||||
z-index: 20;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 6px;
|
|
||||||
width: 260px;
|
|
||||||
background: var(--surface);
|
|
||||||
border: 1px solid var(--line-strong);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 10px;
|
|
||||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
|
|
||||||
}
|
|
||||||
.archive-form[hidden] {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.archive-form input {
|
|
||||||
box-sizing: border-box;
|
|
||||||
width: 100%;
|
|
||||||
background: var(--tile);
|
|
||||||
border: 1px solid var(--line);
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 6px 10px;
|
|
||||||
color: var(--text);
|
|
||||||
font:
|
|
||||||
400 12px/1.4 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
.archive-form input:focus {
|
|
||||||
border-color: var(--line-strong);
|
|
||||||
}
|
|
||||||
.archive-form input::placeholder {
|
|
||||||
color: var(--faint);
|
|
||||||
}
|
|
||||||
.archive-form-submit {
|
|
||||||
border: none;
|
|
||||||
background: var(--line);
|
|
||||||
color: var(--text);
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 6px 10px;
|
|
||||||
font:
|
|
||||||
500 12px/1.4 -apple-system,
|
|
||||||
system-ui,
|
|
||||||
sans-serif;
|
|
||||||
}
|
|
||||||
.archive-form-submit:hover {
|
|
||||||
background: var(--line-strong);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Sichtbare Fehlermeldung (panelToast), oben rechts über dem Panel-Inhalt. */
|
/* Sichtbare Fehlermeldung (panelToast), oben rechts über dem Panel-Inhalt. */
|
||||||
.panel-toast {
|
.panel-toast {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
// Dokument-Ansicht: Wikilink-Verlinkung im DOM und Editor-Flush.
|
|
||||||
import { describe, expect, it, vi } from "vitest";
|
|
||||||
import { initPanelView, linkWikiRefs } from "./panel-view";
|
|
||||||
|
|
||||||
describe("linkWikiRefs", () => {
|
|
||||||
it("verlinkt [[ziel]] und [[ziel|Label]], Code bleibt unangetastet", () => {
|
|
||||||
const root = document.createElement("div");
|
|
||||||
root.innerHTML =
|
|
||||||
"<p>Siehe [[adr-logging]] und [[notiz|die Notiz]].</p>" +
|
|
||||||
"<pre><code>if [[ -f x ]]; then</code></pre>";
|
|
||||||
const onClick = vi.fn();
|
|
||||||
linkWikiRefs(root, onClick);
|
|
||||||
const links = [...root.querySelectorAll<HTMLElement>("a.wiki")];
|
|
||||||
expect(links.map((a) => a.textContent)).toEqual(["adr-logging", "die Notiz"]);
|
|
||||||
links[1].click();
|
|
||||||
expect(onClick).toHaveBeenCalledWith("notiz");
|
|
||||||
expect(root.querySelector("code")!.textContent).toBe("if [[ -f x ]]; then");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
function viewSetup(onCommit: (text: string) => void | Promise<void>) {
|
|
||||||
document.body.innerHTML = `
|
|
||||||
<div id="content"></div>
|
|
||||||
<button id="copy"></button>
|
|
||||||
<button id="mode"></button>
|
|
||||||
<button id="edit"></button>`;
|
|
||||||
const view = initPanelView({
|
|
||||||
content: document.getElementById("content")!,
|
|
||||||
copyBtn: document.getElementById("copy")!,
|
|
||||||
modeBtn: document.getElementById("mode")!,
|
|
||||||
editContentBtn: document.getElementById("edit")!,
|
|
||||||
onCommit,
|
|
||||||
});
|
|
||||||
const editor = document.querySelector<HTMLTextAreaElement>(".panel-editor")!;
|
|
||||||
return { view, editor, editBtn: document.getElementById("edit")! };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("initPanelView — Editor", () => {
|
|
||||||
it("flush speichert eine offene Bearbeitung und beendet sie", async () => {
|
|
||||||
const onCommit = vi.fn();
|
|
||||||
const { view, editor, editBtn } = viewSetup(onCommit);
|
|
||||||
view.set("Alt");
|
|
||||||
editBtn.click();
|
|
||||||
expect(editor.hidden).toBe(false);
|
|
||||||
editor.value = "Neu";
|
|
||||||
await view.flush();
|
|
||||||
expect(onCommit).toHaveBeenCalledWith("Neu");
|
|
||||||
expect(editor.hidden).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("flush ohne offene Bearbeitung tut nichts", async () => {
|
|
||||||
const onCommit = vi.fn();
|
|
||||||
const { view } = viewSetup(onCommit);
|
|
||||||
view.set("Alt");
|
|
||||||
await view.flush();
|
|
||||||
expect(onCommit).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("puffert eingehende Updates während der Bearbeitung", () => {
|
|
||||||
const { view, editor, editBtn } = viewSetup(() => {});
|
|
||||||
view.set("Alt");
|
|
||||||
editBtn.click();
|
|
||||||
view.set("Update von außen");
|
|
||||||
expect(editBtn.classList.contains("changed")).toBe(true);
|
|
||||||
editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
|
|
||||||
expect(view.raw()).toBe("Update von außen");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,271 +0,0 @@
|
|||||||
import { renderMarkdown } from "./markdown";
|
|
||||||
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
|
|
||||||
import { flash } from "./tiles";
|
|
||||||
import { t } from "./messages";
|
|
||||||
|
|
||||||
export interface PanelView {
|
|
||||||
set(text: string): void;
|
|
||||||
raw(): string;
|
|
||||||
/// Schreibt eine offene Inhalts-Bearbeitung zurück (und beendet sie);
|
|
||||||
/// aufgelöst, sobald der Entwurf gespeichert ist.
|
|
||||||
flush(): Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Verkabelt einen Panel-Inhaltsbereich: MD/Roh-Umschalter und Copy-Button.
|
|
||||||
/// Der Rohtext bleibt die Quelle für „Kopieren"; die Ansicht rendert Markdown.
|
|
||||||
/// Entfernt Inline-Markdown (Emphasis, Code, Links), damit der Plain-Text-Titel
|
|
||||||
/// nicht die rohen Marker zeigt.
|
|
||||||
function stripInlineMd(s: string): string {
|
|
||||||
return s
|
|
||||||
.replace(/`([^`]*)`/g, "$1")
|
|
||||||
.replace(/\*\*([^*]+)\*\*/g, "$1")
|
|
||||||
.replace(/\*([^*]+)\*/g, "$1")
|
|
||||||
.replace(/__([^_]+)__/g, "$1")
|
|
||||||
.replace(/_([^_]+)_/g, "$1")
|
|
||||||
.replace(/~~([^~]+)~~/g, "$1")
|
|
||||||
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
|
||||||
.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Titel für den Panel-Kopf: erste Überschrift (# …) oder sonst erste
|
|
||||||
/// nicht-leere Zeile, ohne Inline-Markdown; „Dokument" bei leerem Text.
|
|
||||||
function firstLine(text: string): string {
|
|
||||||
let fallback = "";
|
|
||||||
for (const line of text.split("\n")) {
|
|
||||||
const t = line.trim();
|
|
||||||
if (!t) continue;
|
|
||||||
const h = t.replace(/^#+/, "").trim();
|
|
||||||
if (t.startsWith("#") && h) return stripInlineMd(h);
|
|
||||||
if (!fallback) fallback = t;
|
|
||||||
}
|
|
||||||
return fallback ? stripInlineMd(fallback) : t("panel.tabDraft");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ersetzt die erste Überschrift (bzw. legt eine an) im Rohtext durch `title`.
|
|
||||||
function setHeading(text: string, title: string): string {
|
|
||||||
const lines = text.split("\n");
|
|
||||||
for (let i = 0; i < lines.length; i++) {
|
|
||||||
const t = lines[i].trim();
|
|
||||||
if (!t) continue;
|
|
||||||
if (t.startsWith("#")) {
|
|
||||||
const hashes = (t.match(/^#+/) as RegExpMatchArray)[0];
|
|
||||||
lines[i] = `${hashes} ${title}`;
|
|
||||||
} else {
|
|
||||||
lines.splice(i, 0, `# ${title}`, "");
|
|
||||||
}
|
|
||||||
return lines.join("\n");
|
|
||||||
}
|
|
||||||
return `# ${title}\n`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Macht `[[name]]`-Wikilinks im gerendertem Markdown klickbar. Läuft über die
|
|
||||||
/// Textknoten des DOM statt über den Rohtext, damit Vorkommen in Code-Spans
|
|
||||||
/// und Code-Blöcken (z. B. bash `[[ -f x ]]`) unangetastet bleiben.
|
|
||||||
export function linkWikiRefs(root: HTMLElement, onClick: (name: string) => void) {
|
|
||||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
||||||
const nodes: Text[] = [];
|
|
||||||
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
||||||
const t = n as Text;
|
|
||||||
if (!t.textContent?.includes("[[")) continue;
|
|
||||||
if (t.parentElement?.closest("code, pre, a")) continue;
|
|
||||||
nodes.push(t);
|
|
||||||
}
|
|
||||||
for (const node of nodes) {
|
|
||||||
const parts = node.textContent!.split(/\[\[([^\]]+)\]\]/g);
|
|
||||||
if (parts.length < 3) continue;
|
|
||||||
const frag = document.createDocumentFragment();
|
|
||||||
parts.forEach((part, i) => {
|
|
||||||
if (i % 2) {
|
|
||||||
// `[[ziel]]` oder `[[ziel|label]]`.
|
|
||||||
const sep = part.indexOf("|");
|
|
||||||
const target = sep < 0 ? part : part.slice(0, sep);
|
|
||||||
const label = sep < 0 ? part : part.slice(sep + 1);
|
|
||||||
const a = document.createElement("a");
|
|
||||||
a.href = "#";
|
|
||||||
a.className = "wiki";
|
|
||||||
a.textContent = label;
|
|
||||||
a.addEventListener("click", (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
onClick(target);
|
|
||||||
});
|
|
||||||
frag.append(a);
|
|
||||||
} else if (part) {
|
|
||||||
frag.append(part);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
node.replaceWith(frag);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function initPanelView(opts: {
|
|
||||||
content: HTMLElement;
|
|
||||||
copyBtn: HTMLElement;
|
|
||||||
modeBtn: HTMLElement;
|
|
||||||
titleEl?: HTMLElement;
|
|
||||||
editBtn?: HTMLElement;
|
|
||||||
editContentBtn?: HTMLElement;
|
|
||||||
langSelect?: HTMLSelectElement;
|
|
||||||
/// Standard-Sprache der Rechtschreibprüfung (aus den App-Settings).
|
|
||||||
defaultLang?: string;
|
|
||||||
/// Wird mit dem neuen Rohtext aufgerufen, wenn Titel oder Inhalt geändert
|
|
||||||
/// wurden.
|
|
||||||
onCommit?: (text: string) => void | Promise<void>;
|
|
||||||
/// Klick auf einen `[[name]]`-Wikilink im gerenderten Markdown.
|
|
||||||
onWikiLink?: (name: string) => void;
|
|
||||||
}): PanelView {
|
|
||||||
let rawText = "";
|
|
||||||
let rendered = true;
|
|
||||||
// Content-Edit-Zustand: während des Editierens werden eingehende Updates
|
|
||||||
// gepuffert statt angewandt.
|
|
||||||
let editing = false;
|
|
||||||
let pending: string | null = null;
|
|
||||||
let flushEditor: () => Promise<void> = async () => {};
|
|
||||||
|
|
||||||
function draw() {
|
|
||||||
if (rendered) {
|
|
||||||
opts.content.className = "md";
|
|
||||||
opts.content.innerHTML = renderMarkdown(rawText);
|
|
||||||
if (opts.onWikiLink) linkWikiRefs(opts.content, opts.onWikiLink);
|
|
||||||
} else {
|
|
||||||
opts.content.className = "raw";
|
|
||||||
opts.content.textContent = rawText;
|
|
||||||
}
|
|
||||||
opts.modeBtn.textContent = rendered ? t("panel.rendered") : t("panel.raw");
|
|
||||||
}
|
|
||||||
|
|
||||||
opts.modeBtn.addEventListener("click", () => {
|
|
||||||
rendered = !rendered;
|
|
||||||
draw();
|
|
||||||
});
|
|
||||||
|
|
||||||
opts.copyBtn.addEventListener("click", async () => {
|
|
||||||
await writeText(rawText);
|
|
||||||
flash(opts.copyBtn, "copied");
|
|
||||||
});
|
|
||||||
|
|
||||||
// Titel-Edit: Edit-Button macht den Titel editierbar, Enter/Blur schreibt die
|
|
||||||
// geänderte Überschrift zurück, Escape verwirft.
|
|
||||||
const titleEl = opts.titleEl;
|
|
||||||
if (opts.editBtn && titleEl && opts.onCommit) {
|
|
||||||
const commit = () => {
|
|
||||||
if (titleEl.getAttribute("contenteditable") !== "true") return;
|
|
||||||
titleEl.removeAttribute("contenteditable");
|
|
||||||
const nt = (titleEl.textContent || "").trim();
|
|
||||||
if (nt && nt !== firstLine(rawText)) opts.onCommit!(setHeading(rawText, nt));
|
|
||||||
else titleEl.textContent = firstLine(rawText);
|
|
||||||
};
|
|
||||||
opts.editBtn.addEventListener("click", () => {
|
|
||||||
titleEl.setAttribute("contenteditable", "true");
|
|
||||||
titleEl.focus();
|
|
||||||
const r = document.createRange();
|
|
||||||
r.selectNodeContents(titleEl);
|
|
||||||
const sel = window.getSelection();
|
|
||||||
sel?.removeAllRanges();
|
|
||||||
sel?.addRange(r);
|
|
||||||
});
|
|
||||||
titleEl.addEventListener("keydown", (e) => {
|
|
||||||
if (e.key === "Enter") {
|
|
||||||
e.preventDefault();
|
|
||||||
titleEl.blur();
|
|
||||||
} else if (e.key === "Escape") {
|
|
||||||
titleEl.textContent = firstLine(rawText);
|
|
||||||
titleEl.removeAttribute("contenteditable");
|
|
||||||
titleEl.blur();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
titleEl.addEventListener("blur", commit);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Content-Edit: Button schaltet den Inhalt auf eine Rohtext-Textarea. Speichern
|
|
||||||
// (Button erneut oder Cmd/Ctrl+Enter) schreibt zurück, Escape verwirft.
|
|
||||||
// Eingehende Updates während des Editierens werden gepuffert.
|
|
||||||
if (opts.editContentBtn && opts.onCommit) {
|
|
||||||
const editBtn = opts.editContentBtn;
|
|
||||||
const editor = document.createElement("textarea");
|
|
||||||
editor.className = "panel-editor";
|
|
||||||
editor.spellcheck = true;
|
|
||||||
editor.hidden = true;
|
|
||||||
opts.content.after(editor);
|
|
||||||
|
|
||||||
// Sprache der Rechtschreibprüfung: Default aus den Settings, per Selector
|
|
||||||
// pro Text überschreibbar.
|
|
||||||
let lang = opts.defaultLang || "de";
|
|
||||||
const sel = opts.langSelect;
|
|
||||||
if (sel) {
|
|
||||||
if ([...sel.options].some((o) => o.value === lang)) sel.value = lang;
|
|
||||||
else lang = sel.value;
|
|
||||||
sel.addEventListener("change", () => {
|
|
||||||
lang = sel.value;
|
|
||||||
editor.lang = lang;
|
|
||||||
// Neuprüfung erzwingen.
|
|
||||||
editor.spellcheck = false;
|
|
||||||
editor.spellcheck = true;
|
|
||||||
if (!editor.hidden) editor.focus();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
editor.lang = lang;
|
|
||||||
|
|
||||||
const leave = () => {
|
|
||||||
editing = false;
|
|
||||||
editor.hidden = true;
|
|
||||||
opts.content.hidden = false;
|
|
||||||
editBtn.classList.remove("active", "changed");
|
|
||||||
};
|
|
||||||
const enter = () => {
|
|
||||||
editing = true;
|
|
||||||
pending = null;
|
|
||||||
editor.value = rawText;
|
|
||||||
opts.content.hidden = true;
|
|
||||||
editor.hidden = false;
|
|
||||||
editBtn.classList.add("active");
|
|
||||||
editor.focus();
|
|
||||||
};
|
|
||||||
flushEditor = async () => {
|
|
||||||
if (!editing) return;
|
|
||||||
const v = editor.value;
|
|
||||||
leave();
|
|
||||||
await opts.onCommit!(v); // schreibt Datei -> panel-update -> set() rendert
|
|
||||||
};
|
|
||||||
const save = () => void flushEditor();
|
|
||||||
const cancel = () => {
|
|
||||||
const p = pending;
|
|
||||||
leave();
|
|
||||||
if (p !== null) applyText(p);
|
|
||||||
else draw();
|
|
||||||
};
|
|
||||||
editBtn.addEventListener("click", () => (editing ? save() : enter()));
|
|
||||||
editor.addEventListener("keydown", (e) => {
|
|
||||||
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
|
|
||||||
e.preventDefault();
|
|
||||||
save();
|
|
||||||
} else if (e.key === "Escape") {
|
|
||||||
e.preventDefault();
|
|
||||||
cancel();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function applyText(text: string) {
|
|
||||||
rawText = text;
|
|
||||||
if (titleEl && titleEl.getAttribute("contenteditable") !== "true") {
|
|
||||||
titleEl.textContent = firstLine(text);
|
|
||||||
}
|
|
||||||
draw();
|
|
||||||
}
|
|
||||||
|
|
||||||
draw();
|
|
||||||
return {
|
|
||||||
set(text: string) {
|
|
||||||
// Während einer Inhalts-Bearbeitung nicht überschreiben — puffern und den
|
|
||||||
// Edit-Button als „geändert" markieren.
|
|
||||||
if (editing) {
|
|
||||||
pending = text;
|
|
||||||
opts.editContentBtn?.classList.add("changed");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
applyText(text);
|
|
||||||
},
|
|
||||||
raw: () => rawText,
|
|
||||||
flush: () => flushEditor(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
+1
-122
@@ -185,12 +185,6 @@ body {
|
|||||||
margin: 0 6px;
|
margin: 0 6px;
|
||||||
align-self: center;
|
align-self: center;
|
||||||
}
|
}
|
||||||
.panel-actions {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: flex-end;
|
|
||||||
gap: 2px;
|
|
||||||
}
|
|
||||||
.panel-title {
|
.panel-title {
|
||||||
flex: 0 1 auto;
|
flex: 0 1 auto;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
@@ -199,13 +193,6 @@ body {
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
}
|
}
|
||||||
.panel-title[contenteditable="true"] {
|
|
||||||
overflow: visible;
|
|
||||||
text-overflow: clip;
|
|
||||||
outline: none;
|
|
||||||
color: inherit;
|
|
||||||
cursor: text;
|
|
||||||
}
|
|
||||||
.panel-btn {
|
.panel-btn {
|
||||||
border: none;
|
border: none;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
@@ -249,118 +236,10 @@ body {
|
|||||||
.panel-btn.changed {
|
.panel-btn.changed {
|
||||||
color: var(--warn);
|
color: var(--warn);
|
||||||
}
|
}
|
||||||
.panel-editor {
|
|
||||||
flex: 1;
|
|
||||||
min-height: 0;
|
|
||||||
resize: none;
|
|
||||||
border: none;
|
|
||||||
outline: none;
|
|
||||||
padding: 16px 20px;
|
|
||||||
background: transparent;
|
|
||||||
color: inherit;
|
|
||||||
font-family: "JetBrains Mono", Menlo, monospace;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.55;
|
|
||||||
}
|
|
||||||
.panel-editor[hidden] {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.panel-tabs {
|
.panel-tabs {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 2px;
|
gap: 2px;
|
||||||
}
|
}
|
||||||
.panel-lang {
|
.panel-btn[hidden] {
|
||||||
appearance: none;
|
|
||||||
-webkit-appearance: none;
|
|
||||||
margin-right: auto;
|
|
||||||
background: transparent;
|
|
||||||
color: var(--muted);
|
|
||||||
border: none;
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 6px 9px;
|
|
||||||
font: inherit;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
.panel-lang:hover {
|
|
||||||
background: var(--line);
|
|
||||||
color: var(--text);
|
|
||||||
}
|
|
||||||
#panel-content {
|
|
||||||
flex: 1;
|
|
||||||
min-height: 0;
|
|
||||||
overflow: auto;
|
|
||||||
padding: 16px 20px;
|
|
||||||
user-select: text;
|
|
||||||
-webkit-user-select: text;
|
|
||||||
cursor: text;
|
|
||||||
font-size: 13px;
|
|
||||||
line-height: 1.55;
|
|
||||||
}
|
|
||||||
#panel-content::-webkit-scrollbar {
|
|
||||||
width: 8px;
|
|
||||||
}
|
|
||||||
#panel-content::-webkit-scrollbar-thumb {
|
|
||||||
background: var(--line);
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
#panel-content.raw {
|
|
||||||
white-space: pre-wrap;
|
|
||||||
word-break: break-word;
|
|
||||||
font-family: "JetBrains Mono", Menlo, monospace;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
#panel-content.md h1,
|
|
||||||
#panel-content.md h2,
|
|
||||||
#panel-content.md h3 {
|
|
||||||
line-height: 1.25;
|
|
||||||
margin: 1em 0 0.4em;
|
|
||||||
}
|
|
||||||
#panel-content.md h1 {
|
|
||||||
font-size: 1.4em;
|
|
||||||
}
|
|
||||||
#panel-content.md h2 {
|
|
||||||
font-size: 1.2em;
|
|
||||||
}
|
|
||||||
#panel-content.md h3 {
|
|
||||||
font-size: 1.05em;
|
|
||||||
}
|
|
||||||
#panel-content.md :first-child {
|
|
||||||
margin-top: 0;
|
|
||||||
}
|
|
||||||
#panel-content.md p,
|
|
||||||
#panel-content.md ul,
|
|
||||||
#panel-content.md ol,
|
|
||||||
#panel-content.md pre,
|
|
||||||
#panel-content.md blockquote {
|
|
||||||
margin: 0 0 0.7em;
|
|
||||||
}
|
|
||||||
#panel-content.md code {
|
|
||||||
font-family: "JetBrains Mono", Menlo, monospace;
|
|
||||||
font-size: 0.9em;
|
|
||||||
background: var(--line);
|
|
||||||
border-radius: 4px;
|
|
||||||
padding: 1px 5px;
|
|
||||||
}
|
|
||||||
#panel-content.md pre {
|
|
||||||
background: var(--tile);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 12px 14px;
|
|
||||||
overflow: auto;
|
|
||||||
}
|
|
||||||
#panel-content.md pre code {
|
|
||||||
background: none;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
#panel-content.md blockquote {
|
|
||||||
border-left: 3px solid var(--line);
|
|
||||||
padding-left: 12px;
|
|
||||||
color: var(--muted);
|
|
||||||
}
|
|
||||||
#panel-content.md a {
|
|
||||||
color: var(--accent);
|
|
||||||
}
|
|
||||||
.panel-btn[hidden],
|
|
||||||
.panel-lang[hidden],
|
|
||||||
#panel-content[hidden] {
|
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|||||||
+39
-98
@@ -1,14 +1,11 @@
|
|||||||
/// Gemeinsame Panel-Verdrahtung für das angedockte Panel (terminal.ts) und
|
/// Gemeinsame Panel-Verdrahtung für das angedockte Panel (terminal.ts) und
|
||||||
/// das abgelöste Fenster (panel.ts): die Entwurfs-Ansicht als Kern, alle
|
/// das abgelöste Fenster (panel.ts): alle Tabs kommen aus der Modul-Registry
|
||||||
/// weiteren Tabs aus der Modul-Registry (src/modules) — Tab-Knöpfe und
|
/// (src/modules) — Tab-Knöpfe und Content-Container entstehen hier aus der
|
||||||
/// Content-Container entstehen hier aus der Liste der aktiven Module,
|
/// Liste der aktiven Module, Erstbefüllung per buffer_read, Updates über
|
||||||
/// Erstbefüllung per buffer_read, Updates über `<buffer>-update`-Events.
|
/// `<buffer>-update`-Events.
|
||||||
/// Die Element-IDs des Entwurfs-Markups sind in beiden HTML-Dateien
|
|
||||||
/// identisch; die Draft-Controls trägt das Markup als `.draft-only`.
|
|
||||||
|
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
import { listen } from "@tauri-apps/api/event";
|
import { listen } from "@tauri-apps/api/event";
|
||||||
import { initPanelView, type PanelView } from "./panel-view";
|
|
||||||
import { initPanelMode, type ModeTab, type PanelMode } from "./commands-view";
|
import { initPanelMode, type ModeTab, type PanelMode } from "./commands-view";
|
||||||
import { panelToast } from "./tiles";
|
import { panelToast } from "./tiles";
|
||||||
import { PANEL_TABS, type ModuleCtx, type ModuleView } from "./modules";
|
import { PANEL_TABS, type ModuleCtx, type ModuleView } from "./modules";
|
||||||
@@ -16,12 +13,9 @@ import { t } from "./messages";
|
|||||||
import "./panel-tiles.css";
|
import "./panel-tiles.css";
|
||||||
|
|
||||||
export interface PanelWiring {
|
export interface PanelWiring {
|
||||||
view: PanelView;
|
|
||||||
/// Modul-Ansichten nach Tab-Modus; enthält nur Tabs aktiver Module.
|
/// Modul-Ansichten nach Tab-Modus; enthält nur Tabs aktiver Module.
|
||||||
views: Map<string, ModuleView>;
|
views: Map<string, ModuleView>;
|
||||||
mode: { to(m: PanelMode): void; clear(): void; current(): PanelMode | null };
|
mode: { to(m: PanelMode): void; clear(): void; current(): PanelMode | null };
|
||||||
/// Entwurfstext beim Start (für die Anfangs-Modus-Entscheidung).
|
|
||||||
draft: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function wirePanel(
|
export async function wirePanel(
|
||||||
@@ -29,59 +23,18 @@ export async function wirePanel(
|
|||||||
onIncoming?: () => void,
|
onIncoming?: () => void,
|
||||||
): Promise<PanelWiring> {
|
): Promise<PanelWiring> {
|
||||||
const titleEl = document.querySelector(".panel-title") as HTMLElement;
|
const titleEl = document.querySelector(".panel-title") as HTMLElement;
|
||||||
const [enabled, defaultLang, draft] = await Promise.all([
|
const enabled = await invoke<string[]>("enabled_modules", { project });
|
||||||
invoke<string[]>("enabled_modules", { project }),
|
|
||||||
invoke<string>("spellcheck_lang"),
|
|
||||||
invoke<string>("buffer_read", { project, buffer: "panel" }),
|
|
||||||
]);
|
|
||||||
const tabs = PANEL_TABS.filter((tab) => enabled.includes(tab.module));
|
const tabs = PANEL_TABS.filter((tab) => enabled.includes(tab.module));
|
||||||
|
|
||||||
// Ohne Archiv-Modul (abgewählt oder kein Archiv-Home) verschwinden auch
|
const ctx: ModuleCtx = { project, toast: panelToast };
|
||||||
// die Archiv-Werkzeuge des Entwurfs-Tabs.
|
|
||||||
if (!enabled.includes("archive")) {
|
|
||||||
for (const sel of ["#panel-archive", "#panel-wiki-jump"]) {
|
|
||||||
const el = document.querySelector<HTMLElement>(sel)!;
|
|
||||||
el.hidden = true;
|
|
||||||
// Raus aus der draft-only-Menge, sonst blendet der Modus-Umschalter
|
|
||||||
// die Archiv-Werkzeuge im Dokument-Modus wieder ein.
|
|
||||||
el.classList.remove("draft-only");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Jeder Wiki-Sprung (Wikilink, Chip, Dokument-Sprung) geht als ein Invoke an
|
|
||||||
// den Kern; das Ergebnis kommt über den Wiki-Puffer und `wiki-update` zurück.
|
|
||||||
// Fehler (z. B. Ziel nicht im Archiv) erscheinen als Toast.
|
|
||||||
const openWiki = (name: string) =>
|
|
||||||
void invoke("wiki_open", { project, name }).catch((e) => panelToast(String(e)));
|
|
||||||
|
|
||||||
const ctx: ModuleCtx = {
|
|
||||||
project,
|
|
||||||
toast: panelToast,
|
|
||||||
openDoc: (path) =>
|
|
||||||
void invoke("panel_load", { project, path }).catch((e) => panelToast(String(e))),
|
|
||||||
openWiki,
|
|
||||||
};
|
|
||||||
|
|
||||||
const view = initPanelView({
|
|
||||||
content: document.getElementById("panel-content")!,
|
|
||||||
copyBtn: document.getElementById("panel-copy")!,
|
|
||||||
modeBtn: document.getElementById("panel-mode")!,
|
|
||||||
titleEl,
|
|
||||||
editBtn: document.getElementById("panel-title-edit")!,
|
|
||||||
editContentBtn: document.getElementById("panel-content-edit")!,
|
|
||||||
langSelect: document.getElementById("panel-lang") as HTMLSelectElement,
|
|
||||||
defaultLang,
|
|
||||||
onCommit: (text) => invoke("panel_set", { project, text }),
|
|
||||||
onWikiLink: openWiki,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Tab-Leiste und Container aus der Registry. Die Container-IDs
|
// Tab-Leiste und Container aus der Registry. Die Container-IDs
|
||||||
// (`<mode>-content`) sind zugleich die CSS-Anker der Ansichten; die
|
// (`<mode>-content`) sind zugleich die CSS-Anker der Ansichten; die
|
||||||
// Container reihen sich hinter #panel-content ein.
|
// Container reihen sich hinter der Kopfzeile (.panel-head) ein.
|
||||||
const tabsEl = document.getElementById("panel-tabs")!;
|
const tabsEl = document.getElementById("panel-tabs")!;
|
||||||
const views = new Map<string, ModuleView>();
|
const views = new Map<string, ModuleView>();
|
||||||
const modeTabs: ModeTab[] = [];
|
const modeTabs: ModeTab[] = [];
|
||||||
let anchor = document.getElementById("panel-content")!;
|
let anchor = document.querySelector(".panel-head") as HTMLElement;
|
||||||
for (const tab of tabs) {
|
for (const tab of tabs) {
|
||||||
const btn = document.createElement("button");
|
const btn = document.createElement("button");
|
||||||
btn.className = "panel-btn";
|
btn.className = "panel-btn";
|
||||||
@@ -94,15 +47,12 @@ export async function wirePanel(
|
|||||||
sep.className = "tab-sep";
|
sep.className = "tab-sep";
|
||||||
tabsEl.append(sep);
|
tabsEl.append(sep);
|
||||||
}
|
}
|
||||||
let content: HTMLElement | null = null;
|
const content = document.createElement("div");
|
||||||
if (tab.init) {
|
content.id = `${tab.mode}-content`;
|
||||||
content = document.createElement("div");
|
content.hidden = true;
|
||||||
content.id = `${tab.mode}-content`;
|
anchor.after(content);
|
||||||
content.hidden = true;
|
anchor = content;
|
||||||
anchor.after(content);
|
views.set(tab.mode, tab.init(content, ctx));
|
||||||
anchor = content;
|
|
||||||
views.set(tab.mode, tab.init(content, ctx));
|
|
||||||
}
|
|
||||||
modeTabs.push({
|
modeTabs.push({
|
||||||
mode: tab.mode,
|
mode: tab.mode,
|
||||||
btn,
|
btn,
|
||||||
@@ -113,43 +63,34 @@ export async function wirePanel(
|
|||||||
: undefined,
|
: undefined,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const mode = initPanelMode({
|
// Archiv-Zugang: fester Knopf hinter den Tabs — öffnet das Trilium-Fenster
|
||||||
tabs: modeTabs,
|
// des Projekts (kein Modus, kein Content-Container).
|
||||||
draftEls: [
|
if (enabled.includes("trilium")) {
|
||||||
document.getElementById("panel-content")!,
|
const btn = document.createElement("button");
|
||||||
...document.querySelectorAll<HTMLElement>(".draft-only"),
|
btn.className = "panel-btn";
|
||||||
],
|
btn.textContent = t("panel.archiveOpen");
|
||||||
titleEl,
|
btn.title = t("panel.archiveOpenTitle");
|
||||||
flush: () => void view.flush(),
|
btn.addEventListener("click", () =>
|
||||||
});
|
void invoke("trilium_open", { project, noteId: null }).catch((e) =>
|
||||||
|
panelToast(String(e)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
tabsEl.append(btn);
|
||||||
|
}
|
||||||
|
|
||||||
// Sprung Dokument → Wiki: öffnet den Archiv-Navigator (Dokumentseiten im
|
const mode = initPanelMode({ tabs: modeTabs, titleEl });
|
||||||
// Wiki gibt es nicht mehr — Dokumente öffnen immer im Dokument-Tab).
|
|
||||||
document
|
|
||||||
.getElementById("panel-wiki-jump")!
|
|
||||||
.addEventListener("click", () => openWiki("tag:"));
|
|
||||||
|
|
||||||
view.set(draft);
|
|
||||||
await listen<string>("panel-update", (e) => {
|
|
||||||
// Erst umschalten, dann setzen: to("draft") restauriert den gemerkten
|
|
||||||
// Titel — der neue Inhalt (und damit sein Titel) muss danach kommen.
|
|
||||||
mode.to("draft");
|
|
||||||
view.set(e.payload);
|
|
||||||
onIncoming?.();
|
|
||||||
});
|
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
tabs
|
tabs.map(async (tab) => {
|
||||||
.filter((tab) => tab.init)
|
const v = views.get(tab.mode)!;
|
||||||
.map(async (tab) => {
|
v.set(await invoke<string>("buffer_read", { project, buffer: tab.buffer }));
|
||||||
const v = views.get(tab.mode)!;
|
await listen<string>(`${tab.buffer}-update`, (e) => {
|
||||||
v.set(await invoke<string>("buffer_read", { project, buffer: tab.buffer }));
|
v.set(e.payload);
|
||||||
await listen<string>(`${tab.buffer}-update`, (e) => {
|
mode.to(tab.mode);
|
||||||
v.set(e.payload);
|
onIncoming?.();
|
||||||
mode.to(tab.mode);
|
});
|
||||||
onIncoming?.();
|
}),
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return { view, views, mode, draft };
|
return { views, mode };
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-45
@@ -6,14 +6,11 @@ import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
|||||||
import { PhysicalPosition, PhysicalSize } from "@tauri-apps/api/dpi";
|
import { PhysicalPosition, PhysicalSize } from "@tauri-apps/api/dpi";
|
||||||
import { emit } from "@tauri-apps/api/event";
|
import { emit } from "@tauri-apps/api/event";
|
||||||
import { wirePanel } from "./panel-wiring";
|
import { wirePanel } from "./panel-wiring";
|
||||||
import { flash, panelToast } from "./tiles";
|
|
||||||
import { initArchiveForm } from "./archive-form";
|
|
||||||
import { applyTheme, THEMES } from "./themes";
|
import { applyTheme, THEMES } from "./themes";
|
||||||
import { applyI18n, t } from "./messages";
|
import { applyI18n } from "./messages";
|
||||||
|
|
||||||
// Abgelöstes Panel-Fenster: liest den aktuellen Entwurf einmal ein und folgt
|
// Abgelöstes Panel-Fenster: dieselben Modul-Tabs wie das angedockte Panel,
|
||||||
// danach denselben Update-Events wie das angedockte Panel; startet in
|
// gespeist aus denselben Puffer-Update-Events.
|
||||||
// „Befehle", wenn es (noch) keinen Entwurf gibt.
|
|
||||||
applyI18n();
|
applyI18n();
|
||||||
const project = new URLSearchParams(location.search).get("project")!;
|
const project = new URLSearchParams(location.search).get("project")!;
|
||||||
const win = getCurrentWebviewWindow();
|
const win = getCurrentWebviewWindow();
|
||||||
@@ -99,52 +96,20 @@ applyTheme(picked);
|
|||||||
document.documentElement.style.background = picked.header;
|
document.documentElement.style.background = picked.header;
|
||||||
document.body.style.background = picked.header;
|
document.body.style.background = picked.header;
|
||||||
|
|
||||||
const { view, views, mode, draft } = await wirePanel(project);
|
const { views, mode } = await wirePanel(project);
|
||||||
// Beim Ablösen kommt der dort aktive Tab als URL-Parameter mit; ohne ihn
|
// Beim Ablösen kommt der dort aktive Tab als URL-Parameter mit; ohne ihn
|
||||||
// (Kaltstart) gilt die Default-Logik: ohne Entwurf die ToDo-Liste (falls
|
// (Kaltstart): ToDo-Liste, falls gewählt und nicht leer, sonst der erste Tab.
|
||||||
// gewählt und nicht leer), sonst die Befehle.
|
|
||||||
const initialMode = new URLSearchParams(location.search).get("mode");
|
const initialMode = new URLSearchParams(location.search).get("mode");
|
||||||
const todos = views.get("todo");
|
const todos = views.get("todo");
|
||||||
const cmds = views.get("commands");
|
const first = views.keys().next().value;
|
||||||
if (initialMode) {
|
if (initialMode) {
|
||||||
mode.to(initialMode);
|
mode.to(initialMode);
|
||||||
} else if (!draft.trim()) {
|
} else if (todos && !todos.empty()) {
|
||||||
if (todos && !todos.empty()) mode.to("todo");
|
mode.to("todo");
|
||||||
else if (cmds && !cmds.empty()) mode.to("commands");
|
} else if (first) {
|
||||||
|
mode.to(first);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Archivieren: wie im angedockten Panel — Formular aufklappen, Abschicken
|
|
||||||
// wählt notfalls erst das Archiv-Home per Dialog.
|
|
||||||
const archiveBtn = document.getElementById("panel-archive")!;
|
|
||||||
const archiveForm = initArchiveForm(archiveBtn, async (meta) => {
|
|
||||||
try {
|
|
||||||
const configured = await invoke<string | null>("panel_archive_dir_cmd", {
|
|
||||||
project,
|
|
||||||
});
|
|
||||||
let dir: string | undefined;
|
|
||||||
if (!configured) {
|
|
||||||
const { open } = await import("@tauri-apps/plugin-dialog");
|
|
||||||
const chosen = await open({ directory: true, title: t("panel.chooseArchiveDir") });
|
|
||||||
if (!chosen) return;
|
|
||||||
dir = chosen as string;
|
|
||||||
}
|
|
||||||
await view.flush(); // offene Bearbeitung erst speichern — archiviert, was zu sehen ist
|
|
||||||
const path = await invoke<string>("panel_archive_cmd", {
|
|
||||||
project,
|
|
||||||
dir,
|
|
||||||
folder: meta.folder ?? null,
|
|
||||||
description: meta.description ?? null,
|
|
||||||
tags: meta.tags,
|
|
||||||
});
|
|
||||||
flash(archiveBtn, "copied", 1400);
|
|
||||||
invoke("reveal_path_cmd", { path });
|
|
||||||
} catch (e) {
|
|
||||||
flash(archiveBtn, "error", 1400);
|
|
||||||
panelToast(`Archivieren fehlgeschlagen: ${e}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
archiveBtn.addEventListener("click", () => archiveForm.toggle());
|
|
||||||
|
|
||||||
// „Andocken": angedocktes Panel wieder einblenden, dann dieses Fenster schließen.
|
// „Andocken": angedocktes Panel wieder einblenden, dann dieses Fenster schließen.
|
||||||
document.getElementById("panel-dock")!.addEventListener("click", async () => {
|
document.getElementById("panel-dock")!.addEventListener("click", async () => {
|
||||||
await emit("panel-attached");
|
await emit("panel-attached");
|
||||||
|
|||||||
@@ -20,8 +20,7 @@ function setup() {
|
|||||||
const run = JSON.stringify({
|
const run = JSON.stringify({
|
||||||
query: "arch",
|
query: "arch",
|
||||||
tag: null,
|
tag: null,
|
||||||
home: "/tmp/archiv",
|
hits: [{ note_id: "abc123def", title: "X" }],
|
||||||
hits: [{ relpath: "a/2026-01-01_0000-x.md", title: "X", snippet: "ein **arch**iv" }],
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("initSearchView", () => {
|
describe("initSearchView", () => {
|
||||||
@@ -74,19 +73,18 @@ describe("initSearchView", () => {
|
|||||||
expect(onSearch).toHaveBeenCalledWith("panel arch");
|
expect(onSearch).toHaveBeenCalledWith("panel arch");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rendert Treffer; Klick liefert den absoluten Pfad", () => {
|
it("rendert Treffer; Klick liefert die noteId", () => {
|
||||||
const { view, onOpen } = setup();
|
const { view, onOpen } = setup();
|
||||||
view.set(run);
|
view.set(run);
|
||||||
const tile = document.querySelector<HTMLElement>(".hit-tile")!;
|
const tile = document.querySelector<HTMLElement>(".hit-tile")!;
|
||||||
expect(tile.querySelector(".hit-title")!.textContent).toBe("X");
|
expect(tile.querySelector(".hit-title")!.textContent).toBe("X");
|
||||||
expect(tile.querySelectorAll("mark").length).toBe(1);
|
|
||||||
tile.click();
|
tile.click();
|
||||||
expect(onOpen).toHaveBeenCalledWith("/tmp/archiv/a/2026-01-01_0000-x.md");
|
expect(onOpen).toHaveBeenCalledWith("abc123def");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("zeigt „Keine Treffer“ bei leerem Ergebnis", () => {
|
it("zeigt „Keine Treffer“ bei leerem Ergebnis", () => {
|
||||||
const { view } = setup();
|
const { view } = setup();
|
||||||
view.set(JSON.stringify({ query: "nix", tag: "adr", home: "/a", hits: [] }));
|
view.set(JSON.stringify({ query: "nix", tag: "adr", hits: [] }));
|
||||||
expect(document.querySelector(".hit-head")!.textContent).toBe(
|
expect(document.querySelector(".hit-head")!.textContent).toBe(
|
||||||
"Keine Treffer für „nix“ · #adr",
|
"Keine Treffer für „nix“ · #adr",
|
||||||
);
|
);
|
||||||
|
|||||||
+9
-27
@@ -1,22 +1,20 @@
|
|||||||
/// Kachel-Ansicht der Archiv-Suchtreffer: rendert die Suchtreffer-Datei
|
/// Kachel-Ansicht der Archiv-Suchtreffer: rendert die Suchtreffer-Datei
|
||||||
/// (search_archive im MCP-Server) als klickbare Kacheln — Klick reicht den
|
/// (search_archive im MCP-Server bzw. search_run aus dem Suchfeld) als
|
||||||
/// absoluten Pfad des Treffers an onOpen. Titel/Snippet/Pfad sind Fremdtext und
|
/// klickbare Kacheln — Klick reicht die noteId des Treffers an onOpen
|
||||||
/// gehen nie durch innerHTML; die `**…**`-Marker im Snippet werden per
|
/// (öffnet die Notiz im Trilium-Fenster). Titel sind Fremdtext und gehen
|
||||||
/// Split in <mark>-Elemente übersetzt.
|
/// nie durch innerHTML.
|
||||||
|
|
||||||
import { t } from "./messages";
|
import { t } from "./messages";
|
||||||
import { renderTile } from "./tiles";
|
import { renderTile } from "./tiles";
|
||||||
|
|
||||||
interface Hit {
|
interface Hit {
|
||||||
relpath: string;
|
note_id: string;
|
||||||
title: string;
|
title: string;
|
||||||
snippet: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SearchRun {
|
interface SearchRun {
|
||||||
query: string;
|
query: string;
|
||||||
tag?: string | null;
|
tag?: string | null;
|
||||||
home: string;
|
|
||||||
hits: Hit[];
|
hits: Hit[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,7 +25,7 @@ export interface SearchView {
|
|||||||
|
|
||||||
export function initSearchView(
|
export function initSearchView(
|
||||||
container: HTMLElement,
|
container: HTMLElement,
|
||||||
onOpen: (path: string) => void,
|
onOpen: (noteId: string) => void,
|
||||||
onSearch: (query: string) => void,
|
onSearch: (query: string) => void,
|
||||||
): SearchView {
|
): SearchView {
|
||||||
let count = 0;
|
let count = 0;
|
||||||
@@ -41,7 +39,7 @@ export function initSearchView(
|
|||||||
// Live-Suche ab 3 Zeichen, entprellt (300 ms Debounce); endet die Eingabe
|
// Live-Suche ab 3 Zeichen, entprellt (300 ms Debounce); endet die Eingabe
|
||||||
// mitten im Wort, wird das letzte Wort als Präfix gesucht (arch → arch*) —
|
// mitten im Wort, wird das letzte Wort als Präfix gesucht (arch → arch*) —
|
||||||
// außer es ist ein #tag-Token. Enter sucht sofort und wörtlich — für exakte
|
// außer es ist ein #tag-Token. Enter sucht sofort und wörtlich — für exakte
|
||||||
// FTS-Syntax (Phrasen, OR/NOT).
|
// Trilium-Suchsyntax (Phrasen, Operatoren).
|
||||||
let pending: number | undefined;
|
let pending: number | undefined;
|
||||||
input.addEventListener("input", () => {
|
input.addEventListener("input", () => {
|
||||||
clearTimeout(pending);
|
clearTimeout(pending);
|
||||||
@@ -73,21 +71,6 @@ export function initSearchView(
|
|||||||
const results = document.createElement("div");
|
const results = document.createElement("div");
|
||||||
container.append(bar, results);
|
container.append(bar, results);
|
||||||
|
|
||||||
function snippetEl(snippet: string): HTMLElement {
|
|
||||||
const div = document.createElement("div");
|
|
||||||
div.className = "hit-snippet";
|
|
||||||
snippet.split("**").forEach((part, i) => {
|
|
||||||
if (i % 2) {
|
|
||||||
const m = document.createElement("mark");
|
|
||||||
m.textContent = part;
|
|
||||||
div.append(m);
|
|
||||||
} else if (part) {
|
|
||||||
div.append(document.createTextNode(part));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return div;
|
|
||||||
}
|
|
||||||
|
|
||||||
function render(run: SearchRun) {
|
function render(run: SearchRun) {
|
||||||
results.textContent = "";
|
results.textContent = "";
|
||||||
const head = document.createElement("div");
|
const head = document.createElement("div");
|
||||||
@@ -105,10 +88,9 @@ export function initSearchView(
|
|||||||
cls: "hit-tile",
|
cls: "hit-tile",
|
||||||
parts: [
|
parts: [
|
||||||
{ cls: "hit-title", text: hit.title },
|
{ cls: "hit-title", text: hit.title },
|
||||||
snippetEl(hit.snippet),
|
{ cls: "hit-path", text: hit.note_id },
|
||||||
{ cls: "hit-path", text: hit.relpath },
|
|
||||||
],
|
],
|
||||||
onClick: () => onOpen(`${run.home}/${hit.relpath}`),
|
onClick: () => onOpen(hit.note_id),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-122
@@ -265,12 +265,6 @@ header .panel-tabs[hidden] + #pool {
|
|||||||
#panel-detach {
|
#panel-detach {
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
}
|
}
|
||||||
.panel-actions {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: flex-end;
|
|
||||||
gap: 2px;
|
|
||||||
}
|
|
||||||
.panel-title {
|
.panel-title {
|
||||||
flex: 0 1 auto;
|
flex: 0 1 auto;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
@@ -279,13 +273,6 @@ header .panel-tabs[hidden] + #pool {
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
}
|
}
|
||||||
.panel-title[contenteditable="true"] {
|
|
||||||
overflow: visible;
|
|
||||||
text-overflow: clip;
|
|
||||||
outline: none;
|
|
||||||
color: inherit;
|
|
||||||
cursor: text;
|
|
||||||
}
|
|
||||||
.panel-btn {
|
.panel-btn {
|
||||||
border: none;
|
border: none;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
@@ -329,118 +316,10 @@ header .panel-tabs[hidden] + #pool {
|
|||||||
.panel-btn.changed {
|
.panel-btn.changed {
|
||||||
color: var(--warn);
|
color: var(--warn);
|
||||||
}
|
}
|
||||||
.panel-editor {
|
|
||||||
flex: 1;
|
|
||||||
min-height: 0;
|
|
||||||
resize: none;
|
|
||||||
border: none;
|
|
||||||
outline: none;
|
|
||||||
padding: 14px 16px;
|
|
||||||
background: transparent;
|
|
||||||
color: inherit;
|
|
||||||
font-family: "JetBrains Mono", Menlo, monospace;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.55;
|
|
||||||
}
|
|
||||||
.panel-editor[hidden] {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.panel-tabs {
|
.panel-tabs {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 2px;
|
gap: 2px;
|
||||||
}
|
}
|
||||||
.panel-lang {
|
.panel-btn[hidden] {
|
||||||
appearance: none;
|
|
||||||
-webkit-appearance: none;
|
|
||||||
margin-right: auto;
|
|
||||||
background: transparent;
|
|
||||||
color: var(--muted);
|
|
||||||
border: none;
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 6px 9px;
|
|
||||||
font: inherit;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
.panel-lang:hover {
|
|
||||||
background: var(--line);
|
|
||||||
color: var(--text);
|
|
||||||
}
|
|
||||||
#panel-content {
|
|
||||||
flex: 1;
|
|
||||||
min-height: 0;
|
|
||||||
overflow: auto;
|
|
||||||
padding: 14px 16px;
|
|
||||||
user-select: text;
|
|
||||||
-webkit-user-select: text;
|
|
||||||
cursor: text;
|
|
||||||
font-size: 13px;
|
|
||||||
line-height: 1.55;
|
|
||||||
}
|
|
||||||
#panel-content::-webkit-scrollbar {
|
|
||||||
width: 8px;
|
|
||||||
}
|
|
||||||
#panel-content::-webkit-scrollbar-thumb {
|
|
||||||
background: var(--line);
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
#panel-content.raw {
|
|
||||||
white-space: pre-wrap;
|
|
||||||
word-break: break-word;
|
|
||||||
font-family: "JetBrains Mono", Menlo, monospace;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
#panel-content.md h1,
|
|
||||||
#panel-content.md h2,
|
|
||||||
#panel-content.md h3 {
|
|
||||||
line-height: 1.25;
|
|
||||||
margin: 1em 0 0.4em;
|
|
||||||
}
|
|
||||||
#panel-content.md h1 {
|
|
||||||
font-size: 1.4em;
|
|
||||||
}
|
|
||||||
#panel-content.md h2 {
|
|
||||||
font-size: 1.2em;
|
|
||||||
}
|
|
||||||
#panel-content.md h3 {
|
|
||||||
font-size: 1.05em;
|
|
||||||
}
|
|
||||||
#panel-content.md :first-child {
|
|
||||||
margin-top: 0;
|
|
||||||
}
|
|
||||||
#panel-content.md p,
|
|
||||||
#panel-content.md ul,
|
|
||||||
#panel-content.md ol,
|
|
||||||
#panel-content.md pre,
|
|
||||||
#panel-content.md blockquote {
|
|
||||||
margin: 0 0 0.7em;
|
|
||||||
}
|
|
||||||
#panel-content.md code {
|
|
||||||
font-family: "JetBrains Mono", Menlo, monospace;
|
|
||||||
font-size: 0.9em;
|
|
||||||
background: var(--line);
|
|
||||||
border-radius: 4px;
|
|
||||||
padding: 1px 5px;
|
|
||||||
}
|
|
||||||
#panel-content.md pre {
|
|
||||||
background: var(--tile);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 12px 14px;
|
|
||||||
overflow: auto;
|
|
||||||
}
|
|
||||||
#panel-content.md pre code {
|
|
||||||
background: none;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
#panel-content.md blockquote {
|
|
||||||
border-left: 3px solid var(--line);
|
|
||||||
padding-left: 12px;
|
|
||||||
color: var(--muted);
|
|
||||||
}
|
|
||||||
#panel-content.md a {
|
|
||||||
color: var(--accent);
|
|
||||||
}
|
|
||||||
.panel-btn[hidden],
|
|
||||||
.panel-lang[hidden],
|
|
||||||
#panel-content[hidden] {
|
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-40
@@ -15,8 +15,7 @@ import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
|||||||
import { listen } from "@tauri-apps/api/event";
|
import { listen } from "@tauri-apps/api/event";
|
||||||
import { wirePanel } from "./panel-wiring";
|
import { wirePanel } from "./panel-wiring";
|
||||||
import { applyTheme, THEMES } from "./themes";
|
import { applyTheme, THEMES } from "./themes";
|
||||||
import { flash, panelToast } from "./tiles";
|
import { panelToast } from "./tiles";
|
||||||
import { initArchiveForm } from "./archive-form";
|
|
||||||
import { applyI18n, t } from "./messages";
|
import { applyI18n, t } from "./messages";
|
||||||
|
|
||||||
// Debug-Instrumentierung: Fehler auf der Seite anzeigen und ins Dev-Log spiegeln.
|
// Debug-Instrumentierung: Fehler auf der Seite anzeigen und ins Dev-Log spiegeln.
|
||||||
@@ -189,10 +188,10 @@ window.addEventListener("resize", () => fit.fit());
|
|||||||
await invoke("term_start", { project, rows: term.rows, cols: term.cols });
|
await invoke("term_start", { project, rows: term.rows, cols: term.cols });
|
||||||
term.focus();
|
term.focus();
|
||||||
|
|
||||||
// --- Andockbares Entwurfs-Panel -------------------------------------------
|
// --- Andockbares Panel ----------------------------------------------------
|
||||||
// Der Skill schreibt Entwürfe in eine Datei; terminal.rs meldet neuen Inhalt
|
// Die MCP-Tools schreiben in die Puffer-Dateien; terminal.rs meldet neuen
|
||||||
// per `panel-update`. Das Panel blendet sich dann ein — außer es ist gerade in
|
// Inhalt als `<buffer>-update`. Das Panel blendet sich dann ein — außer es
|
||||||
// ein eigenes Fenster abgelöst (`panel-detached`).
|
// ist gerade in ein eigenes Fenster abgelöst (`panel-detached`).
|
||||||
const panel = document.getElementById("panel")!;
|
const panel = document.getElementById("panel")!;
|
||||||
const splitter = document.getElementById("splitter")!;
|
const splitter = document.getElementById("splitter")!;
|
||||||
|
|
||||||
@@ -212,10 +211,20 @@ function hidePanel() {
|
|||||||
|
|
||||||
// Gemeinsame Verdrahtung (Views, Modi, Update-Events); jedes eingehende
|
// Gemeinsame Verdrahtung (Views, Modi, Update-Events); jedes eingehende
|
||||||
// Update blendet das angedockte Panel ein, solange es nicht abgelöst ist.
|
// Update blendet das angedockte Panel ein, solange es nicht abgelöst ist.
|
||||||
const { view, views, mode } = await wirePanel(project, () => {
|
const { views, mode } = await wirePanel(project, () => {
|
||||||
hasContent = true;
|
hasContent = true;
|
||||||
if (!detached) showPanel();
|
if (!detached) showPanel();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// write_panel hat eine Notiz angelegt: das Trilium-Fenster des Projekts
|
||||||
|
// zeigt sie. Leerer Puffer = Session-Start, keine Notiz.
|
||||||
|
await listen<string>("noteopen-update", (e) => {
|
||||||
|
if (!e.payload.trim()) return;
|
||||||
|
const { noteId } = JSON.parse(e.payload);
|
||||||
|
void invoke("trilium_open", { project, noteId }).catch((err) =>
|
||||||
|
panelToast(String(err)),
|
||||||
|
);
|
||||||
|
});
|
||||||
// Panel startet zugeklappt — außer das ToDo-Modul ist gewählt und die Liste
|
// Panel startet zugeklappt — außer das ToDo-Modul ist gewählt und die Liste
|
||||||
// nicht leer: dann öffnet das Panel beim Start mit der ToDo-Ansicht.
|
// nicht leer: dann öffnet das Panel beim Start mit der ToDo-Ansicht.
|
||||||
const todos = views.get("todo");
|
const todos = views.get("todo");
|
||||||
@@ -265,39 +274,6 @@ document.getElementById("panel-hide")!.addEventListener("click", () => {
|
|||||||
mode.clear();
|
mode.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Archivieren: Button klappt das Formular (Ordner/Beschreibung/Schlagwörter)
|
|
||||||
// auf; Abschicken wählt notfalls erst das Archiv-Home per Dialog.
|
|
||||||
const archiveBtn = document.getElementById("panel-archive")!;
|
|
||||||
const archiveForm = initArchiveForm(archiveBtn, async (meta) => {
|
|
||||||
try {
|
|
||||||
const configured = await invoke<string | null>("panel_archive_dir_cmd", {
|
|
||||||
project,
|
|
||||||
});
|
|
||||||
let dir: string | undefined;
|
|
||||||
if (!configured) {
|
|
||||||
const { open } = await import("@tauri-apps/plugin-dialog");
|
|
||||||
const chosen = await open({ directory: true, title: t("panel.chooseArchiveDir") });
|
|
||||||
if (!chosen) return;
|
|
||||||
dir = chosen as string;
|
|
||||||
}
|
|
||||||
await view.flush(); // offene Bearbeitung erst speichern — archiviert, was zu sehen ist
|
|
||||||
const path = await invoke<string>("panel_archive_cmd", {
|
|
||||||
project,
|
|
||||||
dir,
|
|
||||||
folder: meta.folder ?? null,
|
|
||||||
description: meta.description ?? null,
|
|
||||||
tags: meta.tags,
|
|
||||||
});
|
|
||||||
flash(archiveBtn, "copied", 1400);
|
|
||||||
invoke("reveal_path_cmd", { path });
|
|
||||||
} catch (e) {
|
|
||||||
flash(archiveBtn, "error", 1400);
|
|
||||||
panelToast(`Archivieren fehlgeschlagen: ${e}`);
|
|
||||||
invoke("term_log", { msg: `archive: ${e}` });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
archiveBtn.addEventListener("click", () => archiveForm.toggle());
|
|
||||||
|
|
||||||
// Splitter: Panelbreite ziehen.
|
// Splitter: Panelbreite ziehen.
|
||||||
splitter.addEventListener("mousedown", (e) => {
|
splitter.addEventListener("mousedown", (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -1,246 +0,0 @@
|
|||||||
// Wiki-Ansicht: Ordner-Baum links, flache Inhaltsliste rechts, Zeilen-Aktionen
|
|
||||||
// (öffnen, umbenennen, löschen), Ordner-Umbenennen, Leerzustände.
|
|
||||||
import { describe, expect, it, vi } from "vitest";
|
|
||||||
import { initWikiView } from "./wiki-view";
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
document.body.innerHTML = `<div id="w"></div>`;
|
|
||||||
const openDoc = vi.fn();
|
|
||||||
const openWiki = vi.fn();
|
|
||||||
const actions = {
|
|
||||||
rename: vi.fn(),
|
|
||||||
remove: vi.fn(),
|
|
||||||
moveFolder: vi.fn(),
|
|
||||||
createFolder: vi.fn(),
|
|
||||||
createDoc: vi.fn(),
|
|
||||||
};
|
|
||||||
const view = initWikiView(document.getElementById("w")!, {
|
|
||||||
openDoc,
|
|
||||||
openWiki,
|
|
||||||
actions,
|
|
||||||
});
|
|
||||||
return { view, openDoc, openWiki, actions };
|
|
||||||
}
|
|
||||||
|
|
||||||
const doc = (relpath: string, name: string, extra: object = {}) => ({
|
|
||||||
relpath,
|
|
||||||
name,
|
|
||||||
title: name.toUpperCase(),
|
|
||||||
description: null,
|
|
||||||
tags: [],
|
|
||||||
date: "2026-07-19",
|
|
||||||
backlinks: 0,
|
|
||||||
...extra,
|
|
||||||
});
|
|
||||||
|
|
||||||
const page = JSON.stringify({
|
|
||||||
kind: "page",
|
|
||||||
home: "/tmp/archiv",
|
|
||||||
tag: null,
|
|
||||||
total: 3,
|
|
||||||
tags: [],
|
|
||||||
folders: [
|
|
||||||
{
|
|
||||||
name: "",
|
|
||||||
docs: [
|
|
||||||
doc("2026-07-19_1000-wurzel-doc.md", "wurzel-doc", {
|
|
||||||
backlinks: 2,
|
|
||||||
description: "Beschreibung",
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{ name: "konzepte", docs: [doc("konzepte/2026-07-19_1005-neu.md", "neu")] },
|
|
||||||
{
|
|
||||||
name: "konzepte/panel",
|
|
||||||
docs: [doc("konzepte/panel/2026-07-19_1010-alt.md", "alt")],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("initWikiView — Baum und Liste", () => {
|
|
||||||
it("Baum zeigt nur Ordner, Wurzel ist gewählt und listet ihren Inhalt", () => {
|
|
||||||
const { view } = setup();
|
|
||||||
view.set(page);
|
|
||||||
// Baum: Wurzel-Knopf + Ordner (keine Dokumentzeilen im Baum).
|
|
||||||
expect(document.querySelector(".wiki-tree-root")!.className).toContain("active");
|
|
||||||
const folders = [...document.querySelectorAll(".wiki-tree .wiki-tree-name")].map(
|
|
||||||
(e) => e.textContent,
|
|
||||||
);
|
|
||||||
expect(folders).toEqual(["konzepte", "panel"]);
|
|
||||||
// Liste rechts: nur der direkte Wurzel-Inhalt.
|
|
||||||
expect(document.querySelector(".wiki-head-title")!.textContent).toBe("Archiv");
|
|
||||||
expect(document.querySelector(".wiki-head-right")!.textContent).toBe("1 Dokument");
|
|
||||||
const rows = [...document.querySelectorAll(".wiki-doc .wiki-doc-title")].map(
|
|
||||||
(e) => e.textContent,
|
|
||||||
);
|
|
||||||
expect(rows).toEqual(["WURZEL-DOC"]);
|
|
||||||
expect(document.querySelector(".wiki-doc-back")!.textContent).toBe("↩ 2");
|
|
||||||
expect(document.querySelector(".wiki-doc-desc")!.textContent).toBe("Beschreibung");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Ordner-Klick wählt aus und zeigt dessen flache Liste", () => {
|
|
||||||
const { view } = setup();
|
|
||||||
view.set(page);
|
|
||||||
const names = document.querySelectorAll<HTMLElement>(".wiki-tree .wiki-tree-name");
|
|
||||||
names[0].click(); // konzepte
|
|
||||||
expect(document.querySelector(".wiki-head-title")!.textContent).toBe("konzepte");
|
|
||||||
expect(document.querySelector(".wiki-head-sub")!.textContent).toBe(
|
|
||||||
"/tmp/archiv/konzepte",
|
|
||||||
);
|
|
||||||
const rows = [...document.querySelectorAll(".wiki-doc .wiki-doc-title")].map(
|
|
||||||
(e) => e.textContent,
|
|
||||||
);
|
|
||||||
// Nur direkter Inhalt — das Dokument aus konzepte/panel erscheint nicht.
|
|
||||||
expect(rows).toEqual(["NEU"]);
|
|
||||||
expect(
|
|
||||||
document.querySelector(".wiki-tree summary.active .wiki-tree-name")!.textContent,
|
|
||||||
).toBe("konzepte");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Dokument-Klick öffnet über den absoluten Pfad", () => {
|
|
||||||
const { view, openDoc } = setup();
|
|
||||||
view.set(page);
|
|
||||||
document.querySelector<HTMLElement>(".wiki-doc")!.click();
|
|
||||||
expect(openDoc).toHaveBeenCalledWith("/tmp/archiv/2026-07-19_1000-wurzel-doc.md");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Auswahl übersteht ein Puffer-Update, verschwundener Ordner fällt zur Wurzel", () => {
|
|
||||||
const { view } = setup();
|
|
||||||
view.set(page);
|
|
||||||
document.querySelectorAll<HTMLElement>(".wiki-tree .wiki-tree-name")[0].click();
|
|
||||||
view.set(page); // Update: Auswahl bleibt
|
|
||||||
expect(document.querySelector(".wiki-head-title")!.textContent).toBe("konzepte");
|
|
||||||
view.set(
|
|
||||||
JSON.stringify({
|
|
||||||
kind: "page",
|
|
||||||
home: "/tmp/archiv",
|
|
||||||
tag: null,
|
|
||||||
total: 1,
|
|
||||||
tags: [],
|
|
||||||
folders: [{ name: "", docs: [doc("2026-07-19_1000-wurzel-doc.md", "wurzel-doc")] }],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(document.querySelector(".wiki-head-title")!.textContent).toBe("Archiv");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("initWikiView — Aktionen", () => {
|
|
||||||
it("Stift an der Zeile: Inline-Umbenennen mit Enter, ohne das Dokument zu öffnen", () => {
|
|
||||||
const { view, actions, openDoc } = setup();
|
|
||||||
view.set(page);
|
|
||||||
const row = document.querySelector<HTMLElement>(".wiki-doc")!;
|
|
||||||
row.querySelector<HTMLElement>(".cmd-edit")!.click();
|
|
||||||
const input = row.querySelector<HTMLInputElement>(".wiki-tree-input")!;
|
|
||||||
expect(input.value).toBe("wurzel-doc");
|
|
||||||
input.value = "Neuer Name";
|
|
||||||
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
|
||||||
expect(actions.rename).toHaveBeenCalledWith(
|
|
||||||
"2026-07-19_1000-wurzel-doc.md",
|
|
||||||
"Neuer Name",
|
|
||||||
);
|
|
||||||
expect(openDoc).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Escape stellt die Zeile wieder her", () => {
|
|
||||||
const { view, actions } = setup();
|
|
||||||
view.set(page);
|
|
||||||
document.querySelector<HTMLElement>(".wiki-doc .cmd-edit")!.click();
|
|
||||||
const input = document.querySelector<HTMLInputElement>(".wiki-doc .wiki-tree-input")!;
|
|
||||||
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
|
||||||
expect(document.querySelector(".wiki-doc .wiki-doc-title")!.textContent).toBe(
|
|
||||||
"WURZEL-DOC",
|
|
||||||
);
|
|
||||||
expect(actions.rename).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Löschen meldet mit relpath, ohne das Dokument zu öffnen", () => {
|
|
||||||
const { view, actions, openDoc } = setup();
|
|
||||||
view.set(page);
|
|
||||||
document.querySelector<HTMLElement>(".wiki-doc .cmd-del")!.click();
|
|
||||||
expect(actions.remove).toHaveBeenCalledWith("2026-07-19_1000-wurzel-doc.md");
|
|
||||||
expect(openDoc).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Plus im Listenkopf: Formular legt Dokument im gewählten Ordner an", () => {
|
|
||||||
const { view, actions, openDoc } = setup();
|
|
||||||
view.set(page);
|
|
||||||
document.querySelectorAll<HTMLElement>(".wiki-tree .wiki-tree-name")[0].click();
|
|
||||||
document.querySelector<HTMLElement>(".wiki-head .wiki-add")!.click();
|
|
||||||
const form = document.querySelector<HTMLElement>(".wiki-form")!;
|
|
||||||
expect(form.querySelector(".wiki-form-title")!.textContent).toBe("Neues Dokument");
|
|
||||||
const input = form.querySelector<HTMLInputElement>("input")!;
|
|
||||||
input.value = "Deploy Notiz";
|
|
||||||
form.querySelector<HTMLElement>(".wiki-form-submit")!.click();
|
|
||||||
expect(actions.createDoc).toHaveBeenCalledWith("konzepte", "Deploy Notiz");
|
|
||||||
expect(document.querySelector(".wiki-form")).toBeNull();
|
|
||||||
expect(openDoc).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Abbrechen und Escape schließen das Formular ohne Aktion", () => {
|
|
||||||
const { view, actions } = setup();
|
|
||||||
view.set(page);
|
|
||||||
document.querySelector<HTMLElement>(".wiki-head .wiki-add")!.click();
|
|
||||||
document.querySelector<HTMLElement>(".wiki-form-cancel")!.click();
|
|
||||||
expect(document.querySelector(".wiki-form")).toBeNull();
|
|
||||||
|
|
||||||
document.querySelector<HTMLElement>(".wiki-head .wiki-add")!.click();
|
|
||||||
document
|
|
||||||
.querySelector<HTMLElement>(".wiki-form")!
|
|
||||||
.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
|
||||||
expect(document.querySelector(".wiki-form")).toBeNull();
|
|
||||||
expect(actions.createDoc).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Plus im Baum: Formular legt Ordner an, Pfad mit gewähltem Ordner vorbefüllt", () => {
|
|
||||||
const { view, actions } = setup();
|
|
||||||
view.set(page);
|
|
||||||
document.querySelectorAll<HTMLElement>(".wiki-tree .wiki-tree-name")[0].click();
|
|
||||||
document.querySelector<HTMLElement>(".wiki-tree-head .wiki-add")!.click();
|
|
||||||
const input = document.querySelector<HTMLInputElement>(".wiki-form input")!;
|
|
||||||
expect(input.value).toBe("konzepte/");
|
|
||||||
input.value = "konzepte/neu";
|
|
||||||
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
|
||||||
expect(actions.createFolder).toHaveBeenCalledWith("konzepte/neu");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("Ordner-Stift: Inline-Eingabe des Pfads, Enter meldet moveFolder", () => {
|
|
||||||
const { view, actions } = setup();
|
|
||||||
view.set(page);
|
|
||||||
const summary = document.querySelector<HTMLElement>(".wiki-tree summary")!;
|
|
||||||
summary.querySelector<HTMLElement>(".cmd-edit")!.click();
|
|
||||||
const input = summary.querySelector<HTMLInputElement>(".wiki-tree-input")!;
|
|
||||||
expect(input.value).toBe("konzepte");
|
|
||||||
input.value = "notizen/2026";
|
|
||||||
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
|
||||||
expect(actions.moveFolder).toHaveBeenCalledWith("konzepte", "notizen/2026");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("initWikiView — Leerzustände", () => {
|
|
||||||
it("leeres Archiv erklärt das Archivieren", () => {
|
|
||||||
const { view } = setup();
|
|
||||||
view.set(
|
|
||||||
JSON.stringify({
|
|
||||||
kind: "page",
|
|
||||||
home: "/a",
|
|
||||||
tag: null,
|
|
||||||
total: 0,
|
|
||||||
tags: [],
|
|
||||||
folders: [],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(document.querySelector(".wiki-empty")!.textContent).toContain(
|
|
||||||
"Das Archiv ist leer.",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("leerer Puffer bietet den Übersichts-Einstieg", () => {
|
|
||||||
const { view, openWiki } = setup();
|
|
||||||
view.set("");
|
|
||||||
expect(view.empty()).toBe(true);
|
|
||||||
document.querySelector<HTMLElement>(".wiki-empty .wiki-chip")!.click();
|
|
||||||
expect(openWiki).toHaveBeenCalledWith("tag:");
|
|
||||||
view.set(page);
|
|
||||||
expect(view.empty()).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,370 +0,0 @@
|
|||||||
/// Wiki-Ansicht des Panels: Ordner-Navigator übers Archiv. Links der Baum —
|
|
||||||
/// nur Ordner, oberster Knoten ist die Archiv-Wurzel; Klick auf einen Ordner
|
|
||||||
/// zeigt rechts die flache Liste seines direkten Inhalts. Klick auf eine
|
|
||||||
/// Dokumentzeile lädt das Dokument in den Dokument-Tab (wie ein
|
|
||||||
/// Suchtreffer); an der Zeile: umbenennen (inline) und löschen, am
|
|
||||||
/// Ordnerknoten: umbenennen. Titel, Beschreibungen und Pfade sind Fremdtext
|
|
||||||
/// und gehen nie durch innerHTML.
|
|
||||||
|
|
||||||
import { t } from "./messages";
|
|
||||||
import { deleteAction, editAction } from "./tiles";
|
|
||||||
|
|
||||||
interface DocEntry {
|
|
||||||
relpath: string;
|
|
||||||
name: string;
|
|
||||||
title: string;
|
|
||||||
description?: string | null;
|
|
||||||
tags: string[];
|
|
||||||
date?: string | null;
|
|
||||||
backlinks: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Folder {
|
|
||||||
name: string;
|
|
||||||
docs: DocEntry[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Page {
|
|
||||||
kind: "page";
|
|
||||||
home: string;
|
|
||||||
tag?: string | null;
|
|
||||||
total: number;
|
|
||||||
tags: { name: string; count: number }[];
|
|
||||||
folders: Folder[];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dokument-/Ordner-Operationen — laufen als Tauri-Commands, der neue Stand
|
|
||||||
/// kommt über den Wiki-Puffer zurück.
|
|
||||||
export interface WikiActions {
|
|
||||||
rename(relpath: string, name: string): void;
|
|
||||||
remove(relpath: string): void;
|
|
||||||
moveFolder(folder: string, to: string): void;
|
|
||||||
createFolder(folder: string): void;
|
|
||||||
createDoc(folder: string, name: string): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WikiCallbacks {
|
|
||||||
/// Dokument in den Dokument-Tab laden (absoluter Pfad, wie Suchtreffer).
|
|
||||||
openDoc(path: string): void;
|
|
||||||
/// Wiki-Ziel laden (`tag:` = Übersicht in den Puffer, Einstiegs-Chip).
|
|
||||||
openWiki(name: string): void;
|
|
||||||
actions: WikiActions;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WikiView {
|
|
||||||
set(text: string): void;
|
|
||||||
/// Noch keine Seite im Puffer (Session-Start)?
|
|
||||||
empty(): boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Verschachtelter Ordner-Knoten, aus den Ordnerpfaden gebaut.
|
|
||||||
interface TreeNode {
|
|
||||||
children: Map<string, TreeNode>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildTree(folders: Folder[]): TreeNode {
|
|
||||||
const root: TreeNode = { children: new Map() };
|
|
||||||
for (const folder of folders) {
|
|
||||||
if (!folder.name) continue;
|
|
||||||
let node = root;
|
|
||||||
for (const part of folder.name.split("/")) {
|
|
||||||
if (!node.children.has(part)) {
|
|
||||||
node.children.set(part, { children: new Map() });
|
|
||||||
}
|
|
||||||
node = node.children.get(part)!;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function initWikiView(container: HTMLElement, cb: WikiCallbacks): WikiView {
|
|
||||||
/// Zugeklappte Ordner und gewählter Ordner ("" = Wurzel) — überleben
|
|
||||||
/// Puffer-Updates innerhalb der Ansicht.
|
|
||||||
const closed = new Set<string>();
|
|
||||||
let selected = "";
|
|
||||||
let current: Page | null = null;
|
|
||||||
|
|
||||||
// ---------- Baum-Spalte (nur Ordner) ----------
|
|
||||||
|
|
||||||
function folderRow(name: string, full: string, node: TreeNode): HTMLElement {
|
|
||||||
const det = document.createElement("details");
|
|
||||||
det.className = "wiki-tree-folder";
|
|
||||||
det.open = !closed.has(full);
|
|
||||||
det.addEventListener("toggle", () => {
|
|
||||||
if (det.open) closed.delete(full);
|
|
||||||
else closed.add(full);
|
|
||||||
});
|
|
||||||
const sum = document.createElement("summary");
|
|
||||||
if (full === selected) sum.classList.add("active");
|
|
||||||
const label = document.createElement("span");
|
|
||||||
label.className = "wiki-tree-name";
|
|
||||||
label.textContent = name;
|
|
||||||
// Name wählt den Ordner aus (ohne zu klappen); der Pfeil davor klappt.
|
|
||||||
label.addEventListener("click", (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
select(full);
|
|
||||||
});
|
|
||||||
const rename = editAction(t("wiki.folderRename"), () => {
|
|
||||||
const input = document.createElement("input");
|
|
||||||
input.className = "wiki-tree-input";
|
|
||||||
input.value = full;
|
|
||||||
sum.replaceChildren(input);
|
|
||||||
input.focus();
|
|
||||||
input.select();
|
|
||||||
input.addEventListener("keydown", (e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
if (e.key === "Enter") {
|
|
||||||
cb.actions.moveFolder(full, input.value.trim());
|
|
||||||
} else if (e.key === "Escape") {
|
|
||||||
sum.replaceChildren(label, rename);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
input.addEventListener("click", (e) => e.preventDefault());
|
|
||||||
});
|
|
||||||
rename.addEventListener("click", (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
});
|
|
||||||
sum.append(label, rename);
|
|
||||||
det.append(sum, renderChildren(node, full));
|
|
||||||
return det;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderChildren(node: TreeNode, path: string): HTMLElement {
|
|
||||||
const box = document.createElement("div");
|
|
||||||
box.className = "wiki-tree-children";
|
|
||||||
for (const [name, child] of [...node.children].sort((a, b) =>
|
|
||||||
a[0].localeCompare(b[0]),
|
|
||||||
)) {
|
|
||||||
box.append(folderRow(name, path ? `${path}/${name}` : name, child));
|
|
||||||
}
|
|
||||||
return box;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderTree(p: Page): HTMLElement {
|
|
||||||
const aside = document.createElement("aside");
|
|
||||||
aside.className = "wiki-tree";
|
|
||||||
const head = document.createElement("div");
|
|
||||||
head.className = "wiki-tree-head";
|
|
||||||
const root = document.createElement("button");
|
|
||||||
root.className = "wiki-tree-root" + (selected === "" ? " active" : "");
|
|
||||||
root.textContent = t("wiki.archive");
|
|
||||||
root.addEventListener("click", () => select(""));
|
|
||||||
const add = document.createElement("button");
|
|
||||||
add.className = "wiki-add";
|
|
||||||
add.title = t("wiki.newFolder");
|
|
||||||
add.textContent = "+";
|
|
||||||
add.addEventListener("click", () =>
|
|
||||||
openForm(t("wiki.newFolder"), t("wiki.folderPath"), selected ? `${selected}/` : "", (v) =>
|
|
||||||
cb.actions.createFolder(v),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
head.append(root, add);
|
|
||||||
aside.append(head, renderChildren(buildTree(p.folders), ""));
|
|
||||||
return aside;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- Anlege-Formular (Ordner/Dokument) ----------
|
|
||||||
|
|
||||||
/// Kleines Formular oben in der Liste: ein Textfeld, Anlegen/Abbrechen;
|
|
||||||
/// Enter legt an, Escape schließt. Leere oder ungültige Eingaben meldet
|
|
||||||
/// das Backend als Toast.
|
|
||||||
function openForm(
|
|
||||||
title: string,
|
|
||||||
placeholder: string,
|
|
||||||
initial: string,
|
|
||||||
onSubmit: (value: string) => void,
|
|
||||||
) {
|
|
||||||
const main = container.querySelector<HTMLElement>(".wiki-main")!;
|
|
||||||
main.querySelector(".wiki-form")?.remove();
|
|
||||||
const form = document.createElement("div");
|
|
||||||
form.className = "wiki-form";
|
|
||||||
const caption = document.createElement("div");
|
|
||||||
caption.className = "wiki-form-title";
|
|
||||||
caption.textContent = title;
|
|
||||||
const input = document.createElement("input");
|
|
||||||
input.className = "wiki-tree-input";
|
|
||||||
input.placeholder = placeholder;
|
|
||||||
input.value = initial;
|
|
||||||
const submit = document.createElement("button");
|
|
||||||
submit.className = "wiki-form-submit";
|
|
||||||
submit.textContent = t("wiki.create");
|
|
||||||
const cancel = document.createElement("button");
|
|
||||||
cancel.className = "wiki-form-cancel";
|
|
||||||
cancel.textContent = t("wiki.cancel");
|
|
||||||
const fire = () => {
|
|
||||||
const value = input.value.trim();
|
|
||||||
form.remove();
|
|
||||||
onSubmit(value);
|
|
||||||
};
|
|
||||||
submit.addEventListener("click", fire);
|
|
||||||
cancel.addEventListener("click", () => form.remove());
|
|
||||||
form.addEventListener("keydown", (e) => {
|
|
||||||
if (e.key === "Enter") fire();
|
|
||||||
else if (e.key === "Escape") form.remove();
|
|
||||||
});
|
|
||||||
form.append(caption, input, submit, cancel);
|
|
||||||
main.querySelector(".wiki-head")!.after(form);
|
|
||||||
input.focus();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- Liste rechts: direkter Ordnerinhalt ----------
|
|
||||||
|
|
||||||
function docRow(p: Page, doc: DocEntry): HTMLElement {
|
|
||||||
const row = document.createElement("div");
|
|
||||||
row.className = "wiki-doc";
|
|
||||||
const line = document.createElement("div");
|
|
||||||
line.className = "wiki-doc-line";
|
|
||||||
const title = document.createElement("div");
|
|
||||||
title.className = "wiki-doc-title";
|
|
||||||
title.textContent = doc.title;
|
|
||||||
line.append(title);
|
|
||||||
if (doc.backlinks) {
|
|
||||||
const back = document.createElement("div");
|
|
||||||
back.className = "wiki-doc-back";
|
|
||||||
back.title = t("wiki.backlinks");
|
|
||||||
back.textContent = `↩ ${doc.backlinks}`;
|
|
||||||
line.append(back);
|
|
||||||
}
|
|
||||||
if (doc.date) {
|
|
||||||
const date = document.createElement("div");
|
|
||||||
date.className = "wiki-doc-date";
|
|
||||||
date.textContent = doc.date;
|
|
||||||
line.append(date);
|
|
||||||
}
|
|
||||||
const acts = document.createElement("div");
|
|
||||||
acts.className = "wiki-doc-actions";
|
|
||||||
const rename = editAction(t("wiki.renameDoc"), () => {
|
|
||||||
const input = document.createElement("input");
|
|
||||||
input.className = "wiki-tree-input";
|
|
||||||
input.value = doc.name;
|
|
||||||
row.replaceChildren(input);
|
|
||||||
input.focus();
|
|
||||||
input.select();
|
|
||||||
input.addEventListener("keydown", (e) => {
|
|
||||||
if (e.key === "Enter") {
|
|
||||||
cb.actions.rename(doc.relpath, input.value);
|
|
||||||
} else if (e.key === "Escape" && current) {
|
|
||||||
renderMain(current);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
input.addEventListener("click", (e) => e.stopPropagation());
|
|
||||||
});
|
|
||||||
acts.append(rename, deleteAction(t("wiki.deleteDoc"), () => cb.actions.remove(doc.relpath)));
|
|
||||||
for (const btn of acts.querySelectorAll("button")) {
|
|
||||||
btn.addEventListener("click", (e) => e.stopPropagation());
|
|
||||||
}
|
|
||||||
line.append(acts);
|
|
||||||
row.append(line);
|
|
||||||
if (doc.description) {
|
|
||||||
const desc = document.createElement("div");
|
|
||||||
desc.className = "wiki-doc-desc";
|
|
||||||
desc.textContent = doc.description;
|
|
||||||
row.append(desc);
|
|
||||||
}
|
|
||||||
row.addEventListener("click", () => cb.openDoc(`${p.home}/${doc.relpath}`));
|
|
||||||
return row;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderMain(p: Page) {
|
|
||||||
const main = container.querySelector<HTMLElement>(".wiki-main")!;
|
|
||||||
main.textContent = "";
|
|
||||||
const docs = p.folders.find((f) => f.name === selected)?.docs ?? [];
|
|
||||||
|
|
||||||
const head = document.createElement("div");
|
|
||||||
head.className = "wiki-head";
|
|
||||||
const left = document.createElement("div");
|
|
||||||
left.className = "wiki-head-left";
|
|
||||||
const title = document.createElement("div");
|
|
||||||
title.className = "wiki-head-title";
|
|
||||||
title.textContent = selected ? selected.split("/").pop()! : t("wiki.archive");
|
|
||||||
const sub = document.createElement("div");
|
|
||||||
sub.className = "wiki-head-sub";
|
|
||||||
sub.textContent = selected ? `${p.home}/${selected}` : p.home;
|
|
||||||
left.append(title, sub);
|
|
||||||
const count = document.createElement("div");
|
|
||||||
count.className = "wiki-head-right";
|
|
||||||
count.textContent = t(docs.length === 1 ? "wiki.docOne" : "wiki.docMany", {
|
|
||||||
count: docs.length,
|
|
||||||
});
|
|
||||||
const add = document.createElement("button");
|
|
||||||
add.className = "wiki-add";
|
|
||||||
add.title = t("wiki.newDoc");
|
|
||||||
add.textContent = "+";
|
|
||||||
add.addEventListener("click", () =>
|
|
||||||
openForm(t("wiki.newDoc"), t("wiki.docName"), "", (v) =>
|
|
||||||
cb.actions.createDoc(selected, v),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
head.append(left, count, add);
|
|
||||||
main.append(head);
|
|
||||||
|
|
||||||
if (docs.length === 0) {
|
|
||||||
const empty = document.createElement("div");
|
|
||||||
empty.className = "wiki-empty";
|
|
||||||
const line = document.createElement("strong");
|
|
||||||
line.textContent = p.total === 0 ? t("wiki.emptyArchive") : t("wiki.emptyFolder");
|
|
||||||
empty.append(line);
|
|
||||||
if (p.total === 0) empty.append(t("wiki.emptyHint"));
|
|
||||||
main.append(empty);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for (const doc of docs) main.append(docRow(p, doc));
|
|
||||||
}
|
|
||||||
|
|
||||||
function select(folder: string) {
|
|
||||||
selected = folder;
|
|
||||||
if (current) render(current);
|
|
||||||
}
|
|
||||||
|
|
||||||
function render(p: Page) {
|
|
||||||
container.textContent = "";
|
|
||||||
const layout = document.createElement("div");
|
|
||||||
layout.className = "wiki-layout";
|
|
||||||
const main = document.createElement("div");
|
|
||||||
main.className = "wiki-main";
|
|
||||||
layout.append(renderTree(p), main);
|
|
||||||
container.append(layout);
|
|
||||||
renderMain(p);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Leerer Puffer: Einstieg statt leerer Fläche.
|
|
||||||
function renderIntro() {
|
|
||||||
const empty = document.createElement("div");
|
|
||||||
empty.className = "wiki-empty";
|
|
||||||
const line = document.createElement("strong");
|
|
||||||
line.textContent = t("wiki.noPage");
|
|
||||||
empty.append(line);
|
|
||||||
const open = document.createElement("button");
|
|
||||||
open.className = "wiki-chip";
|
|
||||||
open.textContent = t("wiki.openOverview");
|
|
||||||
open.addEventListener("click", () => cb.openWiki("tag:"));
|
|
||||||
empty.append(open);
|
|
||||||
container.append(empty);
|
|
||||||
}
|
|
||||||
|
|
||||||
let loaded = false;
|
|
||||||
return {
|
|
||||||
set(text: string) {
|
|
||||||
container.textContent = "";
|
|
||||||
loaded = !!text.trim();
|
|
||||||
if (!loaded) {
|
|
||||||
current = null;
|
|
||||||
renderIntro();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
current = JSON.parse(text);
|
|
||||||
// Der gewählte Ordner kann nach Umbenennen/Löschen weg sein — dann
|
|
||||||
// zurück zur Wurzel. Zwischenordner (nur Unterordner, keine eigenen
|
|
||||||
// Dokumente) bleiben wählbar.
|
|
||||||
const exists = current!.folders.some(
|
|
||||||
(f) => f.name === selected || f.name.startsWith(`${selected}/`),
|
|
||||||
);
|
|
||||||
if (selected && !exists) {
|
|
||||||
selected = "";
|
|
||||||
}
|
|
||||||
render(current!);
|
|
||||||
},
|
|
||||||
empty: () => !loaded,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
+2
-28
@@ -27,10 +27,10 @@
|
|||||||
<div id="term"></div>
|
<div id="term"></div>
|
||||||
<div id="splitter" hidden></div>
|
<div id="splitter" hidden></div>
|
||||||
<aside id="panel" hidden>
|
<aside id="panel" hidden>
|
||||||
|
<!-- Modul-Container (<mode>-content) reihen sich hinter der Kopfzeile ein. -->
|
||||||
<div class="panel-head">
|
<div class="panel-head">
|
||||||
<div class="panel-titlerow">
|
<div class="panel-titlerow">
|
||||||
<span class="panel-title" data-i18n="panel.tabDraft">Dokument</span>
|
<span class="panel-title"></span>
|
||||||
<button class="panel-btn panel-edit draft-only" id="panel-title-edit" data-i18n-title="panel.editTitle">✎</button>
|
|
||||||
<button class="panel-btn" id="panel-detach" data-i18n-title="panel.detach">
|
<button class="panel-btn" id="panel-detach" data-i18n-title="panel.detach">
|
||||||
<svg width="14" height="14" viewBox="0 0 16 16"><path d="M12.5 8.5V13a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4.5a1 1 0 0 1 1-1h4.5" /><path d="M10 2h4v4" /><path d="M14 2 8 8" /></svg>
|
<svg width="14" height="14" viewBox="0 0 16 16"><path d="M12.5 8.5V13a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4.5a1 1 0 0 1 1-1h4.5" /><path d="M10 2h4v4" /><path d="M14 2 8 8" /></svg>
|
||||||
</button>
|
</button>
|
||||||
@@ -38,33 +38,7 @@
|
|||||||
<svg width="12" height="12" viewBox="0 0 12 12"><path d="M3 3l6 6M9 3l-6 6" /></svg>
|
<svg width="12" height="12" viewBox="0 0 12 12"><path d="M3 3l6 6M9 3l-6 6" /></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="panel-actions">
|
|
||||||
<select class="panel-lang draft-only" id="panel-lang" data-i18n-title="panel.spellcheckLang">
|
|
||||||
<option value="de">DE</option>
|
|
||||||
<option value="en">EN</option>
|
|
||||||
<option value="en-GB">EN-GB</option>
|
|
||||||
<option value="fr">FR</option>
|
|
||||||
<option value="es">ES</option>
|
|
||||||
<option value="it">IT</option>
|
|
||||||
<option value="nl">NL</option>
|
|
||||||
</select>
|
|
||||||
<button class="panel-btn draft-only" id="panel-wiki-jump" data-i18n-title="panel.openInWiki">
|
|
||||||
<svg width="14" height="14" viewBox="0 0 16 16"><path d="M8 3.5C6.6 2.4 4.6 2 2.5 2v11c2.1 0 4.1.4 5.5 1.5 1.4-1.1 3.4-1.5 5.5-1.5V2c-2.1 0-4.1.4-5.5 1.5z" /><path d="M8 3.5v11" /></svg>
|
|
||||||
</button>
|
|
||||||
<button class="panel-btn draft-only" id="panel-mode" data-i18n-title="panel.toggleRaw" data-i18n="panel.rendered">MD</button>
|
|
||||||
<button class="panel-btn draft-only" id="panel-content-edit" data-i18n-title="panel.editDraft">
|
|
||||||
<svg width="14" height="14" viewBox="0 0 16 16"><path d="M10.8 2.6 13.4 5.2 6 12.6l-3.1.5.5-3.1z" /><path d="M9.7 3.7 12.3 6.3" /></svg>
|
|
||||||
</button>
|
|
||||||
<button class="panel-btn draft-only" id="panel-copy" data-i18n-title="panel.copy">
|
|
||||||
<svg width="14" height="14" viewBox="0 0 16 16"><rect x="5.5" y="5.5" width="8" height="8" rx="1.5" /><path d="M10.5 3.2V3A1.5 1.5 0 0 0 9 1.5H3A1.5 1.5 0 0 0 1.5 3v6A1.5 1.5 0 0 0 3 10.5h.2" /></svg>
|
|
||||||
</button>
|
|
||||||
<button class="panel-btn draft-only" id="panel-archive" data-i18n-title="panel.archive">
|
|
||||||
<svg width="14" height="14" viewBox="0 0 16 16"><rect x="1.5" y="2.5" width="13" height="3.5" rx="1" /><path d="M2.8 6v6.5a1 1 0 0 0 1 1h8.4a1 1 0 0 0 1-1V6" /><path d="M6.3 9h3.4" /></svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<!-- Modul-Container (<mode>-content) reihen sich hier ein. -->
|
|
||||||
<div id="panel-content" class="md"></div>
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
<div id="resize-grips" aria-hidden="true">
|
<div id="resize-grips" aria-hidden="true">
|
||||||
|
|||||||
Reference in New Issue
Block a user