Compare commits
11 Commits
alpha-v202
...
stable-v20
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4c6bb6c57 | ||
|
|
35dd2dd47b | ||
|
|
89141bae14 | ||
|
|
2b9294f884 | ||
|
|
a756af54ec | ||
|
|
b01b156dfb | ||
|
|
2c9361d704 | ||
|
|
cea71a4fd9 | ||
|
|
8b73ef5836 | ||
|
|
a6a727a4c0 | ||
|
|
bf13eed3ab |
@@ -1,2 +1,2 @@
|
||||
HOTSPOT_THRESHOLD=9.9
|
||||
AVERAGE_THRESHOLD=9.79
|
||||
HOTSPOT_THRESHOLD=9.94
|
||||
AVERAGE_THRESHOLD=9.81
|
||||
|
||||
@@ -153,7 +153,7 @@ Type is determined **purely** from the `type:` frontmatter field — it is never
|
||||
└── type/ ← type definition documents
|
||||
```
|
||||
|
||||
New notes are created at the vault root: `{vault}/{slug}.md`. Changing a note's type only requires updating the `type:` field in frontmatter — the file does not move. The `type/` folder exists solely for type definition documents. Legacy `config/` content is still recognized during migration and repair, but Tolaria's managed AI guidance now lives at the vault root.
|
||||
New notes are created at the vault root: `{vault}/{slug}.md`. Changing a note's type only requires updating the `type:` field in frontmatter — the file does not move. Moving a note into a user folder is a separate filesystem concern: the folder path changes, but the note keeps the same filename and `type:` value. The `type/` folder exists solely for type definition documents. Legacy `config/` content is still recognized during migration and repair, but Tolaria's managed AI guidance now lives at the vault root.
|
||||
|
||||
A `flatten_vault` migration command is available to move existing notes from type-based subfolders to the vault root.
|
||||
|
||||
@@ -270,6 +270,7 @@ type SidebarSelection =
|
||||
|
||||
- `FolderTree` keeps the folder interaction surface decomposed into `FolderTreeRow`, `FolderNameInput`, `FolderContextMenu`, and disclosure/context-menu hooks so nested row rendering, inline rename, and right-click actions stay isolated.
|
||||
- `useFolderActions()` composes `useFolderRename()` and `useFolderDelete()` to keep folder mutations selection-aware while the rest of `App.tsx` only wires the resulting callbacks into `Sidebar` and the command registry.
|
||||
- `useNoteRetargeting()` is the shared retargeting abstraction for note drops and command-palette actions. It owns the "can drop here?" checks, updates `type:` via frontmatter when a note lands on a type section, and delegates folder moves through the same crash-safe rename pipeline used by the backend rename commands.
|
||||
- A successful folder rename reloads the folder tree plus vault entries, rewrites any affected folder-scoped tabs, and updates `SidebarSelection` to the new relative path when the renamed folder stays selected.
|
||||
- Folder deletion clears pending rename state, confirms destructive intent, drops affected folder-scoped tabs, reloads vault data, and resets folder selection if the deleted subtree owned the current selection.
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ flowchart TD
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- **Sidebar** (150-400px, resizable): Top-level filters (All Notes, Changes, Pulse), collapsible type-based section groups, and a dedicated folder tree. The folder tree supports inline folder creation and rename, exposes a right-click menu for rename/delete, and auto-expands ancestor folders when the current selection or rename target is nested. Each type can have a custom icon, color, sort, and visibility set via its type document in `type/`.
|
||||
- **Sidebar** (150-400px, resizable): Top-level filters (All Notes, Changes, Pulse), collapsible type-based section groups, and a dedicated folder tree. The folder tree supports inline folder creation and rename, exposes a right-click menu for rename/delete, and auto-expands ancestor folders when the current selection or rename target is nested. Type sections and folder rows also act as note drop targets: dropping a note on a type updates its `type:` frontmatter, while dropping it on a folder runs the same crash-safe move path as the command palette flow. Each type can have a custom icon, color, sort, and visibility set via its type document in `type/`.
|
||||
- **Note List / Pulse View** (200-500px, resizable): When a section group, filter, or saved view is selected, shows filtered notes with snippets, modified dates, status indicators, and per-context note-list controls. When `selection.kind === 'entity'`, the same pane enters **Neighborhood** mode: the source note is pinned at the top as a normal active row, outgoing relationship groups render first, inverse/backlink groups follow, empty groups stay visible with `0`, and duplicates across groups are allowed when multiple relationships are true. Plain click / `Enter` open the focused note without replacing the current Neighborhood, while Cmd/Ctrl-click and Cmd/Ctrl-`Enter` pivot the pane into the clicked note's Neighborhood. Saved views reuse the same sort and visible-column controls as the built-in lists, and those changes persist back into the view `.yml` definition (`sort`, `listPropertiesDisplay`). When Pulse filter is active, shows `PulseView` — a chronological git activity feed grouped by day.
|
||||
- **Editor** (flex, fills remaining space): Single note open at a time (no tabs — see ADR-0003). Breadcrumb bar with word count, BlockNote rich text editor with wikilink support, markdown-safe formatting controls, and schema-backed fenced code block highlighting via `@blocknote/code-block`. Can toggle to diff view (modified files) or raw CodeMirror view. Decomposed into `Editor` (orchestrator), `EditorContent`, `EditorRightPanel`, `SingleEditorView`, with hooks `useDiffMode`, `useEditorFocus`, and `useEditorSave`, plus the `useRawMode`/`RawEditorView` pair for markdown source editing. Navigation history (Cmd+[/]) replaces tabs.
|
||||
- **Inspector / AI Agent** (200-500px or 40px collapsed): Toggles between Inspector (frontmatter, relationships, instances, backlinks, git history) and AI Agent panel (the selected CLI agent with tool execution). The Sparkle icon in the breadcrumb bar toggles between them. Per-note `icon` is a suggested Inspector property and the command palette's "Set Note Icon" action opens that field directly. When viewing a Type note, the Inspector shows an **Instances** section listing all notes of that type (sorted by modified_at desc, capped at 50).
|
||||
@@ -586,7 +586,7 @@ The vault backend (`src-tauri/src/vault/`) is split into focused submodules:
|
||||
| `parsing.rs` | Text processing: snippet extraction, markdown stripping, ISO date parsing, `extract_title` (H1 → legacy frontmatter → filename), `slug_to_title` |
|
||||
| `title_sync.rs` | Legacy filename → `title` frontmatter sync helper; no longer used by the normal note-open flow |
|
||||
| `cache.rs` | Git-based incremental vault caching (`scan_vault_cached`), git helpers |
|
||||
| `rename.rs` | `rename_note` / `rename_note_filename` — stage crash-safe file renames, update `title` frontmatter, recover unfinished rename transactions, and report backlink rewrite failures |
|
||||
| `rename.rs` | `rename_note` / `rename_note_filename` / `move_note_to_folder` — stage crash-safe file moves, update `title` frontmatter when needed, recover unfinished rename transactions, and report backlink rewrite failures |
|
||||
| `image.rs` | `save_image` — saves base64-encoded attachments with sanitized filenames |
|
||||
| `migration.rs` | `flatten_vault`, `vault_health_check`, `migrate_is_a_to_type` |
|
||||
| `config_seed.rs` | Maintains vault AI guidance (`AGENTS.md` + `CLAUDE.md` shim), migrates legacy `config/agents.md`, and repairs missing root type scaffolding such as `type.md` and `note.md` |
|
||||
@@ -620,6 +620,7 @@ The vault backend (`src-tauri/src/vault/`) is split into focused submodules:
|
||||
| `save_note_content` | Write note content to disk |
|
||||
| `delete_note` | Permanently delete note from disk (with confirm dialog) |
|
||||
| `rename_note` | Crash-safe note rename + `title` frontmatter update + cross-vault wikilinks + failed backlink counts |
|
||||
| `move_note_to_folder` | Crash-safe folder move that preserves the filename, reloads the moved note, and rewrites path-based wikilinks |
|
||||
| `create_vault_folder` | Create a folder relative to the active vault root |
|
||||
| `rename_vault_folder` | Rename a folder relative to the active vault root and return old/new relative paths |
|
||||
| `delete_vault_folder` | Permanently delete a folder subtree relative to the active vault root |
|
||||
@@ -737,7 +738,8 @@ No Redux or global context. State lives in the root `App.tsx` and custom hooks:
|
||||
| `useVaultLoader` | `entries`, `allContent`, `modifiedFiles` | Vault data |
|
||||
| `useNoteActions` | `tabs`, `activeTabPath` | Composes `useNoteCreation` + `useNoteRename` + `frontmatterOps` |
|
||||
| `useNoteCreation` | — | Note/type creation with optimistic persistence |
|
||||
| `useNoteRename` | — | Note renaming with wikilink update |
|
||||
| `useNoteRename` | — | Note renaming and folder moves with wikilink update |
|
||||
| `useNoteRetargeting` | — | Shared note retargeting logic for drag/drop and command-palette actions |
|
||||
| `frontmatterOps` | — (pure functions) | Frontmatter CRUD: key→VaultEntry mapping, mock/Tauri dispatch |
|
||||
| `useTabManagement` | Navigation history, note switching | Note navigation lifecycle |
|
||||
| `useVaultSwitcher` | `vaultPath`, `extraVaults` | Vault switching |
|
||||
@@ -768,7 +770,7 @@ Data flows unidirectionally: `App` passes data and callbacks as props to child c
|
||||
| Cmd+[ / Cmd+] | Navigate back / forward |
|
||||
| `[[` in editor | Open wikilink suggestion menu |
|
||||
|
||||
Selection-dependent actions are wired through the command palette and the native menus. For example, a deleted file opened from Changes view becomes a read-only diff preview, and that state enables the "Restore Deleted Note" menu/command while normal note mutation actions stay disabled. Folder selection follows the same pattern: when `selection.kind === 'folder'`, the command palette exposes "Rename Folder" and "Delete Folder", and the sidebar row can launch the same flows directly through inline rename or the folder context menu.
|
||||
Selection-dependent actions are wired through the command palette and the native menus. For example, a deleted file opened from Changes view becomes a read-only diff preview, and that state enables the "Restore Deleted Note" menu/command while normal note mutation actions stay disabled. Folder selection follows the same pattern: when `selection.kind === 'folder'`, the command palette exposes "Rename Folder" and "Delete Folder", and the sidebar row can launch the same flows directly through inline rename or the folder context menu. Active notes now follow the same shared-action model for retargeting: Cmd+K can open "Change Note Type…" and "Move Note to Folder…", and the sidebar drop targets call the same hook-backed implementations instead of maintaining separate mutation paths.
|
||||
|
||||
Shortcut routing is explicit:
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
type: ADR
|
||||
id: "0076"
|
||||
title: "Note retargeting separates type changes from folder moves"
|
||||
status: active
|
||||
date: 2026-04-22
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
ADR-0025 made `type:` the canonical classification field, and ADR-0033 reopened subfolders as a valid way to organize files in the vault. Once Tolaria exposed both type sections and the folder tree in the sidebar, note reorganization had an unresolved ambiguity: does retargeting a note mean changing its semantic type, moving its file, or both?
|
||||
|
||||
Without an explicit model, drag-and-drop and command-palette flows would need to duplicate their own validation and persistence logic, and Tolaria could easily drift back toward the old type-folder coupling that ADR-0006 deliberately removed.
|
||||
|
||||
## Decision
|
||||
|
||||
**Tolaria treats note retargeting as one shared interaction model with two distinct mutation paths: types change metadata, folders change file paths.**
|
||||
|
||||
- Retargeting a note to a type updates only the note's `type:` frontmatter. The file stays where it is.
|
||||
- Retargeting a note to a folder preserves the current filename and `type:` value, and moves the file through the same crash-safe rename transaction pipeline used for backend rename commands.
|
||||
- Drag/drop targets and command-palette actions both route through the same frontend retargeting abstraction so validation, dialogs, collision handling, and success/error behavior stay consistent.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Shared retargeting model with separate type-vs-folder semantics** (chosen): preserves ADR-0025/ADR-0006's decoupling of type from path, lets folder moves reuse ADR-0075's crash-safe rename guarantees, and keeps multiple UI surfaces behaviorally aligned.
|
||||
- **Treat folders as the source of truth for note type**: simpler mental model for some vaults, but it reintroduces path-based type inference and makes type changes depend on file moves again.
|
||||
- **Implement drag/drop and command-palette retargeting as separate flows**: lower short-term coordination cost, but it duplicates mutation rules and makes consistency regressions likely.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Type sections are semantic targets only; they must never imply a filesystem move.
|
||||
- Folder targets are physical move operations; they must preserve filename/title behavior, reject collisions, and rewrite path-based wikilinks through the shared rename pipeline.
|
||||
- Future note-retargeting surfaces should reuse the shared retargeting abstraction instead of introducing another mutation path.
|
||||
- Re-evaluate this ADR if Tolaria later supports bulk retargeting, folder rules that intentionally infer type, or another organization primitive that needs different semantics.
|
||||
@@ -130,3 +130,5 @@ proposed → active → superseded
|
||||
| [0072](0072-confirmed-vault-paths-gate-startup-state.md) | Confirmed vault paths gate startup state | active |
|
||||
| [0073](0073-persistent-linkify-protocol-registry-across-editor-remounts.md) | Persistent linkify protocol registry across editor remounts | active |
|
||||
| [0074](0074-explicit-external-ai-tool-setup-and-least-privilege-desktop-scope.md) | Explicit external AI tool setup and least-privilege desktop scope | active |
|
||||
| [0075](0075-crash-safe-note-rename-transactions.md) | Crash-safe note rename transactions | active |
|
||||
| [0076](0076-note-retargeting-separates-type-and-folder-moves.md) | Note retargeting separates type changes from folder moves | active |
|
||||
|
||||
@@ -139,6 +139,22 @@ mod tests {
|
||||
assert_eq!(err, ACTIVE_VAULT_PATH_ERROR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_note_content_rejects_traversal_outside_active_vault() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let vault_path = dir.path();
|
||||
let escape_path = vault_path.join("../outside.md");
|
||||
|
||||
let err = create_note_content(
|
||||
escape_path,
|
||||
"# Outside\n".to_string(),
|
||||
vault_path_arg(vault_path),
|
||||
)
|
||||
.expect_err("expected traversal create to be rejected");
|
||||
|
||||
assert_eq!(err, ACTIVE_VAULT_PATH_ERROR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_vault_folder_rejects_escape_path() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
|
||||
@@ -39,6 +39,22 @@ fn with_requested_root_path<T>(
|
||||
with_requested_root(raw_vault_path.as_ref(), action)
|
||||
}
|
||||
|
||||
fn with_writable_note_path<T>(
|
||||
path: PathBuf,
|
||||
vault_path: Option<PathBuf>,
|
||||
action: impl FnOnce(&str) -> Result<T, String>,
|
||||
) -> Result<T, String> {
|
||||
with_validated_path(
|
||||
path.to_string_lossy().as_ref(),
|
||||
vault_path
|
||||
.as_ref()
|
||||
.map(|value| value.to_string_lossy())
|
||||
.as_deref(),
|
||||
ValidatedPathMode::Writable,
|
||||
action,
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_note_content(path: PathBuf, vault_path: Option<PathBuf>) -> Result<String, String> {
|
||||
with_note_path(
|
||||
@@ -55,15 +71,20 @@ pub fn save_note_content(
|
||||
content: String,
|
||||
vault_path: Option<PathBuf>,
|
||||
) -> Result<(), String> {
|
||||
with_validated_path(
|
||||
path.to_string_lossy().as_ref(),
|
||||
vault_path
|
||||
.as_ref()
|
||||
.map(|value| value.to_string_lossy())
|
||||
.as_deref(),
|
||||
ValidatedPathMode::Writable,
|
||||
|validated_path| vault::save_note_content(validated_path, &content),
|
||||
)
|
||||
with_writable_note_path(path, vault_path, |validated_path| {
|
||||
vault::save_note_content(validated_path, &content)
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn create_note_content(
|
||||
path: PathBuf,
|
||||
content: String,
|
||||
vault_path: Option<PathBuf>,
|
||||
) -> Result<(), String> {
|
||||
with_writable_note_path(path, vault_path, |validated_path| {
|
||||
vault::create_note_content(validated_path, &content)
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::commands::expand_tilde;
|
||||
use crate::vault::{self, DetectedRename, RenameResult};
|
||||
use std::path::Path;
|
||||
|
||||
use super::boundary::with_existing_path_in_requested_vault;
|
||||
use super::boundary::{
|
||||
with_existing_path_in_requested_vault, with_validated_path, ValidatedPathMode,
|
||||
};
|
||||
|
||||
#[tauri::command]
|
||||
pub fn rename_note(
|
||||
@@ -39,6 +42,42 @@ pub fn rename_note_filename(
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn move_note_to_folder(
|
||||
vault_path: String,
|
||||
old_path: String,
|
||||
folder_path: String,
|
||||
) -> Result<RenameResult, String> {
|
||||
with_existing_path_in_requested_vault(
|
||||
&vault_path,
|
||||
&old_path,
|
||||
|requested_root, validated_path| {
|
||||
let trimmed_folder_path = folder_path.trim();
|
||||
if trimmed_folder_path.is_empty() {
|
||||
return Err("Folder path cannot be empty".to_string());
|
||||
}
|
||||
|
||||
let folder_absolute_path = Path::new(requested_root).join(trimmed_folder_path);
|
||||
with_validated_path(
|
||||
folder_absolute_path.to_string_lossy().as_ref(),
|
||||
Some(&vault_path),
|
||||
ValidatedPathMode::Existing,
|
||||
|validated_folder_path| {
|
||||
let validated_folder = Path::new(validated_folder_path);
|
||||
if !validated_folder.is_dir() {
|
||||
return Err(format!("Folder does not exist: {}", trimmed_folder_path));
|
||||
}
|
||||
vault::move_note_to_folder(
|
||||
requested_root,
|
||||
validated_path,
|
||||
validated_folder_path,
|
||||
)
|
||||
},
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn auto_rename_untitled(
|
||||
vault_path: String,
|
||||
|
||||
@@ -196,11 +196,13 @@ macro_rules! app_invoke_handler {
|
||||
commands::list_vault,
|
||||
commands::list_vault_folders,
|
||||
commands::get_note_content,
|
||||
commands::create_note_content,
|
||||
commands::save_note_content,
|
||||
commands::update_frontmatter,
|
||||
commands::delete_frontmatter_property,
|
||||
commands::rename_note,
|
||||
commands::rename_note_filename,
|
||||
commands::move_note_to_folder,
|
||||
commands::auto_rename_untitled,
|
||||
commands::detect_renames,
|
||||
commands::update_wikilinks_for_renames,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use std::fs;
|
||||
use std::io::{ErrorKind, Write};
|
||||
use std::path::Path;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
@@ -63,3 +64,25 @@ pub fn save_note_content(path: &str, content: &str) -> Result<(), String> {
|
||||
validate_save_path(file_path, path)?;
|
||||
fs::write(file_path, content).map_err(|e| format!("Failed to save {}: {}", path, e))
|
||||
}
|
||||
|
||||
/// Create a new note file without overwriting any existing file.
|
||||
pub fn create_note_content(path: &str, content: &str) -> Result<(), String> {
|
||||
let file_path = Path::new(path);
|
||||
if let Some(parent) = file_path.parent() {
|
||||
if !parent.exists() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|e| format!("Failed to create directory {}: {}", parent.display(), e))?;
|
||||
}
|
||||
}
|
||||
validate_save_path(file_path, path)?;
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(file_path)
|
||||
.map_err(|e| match e.kind() {
|
||||
ErrorKind::AlreadyExists => format!("File already exists: {}", path),
|
||||
_ => format!("Failed to create {}: {}", path, e),
|
||||
})?;
|
||||
file.write_all(content.as_bytes())
|
||||
.map_err(|e| format!("Failed to save {}: {}", path, e))
|
||||
}
|
||||
|
||||
@@ -20,13 +20,13 @@ pub use config_seed::{
|
||||
seed_config_files, AiGuidanceFileState, VaultAiGuidanceStatus,
|
||||
};
|
||||
pub use entry::{FolderNode, VaultEntry};
|
||||
pub use file::{get_note_content, save_note_content};
|
||||
pub use file::{create_note_content, get_note_content, save_note_content};
|
||||
pub use folders::{delete_folder, rename_folder, FolderRenameResult};
|
||||
pub use getting_started::{create_getting_started_vault, default_vault_path, vault_exists};
|
||||
pub use image::{copy_image_to_vault, save_image};
|
||||
pub use migration::migrate_is_a_to_type;
|
||||
pub use rename::{
|
||||
auto_rename_untitled, detect_renames, rename_note, rename_note_filename,
|
||||
auto_rename_untitled, detect_renames, move_note_to_folder, rename_note, rename_note_filename,
|
||||
update_wikilinks_for_renames, DetectedRename, RenameResult,
|
||||
};
|
||||
pub use title_sync::{sync_title_on_open, SyncAction};
|
||||
|
||||
@@ -165,3 +165,29 @@ fn test_save_note_content_deeply_nested_new_directory() {
|
||||
assert!(path.exists());
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), content);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_note_content_creates_parent_directory() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let path = dir.path().join("new-type/briefing.md");
|
||||
let content = "---\ntitle: Briefing\ntype: Note\n---\n";
|
||||
|
||||
assert!(!path.parent().unwrap().exists());
|
||||
create_note_content(path.to_str().unwrap(), content).unwrap();
|
||||
|
||||
assert!(path.exists());
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), content);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_note_content_rejects_existing_file() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let path = dir.path().join("briefing.md");
|
||||
fs::write(&path, "# Existing\n").unwrap();
|
||||
|
||||
let err = create_note_content(path.to_str().unwrap(), "# Replacement\n")
|
||||
.expect_err("expected create-only write to reject collisions");
|
||||
|
||||
assert!(err.contains("already exists"));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "# Existing\n");
|
||||
}
|
||||
|
||||
@@ -385,6 +385,57 @@ pub fn rename_note_filename(
|
||||
Ok(finalize_rename(vault, &old_targets, committed.new_file()))
|
||||
}
|
||||
|
||||
/// Move a note into a different folder while preserving its filename and content.
|
||||
pub fn move_note_to_folder(
|
||||
vault_path: &str,
|
||||
old_path: &str,
|
||||
destination_folder_path: &str,
|
||||
) -> Result<RenameResult, String> {
|
||||
let vault = Path::new(vault_path);
|
||||
let old_file = Path::new(old_path);
|
||||
let destination_dir = Path::new(destination_folder_path);
|
||||
|
||||
recover_pending_rename_transactions(vault)?;
|
||||
ensure_existing_note(old_file, old_path)?;
|
||||
|
||||
if !destination_dir.exists() {
|
||||
return Err(format!(
|
||||
"Folder does not exist: {}",
|
||||
destination_folder_path
|
||||
));
|
||||
}
|
||||
if !destination_dir.is_dir() {
|
||||
return Err(format!(
|
||||
"Folder is not a directory: {}",
|
||||
destination_folder_path
|
||||
));
|
||||
}
|
||||
|
||||
let old_filename = old_file
|
||||
.file_name()
|
||||
.map(|f| f.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let content =
|
||||
fs::read_to_string(old_file).map_err(|e| format!("Failed to read {}: {}", old_path, e))?;
|
||||
let fm_title = extract_fm_title_value(&content);
|
||||
let old_title = super::extract_title(fm_title.as_deref(), &content, &old_filename);
|
||||
let new_file = destination_dir.join(&old_filename);
|
||||
|
||||
if new_file == old_file {
|
||||
return Ok(unchanged_result(old_path));
|
||||
}
|
||||
|
||||
let workspace = RenameWorkspace::new(vault)?;
|
||||
let committed = workspace
|
||||
.operation(old_path, old_file)
|
||||
.rename_exact(workspace.stage_note_content(&content)?, &new_file)?;
|
||||
|
||||
let vault_prefix = format!("{}/", vault.to_string_lossy());
|
||||
let old_path_stem = to_path_stem(old_path, &vault_prefix);
|
||||
let old_targets = collect_legacy_wikilink_targets(&old_title, old_path_stem);
|
||||
Ok(finalize_rename(vault, &old_targets, committed.new_file()))
|
||||
}
|
||||
|
||||
/// Check if a filename matches the untitled pattern (e.g. "untitled-note-1234567890.md").
|
||||
fn is_untitled_filename(filename: &str) -> bool {
|
||||
let stem = filename.strip_suffix(".md").unwrap_or(filename);
|
||||
@@ -931,6 +982,72 @@ mod tests {
|
||||
assert_eq!(result.unwrap_err(), "A note with that name already exists");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_move_note_to_folder_preserves_filename_and_updates_wikilinks() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let vault = dir.path();
|
||||
create_test_file(
|
||||
vault,
|
||||
"projects/weekly-review.md",
|
||||
"---\ntitle: Weekly Review\n---\n# Weekly Review\nBody\n",
|
||||
);
|
||||
create_test_file(
|
||||
vault,
|
||||
"areas/linked.md",
|
||||
"Reference [[projects/weekly-review]]\n",
|
||||
);
|
||||
|
||||
let result = move_note_to_folder(
|
||||
vault.to_str().unwrap(),
|
||||
vault.join("projects/weekly-review.md").to_str().unwrap(),
|
||||
vault.join("areas").to_str().unwrap(),
|
||||
)
|
||||
.expect("move should succeed");
|
||||
|
||||
assert!(result.new_path.ends_with("areas/weekly-review.md"));
|
||||
assert!(!vault.join("projects/weekly-review.md").exists());
|
||||
assert!(vault.join("areas/weekly-review.md").exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(vault.join("areas/linked.md")).unwrap(),
|
||||
"Reference [[areas/weekly-review]]\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_move_note_to_folder_noop_when_destination_matches_current_parent() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let vault = dir.path();
|
||||
create_test_file(vault, "projects/weekly-review.md", "# Weekly Review\n");
|
||||
|
||||
let source = vault.join("projects/weekly-review.md");
|
||||
let result = move_note_to_folder(
|
||||
vault.to_str().unwrap(),
|
||||
source.to_str().unwrap(),
|
||||
vault.join("projects").to_str().unwrap(),
|
||||
)
|
||||
.expect("move should noop");
|
||||
|
||||
assert_eq!(result.new_path, source.to_string_lossy());
|
||||
assert!(source.exists());
|
||||
assert_eq!(result.updated_files, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_move_note_to_folder_rejects_existing_destination() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let vault = dir.path();
|
||||
create_test_file(vault, "projects/weekly-review.md", "# Weekly Review\n");
|
||||
create_test_file(vault, "areas/weekly-review.md", "# Existing\n");
|
||||
|
||||
let result = move_note_to_folder(
|
||||
vault.to_str().unwrap(),
|
||||
vault.join("projects/weekly-review.md").to_str().unwrap(),
|
||||
vault.join("areas").to_str().unwrap(),
|
||||
);
|
||||
|
||||
assert_eq!(result.unwrap_err(), "A note with that name already exists");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rename_note_with_old_title_hint_updates_wikilinks() {
|
||||
// Simulates H1 sync: content already saved with new H1, but wikilinks still use old title.
|
||||
|
||||
484
src/App.tsx
484
src/App.tsx
@@ -20,6 +20,8 @@ import { AiAgentsOnboardingPrompt } from './components/AiAgentsOnboardingPrompt'
|
||||
import { TelemetryConsentDialog } from './components/TelemetryConsentDialog'
|
||||
import { FeedbackDialog } from './components/FeedbackDialog'
|
||||
import { McpSetupDialog } from './components/McpSetupDialog'
|
||||
import { NoteRetargetingDialogs } from './components/note-retargeting/NoteRetargetingDialogs'
|
||||
import { NoteRetargetingProvider } from './components/note-retargeting/noteRetargetingContext'
|
||||
import { useTelemetry } from './hooks/useTelemetry'
|
||||
import { useMcpStatus } from './hooks/useMcpStatus'
|
||||
import { useAiAgentsOnboarding } from './hooks/useAiAgentsOnboarding'
|
||||
@@ -30,7 +32,7 @@ import { useVaultLoader } from './hooks/useVaultLoader'
|
||||
import { useAiAgentPreferences } from './hooks/useAiAgentPreferences'
|
||||
import { useSettings } from './hooks/useSettings'
|
||||
import { useNoteActions } from './hooks/useNoteActions'
|
||||
import { slugify } from './hooks/useNoteCreation'
|
||||
import { planNewTypeCreation } from './hooks/useNoteCreation'
|
||||
import { useCommitFlow } from './hooks/useCommitFlow'
|
||||
import { useGitRemoteStatus } from './hooks/useGitRemoteStatus'
|
||||
import { useViewMode, type ViewMode } from './hooks/useViewMode'
|
||||
@@ -63,6 +65,7 @@ import { useFolderActions } from './hooks/useFolderActions'
|
||||
import { useLayoutPanels } from './hooks/useLayoutPanels'
|
||||
import { useConflictFlow } from './hooks/useConflictFlow'
|
||||
import { useAppSave } from './hooks/useAppSave'
|
||||
import { useNoteRetargetingUi } from './hooks/useNoteRetargetingUi'
|
||||
import { useVaultBridge } from './hooks/useVaultBridge'
|
||||
import type { CommitDiffRequest } from './hooks/useDiffMode'
|
||||
import { ConflictResolverModal } from './components/ConflictResolverModal'
|
||||
@@ -348,44 +351,6 @@ function App() {
|
||||
return true
|
||||
}, [handleSetSelection])
|
||||
|
||||
const shouldBlockNeighborhoodEscape = (
|
||||
dialogs.showCreateTypeDialog
|
||||
|| dialogs.showQuickOpen
|
||||
|| dialogs.showCommandPalette
|
||||
|| dialogs.showAIChat
|
||||
|| dialogs.showSettings
|
||||
|| dialogs.showCloneVault
|
||||
|| dialogs.showSearch
|
||||
|| dialogs.showConflictResolver
|
||||
|| dialogs.showCreateViewDialog
|
||||
|| showFeedback
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const handleWindowKeyDown = (event: KeyboardEvent) => {
|
||||
if (!shouldProcessNeighborhoodEscape(event, selectionRef.current, shouldBlockNeighborhoodEscape)) return
|
||||
|
||||
const activeElement = document.activeElement
|
||||
if (isEditorEscapeTarget(activeElement)) {
|
||||
event.preventDefault()
|
||||
activeElement.blur()
|
||||
requestAnimationFrame(() => {
|
||||
focusNoteListContainer(document)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (isEditableElement(activeElement)) return
|
||||
|
||||
if (handleNeighborhoodHistoryBack()) {
|
||||
event.preventDefault()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('keydown', handleWindowKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleWindowKeyDown)
|
||||
}, [handleNeighborhoodHistoryBack, shouldBlockNeighborhoodEscape])
|
||||
|
||||
const handleSaveExplicitOrganization = useCallback((enabled: boolean) => {
|
||||
updateConfig('inbox', {
|
||||
noteListProperties: vaultConfig.inbox?.noteListProperties ?? null,
|
||||
@@ -937,37 +902,40 @@ function App() {
|
||||
const shouldLoadGitHistory = !layout.inspectorCollapsed && !showAIChat
|
||||
const gitHistory = useGitHistory(notes.activeTabPath, vault.loadGitHistory, shouldLoadGitHistory)
|
||||
|
||||
const handleCreateType = useCallback((name: string) => {
|
||||
notes.handleCreateType(name)
|
||||
setToastMessage(`Type "${name}" created`)
|
||||
const handleCreateType = useCallback(async (name: string) => {
|
||||
const created = await notes.handleCreateType(name)
|
||||
if (created) setToastMessage(`Type "${name}" created`)
|
||||
return created
|
||||
}, [notes, setToastMessage])
|
||||
|
||||
const handleCreateMissingType = useCallback(async (path: string, missingType: string, nextTypeName: string) => {
|
||||
const trimmed = nextTypeName.trim()
|
||||
if (!trimmed) return
|
||||
if (!trimmed) return false
|
||||
|
||||
const targetFilename = `${slugify(trimmed)}.md`
|
||||
const exactType = vault.entries.find((entry) => entry.isA === 'Type' && entry.title === trimmed)
|
||||
const slugMatch = vault.entries.find((entry) => entry.isA === 'Type' && slugify(entry.title) === slugify(trimmed))
|
||||
const filenameCollision = vault.entries.find((entry) => entry.filename.toLowerCase() === targetFilename)
|
||||
const resolvedTypeName = exactType?.title ?? slugMatch?.title ?? trimmed
|
||||
|
||||
if (filenameCollision && filenameCollision.isA !== 'Type') {
|
||||
setToastMessage(`Cannot create type "${trimmed}" because ${targetFilename} already exists`)
|
||||
throw new Error(`Type filename collision for ${targetFilename}`)
|
||||
const plan = planNewTypeCreation({ entries: vault.entries, typeName: trimmed, vaultPath: resolvedPath })
|
||||
if (plan.status === 'blocked') {
|
||||
setToastMessage(plan.message)
|
||||
return false
|
||||
}
|
||||
|
||||
if (!exactType && !slugMatch) {
|
||||
await notes.createTypeEntrySilent(trimmed)
|
||||
let resolvedTypeName = plan.status === 'existing' ? plan.entry.title : trimmed
|
||||
|
||||
if (plan.status === 'create') {
|
||||
try {
|
||||
resolvedTypeName = (await notes.createTypeEntrySilent(trimmed)).title
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
await notes.handleUpdateFrontmatter(path, 'type', resolvedTypeName)
|
||||
setToastMessage(
|
||||
resolvedTypeName === missingType
|
||||
plan.status === 'create' && resolvedTypeName === missingType
|
||||
? `Type "${resolvedTypeName}" created`
|
||||
: `Type set to "${resolvedTypeName}"`,
|
||||
)
|
||||
}, [notes, setToastMessage, vault.entries])
|
||||
return true
|
||||
}, [notes, resolvedPath, setToastMessage, vault.entries])
|
||||
|
||||
const handleCreateOrUpdateView = useCallback(async (definition: ViewDefinition) => {
|
||||
const editing = dialogs.editingView
|
||||
@@ -1140,10 +1108,60 @@ function App() {
|
||||
?? vault.entries.find((entry) => entry.path === notes.activeTabPath)
|
||||
?? null
|
||||
}, [notes.activeTabPath, notes.tabs, vault.entries])
|
||||
const noteRetargetingUi = useNoteRetargetingUi({
|
||||
activeEntry: activeCommandEntry,
|
||||
activeNoteBlocked: !!activeDeletedFile,
|
||||
entries: vault.entries,
|
||||
folders: vault.folders,
|
||||
selection: effectiveSelection,
|
||||
setSelection: handleSetSelection,
|
||||
setToastMessage,
|
||||
vaultPath: resolvedPath,
|
||||
updateFrontmatter: notes.handleUpdateFrontmatter,
|
||||
moveNoteToFolder: notes.handleMoveNoteToFolder,
|
||||
})
|
||||
|
||||
const canToggleRichEditor = !!activeCommandEntry
|
||||
&& activeCommandEntry.filename.toLowerCase().endsWith('.md')
|
||||
&& !activeDeletedFile
|
||||
const shouldBlockNeighborhoodEscape = (
|
||||
dialogs.showCreateTypeDialog
|
||||
|| dialogs.showQuickOpen
|
||||
|| dialogs.showCommandPalette
|
||||
|| dialogs.showAIChat
|
||||
|| dialogs.showSettings
|
||||
|| dialogs.showCloneVault
|
||||
|| dialogs.showSearch
|
||||
|| dialogs.showConflictResolver
|
||||
|| dialogs.showCreateViewDialog
|
||||
|| noteRetargetingUi.isDialogOpen
|
||||
|| showFeedback
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const handleWindowKeyDown = (event: KeyboardEvent) => {
|
||||
if (!shouldProcessNeighborhoodEscape(event, selectionRef.current, shouldBlockNeighborhoodEscape)) return
|
||||
|
||||
const activeElement = document.activeElement
|
||||
if (isEditorEscapeTarget(activeElement)) {
|
||||
event.preventDefault()
|
||||
activeElement.blur()
|
||||
requestAnimationFrame(() => {
|
||||
focusNoteListContainer(document)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (isEditableElement(activeElement)) return
|
||||
|
||||
if (handleNeighborhoodHistoryBack()) {
|
||||
event.preventDefault()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('keydown', handleWindowKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleWindowKeyDown)
|
||||
}, [handleNeighborhoodHistoryBack, shouldBlockNeighborhoodEscape])
|
||||
|
||||
const noteListColumnsLabel = useMemo(() => {
|
||||
if (effectiveSelection.kind === 'view') {
|
||||
@@ -1155,6 +1173,45 @@ function App() {
|
||||
? 'Customize All Notes columns'
|
||||
: 'Customize Inbox columns'
|
||||
}, [effectiveSelection, vault.views])
|
||||
const activeNoteModified = useMemo(
|
||||
() => vault.modifiedFiles.some((file) => file.path === notes.activeTabPath),
|
||||
[notes.activeTabPath, vault.modifiedFiles],
|
||||
)
|
||||
const toggleDiffCommand = useCallback(() => diffToggleRef.current(), [])
|
||||
const toggleRawEditorCommand = useMemo(
|
||||
() => canToggleRichEditor ? () => rawToggleRef.current() : undefined,
|
||||
[canToggleRichEditor],
|
||||
)
|
||||
const removeActiveVaultCommand = useCallback(() => {
|
||||
vaultSwitcher.removeVault(vaultSwitcher.vaultPath)
|
||||
}, [vaultSwitcher])
|
||||
const restoreVaultAiGuidanceCommand = useCallback(() => {
|
||||
void restoreVaultAiGuidance()
|
||||
}, [restoreVaultAiGuidance])
|
||||
const changeNoteTypeCommand = useMemo(
|
||||
() => noteRetargetingUi.canChangeActiveNoteType ? noteRetargetingUi.openChangeNoteTypeDialog : undefined,
|
||||
[noteRetargetingUi.canChangeActiveNoteType, noteRetargetingUi.openChangeNoteTypeDialog],
|
||||
)
|
||||
const moveNoteToFolderCommand = useMemo(
|
||||
() => noteRetargetingUi.canMoveActiveNoteToFolder ? noteRetargetingUi.openMoveNoteToFolderDialog : undefined,
|
||||
[noteRetargetingUi.canMoveActiveNoteToFolder, noteRetargetingUi.openMoveNoteToFolderDialog],
|
||||
)
|
||||
const activeNoteHasIcon = useMemo(() => {
|
||||
const entry = vault.entries.find((candidate) => candidate.path === notes.activeTabPath)
|
||||
return hasNoteIconValue(entry?.icon)
|
||||
}, [notes.activeTabPath, vault.entries])
|
||||
const toggleOrganizedCommand = explicitOrganizationEnabled ? entryActions.handleToggleOrganized : undefined
|
||||
const canCustomizeNoteListColumns = useMemo(() => (
|
||||
effectiveSelection.kind === 'view'
|
||||
|| (
|
||||
effectiveSelection.kind === 'filter'
|
||||
&& (effectiveSelection.filter === 'all' || (explicitOrganizationEnabled && effectiveSelection.filter === 'inbox'))
|
||||
)
|
||||
), [effectiveSelection, explicitOrganizationEnabled])
|
||||
const restoreDeletedNoteCommand = useMemo(
|
||||
() => activeDeletedFile ? () => { void handleDiscardFile(activeDeletedFile.relativePath) } : undefined,
|
||||
[activeDeletedFile, handleDiscardFile],
|
||||
)
|
||||
|
||||
const commands = useAppCommands({
|
||||
activeTabPath: notes.activeTabPath, activeTabPathRef: notes.activeTabPathRef,
|
||||
@@ -1162,7 +1219,7 @@ function App() {
|
||||
visibleNotesRef,
|
||||
multiSelectionCommandRef,
|
||||
modifiedCount: vault.modifiedFiles.length,
|
||||
activeNoteModified: vault.modifiedFiles.some(f => f.path === notes.activeTabPath),
|
||||
activeNoteModified,
|
||||
selection: effectiveSelection,
|
||||
onQuickOpen: dialogs.openQuickOpen, onCommandPalette: dialogs.openCommandPalette,
|
||||
onSearch: dialogs.openSearch,
|
||||
@@ -1178,8 +1235,8 @@ function App() {
|
||||
onResolveConflicts: conflictFlow.handleOpenConflictResolver,
|
||||
onSetViewMode: handleSetViewMode,
|
||||
onToggleInspector: handleToggleInspector,
|
||||
onToggleDiff: () => diffToggleRef.current(),
|
||||
onToggleRawEditor: canToggleRichEditor ? () => rawToggleRef.current() : undefined,
|
||||
onToggleDiff: toggleDiffCommand,
|
||||
onToggleRawEditor: toggleRawEditorCommand,
|
||||
onZoomIn: zoom.zoomIn, onZoomOut: zoom.zoomOut, onZoomReset: zoom.zoomReset,
|
||||
zoomLevel: zoom.zoomLevel,
|
||||
onSelect: handleSetSelection,
|
||||
@@ -1195,7 +1252,7 @@ function App() {
|
||||
onCreateType: dialogs.openCreateType,
|
||||
onToggleAIChat: dialogs.toggleAIChat,
|
||||
onCheckForUpdates: handleCheckForUpdates,
|
||||
onRemoveActiveVault: () => vaultSwitcher.removeVault(vaultSwitcher.vaultPath),
|
||||
onRemoveActiveVault: removeActiveVaultCommand,
|
||||
onRestoreGettingStarted: cloneGettingStartedVault,
|
||||
isGettingStartedHidden: vaultSwitcher.isGettingStartedHidden,
|
||||
vaultCount: vaultSwitcher.allVaults.length,
|
||||
@@ -1204,7 +1261,7 @@ function App() {
|
||||
onOpenAiAgents: dialogs.openSettings,
|
||||
aiAgentsStatus,
|
||||
vaultAiGuidanceStatus,
|
||||
onRestoreVaultAiGuidance: () => { void restoreVaultAiGuidance() },
|
||||
onRestoreVaultAiGuidance: restoreVaultAiGuidanceCommand,
|
||||
selectedAiAgent: aiAgentPreferences.defaultAiAgent,
|
||||
onSetDefaultAiAgent: aiAgentPreferences.setDefaultAiAgent,
|
||||
onCycleDefaultAiAgent: aiAgentPreferences.cycleDefaultAiAgent,
|
||||
@@ -1213,23 +1270,19 @@ function App() {
|
||||
onRepairVault: handleRepairVault,
|
||||
onSetNoteIcon: handleSetNoteIconCommand,
|
||||
onRemoveNoteIcon: handleRemoveNoteIconCommand,
|
||||
activeNoteHasIcon: (() => {
|
||||
const ae = vault.entries.find(e => e.path === notes.activeTabPath)
|
||||
return hasNoteIconValue(ae?.icon)
|
||||
})(),
|
||||
onChangeNoteType: changeNoteTypeCommand,
|
||||
onMoveNoteToFolder: moveNoteToFolderCommand,
|
||||
canMoveNoteToFolder: noteRetargetingUi.canMoveActiveNoteToFolder,
|
||||
activeNoteHasIcon,
|
||||
noteListFilter,
|
||||
onSetNoteListFilter: setNoteListFilter,
|
||||
onOpenInNewWindow: handleOpenInNewWindow,
|
||||
onToggleFavorite: entryActions.handleToggleFavorite,
|
||||
onToggleOrganized: explicitOrganizationEnabled ? entryActions.handleToggleOrganized : undefined,
|
||||
onToggleOrganized: toggleOrganizedCommand,
|
||||
onCustomizeNoteListColumns: handleCustomizeNoteListColumns,
|
||||
canCustomizeNoteListColumns: effectiveSelection.kind === 'view'
|
||||
|| (
|
||||
effectiveSelection.kind === 'filter'
|
||||
&& (effectiveSelection.filter === 'all' || (explicitOrganizationEnabled && effectiveSelection.filter === 'inbox'))
|
||||
),
|
||||
canCustomizeNoteListColumns,
|
||||
noteListColumnsLabel,
|
||||
onRestoreDeletedNote: activeDeletedFile ? () => { void handleDiscardFile(activeDeletedFile.relativePath) } : undefined,
|
||||
onRestoreDeletedNote: restoreDeletedNoteCommand,
|
||||
canRestoreDeletedNote: !!activeDeletedFile,
|
||||
})
|
||||
|
||||
@@ -1325,146 +1378,157 @@ function App() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<div className="app">
|
||||
{sidebarVisible && (
|
||||
<>
|
||||
<div className="app__sidebar" style={{ width: layout.sidebarWidth }}>
|
||||
<Sidebar entries={vault.entries} folders={vault.folders} views={vault.views} selection={effectiveSelection} onSelect={handleSetSelection} onSelectNote={notes.handleSelectNote} onSelectFavorite={handleOpenFavorite} onReorderFavorites={entryActions.handleReorderFavorites} onCreateType={notes.handleCreateNoteImmediate} onCreateNewType={dialogs.openCreateType} onCustomizeType={entryActions.handleCustomizeType} onUpdateTypeTemplate={entryActions.handleUpdateTypeTemplate} onReorderSections={entryActions.handleReorderSections} onRenameSection={entryActions.handleRenameSection} onToggleTypeVisibility={entryActions.handleToggleTypeVisibility} onCreateFolder={handleCreateFolder} onRenameFolder={folderActions.renameFolder} onDeleteFolder={folderActions.requestDeleteFolder} renamingFolderPath={folderActions.renamingFolderPath} onStartRenameFolder={folderActions.startFolderRename} onCancelRenameFolder={folderActions.cancelFolderRename} onCreateView={dialogs.openCreateView} onEditView={handleEditView} onDeleteView={handleDeleteView} showInbox={explicitOrganizationEnabled} inboxCount={inboxCount} />
|
||||
</div>
|
||||
<ResizeHandle onResize={layout.handleSidebarResize} />
|
||||
</>
|
||||
)}
|
||||
{noteListVisible && (
|
||||
<>
|
||||
<div className={`app__note-list${aiActivity.highlightElement === 'notelist' ? ' ai-highlight' : ''}`} style={{ width: layout.noteListWidth }}>
|
||||
{effectiveSelection.kind === 'filter' && effectiveSelection.filter === 'pulse' ? (
|
||||
<PulseView vaultPath={resolvedPath} onOpenNote={handlePulseOpenNote} sidebarCollapsed={!sidebarVisible} onExpandSidebar={() => handleSetViewMode('all')} />
|
||||
) : (
|
||||
<NoteList entries={vault.entries} selection={effectiveSelection} selectedNote={activeTab?.entry ?? null} noteListFilter={noteListFilter} onNoteListFilterChange={setNoteListFilter} inboxPeriod={inboxPeriod} modifiedFiles={vault.modifiedFiles} modifiedFilesError={vault.modifiedFilesError} getNoteStatus={vault.getNoteStatus} sidebarCollapsed={!sidebarVisible} onSelectNote={notes.handleSelectNote} onReplaceActiveTab={notes.handleReplaceActiveTab} onEnterNeighborhood={handleEnterNeighborhood} onCreateNote={notes.handleCreateNoteImmediate} onBulkOrganize={explicitOrganizationEnabled ? bulkActions.handleBulkOrganize : undefined} onBulkArchive={bulkActions.handleBulkArchive} onBulkDeletePermanently={deleteActions.handleBulkDeletePermanently} onUpdateTypeSort={notes.handleUpdateFrontmatter} onUpdateViewDefinition={handleUpdateViewDefinition} updateEntry={vault.updateEntry} onOpenInNewWindow={handleOpenEntryInNewWindow} onDiscardFile={handleDiscardFile} onAutoTriggerDiff={() => diffToggleRef.current()} onOpenDeletedNote={handleOpenDeletedNote} allNotesNoteListProperties={vaultConfig.allNotes?.noteListProperties ?? null} onUpdateAllNotesNoteListProperties={handleUpdateAllNotesNoteListProperties} inboxNoteListProperties={vaultConfig.inbox?.noteListProperties ?? null} onUpdateInboxNoteListProperties={handleUpdateInboxNoteListProperties} views={vault.views} visibleNotesRef={visibleNotesRef} multiSelectionCommandRef={multiSelectionCommandRef} />
|
||||
)}
|
||||
</div>
|
||||
<ResizeHandle onResize={layout.handleNoteListResize} />
|
||||
</>
|
||||
)}
|
||||
<div className={`app__editor${aiActivity.highlightElement === 'editor' || aiActivity.highlightElement === 'tab' ? ' ai-highlight' : ''}`}>
|
||||
<Editor
|
||||
tabs={notes.tabs}
|
||||
activeTabPath={notes.activeTabPath}
|
||||
entries={vault.entries}
|
||||
onNavigateWikilink={notes.handleNavigateWikilink}
|
||||
onLoadDiff={vault.loadDiff}
|
||||
onLoadDiffAtCommit={vault.loadDiffAtCommit}
|
||||
pendingCommitDiffRequest={pulseCommitDiffRequest}
|
||||
onPendingCommitDiffHandled={handlePulseCommitDiffHandled}
|
||||
getNoteStatus={vault.getNoteStatus}
|
||||
onCreateNote={notes.handleCreateNoteImmediate}
|
||||
inspectorCollapsed={layout.inspectorCollapsed}
|
||||
onToggleInspector={handleToggleInspector}
|
||||
inspectorWidth={layout.inspectorWidth}
|
||||
defaultAiAgent={aiAgentPreferences.defaultAiAgent}
|
||||
defaultAiAgentReady={aiAgentPreferences.defaultAiAgentReady}
|
||||
onInspectorResize={layout.handleInspectorResize}
|
||||
inspectorEntry={activeTab?.entry ?? null}
|
||||
inspectorContent={activeTab?.content ?? null}
|
||||
gitHistory={gitHistory}
|
||||
onUpdateFrontmatter={notes.handleUpdateFrontmatter}
|
||||
onDeleteProperty={notes.handleDeleteProperty}
|
||||
onAddProperty={notes.handleAddProperty}
|
||||
onCreateMissingType={handleCreateMissingType}
|
||||
onCreateAndOpenNote={notes.handleCreateNoteForRelationship}
|
||||
onInitializeProperties={handleInitializeProperties}
|
||||
showAIChat={dialogs.showAIChat}
|
||||
onToggleAIChat={dialogs.toggleAIChat}
|
||||
vaultPath={resolvedPath}
|
||||
noteList={aiNoteList}
|
||||
noteListFilter={aiNoteListFilter}
|
||||
onToggleFavorite={activeDeletedFile ? undefined : entryActions.handleToggleFavorite}
|
||||
onToggleOrganized={activeDeletedFile || !explicitOrganizationEnabled ? undefined : entryActions.handleToggleOrganized}
|
||||
onDeleteNote={activeDeletedFile ? undefined : deleteActions.handleDeleteNote}
|
||||
onArchiveNote={activeDeletedFile ? undefined : entryActions.handleArchiveNote}
|
||||
onUnarchiveNote={activeDeletedFile ? undefined : entryActions.handleUnarchiveNote}
|
||||
onContentChange={handleTrackedContentChange}
|
||||
onSave={handleTrackedSave}
|
||||
onRenameFilename={activeDeletedFile ? undefined : appSave.handleFilenameRename}
|
||||
rawToggleRef={rawToggleRef}
|
||||
diffToggleRef={diffToggleRef}
|
||||
canGoBack={canGoBack}
|
||||
canGoForward={canGoForward}
|
||||
onGoBack={handleGoBack}
|
||||
onGoForward={handleGoForward}
|
||||
leftPanelsCollapsed={!sidebarVisible && !noteListVisible}
|
||||
onFileCreated={vaultBridge.handleAgentFileCreated}
|
||||
onFileModified={vaultBridge.handleAgentFileModified}
|
||||
onVaultChanged={vaultBridge.handleAgentVaultChanged}
|
||||
isConflicted={conflictFlow.isConflicted}
|
||||
onKeepMine={conflictFlow.handleKeepMine}
|
||||
onKeepTheirs={conflictFlow.handleKeepTheirs}
|
||||
flushPendingRawContentRef={flushPendingRawContentRef}
|
||||
/>
|
||||
<NoteRetargetingProvider value={noteRetargetingUi.contextValue}>
|
||||
<div className="app-shell">
|
||||
<div className="app">
|
||||
{sidebarVisible && (
|
||||
<>
|
||||
<div className="app__sidebar" style={{ width: layout.sidebarWidth }}>
|
||||
<Sidebar entries={vault.entries} folders={vault.folders} views={vault.views} selection={effectiveSelection} onSelect={handleSetSelection} onSelectNote={notes.handleSelectNote} onSelectFavorite={handleOpenFavorite} onReorderFavorites={entryActions.handleReorderFavorites} onCreateType={notes.handleCreateNoteImmediate} onCreateNewType={dialogs.openCreateType} onCustomizeType={entryActions.handleCustomizeType} onUpdateTypeTemplate={entryActions.handleUpdateTypeTemplate} onReorderSections={entryActions.handleReorderSections} onRenameSection={entryActions.handleRenameSection} onToggleTypeVisibility={entryActions.handleToggleTypeVisibility} onCreateFolder={handleCreateFolder} onRenameFolder={folderActions.renameFolder} onDeleteFolder={folderActions.requestDeleteFolder} renamingFolderPath={folderActions.renamingFolderPath} onStartRenameFolder={folderActions.startFolderRename} onCancelRenameFolder={folderActions.cancelFolderRename} onCreateView={dialogs.openCreateView} onEditView={handleEditView} onDeleteView={handleDeleteView} showInbox={explicitOrganizationEnabled} inboxCount={inboxCount} />
|
||||
</div>
|
||||
<ResizeHandle onResize={layout.handleSidebarResize} />
|
||||
</>
|
||||
)}
|
||||
{noteListVisible && (
|
||||
<>
|
||||
<div className={`app__note-list${aiActivity.highlightElement === 'notelist' ? ' ai-highlight' : ''}`} style={{ width: layout.noteListWidth }}>
|
||||
{effectiveSelection.kind === 'filter' && effectiveSelection.filter === 'pulse' ? (
|
||||
<PulseView vaultPath={resolvedPath} onOpenNote={handlePulseOpenNote} sidebarCollapsed={!sidebarVisible} onExpandSidebar={() => handleSetViewMode('all')} />
|
||||
) : (
|
||||
<NoteList entries={vault.entries} selection={effectiveSelection} selectedNote={activeTab?.entry ?? null} noteListFilter={noteListFilter} onNoteListFilterChange={setNoteListFilter} inboxPeriod={inboxPeriod} modifiedFiles={vault.modifiedFiles} modifiedFilesError={vault.modifiedFilesError} getNoteStatus={vault.getNoteStatus} sidebarCollapsed={!sidebarVisible} onSelectNote={notes.handleSelectNote} onReplaceActiveTab={notes.handleReplaceActiveTab} onEnterNeighborhood={handleEnterNeighborhood} onCreateNote={notes.handleCreateNoteImmediate} onBulkOrganize={explicitOrganizationEnabled ? bulkActions.handleBulkOrganize : undefined} onBulkArchive={bulkActions.handleBulkArchive} onBulkDeletePermanently={deleteActions.handleBulkDeletePermanently} onUpdateTypeSort={notes.handleUpdateFrontmatter} onUpdateViewDefinition={handleUpdateViewDefinition} updateEntry={vault.updateEntry} onOpenInNewWindow={handleOpenEntryInNewWindow} onDiscardFile={handleDiscardFile} onAutoTriggerDiff={() => diffToggleRef.current()} onOpenDeletedNote={handleOpenDeletedNote} allNotesNoteListProperties={vaultConfig.allNotes?.noteListProperties ?? null} onUpdateAllNotesNoteListProperties={handleUpdateAllNotesNoteListProperties} inboxNoteListProperties={vaultConfig.inbox?.noteListProperties ?? null} onUpdateInboxNoteListProperties={handleUpdateInboxNoteListProperties} views={vault.views} visibleNotesRef={visibleNotesRef} multiSelectionCommandRef={multiSelectionCommandRef} />
|
||||
)}
|
||||
</div>
|
||||
<ResizeHandle onResize={layout.handleNoteListResize} />
|
||||
</>
|
||||
)}
|
||||
<div className={`app__editor${aiActivity.highlightElement === 'editor' || aiActivity.highlightElement === 'tab' ? ' ai-highlight' : ''}`}>
|
||||
<Editor
|
||||
tabs={notes.tabs}
|
||||
activeTabPath={notes.activeTabPath}
|
||||
entries={vault.entries}
|
||||
onNavigateWikilink={notes.handleNavigateWikilink}
|
||||
onLoadDiff={vault.loadDiff}
|
||||
onLoadDiffAtCommit={vault.loadDiffAtCommit}
|
||||
pendingCommitDiffRequest={pulseCommitDiffRequest}
|
||||
onPendingCommitDiffHandled={handlePulseCommitDiffHandled}
|
||||
getNoteStatus={vault.getNoteStatus}
|
||||
onCreateNote={notes.handleCreateNoteImmediate}
|
||||
inspectorCollapsed={layout.inspectorCollapsed}
|
||||
onToggleInspector={handleToggleInspector}
|
||||
inspectorWidth={layout.inspectorWidth}
|
||||
defaultAiAgent={aiAgentPreferences.defaultAiAgent}
|
||||
defaultAiAgentReady={aiAgentPreferences.defaultAiAgentReady}
|
||||
onInspectorResize={layout.handleInspectorResize}
|
||||
inspectorEntry={activeTab?.entry ?? null}
|
||||
inspectorContent={activeTab?.content ?? null}
|
||||
gitHistory={gitHistory}
|
||||
onUpdateFrontmatter={notes.handleUpdateFrontmatter}
|
||||
onDeleteProperty={notes.handleDeleteProperty}
|
||||
onAddProperty={notes.handleAddProperty}
|
||||
onCreateMissingType={handleCreateMissingType}
|
||||
onCreateAndOpenNote={notes.handleCreateNoteForRelationship}
|
||||
onInitializeProperties={handleInitializeProperties}
|
||||
showAIChat={dialogs.showAIChat}
|
||||
onToggleAIChat={dialogs.toggleAIChat}
|
||||
vaultPath={resolvedPath}
|
||||
noteList={aiNoteList}
|
||||
noteListFilter={aiNoteListFilter}
|
||||
onToggleFavorite={activeDeletedFile ? undefined : entryActions.handleToggleFavorite}
|
||||
onToggleOrganized={activeDeletedFile || !explicitOrganizationEnabled ? undefined : entryActions.handleToggleOrganized}
|
||||
onDeleteNote={activeDeletedFile ? undefined : deleteActions.handleDeleteNote}
|
||||
onArchiveNote={activeDeletedFile ? undefined : entryActions.handleArchiveNote}
|
||||
onUnarchiveNote={activeDeletedFile ? undefined : entryActions.handleUnarchiveNote}
|
||||
onContentChange={handleTrackedContentChange}
|
||||
onSave={handleTrackedSave}
|
||||
onRenameFilename={activeDeletedFile ? undefined : appSave.handleFilenameRename}
|
||||
rawToggleRef={rawToggleRef}
|
||||
diffToggleRef={diffToggleRef}
|
||||
canGoBack={canGoBack}
|
||||
canGoForward={canGoForward}
|
||||
onGoBack={handleGoBack}
|
||||
onGoForward={handleGoForward}
|
||||
leftPanelsCollapsed={!sidebarVisible && !noteListVisible}
|
||||
onFileCreated={vaultBridge.handleAgentFileCreated}
|
||||
onFileModified={vaultBridge.handleAgentFileModified}
|
||||
onVaultChanged={vaultBridge.handleAgentVaultChanged}
|
||||
isConflicted={conflictFlow.isConflicted}
|
||||
onKeepMine={conflictFlow.handleKeepMine}
|
||||
onKeepTheirs={conflictFlow.handleKeepTheirs}
|
||||
flushPendingRawContentRef={flushPendingRawContentRef}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<UpdateBanner status={updateStatus} actions={updateActions} />
|
||||
<RenameDetectedBanner renames={detectedRenames} onUpdate={handleUpdateWikilinks} onDismiss={handleDismissRenames} />
|
||||
<StatusBar noteCount={vault.entries.length} modifiedCount={vault.modifiedFiles.length} vaultPath={resolvedPath} vaults={vaultSwitcher.allVaults} onSwitchVault={vaultSwitcher.switchVault} onOpenSettings={dialogs.openSettings} onOpenFeedback={openFeedback} onOpenLocalFolder={vaultSwitcher.handleOpenLocalFolder} onCreateEmptyVault={vaultSwitcher.handleCreateEmptyVault} onCloneVault={dialogs.openCloneVault} onCloneGettingStarted={cloneGettingStartedVault} onClickPending={() => handleSetSelection({ kind: 'filter', filter: 'changes' })} onClickPulse={() => handleSetSelection({ kind: 'filter', filter: 'pulse' })} onCommitPush={handleCommitPush} isOffline={networkStatus.isOffline} isGitVault={isGitVault} syncStatus={autoSync.syncStatus} lastSyncTime={autoSync.lastSyncTime} conflictCount={autoSync.conflictFiles.length} remoteStatus={autoSync.remoteStatus} onTriggerSync={autoSync.triggerSync} onPullAndPush={autoSync.pullAndPush} onOpenConflictResolver={conflictFlow.handleOpenConflictResolver} zoomLevel={zoom.zoomLevel} onZoomReset={zoom.zoomReset} buildNumber={buildNumber} onCheckForUpdates={handleCheckForUpdates} onRemoveVault={vaultSwitcher.removeVault} mcpStatus={mcpStatus} onInstallMcp={openMcpSetupDialog} aiAgentsStatus={aiAgentsStatus} vaultAiGuidanceStatus={vaultAiGuidanceStatus} defaultAiAgent={aiAgentPreferences.defaultAiAgent} onSetDefaultAiAgent={aiAgentPreferences.setDefaultAiAgent} onRestoreVaultAiGuidance={() => { void restoreVaultAiGuidance() }} />
|
||||
<DeleteProgressNotice count={deleteActions.pendingDeleteCount} />
|
||||
<Toast message={toastMessage} onDismiss={() => setToastMessage(null)} />
|
||||
<QuickOpenPalette open={dialogs.showQuickOpen} entries={vault.entries} onSelect={notes.handleSelectNote} onClose={dialogs.closeQuickOpen} />
|
||||
<CommandPalette
|
||||
open={dialogs.showCommandPalette}
|
||||
commands={commands}
|
||||
entries={vault.entries}
|
||||
aiAgentReady={aiAgentPreferences.defaultAiAgentReady}
|
||||
aiAgentLabel={aiAgentPreferences.defaultAiAgentLabel}
|
||||
onClose={dialogs.closeCommandPalette}
|
||||
/>
|
||||
<SearchPanel open={dialogs.showSearch} vaultPath={resolvedPath} entries={vault.entries} onSelectNote={notes.handleSelectNote} onClose={dialogs.closeSearch} />
|
||||
<CreateTypeDialog open={dialogs.showCreateTypeDialog} onClose={dialogs.closeCreateType} onCreate={handleCreateType} />
|
||||
<NoteRetargetingDialogs
|
||||
dialogState={noteRetargetingUi.dialogState}
|
||||
dialogEntry={noteRetargetingUi.dialogEntry}
|
||||
typeOptions={noteRetargetingUi.typeOptions}
|
||||
folderOptions={noteRetargetingUi.folderOptions}
|
||||
onClose={noteRetargetingUi.closeDialog}
|
||||
onSelectType={noteRetargetingUi.selectType}
|
||||
onSelectFolder={noteRetargetingUi.selectFolder}
|
||||
/>
|
||||
<CreateViewDialog open={dialogs.showCreateViewDialog} onClose={dialogs.closeCreateView} onCreate={handleCreateOrUpdateView} availableFields={availableFields} editingView={dialogs.editingView?.definition ?? null} />
|
||||
<CommitDialog
|
||||
open={commitFlow.showCommitDialog}
|
||||
modifiedCount={vault.modifiedFiles.length}
|
||||
commitMode={commitFlow.commitMode}
|
||||
suggestedMessage={suggestedCommitMessage}
|
||||
onCommit={commitFlow.handleCommitPush}
|
||||
onClose={commitFlow.closeCommitDialog}
|
||||
/>
|
||||
<ConflictResolverModal
|
||||
open={dialogs.showConflictResolver}
|
||||
fileStates={conflictResolver.fileStates}
|
||||
allResolved={conflictResolver.allResolved}
|
||||
committing={conflictResolver.committing}
|
||||
error={conflictResolver.error}
|
||||
onResolveFile={conflictResolver.resolveFile}
|
||||
onOpenInEditor={conflictResolver.openInEditor}
|
||||
onCommit={conflictResolver.commitResolution}
|
||||
onClose={conflictFlow.handleCloseConflictResolver}
|
||||
/>
|
||||
<SettingsPanel open={dialogs.showSettings} settings={settings} aiAgentsStatus={aiAgentsStatus} isGitVault={isGitVault} onSave={saveSettings} explicitOrganizationEnabled={explicitOrganizationEnabled} onSaveExplicitOrganization={handleSaveExplicitOrganization} onClose={dialogs.closeSettings} />
|
||||
<FeedbackDialog open={showFeedback} onClose={closeFeedback} />
|
||||
<McpSetupDialog open={showMcpSetupDialog} status={mcpStatus} busyAction={mcpDialogAction} onClose={closeMcpSetupDialog} onConnect={handleConnectMcp} onDisconnect={handleDisconnectMcp} />
|
||||
<CloneVaultModal key={dialogs.showCloneVault ? 'clone-open' : 'clone-closed'} open={dialogs.showCloneVault} onClose={dialogs.closeCloneVault} onVaultCloned={vaultSwitcher.handleVaultCloned} />
|
||||
{deleteActions.confirmDelete && (
|
||||
<ConfirmDeleteDialog
|
||||
open={true}
|
||||
title={deleteActions.confirmDelete.title}
|
||||
message={deleteActions.confirmDelete.message}
|
||||
confirmLabel={deleteActions.confirmDelete.confirmLabel}
|
||||
onConfirm={deleteActions.confirmDelete.onConfirm}
|
||||
onCancel={() => deleteActions.setConfirmDelete(null)}
|
||||
/>
|
||||
)}
|
||||
{folderActions.confirmDeleteFolder && (
|
||||
<ConfirmDeleteDialog
|
||||
open={true}
|
||||
title={folderActions.confirmDeleteFolder.title}
|
||||
message={folderActions.confirmDeleteFolder.message}
|
||||
confirmLabel={folderActions.confirmDeleteFolder.confirmLabel}
|
||||
onConfirm={folderActions.confirmDeleteSelectedFolder}
|
||||
onCancel={folderActions.cancelDeleteFolder}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<UpdateBanner status={updateStatus} actions={updateActions} />
|
||||
<RenameDetectedBanner renames={detectedRenames} onUpdate={handleUpdateWikilinks} onDismiss={handleDismissRenames} />
|
||||
<StatusBar noteCount={vault.entries.length} modifiedCount={vault.modifiedFiles.length} vaultPath={resolvedPath} vaults={vaultSwitcher.allVaults} onSwitchVault={vaultSwitcher.switchVault} onOpenSettings={dialogs.openSettings} onOpenFeedback={openFeedback} onOpenLocalFolder={vaultSwitcher.handleOpenLocalFolder} onCreateEmptyVault={vaultSwitcher.handleCreateEmptyVault} onCloneVault={dialogs.openCloneVault} onCloneGettingStarted={cloneGettingStartedVault} onClickPending={() => handleSetSelection({ kind: 'filter', filter: 'changes' })} onClickPulse={() => handleSetSelection({ kind: 'filter', filter: 'pulse' })} onCommitPush={handleCommitPush} isOffline={networkStatus.isOffline} isGitVault={isGitVault} syncStatus={autoSync.syncStatus} lastSyncTime={autoSync.lastSyncTime} conflictCount={autoSync.conflictFiles.length} remoteStatus={autoSync.remoteStatus} onTriggerSync={autoSync.triggerSync} onPullAndPush={autoSync.pullAndPush} onOpenConflictResolver={conflictFlow.handleOpenConflictResolver} zoomLevel={zoom.zoomLevel} onZoomReset={zoom.zoomReset} buildNumber={buildNumber} onCheckForUpdates={handleCheckForUpdates} onRemoveVault={vaultSwitcher.removeVault} mcpStatus={mcpStatus} onInstallMcp={openMcpSetupDialog} aiAgentsStatus={aiAgentsStatus} vaultAiGuidanceStatus={vaultAiGuidanceStatus} defaultAiAgent={aiAgentPreferences.defaultAiAgent} onSetDefaultAiAgent={aiAgentPreferences.setDefaultAiAgent} onRestoreVaultAiGuidance={() => { void restoreVaultAiGuidance() }} />
|
||||
<DeleteProgressNotice count={deleteActions.pendingDeleteCount} />
|
||||
<Toast message={toastMessage} onDismiss={() => setToastMessage(null)} />
|
||||
<QuickOpenPalette open={dialogs.showQuickOpen} entries={vault.entries} onSelect={notes.handleSelectNote} onClose={dialogs.closeQuickOpen} />
|
||||
<CommandPalette
|
||||
open={dialogs.showCommandPalette}
|
||||
commands={commands}
|
||||
entries={vault.entries}
|
||||
aiAgentReady={aiAgentPreferences.defaultAiAgentReady}
|
||||
aiAgentLabel={aiAgentPreferences.defaultAiAgentLabel}
|
||||
onClose={dialogs.closeCommandPalette}
|
||||
/>
|
||||
<SearchPanel open={dialogs.showSearch} vaultPath={resolvedPath} entries={vault.entries} onSelectNote={notes.handleSelectNote} onClose={dialogs.closeSearch} />
|
||||
<CreateTypeDialog open={dialogs.showCreateTypeDialog} onClose={dialogs.closeCreateType} onCreate={handleCreateType} />
|
||||
<CreateViewDialog open={dialogs.showCreateViewDialog} onClose={dialogs.closeCreateView} onCreate={handleCreateOrUpdateView} availableFields={availableFields} editingView={dialogs.editingView?.definition ?? null} />
|
||||
<CommitDialog
|
||||
open={commitFlow.showCommitDialog}
|
||||
modifiedCount={vault.modifiedFiles.length}
|
||||
commitMode={commitFlow.commitMode}
|
||||
suggestedMessage={suggestedCommitMessage}
|
||||
onCommit={commitFlow.handleCommitPush}
|
||||
onClose={commitFlow.closeCommitDialog}
|
||||
/>
|
||||
<ConflictResolverModal
|
||||
open={dialogs.showConflictResolver}
|
||||
fileStates={conflictResolver.fileStates}
|
||||
allResolved={conflictResolver.allResolved}
|
||||
committing={conflictResolver.committing}
|
||||
error={conflictResolver.error}
|
||||
onResolveFile={conflictResolver.resolveFile}
|
||||
onOpenInEditor={conflictResolver.openInEditor}
|
||||
onCommit={conflictResolver.commitResolution}
|
||||
onClose={conflictFlow.handleCloseConflictResolver}
|
||||
/>
|
||||
<SettingsPanel open={dialogs.showSettings} settings={settings} aiAgentsStatus={aiAgentsStatus} isGitVault={isGitVault} onSave={saveSettings} explicitOrganizationEnabled={explicitOrganizationEnabled} onSaveExplicitOrganization={handleSaveExplicitOrganization} onClose={dialogs.closeSettings} />
|
||||
<FeedbackDialog open={showFeedback} onClose={closeFeedback} />
|
||||
<McpSetupDialog open={showMcpSetupDialog} status={mcpStatus} busyAction={mcpDialogAction} onClose={closeMcpSetupDialog} onConnect={handleConnectMcp} onDisconnect={handleDisconnectMcp} />
|
||||
<CloneVaultModal key={dialogs.showCloneVault ? 'clone-open' : 'clone-closed'} open={dialogs.showCloneVault} onClose={dialogs.closeCloneVault} onVaultCloned={vaultSwitcher.handleVaultCloned} />
|
||||
{deleteActions.confirmDelete && (
|
||||
<ConfirmDeleteDialog
|
||||
open={true}
|
||||
title={deleteActions.confirmDelete.title}
|
||||
message={deleteActions.confirmDelete.message}
|
||||
confirmLabel={deleteActions.confirmDelete.confirmLabel}
|
||||
onConfirm={deleteActions.confirmDelete.onConfirm}
|
||||
onCancel={() => deleteActions.setConfirmDelete(null)}
|
||||
/>
|
||||
)}
|
||||
{folderActions.confirmDeleteFolder && (
|
||||
<ConfirmDeleteDialog
|
||||
open={true}
|
||||
title={folderActions.confirmDeleteFolder.title}
|
||||
message={folderActions.confirmDeleteFolder.message}
|
||||
confirmLabel={folderActions.confirmDeleteFolder.confirmLabel}
|
||||
onConfirm={folderActions.confirmDeleteSelectedFolder}
|
||||
onCancel={folderActions.cancelDeleteFolder}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</NoteRetargetingProvider>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,19 @@ describe('CreateTypeDialog', () => {
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('stays open when create reports a handled collision', async () => {
|
||||
const onClose = vi.fn()
|
||||
const onCreate = vi.fn().mockResolvedValue(false)
|
||||
render(<CreateTypeDialog open={true} onClose={onClose} onCreate={onCreate} />)
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('e.g. Recipe, Book, Habit...'), { target: { value: 'Recipe' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
|
||||
|
||||
await waitFor(() => expect(onCreate).toHaveBeenCalledWith('Recipe'))
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
expect(screen.getByText('Create New Type')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onClose when Cancel is clicked', () => {
|
||||
const onClose = vi.fn()
|
||||
render(<CreateTypeDialog open={true} onClose={onClose} onCreate={() => {}} />)
|
||||
|
||||
@@ -6,14 +6,14 @@ import { Input } from '@/components/ui/input'
|
||||
interface CreateTypeDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onCreate: (name: string) => void | Promise<void>
|
||||
onCreate: (name: string) => boolean | void | Promise<boolean | void>
|
||||
initialName?: string
|
||||
}
|
||||
|
||||
interface CreateTypeDialogFormProps {
|
||||
initialName: string
|
||||
onClose: () => void
|
||||
onCreate: (name: string) => void | Promise<void>
|
||||
onCreate: (name: string) => boolean | void | Promise<boolean | void>
|
||||
}
|
||||
|
||||
function CreateTypeDialogForm({ initialName, onClose, onCreate }: CreateTypeDialogFormProps) {
|
||||
@@ -23,8 +23,8 @@ function CreateTypeDialogForm({ initialName, onClose, onCreate }: CreateTypeDial
|
||||
e.preventDefault()
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) return
|
||||
await onCreate(trimmed)
|
||||
onClose()
|
||||
const created = await onCreate(trimmed)
|
||||
if (created !== false) onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -239,7 +239,7 @@ export function DynamicPropertiesPanel({
|
||||
onDeleteProperty?: (key: string) => void
|
||||
onAddProperty?: (key: string, value: FrontmatterValue) => void
|
||||
onNavigate?: (target: string) => void
|
||||
onCreateMissingType?: (typeName: string) => void | Promise<void>
|
||||
onCreateMissingType?: (typeName: string) => boolean | void | Promise<boolean | void>
|
||||
}) {
|
||||
const {
|
||||
editingKey, setEditingKey, showAddDialog, setShowAddDialog, displayOverrides,
|
||||
|
||||
@@ -52,7 +52,7 @@ interface EditorProps {
|
||||
onUpdateFrontmatter?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onDeleteProperty?: (path: string, key: string) => Promise<void>
|
||||
onAddProperty?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<boolean | void>
|
||||
onCreateAndOpenNote?: (title: string) => Promise<boolean>
|
||||
onInitializeProperties?: (path: string) => void
|
||||
showAIChat?: boolean
|
||||
@@ -360,7 +360,7 @@ function EditorLayout({
|
||||
onUpdateFrontmatter?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onDeleteProperty?: (path: string, key: string) => Promise<void>
|
||||
onAddProperty?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<boolean | void>
|
||||
onCreateAndOpenNote?: (title: string) => Promise<boolean>
|
||||
onInitializeProperties?: (path: string) => void
|
||||
onFileCreated?: (relativePath: string) => void
|
||||
|
||||
@@ -27,7 +27,7 @@ interface EditorRightPanelProps {
|
||||
onUpdateFrontmatter?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onDeleteProperty?: (path: string, key: string) => Promise<void>
|
||||
onAddProperty?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<boolean | void>
|
||||
onCreateAndOpenNote?: (title: string) => Promise<boolean>
|
||||
onInitializeProperties?: (path: string) => void
|
||||
onToggleRawEditor?: () => void
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { useState } from 'react'
|
||||
import { act, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { FolderTree } from './FolderTree'
|
||||
import { FOLDER_ROW_SINGLE_CLICK_DELAY_MS } from './folder-tree/useFolderRowInteractions'
|
||||
import type { FolderNode, SidebarSelection } from '../types'
|
||||
|
||||
const mockFolders: FolderNode[] = [
|
||||
@@ -49,6 +51,32 @@ describe('FolderTree', () => {
|
||||
expect(onSelect).toHaveBeenCalledWith({ kind: 'folder', path: 'projects' })
|
||||
})
|
||||
|
||||
it('expands children when single-clicking a folder row with children', () => {
|
||||
vi.useFakeTimers()
|
||||
function FolderTreeHarness() {
|
||||
const [selection, setSelection] = useState<SidebarSelection>(defaultSelection)
|
||||
return <FolderTree folders={mockFolders} selection={selection} onSelect={setSelection} />
|
||||
}
|
||||
|
||||
render(<FolderTreeHarness />)
|
||||
|
||||
fireEvent.click(screen.getByTestId('folder-row:projects'))
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(FOLDER_ROW_SINGLE_CLICK_DELAY_MS)
|
||||
})
|
||||
|
||||
expect(screen.getByText('laputa')).toBeInTheDocument()
|
||||
expect(screen.getByText('portfolio')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByTestId('folder-row:projects'))
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(FOLDER_ROW_SINGLE_CLICK_DELAY_MS)
|
||||
})
|
||||
|
||||
expect(screen.queryByText('laputa')).not.toBeInTheDocument()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('collapses section when clicking the FOLDERS header', () => {
|
||||
render(<FolderTree folders={mockFolders} selection={defaultSelection} onSelect={vi.fn()} />)
|
||||
expect(screen.getByText('projects')).toBeInTheDocument()
|
||||
@@ -87,8 +115,45 @@ describe('FolderTree', () => {
|
||||
onCancelRenameFolder={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
fireEvent.doubleClick(screen.getByTestId('folder-row:areas'))
|
||||
expect(onStartRenameFolder).toHaveBeenCalledWith('areas')
|
||||
fireEvent.doubleClick(screen.getByTestId('folder-row:projects'))
|
||||
expect(onStartRenameFolder).toHaveBeenCalledWith('projects')
|
||||
})
|
||||
|
||||
it('shows inline rename and delete actions for folders', () => {
|
||||
const onDeleteFolder = vi.fn()
|
||||
const onStartRenameFolder = vi.fn()
|
||||
const onSelect = vi.fn()
|
||||
render(
|
||||
<FolderTree
|
||||
folders={mockFolders}
|
||||
selection={defaultSelection}
|
||||
onSelect={onSelect}
|
||||
onDeleteFolder={onDeleteFolder}
|
||||
onRenameFolder={vi.fn().mockResolvedValue(true)}
|
||||
onStartRenameFolder={onStartRenameFolder}
|
||||
onCancelRenameFolder={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByTestId('rename-folder-btn:projects'))
|
||||
fireEvent.click(screen.getByTestId('delete-folder-btn:projects'))
|
||||
|
||||
expect(onSelect).toHaveBeenNthCalledWith(1, { kind: 'folder', path: 'projects' })
|
||||
expect(onStartRenameFolder).toHaveBeenCalledWith('projects')
|
||||
expect(onSelect).toHaveBeenNthCalledWith(2, { kind: 'folder', path: 'projects' })
|
||||
expect(onDeleteFolder).toHaveBeenCalledWith('projects')
|
||||
})
|
||||
|
||||
it('does not reserve a disclosure slot for leaf folders', () => {
|
||||
render(<FolderTree folders={mockFolders} selection={defaultSelection} onSelect={vi.fn()} />)
|
||||
|
||||
const leafRowContainer = screen.getByTestId('folder-row:areas').parentElement
|
||||
const parentRowContainer = screen.getByTestId('folder-row:projects').parentElement
|
||||
|
||||
expect(leafRowContainer).not.toBeNull()
|
||||
expect(parentRowContainer).not.toBeNull()
|
||||
expect(within(leafRowContainer as HTMLElement).queryAllByRole('button')).toHaveLength(1)
|
||||
expect(within(parentRowContainer as HTMLElement).queryAllByRole('button')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('shows the rename input when a folder is being renamed', () => {
|
||||
@@ -105,6 +170,43 @@ describe('FolderTree', () => {
|
||||
expect(screen.getByTestId('rename-folder-input')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps folder toggling healthy after cancelling rename', () => {
|
||||
vi.useFakeTimers()
|
||||
const onCancelRenameFolder = vi.fn()
|
||||
const { rerender } = render(
|
||||
<FolderTree
|
||||
folders={mockFolders}
|
||||
selection={{ kind: 'folder', path: 'projects' }}
|
||||
onSelect={vi.fn()}
|
||||
onRenameFolder={vi.fn().mockResolvedValue(true)}
|
||||
renamingFolderPath="projects"
|
||||
onCancelRenameFolder={onCancelRenameFolder}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.keyDown(screen.getByTestId('rename-folder-input'), { key: 'Escape' })
|
||||
expect(onCancelRenameFolder).toHaveBeenCalledTimes(1)
|
||||
|
||||
rerender(
|
||||
<FolderTree
|
||||
folders={mockFolders}
|
||||
selection={{ kind: 'folder', path: 'projects' }}
|
||||
onSelect={vi.fn()}
|
||||
onRenameFolder={vi.fn().mockResolvedValue(true)}
|
||||
onCancelRenameFolder={onCancelRenameFolder}
|
||||
/>,
|
||||
)
|
||||
|
||||
const wasExpanded = screen.queryByText('laputa') !== null
|
||||
fireEvent.click(screen.getByTestId('folder-row:projects'))
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(FOLDER_ROW_SINGLE_CLICK_DELAY_MS)
|
||||
})
|
||||
|
||||
expect(screen.queryByText('laputa') !== null).toBe(!wasExpanded)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('opens a context menu with a delete action on right-click', () => {
|
||||
const onDeleteFolder = vi.fn()
|
||||
render(
|
||||
|
||||
@@ -32,7 +32,7 @@ interface InspectorProps {
|
||||
onUpdateFrontmatter?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onDeleteProperty?: (path: string, key: string) => Promise<void>
|
||||
onAddProperty?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<boolean | void>
|
||||
onCreateAndOpenNote?: (title: string) => Promise<boolean>
|
||||
onInitializeProperties?: (path: string) => void
|
||||
onToggleRawEditor?: () => void
|
||||
@@ -71,7 +71,7 @@ function ValidFrontmatterPanels({
|
||||
onUpdateProperty?: (key: string, value: FrontmatterValue) => void
|
||||
onDeleteProperty?: (key: string) => void
|
||||
onAddProperty?: (key: string, value: FrontmatterValue) => void
|
||||
onCreateMissingType?: (typeName: string) => Promise<void>
|
||||
onCreateMissingType?: (typeName: string) => Promise<boolean | void>
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
@@ -134,7 +134,7 @@ function PrimaryInspectorPanel({
|
||||
onUpdateProperty?: (key: string, value: FrontmatterValue) => void
|
||||
onDeleteProperty?: (key: string) => void
|
||||
onAddProperty?: (key: string, value: FrontmatterValue) => void
|
||||
onCreateMissingType?: (typeName: string) => Promise<void>
|
||||
onCreateMissingType?: (typeName: string) => Promise<boolean | void>
|
||||
}) {
|
||||
if (frontmatterState === 'valid') {
|
||||
return (
|
||||
@@ -162,12 +162,10 @@ function PrimaryInspectorPanel({
|
||||
return onInitializeProperties ? <InitializePropertiesPrompt onClick={() => onInitializeProperties(entry.path)} /> : null
|
||||
}
|
||||
|
||||
export function Inspector({
|
||||
collapsed,
|
||||
onToggle,
|
||||
function InspectorBody({
|
||||
entry,
|
||||
content,
|
||||
entries,
|
||||
content,
|
||||
gitHistory,
|
||||
vaultPath,
|
||||
onNavigate,
|
||||
@@ -179,7 +177,7 @@ export function Inspector({
|
||||
onCreateAndOpenNote,
|
||||
onInitializeProperties,
|
||||
onToggleRawEditor,
|
||||
}: InspectorProps) {
|
||||
}: Omit<InspectorProps, 'collapsed' | 'onToggle'>) {
|
||||
const referencedBy = useReferencedBy(entry, entries)
|
||||
const backlinks = useBacklinks(entry, entries, referencedBy)
|
||||
const frontmatter = useMemo(() => parseFrontmatter(content), [content])
|
||||
@@ -198,40 +196,46 @@ export function Inspector({
|
||||
onCreateMissingType,
|
||||
})
|
||||
|
||||
if (!entry) {
|
||||
return <EmptyInspector />
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PrimaryInspectorPanel
|
||||
entry={entry}
|
||||
frontmatterState={frontmatterState}
|
||||
frontmatter={frontmatter}
|
||||
entries={entries}
|
||||
typeEntryMap={typeEntryMap}
|
||||
vaultPath={vaultPath}
|
||||
referencedBy={referencedBy}
|
||||
onNavigate={onNavigate}
|
||||
onToggleRawEditor={onToggleRawEditor}
|
||||
onInitializeProperties={onInitializeProperties}
|
||||
onCreateAndOpenNote={onCreateAndOpenNote}
|
||||
onUpdateProperty={onUpdateFrontmatter ? handleUpdateProperty : undefined}
|
||||
onDeleteProperty={onDeleteProperty ? handleDeleteProperty : undefined}
|
||||
onAddProperty={onAddProperty ? handleAddProperty : undefined}
|
||||
onCreateMissingType={onCreateMissingType ? handleCreateMissingType : undefined}
|
||||
/>
|
||||
{backlinks.length > 0 && <Separator />}
|
||||
<BacklinksPanel backlinks={backlinks} onNavigate={onNavigate} />
|
||||
<Separator />
|
||||
<NoteInfoPanel entry={entry} content={content} />
|
||||
{gitHistory.length > 0 && <Separator />}
|
||||
<GitHistoryPanel commits={gitHistory} onViewCommitDiff={onViewCommitDiff} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function Inspector({ collapsed, onToggle, ...bodyProps }: InspectorProps) {
|
||||
return (
|
||||
<aside className={cn('flex flex-1 flex-col overflow-hidden border-l border-border bg-background text-foreground transition-[width] duration-200', collapsed && '!w-10 !min-w-10')}>
|
||||
<InspectorHeader collapsed={collapsed} onToggle={onToggle} />
|
||||
{!collapsed && (
|
||||
<div className="flex flex-1 flex-col gap-4 overflow-y-auto p-3">
|
||||
{entry ? (
|
||||
<>
|
||||
<PrimaryInspectorPanel
|
||||
entry={entry}
|
||||
frontmatterState={frontmatterState}
|
||||
frontmatter={frontmatter}
|
||||
entries={entries}
|
||||
typeEntryMap={typeEntryMap}
|
||||
vaultPath={vaultPath}
|
||||
referencedBy={referencedBy}
|
||||
onNavigate={onNavigate}
|
||||
onToggleRawEditor={onToggleRawEditor}
|
||||
onInitializeProperties={onInitializeProperties}
|
||||
onCreateAndOpenNote={onCreateAndOpenNote}
|
||||
onUpdateProperty={onUpdateFrontmatter ? handleUpdateProperty : undefined}
|
||||
onDeleteProperty={onDeleteProperty ? handleDeleteProperty : undefined}
|
||||
onAddProperty={onAddProperty ? handleAddProperty : undefined}
|
||||
onCreateMissingType={onCreateMissingType ? handleCreateMissingType : undefined}
|
||||
/>
|
||||
{backlinks.length > 0 && <Separator />}
|
||||
<BacklinksPanel backlinks={backlinks} onNavigate={onNavigate} />
|
||||
<Separator />
|
||||
<NoteInfoPanel entry={entry} content={content} />
|
||||
{gitHistory.length > 0 && <Separator />}
|
||||
<GitHistoryPanel commits={gitHistory} onViewCommitDiff={onViewCommitDiff} />
|
||||
</>
|
||||
) : (
|
||||
<EmptyInspector />
|
||||
)}
|
||||
<InspectorBody {...bodyProps} />
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
|
||||
@@ -118,7 +118,7 @@ function MissingTypeWarning({
|
||||
onCreateMissingType,
|
||||
}: {
|
||||
missingTypeName: string
|
||||
onCreateMissingType?: (typeName: string) => void | Promise<void>
|
||||
onCreateMissingType?: (typeName: string) => boolean | void | Promise<boolean | void>
|
||||
}) {
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const canCreateMissingType = Boolean(onCreateMissingType)
|
||||
@@ -148,9 +148,7 @@ function MissingTypeWarning({
|
||||
<CreateTypeDialog
|
||||
open={dialogOpen}
|
||||
onClose={() => setDialogOpen(false)}
|
||||
onCreate={async (typeName) => {
|
||||
await onCreateMissingType?.(typeName)
|
||||
}}
|
||||
onCreate={(typeName) => onCreateMissingType?.(typeName)}
|
||||
initialName={missingTypeName}
|
||||
/>
|
||||
)}
|
||||
@@ -165,7 +163,7 @@ function TypeRowValue({
|
||||
}: {
|
||||
children: ReactNode
|
||||
missingTypeName?: string | null
|
||||
onCreateMissingType?: (typeName: string) => void | Promise<void>
|
||||
onCreateMissingType?: (typeName: string) => boolean | void | Promise<boolean | void>
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-w-0 items-center justify-start gap-1">
|
||||
@@ -191,7 +189,7 @@ function ReadOnlyType({
|
||||
customColorKey?: string | null
|
||||
onNavigate?: (target: string) => void
|
||||
missingTypeName?: string | null
|
||||
onCreateMissingType?: (typeName: string) => void | Promise<void>
|
||||
onCreateMissingType?: (typeName: string) => boolean | void | Promise<boolean | void>
|
||||
}) {
|
||||
if (!isA) return null
|
||||
return (
|
||||
@@ -230,7 +228,7 @@ interface TypeSelectorProps {
|
||||
onUpdateProperty?: (key: string, value: FrontmatterValue) => void
|
||||
onNavigate?: (target: string) => void
|
||||
missingTypeName?: string | null
|
||||
onCreateMissingType?: (typeName: string) => void | Promise<void>
|
||||
onCreateMissingType?: (typeName: string) => boolean | void | Promise<boolean | void>
|
||||
}
|
||||
|
||||
export function TypeSelector({ onUpdateProperty, ...props }: TypeSelectorProps) {
|
||||
|
||||
228
src/components/folder-tree/FolderItemRow.tsx
Normal file
228
src/components/folder-tree/FolderItemRow.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
import type { MouseEvent as ReactMouseEvent, ReactNode } from 'react'
|
||||
import {
|
||||
CaretDown,
|
||||
CaretRight,
|
||||
Folder,
|
||||
FolderOpen,
|
||||
PencilSimple,
|
||||
Trash,
|
||||
} from '@phosphor-icons/react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { FolderNode } from '../../types'
|
||||
import { useFolderRowInteractions } from './useFolderRowInteractions'
|
||||
|
||||
interface FolderItemRowProps {
|
||||
contentInset: number
|
||||
depthIndent: number
|
||||
isExpanded: boolean
|
||||
isSelected: boolean
|
||||
node: FolderNode
|
||||
onDeleteFolder?: (folderPath: string) => void
|
||||
onOpenMenu: (node: FolderNode, event: ReactMouseEvent<HTMLDivElement>) => void
|
||||
onSelect: () => void
|
||||
onStartRenameFolder?: (folderPath: string) => void
|
||||
onToggle: (path: string) => void
|
||||
}
|
||||
|
||||
export function FolderItemRow({
|
||||
contentInset,
|
||||
depthIndent,
|
||||
isExpanded,
|
||||
isSelected,
|
||||
node,
|
||||
onDeleteFolder,
|
||||
onOpenMenu,
|
||||
onSelect,
|
||||
onStartRenameFolder,
|
||||
onToggle,
|
||||
}: FolderItemRowProps) {
|
||||
const hasChildren = node.children.length > 0
|
||||
const expandLabel = isExpanded ? `Collapse ${node.name}` : `Expand ${node.name}`
|
||||
const hasActions = !!onStartRenameFolder || !!onDeleteFolder
|
||||
const { handleRenameDoubleClick, handleSelectClick } = useFolderRowInteractions({
|
||||
hasChildren,
|
||||
onRenameFolder: onStartRenameFolder ? () => onStartRenameFolder(node.path) : undefined,
|
||||
onSelect,
|
||||
onToggle: () => onToggle(node.path),
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group relative flex items-center gap-1 rounded transition-colors',
|
||||
isSelected
|
||||
? 'bg-[var(--accent-blue-light,rgba(0,100,255,0.08))] text-primary'
|
||||
: 'text-foreground hover:bg-accent',
|
||||
)}
|
||||
style={{ paddingLeft: depthIndent, borderRadius: 4 }}
|
||||
onContextMenu={(event) => {
|
||||
onSelect()
|
||||
onOpenMenu(node, event)
|
||||
}}
|
||||
>
|
||||
<FolderToggleButton
|
||||
expandLabel={expandLabel}
|
||||
hasChildren={hasChildren}
|
||||
isExpanded={isExpanded}
|
||||
onToggle={() => onToggle(node.path)}
|
||||
/>
|
||||
<FolderSelectButton
|
||||
contentInset={contentInset}
|
||||
hasActions={hasActions}
|
||||
hasChildren={hasChildren}
|
||||
isExpanded={isExpanded}
|
||||
isSelected={isSelected}
|
||||
node={node}
|
||||
onClick={handleSelectClick}
|
||||
onDoubleClick={handleRenameDoubleClick}
|
||||
/>
|
||||
{hasActions && (
|
||||
<div className="pointer-events-none absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-0.5 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
|
||||
{onStartRenameFolder && (
|
||||
<FolderActionButton
|
||||
ariaLabel={`Rename ${node.name}`}
|
||||
testId={`rename-folder-btn:${node.path}`}
|
||||
title="Rename folder"
|
||||
onClick={() => {
|
||||
onSelect()
|
||||
onStartRenameFolder(node.path)
|
||||
}}
|
||||
>
|
||||
<PencilSimple size={12} />
|
||||
</FolderActionButton>
|
||||
)}
|
||||
{onDeleteFolder && (
|
||||
<FolderActionButton
|
||||
ariaLabel={`Delete ${node.name}`}
|
||||
testId={`delete-folder-btn:${node.path}`}
|
||||
title="Delete folder"
|
||||
destructive
|
||||
onClick={() => {
|
||||
onSelect()
|
||||
onDeleteFolder(node.path)
|
||||
}}
|
||||
>
|
||||
<Trash size={12} />
|
||||
</FolderActionButton>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FolderToggleButton({
|
||||
expandLabel,
|
||||
hasChildren,
|
||||
isExpanded,
|
||||
onToggle,
|
||||
}: {
|
||||
expandLabel: string
|
||||
hasChildren: boolean
|
||||
isExpanded: boolean
|
||||
onToggle: () => void
|
||||
}) {
|
||||
if (!hasChildren) return null
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="h-6 w-4 shrink-0 p-0 text-muted-foreground hover:bg-transparent hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onToggle()
|
||||
}}
|
||||
aria-label={expandLabel}
|
||||
>
|
||||
{isExpanded ? <CaretDown size={12} /> : <CaretRight size={12} />}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function FolderActionButton({
|
||||
ariaLabel,
|
||||
children,
|
||||
destructive = false,
|
||||
onClick,
|
||||
testId,
|
||||
title,
|
||||
}: {
|
||||
ariaLabel: string
|
||||
children: ReactNode
|
||||
destructive?: boolean
|
||||
onClick: () => void
|
||||
testId: string
|
||||
title: string
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
aria-label={ariaLabel}
|
||||
title={title}
|
||||
className={cn(
|
||||
'h-5 w-5 rounded p-0 text-muted-foreground',
|
||||
destructive ? 'hover:text-destructive' : 'hover:text-foreground',
|
||||
)}
|
||||
data-testid={testId}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onClick()
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function FolderSelectButton({
|
||||
contentInset,
|
||||
hasActions,
|
||||
hasChildren,
|
||||
isExpanded,
|
||||
isSelected,
|
||||
node,
|
||||
onClick,
|
||||
onDoubleClick,
|
||||
}: {
|
||||
contentInset: number
|
||||
hasActions: boolean
|
||||
hasChildren: boolean
|
||||
isExpanded: boolean
|
||||
isSelected: boolean
|
||||
node: FolderNode
|
||||
onClick: (clickDetail: number) => void
|
||||
onDoubleClick: () => void
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'h-auto flex-1 justify-start gap-2 rounded text-left text-[13px] font-medium hover:bg-transparent',
|
||||
isSelected ? 'text-primary hover:text-primary' : 'text-foreground hover:text-foreground',
|
||||
)}
|
||||
style={{
|
||||
paddingTop: 6,
|
||||
paddingBottom: 6,
|
||||
paddingLeft: hasChildren ? 0 : contentInset,
|
||||
paddingRight: hasActions ? 48 : 16,
|
||||
}}
|
||||
title={node.path}
|
||||
onClick={(event) => onClick(event.detail)}
|
||||
onDoubleClick={onDoubleClick}
|
||||
data-testid={`folder-row:${node.path}`}
|
||||
>
|
||||
{isSelected || isExpanded ? (
|
||||
<FolderOpen size={17} weight="fill" className="size-[17px] shrink-0" />
|
||||
) : (
|
||||
<Folder size={17} className="size-[17px] shrink-0" />
|
||||
)}
|
||||
<span className="truncate">{node.name}</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ interface FolderNameInputProps {
|
||||
ariaLabel: string
|
||||
initialValue: string
|
||||
placeholder: string
|
||||
leftInset?: number
|
||||
selectTextOnFocus?: boolean
|
||||
submitOnBlur?: boolean
|
||||
testId: string
|
||||
@@ -17,6 +18,7 @@ export function FolderNameInput({
|
||||
ariaLabel,
|
||||
initialValue,
|
||||
placeholder,
|
||||
leftInset = 16,
|
||||
selectTextOnFocus = false,
|
||||
submitOnBlur = false,
|
||||
testId,
|
||||
@@ -45,12 +47,12 @@ export function FolderNameInput({
|
||||
}, [onSubmit, value])
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2" style={{ padding: '4px 8px' }}>
|
||||
<Folder size={18} className="shrink-0 text-muted-foreground" />
|
||||
<div className="flex items-center gap-2 rounded" style={{ paddingTop: 6, paddingBottom: 6, paddingRight: 16, paddingLeft: leftInset, borderRadius: 4 }}>
|
||||
<Folder size={17} className="size-[17px] shrink-0 text-muted-foreground" />
|
||||
<Input
|
||||
ref={inputRef}
|
||||
aria-label={ariaLabel}
|
||||
className="h-7 flex-1 rounded-sm px-2 text-[13px]"
|
||||
className="h-auto min-h-0 flex-1 rounded-sm px-2 py-[3px] text-[13px] font-medium"
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
onBlur={submitOnBlur ? () => { void handleSubmit() } : undefined}
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
import { memo, useCallback, type MouseEvent as ReactMouseEvent } from 'react'
|
||||
import {
|
||||
CaretDown,
|
||||
CaretRight,
|
||||
Folder,
|
||||
FolderOpen,
|
||||
} from '@phosphor-icons/react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { FolderNode, SidebarSelection } from '../../types'
|
||||
import { NoteDropTarget } from '../note-retargeting/NoteDropTarget'
|
||||
import { useNoteRetargetingContext } from '../note-retargeting/noteRetargetingContext'
|
||||
import { FolderNameInput } from './FolderNameInput'
|
||||
import { FolderItemRow } from './FolderItemRow'
|
||||
|
||||
interface FolderTreeRowProps {
|
||||
depth: number
|
||||
@@ -26,22 +21,25 @@ interface FolderTreeRowProps {
|
||||
}
|
||||
|
||||
function FolderRenameRow({
|
||||
indentation,
|
||||
contentInset,
|
||||
depthIndent,
|
||||
node,
|
||||
onCancelRenameFolder,
|
||||
onRenameFolder,
|
||||
}: {
|
||||
indentation: number
|
||||
contentInset: number
|
||||
depthIndent: number
|
||||
node: FolderNode
|
||||
onCancelRenameFolder: () => void
|
||||
onRenameFolder: (folderPath: string, nextName: string) => Promise<boolean> | boolean
|
||||
}) {
|
||||
return (
|
||||
<div style={{ paddingLeft: indentation }}>
|
||||
<div style={{ paddingLeft: depthIndent }}>
|
||||
<FolderNameInput
|
||||
ariaLabel="Folder name"
|
||||
initialValue={node.name}
|
||||
placeholder="Folder name"
|
||||
leftInset={contentInset}
|
||||
selectTextOnFocus={true}
|
||||
testId="rename-folder-input"
|
||||
onCancel={onCancelRenameFolder}
|
||||
@@ -51,131 +49,6 @@ function FolderRenameRow({
|
||||
)
|
||||
}
|
||||
|
||||
function FolderItemRow({
|
||||
indentation,
|
||||
isExpanded,
|
||||
isSelected,
|
||||
node,
|
||||
onOpenMenu,
|
||||
onSelect,
|
||||
onStartRenameFolder,
|
||||
onToggle,
|
||||
}: {
|
||||
indentation: number
|
||||
isExpanded: boolean
|
||||
isSelected: boolean
|
||||
node: FolderNode
|
||||
onOpenMenu: FolderTreeRowProps['onOpenMenu']
|
||||
onSelect: () => void
|
||||
onStartRenameFolder?: (folderPath: string) => void
|
||||
onToggle: (path: string) => void
|
||||
}) {
|
||||
const hasChildren = node.children.length > 0
|
||||
const expandLabel = isExpanded ? `Collapse ${node.name}` : `Expand ${node.name}`
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group flex items-center gap-1 rounded-[5px] transition-colors',
|
||||
isSelected
|
||||
? 'bg-[var(--accent-blue-light,rgba(0,100,255,0.08))] text-primary'
|
||||
: 'text-foreground hover:bg-accent',
|
||||
)}
|
||||
style={{ paddingLeft: indentation }}
|
||||
onContextMenu={(event) => {
|
||||
onSelect()
|
||||
onOpenMenu(node, event)
|
||||
}}
|
||||
>
|
||||
<FolderToggleButton
|
||||
expandLabel={expandLabel}
|
||||
hasChildren={hasChildren}
|
||||
isExpanded={isExpanded}
|
||||
onToggle={() => onToggle(node.path)}
|
||||
/>
|
||||
<FolderSelectButton
|
||||
isExpanded={isExpanded}
|
||||
isSelected={isSelected}
|
||||
node={node}
|
||||
onSelect={onSelect}
|
||||
onStartRenameFolder={onStartRenameFolder}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FolderToggleButton({
|
||||
expandLabel,
|
||||
hasChildren,
|
||||
isExpanded,
|
||||
onToggle,
|
||||
}: {
|
||||
expandLabel: string
|
||||
hasChildren: boolean
|
||||
isExpanded: boolean
|
||||
onToggle: () => void
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="h-6 w-4 shrink-0 p-0 text-muted-foreground hover:bg-transparent hover:text-foreground"
|
||||
disabled={!hasChildren}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
if (hasChildren) onToggle()
|
||||
}}
|
||||
aria-label={hasChildren ? expandLabel : undefined}
|
||||
>
|
||||
{hasChildren ? (
|
||||
isExpanded ? <CaretDown size={12} /> : <CaretRight size={12} />
|
||||
) : (
|
||||
<span className="block h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function FolderSelectButton({
|
||||
isExpanded,
|
||||
isSelected,
|
||||
node,
|
||||
onSelect,
|
||||
onStartRenameFolder,
|
||||
}: {
|
||||
isExpanded: boolean
|
||||
isSelected: boolean
|
||||
node: FolderNode
|
||||
onSelect: () => void
|
||||
onStartRenameFolder?: (folderPath: string) => void
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'h-7 flex-1 justify-start gap-2 rounded-[5px] px-2 py-0 text-left text-[13px]',
|
||||
isSelected ? 'font-medium text-primary hover:text-primary' : 'hover:text-foreground',
|
||||
)}
|
||||
title={node.path}
|
||||
onClick={onSelect}
|
||||
onDoubleClick={() => {
|
||||
onSelect()
|
||||
onStartRenameFolder?.(node.path)
|
||||
}}
|
||||
data-testid={`folder-row:${node.path}`}
|
||||
>
|
||||
{isSelected || isExpanded ? (
|
||||
<FolderOpen size={18} weight="fill" className="shrink-0" />
|
||||
) : (
|
||||
<Folder size={18} className="shrink-0" />
|
||||
)}
|
||||
<span className="truncate">{node.name}</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function FolderChildren({
|
||||
depth,
|
||||
expanded,
|
||||
@@ -238,31 +111,46 @@ export const FolderTreeRow = memo(function FolderTreeRow({
|
||||
const isExpanded = expanded[node.path] ?? false
|
||||
const isRenaming = renamingFolderPath === node.path
|
||||
const isSelected = selection.kind === 'folder' && selection.path === node.path
|
||||
const indentation = 8 + depth * 16
|
||||
const depthIndent = depth * 16
|
||||
const contentInset = 16
|
||||
const noteRetargeting = useNoteRetargetingContext()
|
||||
const selectFolder = useCallback(() => {
|
||||
onSelect({ kind: 'folder', path: node.path })
|
||||
}, [node.path, onSelect])
|
||||
const row = (
|
||||
<FolderItemRow
|
||||
contentInset={contentInset}
|
||||
depthIndent={depthIndent}
|
||||
isExpanded={isExpanded}
|
||||
isSelected={isSelected}
|
||||
node={node}
|
||||
onDeleteFolder={onDeleteFolder}
|
||||
onOpenMenu={onOpenMenu}
|
||||
onSelect={selectFolder}
|
||||
onStartRenameFolder={onStartRenameFolder}
|
||||
onToggle={onToggle}
|
||||
/>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{isRenaming && onRenameFolder && onCancelRenameFolder ? (
|
||||
<FolderRenameRow
|
||||
indentation={indentation}
|
||||
contentInset={contentInset}
|
||||
depthIndent={depthIndent}
|
||||
node={node}
|
||||
onCancelRenameFolder={onCancelRenameFolder}
|
||||
onRenameFolder={onRenameFolder}
|
||||
/>
|
||||
) : (
|
||||
<FolderItemRow
|
||||
indentation={indentation}
|
||||
isExpanded={isExpanded}
|
||||
isSelected={isSelected}
|
||||
node={node}
|
||||
onOpenMenu={onOpenMenu}
|
||||
onSelect={selectFolder}
|
||||
onStartRenameFolder={onStartRenameFolder}
|
||||
onToggle={onToggle}
|
||||
/>
|
||||
noteRetargeting ? (
|
||||
<NoteDropTarget
|
||||
canAcceptNotePath={(notePath) => noteRetargeting.canDropNoteOnFolder(notePath, node.path)}
|
||||
onDropNote={(notePath) => noteRetargeting.dropNoteOnFolder(notePath, node.path)}
|
||||
>
|
||||
{row}
|
||||
</NoteDropTarget>
|
||||
) : row
|
||||
)}
|
||||
<FolderChildren
|
||||
depth={depth}
|
||||
|
||||
@@ -3,6 +3,10 @@ export function expandedTreePaths(path: string): string[] {
|
||||
return segments.map((_, index) => segments.slice(0, index + 1).join('/'))
|
||||
}
|
||||
|
||||
export function ancestorTreePaths(path: string): string[] {
|
||||
return expandedTreePaths(path).slice(0, -1)
|
||||
}
|
||||
|
||||
export function mergeExpandedPaths(
|
||||
current: Record<string, boolean>,
|
||||
paths: string[],
|
||||
|
||||
56
src/components/folder-tree/useFolderRowInteractions.ts
Normal file
56
src/components/folder-tree/useFolderRowInteractions.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
|
||||
export const FOLDER_ROW_SINGLE_CLICK_DELAY_MS = 180
|
||||
|
||||
interface UseFolderRowInteractionsInput {
|
||||
hasChildren: boolean
|
||||
onRenameFolder?: () => void
|
||||
onSelect: () => void
|
||||
onToggle: () => void
|
||||
}
|
||||
|
||||
export function useFolderRowInteractions({
|
||||
hasChildren,
|
||||
onRenameFolder,
|
||||
onSelect,
|
||||
onToggle,
|
||||
}: UseFolderRowInteractionsInput) {
|
||||
const pendingToggleRef = useRef<number | null>(null)
|
||||
|
||||
const clearPendingToggle = useCallback(() => {
|
||||
if (pendingToggleRef.current === null) return
|
||||
window.clearTimeout(pendingToggleRef.current)
|
||||
pendingToggleRef.current = null
|
||||
}, [])
|
||||
|
||||
useEffect(() => clearPendingToggle, [clearPendingToggle])
|
||||
|
||||
const handleSelectClick = useCallback((clickDetail: number) => {
|
||||
onSelect()
|
||||
if (!hasChildren) return
|
||||
|
||||
if (clickDetail === 0) {
|
||||
clearPendingToggle()
|
||||
onToggle()
|
||||
return
|
||||
}
|
||||
|
||||
if (clickDetail !== 1) return
|
||||
|
||||
clearPendingToggle()
|
||||
pendingToggleRef.current = window.setTimeout(() => {
|
||||
pendingToggleRef.current = null
|
||||
onToggle()
|
||||
}, FOLDER_ROW_SINGLE_CLICK_DELAY_MS)
|
||||
}, [clearPendingToggle, hasChildren, onSelect, onToggle])
|
||||
|
||||
const handleRenameDoubleClick = useCallback(() => {
|
||||
clearPendingToggle()
|
||||
onRenameFolder?.()
|
||||
}, [clearPendingToggle, onRenameFolder])
|
||||
|
||||
return {
|
||||
handleRenameDoubleClick,
|
||||
handleSelectClick,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import type { SidebarSelection } from '../../types'
|
||||
import { expandedTreePaths, mergeExpandedPaths } from './folderTreeUtils'
|
||||
import { ancestorTreePaths, expandedTreePaths, mergeExpandedPaths } from './folderTreeUtils'
|
||||
|
||||
interface UseFolderTreeDisclosureInput {
|
||||
collapsed?: boolean
|
||||
@@ -9,21 +9,11 @@ interface UseFolderTreeDisclosureInput {
|
||||
selection: SidebarSelection
|
||||
}
|
||||
|
||||
export function useFolderTreeDisclosure({
|
||||
collapsed: externalCollapsed,
|
||||
onToggle,
|
||||
renamingFolderPath,
|
||||
selection,
|
||||
}: UseFolderTreeDisclosureInput) {
|
||||
const [internalCollapsed, setInternalCollapsed] = useState(false)
|
||||
function useExpandedFolders(selection: SidebarSelection, renamingFolderPath?: string | null) {
|
||||
const [manualExpanded, setManualExpanded] = useState<Record<string, boolean>>({})
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
|
||||
const baseSectionCollapsed = externalCollapsed ?? internalCollapsed
|
||||
const sectionCollapsed = !isCreating && !renamingFolderPath && baseSectionCollapsed
|
||||
const requiredExpandedPaths = useMemo(() => {
|
||||
const nextPaths: string[] = []
|
||||
if (selection.kind === 'folder') nextPaths.push(...expandedTreePaths(selection.path))
|
||||
if (selection.kind === 'folder') nextPaths.push(...ancestorTreePaths(selection.path))
|
||||
if (renamingFolderPath) nextPaths.push(...expandedTreePaths(renamingFolderPath))
|
||||
return [...new Set(nextPaths)]
|
||||
}, [renamingFolderPath, selection])
|
||||
@@ -33,6 +23,27 @@ export function useFolderTreeDisclosure({
|
||||
[manualExpanded, requiredExpandedPaths],
|
||||
)
|
||||
|
||||
const toggleFolder = useCallback((path: string) => {
|
||||
setManualExpanded((current) => ({ ...current, [path]: !current[path] }))
|
||||
}, [])
|
||||
|
||||
return {
|
||||
expanded,
|
||||
toggleFolder,
|
||||
}
|
||||
}
|
||||
|
||||
function useFolderSectionState(
|
||||
externalCollapsed: boolean | undefined,
|
||||
onToggle: (() => void) | undefined,
|
||||
renamingFolderPath?: string | null,
|
||||
) {
|
||||
const [internalCollapsed, setInternalCollapsed] = useState(false)
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
|
||||
const baseSectionCollapsed = externalCollapsed ?? internalCollapsed
|
||||
const sectionCollapsed = !isCreating && !renamingFolderPath && baseSectionCollapsed
|
||||
|
||||
const handleToggleSection = useCallback(() => {
|
||||
if (onToggle) {
|
||||
onToggle()
|
||||
@@ -50,9 +61,30 @@ export function useFolderTreeDisclosure({
|
||||
}, [baseSectionCollapsed, onToggle])
|
||||
|
||||
const closeCreateForm = useCallback(() => setIsCreating(false), [])
|
||||
const toggleFolder = useCallback((path: string) => {
|
||||
setManualExpanded((current) => ({ ...current, [path]: !current[path] }))
|
||||
}, [])
|
||||
|
||||
return {
|
||||
handleToggleSection,
|
||||
isCreating,
|
||||
openCreateForm,
|
||||
sectionCollapsed,
|
||||
closeCreateForm,
|
||||
}
|
||||
}
|
||||
|
||||
export function useFolderTreeDisclosure({
|
||||
collapsed: externalCollapsed,
|
||||
onToggle,
|
||||
renamingFolderPath,
|
||||
selection,
|
||||
}: UseFolderTreeDisclosureInput) {
|
||||
const { expanded, toggleFolder } = useExpandedFolders(selection, renamingFolderPath)
|
||||
const {
|
||||
closeCreateForm,
|
||||
handleToggleSection,
|
||||
isCreating,
|
||||
openCreateForm,
|
||||
sectionCollapsed,
|
||||
} = useFolderSectionState(externalCollapsed, onToggle, renamingFolderPath)
|
||||
|
||||
return {
|
||||
closeCreateForm,
|
||||
|
||||
@@ -8,7 +8,7 @@ interface InspectorPropertyActionsConfig {
|
||||
onUpdateFrontmatter?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onDeleteProperty?: (path: string, key: string) => Promise<void>
|
||||
onAddProperty?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<void>
|
||||
onCreateMissingType?: (path: string, missingType: string, nextTypeName: string) => Promise<boolean | void>
|
||||
}
|
||||
|
||||
function bindEntryAction<TArgs extends unknown[], TResult>(
|
||||
@@ -21,7 +21,7 @@ function bindEntryAction<TArgs extends unknown[], TResult>(
|
||||
|
||||
function bindMissingTypeAction(
|
||||
entry: VaultEntry | null,
|
||||
action: ((path: string, missingType: string, nextTypeName: string) => Promise<void>) | undefined,
|
||||
action: ((path: string, missingType: string, nextTypeName: string) => Promise<boolean | void>) | undefined,
|
||||
) {
|
||||
const missingType = entry?.isA
|
||||
if (!entry || !missingType || !action) return undefined
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
import type { NoteListFilter } from '../../utils/noteListHelpers'
|
||||
import { countByFilter, countAllByFilter, countAllNotesByFilter } from '../../utils/noteListHelpers'
|
||||
import { NoteItem } from '../NoteItem'
|
||||
import { DraggableNoteItem } from '../note-retargeting/DraggableNoteItem'
|
||||
import { prefetchNoteContent } from '../../hooks/useTabManagement'
|
||||
import type { MultiSelectState } from '../../hooks/useMultiSelect'
|
||||
import { isDeletedNoteEntry, resolveHeaderTitle, type DeletedNoteEntry } from './noteListUtils'
|
||||
@@ -349,21 +350,39 @@ function useRenderItem({
|
||||
const contextMenuHandler = isChangesView && onDiscardFile ? noteContextMenu : undefined
|
||||
|
||||
return useCallback((entry: VaultEntry, options?: { forceSelected?: boolean }) => (
|
||||
<NoteItem
|
||||
key={entry.path}
|
||||
entry={entry}
|
||||
isSelected={options?.forceSelected || selectedNotePath === entry.path}
|
||||
isMultiSelected={multiSelect.selectedPaths.has(entry.path)}
|
||||
isHighlighted={entry.path === noteListKeyboard.highlightedPath}
|
||||
noteStatus={resolvedGetNoteStatus(entry.path)}
|
||||
changeStatus={getChangeStatus(entry.path)}
|
||||
typeEntryMap={typeEntryMap}
|
||||
allEntries={entries}
|
||||
displayPropsOverride={displayPropsOverride}
|
||||
onClickNote={handleClickNote}
|
||||
onPrefetch={isDeletedNoteEntry(entry) ? undefined : prefetchNoteContent}
|
||||
onContextMenu={contextMenuHandler}
|
||||
/>
|
||||
isDeletedNoteEntry(entry) ? (
|
||||
<NoteItem
|
||||
key={entry.path}
|
||||
entry={entry}
|
||||
isSelected={options?.forceSelected || selectedNotePath === entry.path}
|
||||
isMultiSelected={multiSelect.selectedPaths.has(entry.path)}
|
||||
isHighlighted={entry.path === noteListKeyboard.highlightedPath}
|
||||
noteStatus={resolvedGetNoteStatus(entry.path)}
|
||||
changeStatus={getChangeStatus(entry.path)}
|
||||
typeEntryMap={typeEntryMap}
|
||||
allEntries={entries}
|
||||
displayPropsOverride={displayPropsOverride}
|
||||
onClickNote={handleClickNote}
|
||||
onContextMenu={contextMenuHandler}
|
||||
/>
|
||||
) : (
|
||||
<DraggableNoteItem key={entry.path} notePath={entry.path}>
|
||||
<NoteItem
|
||||
entry={entry}
|
||||
isSelected={options?.forceSelected || selectedNotePath === entry.path}
|
||||
isMultiSelected={multiSelect.selectedPaths.has(entry.path)}
|
||||
isHighlighted={entry.path === noteListKeyboard.highlightedPath}
|
||||
noteStatus={resolvedGetNoteStatus(entry.path)}
|
||||
changeStatus={getChangeStatus(entry.path)}
|
||||
typeEntryMap={typeEntryMap}
|
||||
allEntries={entries}
|
||||
displayPropsOverride={displayPropsOverride}
|
||||
onClickNote={handleClickNote}
|
||||
onPrefetch={prefetchNoteContent}
|
||||
onContextMenu={contextMenuHandler}
|
||||
/>
|
||||
</DraggableNoteItem>
|
||||
)
|
||||
), [
|
||||
contextMenuHandler,
|
||||
displayPropsOverride,
|
||||
@@ -581,18 +600,22 @@ export function useNoteListModel({
|
||||
interaction.noteListKeyboard.focusList()
|
||||
})
|
||||
}
|
||||
const {
|
||||
isPanelActive: isNoteListSearchActive,
|
||||
toggleSearchShortcut,
|
||||
} = interaction.noteListKeyboard
|
||||
|
||||
useEffect(() => {
|
||||
dispatchNoteListSearchAvailability(interaction.noteListKeyboard.isPanelActive)
|
||||
dispatchNoteListSearchAvailability(isNoteListSearchActive)
|
||||
return () => dispatchNoteListSearchAvailability(false)
|
||||
}, [interaction.noteListKeyboard.isPanelActive])
|
||||
}, [isNoteListSearchActive])
|
||||
|
||||
useEffect(() => {
|
||||
return addNoteListSearchToggleListener(() => {
|
||||
if (!interaction.noteListKeyboard.isPanelActive) return
|
||||
interaction.noteListKeyboard.toggleSearchShortcut()
|
||||
if (!isNoteListSearchActive) return
|
||||
toggleSearchShortcut()
|
||||
})
|
||||
}, [interaction.noteListKeyboard.isPanelActive, interaction.noteListKeyboard.toggleSearchShortcut])
|
||||
}, [isNoteListSearchActive, toggleSearchShortcut])
|
||||
|
||||
return buildNoteListLayoutModel({
|
||||
selection,
|
||||
|
||||
29
src/components/note-retargeting/DraggableNoteItem.tsx
Normal file
29
src/components/note-retargeting/DraggableNoteItem.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { DragEvent, ReactNode } from 'react'
|
||||
import { clearDraggedNotePath, writeDraggedNotePath } from './noteDragData'
|
||||
|
||||
interface DraggableNoteItemProps {
|
||||
notePath: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function DraggableNoteItem({ notePath, children }: DraggableNoteItemProps) {
|
||||
const handleDragStart = (event: DragEvent<HTMLDivElement>) => {
|
||||
writeDraggedNotePath(event, notePath)
|
||||
}
|
||||
|
||||
const handleDragEnd = () => {
|
||||
clearDraggedNotePath()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
draggable
|
||||
data-testid={`draggable-note:${notePath}`}
|
||||
className="cursor-grab active:cursor-grabbing"
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
99
src/components/note-retargeting/NoteDropTarget.test.tsx
Normal file
99
src/components/note-retargeting/NoteDropTarget.test.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { DraggableNoteItem } from './DraggableNoteItem'
|
||||
import { NoteDropTarget } from './NoteDropTarget'
|
||||
import { clearDraggedNotePath } from './noteDragData'
|
||||
|
||||
const NOTE_DRAG_MIME = 'application/x-laputa-note-path'
|
||||
const NOTE_PATH = '/vault/inbox/tolaria-social-media.md'
|
||||
|
||||
function createMockDataTransfer(options?: {
|
||||
readable?: boolean
|
||||
seedData?: Record<string, string>
|
||||
}): DataTransfer {
|
||||
const data = new Map(Object.entries(options?.seedData ?? {}))
|
||||
const types = Array.from(data.keys())
|
||||
|
||||
return {
|
||||
effectAllowed: 'move',
|
||||
dropEffect: 'none',
|
||||
setData(type: string, value: string) {
|
||||
data.set(type, value)
|
||||
if (!types.includes(type)) types.push(type)
|
||||
},
|
||||
getData(type: string) {
|
||||
if (options?.readable === false) return ''
|
||||
return data.get(type) ?? ''
|
||||
},
|
||||
clearData(type?: string) {
|
||||
if (type) {
|
||||
data.delete(type)
|
||||
const typeIndex = types.indexOf(type)
|
||||
if (typeIndex >= 0) types.splice(typeIndex, 1)
|
||||
return
|
||||
}
|
||||
data.clear()
|
||||
types.splice(0, types.length)
|
||||
},
|
||||
get types() {
|
||||
return types
|
||||
},
|
||||
} as DataTransfer
|
||||
}
|
||||
|
||||
function serializedDragData(dataTransfer: DataTransfer) {
|
||||
return {
|
||||
[NOTE_DRAG_MIME]: dataTransfer.getData(NOTE_DRAG_MIME),
|
||||
'text/plain': dataTransfer.getData('text/plain'),
|
||||
}
|
||||
}
|
||||
|
||||
describe('NoteDropTarget', () => {
|
||||
afterEach(() => {
|
||||
clearDraggedNotePath()
|
||||
})
|
||||
|
||||
it('keeps a note drag valid when dragover cannot read DataTransfer payloads', async () => {
|
||||
const onDropNote = vi.fn()
|
||||
const canAcceptNotePath = vi.fn((notePath: string) => notePath === NOTE_PATH)
|
||||
|
||||
render(
|
||||
<>
|
||||
<DraggableNoteItem notePath={NOTE_PATH}>
|
||||
<span>Drag Tolaria Social media</span>
|
||||
</DraggableNoteItem>
|
||||
<NoteDropTarget canAcceptNotePath={canAcceptNotePath} onDropNote={onDropNote}>
|
||||
<span>CircleCI Series</span>
|
||||
</NoteDropTarget>
|
||||
</>,
|
||||
)
|
||||
|
||||
const dragStartData = createMockDataTransfer()
|
||||
fireEvent.dragStart(screen.getByTestId(`draggable-note:${NOTE_PATH}`), { dataTransfer: dragStartData })
|
||||
|
||||
const target = screen.getByText('CircleCI Series').parentElement
|
||||
expect(target).not.toBeNull()
|
||||
|
||||
const lockedDragData = createMockDataTransfer({
|
||||
readable: false,
|
||||
seedData: serializedDragData(dragStartData),
|
||||
})
|
||||
|
||||
fireEvent.dragEnter(target as HTMLElement, { dataTransfer: lockedDragData })
|
||||
fireEvent.dragOver(target as HTMLElement, { dataTransfer: lockedDragData })
|
||||
|
||||
expect(canAcceptNotePath).toHaveBeenCalledWith(NOTE_PATH)
|
||||
expect(target).toHaveAttribute('data-drop-state', 'valid')
|
||||
|
||||
const dropData = createMockDataTransfer({
|
||||
seedData: serializedDragData(dragStartData),
|
||||
})
|
||||
|
||||
fireEvent.drop(target as HTMLElement, { dataTransfer: dropData })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onDropNote).toHaveBeenCalledWith(NOTE_PATH)
|
||||
})
|
||||
expect(target).not.toHaveAttribute('data-drop-state')
|
||||
})
|
||||
})
|
||||
92
src/components/note-retargeting/NoteDropTarget.tsx
Normal file
92
src/components/note-retargeting/NoteDropTarget.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import { useRef, useState, type DragEvent, type ReactNode } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { clearDraggedNotePath, readDraggedNotePath } from './noteDragData'
|
||||
|
||||
type DropState = 'idle' | 'valid' | 'invalid'
|
||||
|
||||
interface NoteDropTargetProps {
|
||||
children: ReactNode
|
||||
className?: string
|
||||
validClassName?: string
|
||||
invalidClassName?: string
|
||||
canAcceptNotePath: (notePath: string) => boolean
|
||||
onDropNote: (notePath: string) => void | Promise<void>
|
||||
}
|
||||
|
||||
export function NoteDropTarget({
|
||||
children,
|
||||
className,
|
||||
validClassName = 'ring-1 ring-primary/40 bg-primary/10',
|
||||
invalidClassName = 'ring-1 ring-destructive/35 bg-destructive/5',
|
||||
canAcceptNotePath,
|
||||
onDropNote,
|
||||
}: NoteDropTargetProps) {
|
||||
const [dropState, setDropState] = useState<DropState>('idle')
|
||||
const dragDepthRef = useRef(0)
|
||||
|
||||
const updateDropState = (event: DragEvent<HTMLDivElement>): string | null => {
|
||||
const notePath = readDraggedNotePath(event.dataTransfer)
|
||||
if (!notePath) return null
|
||||
|
||||
const isValid = canAcceptNotePath(notePath)
|
||||
event.preventDefault()
|
||||
event.dataTransfer.dropEffect = isValid ? 'move' : 'none'
|
||||
setDropState(isValid ? 'valid' : 'invalid')
|
||||
return notePath
|
||||
}
|
||||
|
||||
const resetDropState = () => {
|
||||
dragDepthRef.current = 0
|
||||
setDropState('idle')
|
||||
}
|
||||
|
||||
const handleDragEnter = (event: DragEvent<HTMLDivElement>) => {
|
||||
const notePath = readDraggedNotePath(event.dataTransfer)
|
||||
if (!notePath) return
|
||||
dragDepthRef.current += 1
|
||||
updateDropState(event)
|
||||
}
|
||||
|
||||
const handleDragOver = (event: DragEvent<HTMLDivElement>) => {
|
||||
updateDropState(event)
|
||||
}
|
||||
|
||||
const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {
|
||||
const notePath = readDraggedNotePath(event.dataTransfer)
|
||||
if (!notePath) return
|
||||
|
||||
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)
|
||||
if (dragDepthRef.current === 0 && !event.currentTarget.contains(event.relatedTarget as Node | null)) {
|
||||
setDropState('idle')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDrop = (event: DragEvent<HTMLDivElement>) => {
|
||||
const notePath = updateDropState(event)
|
||||
if (!notePath) return
|
||||
|
||||
const isValid = canAcceptNotePath(notePath)
|
||||
resetDropState()
|
||||
clearDraggedNotePath()
|
||||
if (!isValid) return
|
||||
void onDropNote(notePath)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-[5px] transition-colors',
|
||||
className,
|
||||
dropState === 'valid' && validClassName,
|
||||
dropState === 'invalid' && invalidClassName,
|
||||
)}
|
||||
data-drop-state={dropState === 'idle' ? undefined : dropState}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
19
src/components/note-retargeting/NoteRetargetingContext.tsx
Normal file
19
src/components/note-retargeting/NoteRetargetingContext.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import {
|
||||
noteRetargetingContext,
|
||||
type NoteRetargetingContextValue,
|
||||
} from './noteRetargetingContext'
|
||||
|
||||
export function NoteRetargetingProvider({
|
||||
children,
|
||||
value,
|
||||
}: {
|
||||
children: ReactNode
|
||||
value: NoteRetargetingContextValue | null
|
||||
}) {
|
||||
return (
|
||||
<noteRetargetingContext.Provider value={value}>
|
||||
{children}
|
||||
</noteRetargetingContext.Provider>
|
||||
)
|
||||
}
|
||||
62
src/components/note-retargeting/NoteRetargetingDialogs.tsx
Normal file
62
src/components/note-retargeting/NoteRetargetingDialogs.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { VaultEntry } from '../../types'
|
||||
import type { RetargetOption } from './RetargetNoteDialog'
|
||||
import { RetargetNoteDialog } from './RetargetNoteDialog'
|
||||
|
||||
interface NoteRetargetingDialogsProps {
|
||||
dialogState: { kind: 'type' | 'folder'; notePath: string } | null
|
||||
dialogEntry: VaultEntry | null
|
||||
typeOptions: RetargetOption[]
|
||||
folderOptions: RetargetOption[]
|
||||
onClose: () => void
|
||||
onSelectType: (type: string) => boolean | Promise<boolean>
|
||||
onSelectFolder: (folderPath: string) => boolean | Promise<boolean>
|
||||
}
|
||||
|
||||
function typeDialogDescription(entry: VaultEntry | null): string {
|
||||
return entry
|
||||
? `Set a new type for "${entry.title}".`
|
||||
: 'Select a type for the active note.'
|
||||
}
|
||||
|
||||
function folderDialogDescription(entry: VaultEntry | null): string {
|
||||
return entry
|
||||
? `Choose a destination folder for "${entry.title}".`
|
||||
: 'Select a destination folder for the active note.'
|
||||
}
|
||||
|
||||
export function NoteRetargetingDialogs({
|
||||
dialogState,
|
||||
dialogEntry,
|
||||
typeOptions,
|
||||
folderOptions,
|
||||
onClose,
|
||||
onSelectType,
|
||||
onSelectFolder,
|
||||
}: NoteRetargetingDialogsProps) {
|
||||
return (
|
||||
<>
|
||||
<RetargetNoteDialog
|
||||
open={dialogState?.kind === 'type'}
|
||||
title="Change Note Type"
|
||||
description={typeDialogDescription(dialogEntry)}
|
||||
searchPlaceholder="Search types"
|
||||
emptyMessage="No other note types available."
|
||||
options={typeOptions}
|
||||
onClose={onClose}
|
||||
onSelect={onSelectType}
|
||||
testIdPrefix="retarget-note-type"
|
||||
/>
|
||||
<RetargetNoteDialog
|
||||
open={dialogState?.kind === 'folder'}
|
||||
title="Move Note to Folder"
|
||||
description={folderDialogDescription(dialogEntry)}
|
||||
searchPlaceholder="Search folders"
|
||||
emptyMessage="No other folders available."
|
||||
options={folderOptions}
|
||||
onClose={onClose}
|
||||
onSelect={onSelectFolder}
|
||||
testIdPrefix="retarget-note-folder"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
174
src/components/note-retargeting/RetargetNoteDialog.tsx
Normal file
174
src/components/note-retargeting/RetargetNoteDialog.tsx
Normal file
@@ -0,0 +1,174 @@
|
||||
import { Check, StackSimple } from '@phosphor-icons/react'
|
||||
import { useMemo, useState, type KeyboardEvent } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface RetargetOption {
|
||||
id: string
|
||||
label: string
|
||||
detail?: string
|
||||
current?: boolean
|
||||
}
|
||||
|
||||
interface RetargetNoteDialogProps {
|
||||
open: boolean
|
||||
title: string
|
||||
description: string
|
||||
searchPlaceholder: string
|
||||
emptyMessage: string
|
||||
options: RetargetOption[]
|
||||
onClose: () => void
|
||||
onSelect: (id: string) => boolean | Promise<boolean>
|
||||
testIdPrefix: string
|
||||
}
|
||||
|
||||
function matchesQuery(option: RetargetOption, query: string): boolean {
|
||||
const normalized = query.trim().toLowerCase()
|
||||
if (!normalized) return true
|
||||
return option.label.toLowerCase().includes(normalized)
|
||||
|| option.detail?.toLowerCase().includes(normalized)
|
||||
|| false
|
||||
}
|
||||
|
||||
function initialHighlightIndex(options: RetargetOption[]): number {
|
||||
if (options.length === 0) return -1
|
||||
const currentIndex = options.findIndex((option) => option.current)
|
||||
return currentIndex >= 0 ? currentIndex : 0
|
||||
}
|
||||
|
||||
function nextHighlightIndex(current: number, total: number, direction: 'next' | 'previous'): number {
|
||||
if (total === 0) return -1
|
||||
if (current < 0) return direction === 'next' ? 0 : total - 1
|
||||
return direction === 'next'
|
||||
? (current + 1) % total
|
||||
: (current - 1 + total) % total
|
||||
}
|
||||
|
||||
export function RetargetNoteDialog({
|
||||
open,
|
||||
title,
|
||||
description,
|
||||
searchPlaceholder,
|
||||
emptyMessage,
|
||||
options,
|
||||
onClose,
|
||||
onSelect,
|
||||
testIdPrefix,
|
||||
}: RetargetNoteDialogProps) {
|
||||
const [query, setQuery] = useState('')
|
||||
const [highlightedIndex, setHighlightedIndex] = useState(-1)
|
||||
|
||||
const filteredOptions = useMemo(
|
||||
() => options.filter((option) => matchesQuery(option, query)),
|
||||
[options, query],
|
||||
)
|
||||
|
||||
const effectiveHighlightedIndex = highlightedIndex >= 0 && highlightedIndex < filteredOptions.length
|
||||
? highlightedIndex
|
||||
: initialHighlightIndex(filteredOptions)
|
||||
|
||||
const resetDialogState = () => {
|
||||
setQuery('')
|
||||
setHighlightedIndex(-1)
|
||||
}
|
||||
|
||||
const submitSelection = async (optionId: string) => {
|
||||
const shouldClose = await onSelect(optionId)
|
||||
if (!shouldClose) return
|
||||
resetDialogState()
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handleSearchKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === 'ArrowDown') {
|
||||
event.preventDefault()
|
||||
setHighlightedIndex((current) => nextHighlightIndex(current, filteredOptions.length, 'next'))
|
||||
return
|
||||
}
|
||||
if (event.key === 'ArrowUp') {
|
||||
event.preventDefault()
|
||||
setHighlightedIndex((current) => nextHighlightIndex(current, filteredOptions.length, 'previous'))
|
||||
return
|
||||
}
|
||||
if (event.key === 'Enter' && effectiveHighlightedIndex >= 0) {
|
||||
event.preventDefault()
|
||||
void submitSelection(filteredOptions[effectiveHighlightedIndex].id)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (nextOpen) return
|
||||
resetDialogState()
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-xl gap-3" showCloseButton={true}>
|
||||
<DialogHeader className="gap-1">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
autoFocus
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
onKeyDown={handleSearchKeyDown}
|
||||
placeholder={searchPlaceholder}
|
||||
data-testid={`${testIdPrefix}-search`}
|
||||
/>
|
||||
<ScrollArea className="max-h-80 rounded-md border">
|
||||
{filteredOptions.length === 0 ? (
|
||||
<div className="px-4 py-6 text-sm text-muted-foreground" data-testid={`${testIdPrefix}-empty`}>
|
||||
{emptyMessage}
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-1" data-testid={`${testIdPrefix}-options`}>
|
||||
{filteredOptions.map((option, index) => (
|
||||
<Button
|
||||
key={option.id}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'h-auto w-full justify-start rounded-md px-3 py-2 text-left',
|
||||
effectiveHighlightedIndex === index && 'bg-accent text-accent-foreground',
|
||||
)}
|
||||
data-testid={`${testIdPrefix}-option:${option.id}`}
|
||||
onMouseMove={() => setHighlightedIndex(index)}
|
||||
onClick={() => { void submitSelection(option.id) }}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-start gap-2">
|
||||
<span className="mt-0.5 shrink-0 text-muted-foreground">
|
||||
{option.current ? <Check size={14} weight="bold" /> : <StackSimple size={14} />}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-sm font-medium text-foreground">{option.label}</span>
|
||||
{option.detail && (
|
||||
<span className="truncate text-xs text-muted-foreground">{option.detail}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{option.current && (
|
||||
<span className="shrink-0 text-xs font-medium text-muted-foreground">
|
||||
Current
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
27
src/components/note-retargeting/noteDragData.ts
Normal file
27
src/components/note-retargeting/noteDragData.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { DragEvent } from 'react'
|
||||
|
||||
const NOTE_DRAG_MIME = 'application/x-laputa-note-path'
|
||||
let activeDraggedNotePath: string | null = null
|
||||
|
||||
export function writeDraggedNotePath(event: DragEvent<HTMLElement>, notePath: string): void {
|
||||
activeDraggedNotePath = notePath
|
||||
event.dataTransfer.effectAllowed = 'move'
|
||||
event.dataTransfer.setData(NOTE_DRAG_MIME, notePath)
|
||||
event.dataTransfer.setData('text/plain', notePath)
|
||||
}
|
||||
|
||||
export function clearDraggedNotePath(): void {
|
||||
activeDraggedNotePath = null
|
||||
}
|
||||
|
||||
export function readDraggedNotePath(dataTransfer: DataTransfer | null): string | null {
|
||||
if (!dataTransfer) return activeDraggedNotePath
|
||||
|
||||
const customPath = dataTransfer.getData(NOTE_DRAG_MIME).trim()
|
||||
if (customPath) return customPath
|
||||
|
||||
const fallbackPath = dataTransfer.getData('text/plain').trim()
|
||||
if (fallbackPath) return fallbackPath
|
||||
|
||||
return activeDraggedNotePath
|
||||
}
|
||||
24
src/components/note-retargeting/noteRetargetingContext.ts
Normal file
24
src/components/note-retargeting/noteRetargetingContext.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { createContext, createElement, useContext, type ReactNode } from 'react'
|
||||
|
||||
export interface NoteRetargetingContextValue {
|
||||
canDropNoteOnType: (notePath: string, type: string) => boolean
|
||||
dropNoteOnType: (notePath: string, type: string) => Promise<void>
|
||||
canDropNoteOnFolder: (notePath: string, folderPath: string) => boolean
|
||||
dropNoteOnFolder: (notePath: string, folderPath: string) => Promise<void>
|
||||
}
|
||||
|
||||
export const noteRetargetingContext = createContext<NoteRetargetingContextValue | null>(null)
|
||||
|
||||
export function useNoteRetargetingContext() {
|
||||
return useContext(noteRetargetingContext)
|
||||
}
|
||||
|
||||
export function NoteRetargetingProvider({
|
||||
children,
|
||||
value,
|
||||
}: {
|
||||
children: ReactNode
|
||||
value: NoteRetargetingContextValue | null
|
||||
}) {
|
||||
return createElement(noteRetargetingContext.Provider, { value }, children)
|
||||
}
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
} from '../SidebarParts'
|
||||
import { TypeCustomizePopover } from '../TypeCustomizePopover'
|
||||
import { useDragRegion } from '../../hooks/useDragRegion'
|
||||
import { NoteDropTarget } from '../note-retargeting/NoteDropTarget'
|
||||
import { useNoteRetargetingContext } from '../note-retargeting/noteRetargetingContext'
|
||||
import { SidebarGroupHeader } from './SidebarGroupHeader'
|
||||
import { SidebarViewItem } from './SidebarViewItem'
|
||||
import { countByFilter } from '../../utils/noteListHelpers'
|
||||
@@ -95,9 +97,24 @@ function SortableSection({
|
||||
group: SectionGroup
|
||||
sectionProps: SidebarSectionProps
|
||||
}) {
|
||||
const noteRetargeting = useNoteRetargetingContext()
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: group.type })
|
||||
const itemCount = countByFilter(sectionProps.entries, group.type).open
|
||||
const isRenaming = sectionProps.renamingType === group.type
|
||||
const content = (
|
||||
<SectionContent
|
||||
group={group}
|
||||
itemCount={itemCount}
|
||||
selection={sectionProps.selection}
|
||||
onSelect={sectionProps.onSelect}
|
||||
onContextMenu={sectionProps.onContextMenu}
|
||||
dragHandleProps={listeners}
|
||||
isRenaming={isRenaming}
|
||||
renameInitialValue={isRenaming ? sectionProps.renameInitialValue : undefined}
|
||||
onRenameSubmit={sectionProps.onRenameSubmit}
|
||||
onRenameCancel={sectionProps.onRenameCancel}
|
||||
/>
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -110,18 +127,14 @@ function SortableSection({
|
||||
}}
|
||||
{...attributes}
|
||||
>
|
||||
<SectionContent
|
||||
group={group}
|
||||
itemCount={itemCount}
|
||||
selection={sectionProps.selection}
|
||||
onSelect={sectionProps.onSelect}
|
||||
onContextMenu={sectionProps.onContextMenu}
|
||||
dragHandleProps={listeners}
|
||||
isRenaming={isRenaming}
|
||||
renameInitialValue={isRenaming ? sectionProps.renameInitialValue : undefined}
|
||||
onRenameSubmit={sectionProps.onRenameSubmit}
|
||||
onRenameCancel={sectionProps.onRenameCancel}
|
||||
/>
|
||||
{noteRetargeting ? (
|
||||
<NoteDropTarget
|
||||
canAcceptNotePath={(notePath) => noteRetargeting.canDropNoteOnType(notePath, group.type)}
|
||||
onDropNote={(notePath) => noteRetargeting.dropNoteOnType(notePath, group.type)}
|
||||
>
|
||||
{content}
|
||||
</NoteDropTarget>
|
||||
) : content}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,9 @@ interface NoteCommandsConfig {
|
||||
onDeleteNote: (path: string) => void
|
||||
onArchiveNote: (path: string) => void
|
||||
onUnarchiveNote: (path: string) => void
|
||||
onChangeNoteType?: () => void
|
||||
onMoveNoteToFolder?: () => void
|
||||
canMoveNoteToFolder?: boolean
|
||||
onSetNoteIcon?: () => void
|
||||
onRemoveNoteIcon?: () => void
|
||||
onOpenInNewWindow?: () => void
|
||||
@@ -22,17 +25,18 @@ interface NoteCommandsConfig {
|
||||
canRestoreDeletedNote?: boolean
|
||||
}
|
||||
|
||||
interface ActivePathCommandConfig {
|
||||
interface NoteCommandConfig {
|
||||
id: string
|
||||
label: string
|
||||
keywords: string[]
|
||||
enabled: boolean
|
||||
path: string | null
|
||||
execute?: () => void
|
||||
shortcut?: string
|
||||
run: (path: string) => void
|
||||
path?: string | null
|
||||
run?: (path: string) => void
|
||||
}
|
||||
|
||||
function createActivePathCommand(config: ActivePathCommandConfig): CommandAction {
|
||||
function createNoteCommand(config: NoteCommandConfig): CommandAction {
|
||||
return {
|
||||
id: config.id,
|
||||
label: config.label,
|
||||
@@ -41,84 +45,165 @@ function createActivePathCommand(config: ActivePathCommandConfig): CommandAction
|
||||
keywords: config.keywords,
|
||||
enabled: config.enabled,
|
||||
execute: () => {
|
||||
if (config.path) config.run(config.path)
|
||||
if (config.path && config.run) {
|
||||
config.run(config.path)
|
||||
return
|
||||
}
|
||||
config.execute?.()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function buildNoteCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
const {
|
||||
hasActiveNote, activeTabPath, isArchived,
|
||||
onCreateNote, onCreateType, onSave,
|
||||
onDeleteNote, onArchiveNote, onUnarchiveNote,
|
||||
onSetNoteIcon, onRemoveNoteIcon, activeNoteHasIcon,
|
||||
onOpenInNewWindow, onToggleFavorite, isFavorite,
|
||||
onToggleOrganized, isOrganized,
|
||||
onRestoreDeletedNote, canRestoreDeletedNote,
|
||||
} = config
|
||||
|
||||
function buildCoreNoteCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
return [
|
||||
{ id: 'create-note', label: 'New Note', group: 'Note', shortcut: '⌘N', keywords: ['new', 'create', 'add'], enabled: true, execute: onCreateNote },
|
||||
{ id: 'create-type', label: 'New Type', group: 'Note', keywords: ['new', 'create', 'type', 'template'], enabled: !!onCreateType, execute: () => onCreateType?.() },
|
||||
{ id: 'save-note', label: 'Save Note', group: 'Note', shortcut: '⌘S', keywords: ['write'], enabled: hasActiveNote, execute: onSave },
|
||||
createActivePathCommand({
|
||||
createNoteCommand({
|
||||
id: 'create-note',
|
||||
label: 'New Note',
|
||||
shortcut: '⌘N',
|
||||
keywords: ['new', 'create', 'add'],
|
||||
enabled: true,
|
||||
execute: config.onCreateNote,
|
||||
}),
|
||||
createNoteCommand({
|
||||
id: 'create-type',
|
||||
label: 'New Type',
|
||||
keywords: ['new', 'create', 'type', 'template'],
|
||||
enabled: !!config.onCreateType,
|
||||
execute: () => config.onCreateType?.(),
|
||||
}),
|
||||
createNoteCommand({
|
||||
id: 'save-note',
|
||||
label: 'Save Note',
|
||||
shortcut: '⌘S',
|
||||
keywords: ['write'],
|
||||
enabled: config.hasActiveNote,
|
||||
execute: config.onSave,
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
function buildPathNoteCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
return [
|
||||
...buildDestructiveNoteCommands(config),
|
||||
...buildPinnedNoteCommands(config),
|
||||
]
|
||||
}
|
||||
|
||||
function buildDestructiveNoteCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
return [
|
||||
createNoteCommand({
|
||||
id: 'delete-note',
|
||||
label: 'Delete Note',
|
||||
shortcut: '⌘⌫',
|
||||
keywords: ['delete', 'remove'],
|
||||
enabled: hasActiveNote,
|
||||
path: activeTabPath,
|
||||
run: onDeleteNote,
|
||||
enabled: config.hasActiveNote,
|
||||
path: config.activeTabPath,
|
||||
run: config.onDeleteNote,
|
||||
}),
|
||||
createActivePathCommand({
|
||||
createNoteCommand({
|
||||
id: 'archive-note',
|
||||
label: isArchived ? 'Unarchive Note' : 'Archive Note',
|
||||
label: config.isArchived ? 'Unarchive Note' : 'Archive Note',
|
||||
keywords: ['archive'],
|
||||
enabled: hasActiveNote,
|
||||
path: activeTabPath,
|
||||
run: isArchived ? onUnarchiveNote : onArchiveNote,
|
||||
enabled: config.hasActiveNote,
|
||||
path: config.activeTabPath,
|
||||
run: config.isArchived ? config.onUnarchiveNote : config.onArchiveNote,
|
||||
}),
|
||||
{
|
||||
id: 'restore-deleted-note', label: 'Restore Deleted Note', group: 'Note',
|
||||
keywords: ['restore', 'deleted', 'undelete', 'git', 'checkout'],
|
||||
enabled: !!canRestoreDeletedNote && !!onRestoreDeletedNote,
|
||||
execute: () => onRestoreDeletedNote?.(),
|
||||
},
|
||||
createActivePathCommand({
|
||||
id: 'toggle-favorite',
|
||||
label: isFavorite ? 'Remove from Favorites' : 'Add to Favorites',
|
||||
shortcut: '⌘D',
|
||||
keywords: ['favorite', 'star', 'bookmark', 'pin'],
|
||||
enabled: hasActiveNote && !!onToggleFavorite,
|
||||
path: activeTabPath,
|
||||
run: (path) => onToggleFavorite?.(path),
|
||||
}),
|
||||
createActivePathCommand({
|
||||
id: 'toggle-organized',
|
||||
label: isOrganized ? 'Mark as Unorganized' : 'Mark as Organized',
|
||||
shortcut: '⌘E',
|
||||
keywords: ['organized', 'inbox', 'triage', 'done'],
|
||||
enabled: hasActiveNote && !!onToggleOrganized,
|
||||
path: activeTabPath,
|
||||
run: (path) => onToggleOrganized?.(path),
|
||||
}),
|
||||
{
|
||||
id: 'set-note-icon', label: 'Set Note Icon', group: 'Note',
|
||||
keywords: ['icon', 'emoji', 'set', 'add', 'change', 'picker'],
|
||||
enabled: hasActiveNote && !!onSetNoteIcon,
|
||||
execute: () => onSetNoteIcon?.(),
|
||||
},
|
||||
{
|
||||
id: 'remove-note-icon', label: 'Remove Note Icon', group: 'Note',
|
||||
keywords: ['icon', 'emoji', 'remove', 'delete', 'clear'],
|
||||
enabled: hasActiveNote && !!activeNoteHasIcon && !!onRemoveNoteIcon,
|
||||
execute: () => onRemoveNoteIcon?.(),
|
||||
},
|
||||
{
|
||||
id: 'open-in-new-window', label: 'Open in New Window', group: 'Note', shortcut: '⌘⇧O',
|
||||
keywords: ['window', 'new', 'detach', 'pop', 'external', 'separate'],
|
||||
enabled: hasActiveNote,
|
||||
execute: () => onOpenInNewWindow?.(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function buildPinnedNoteCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
return [
|
||||
createNoteCommand({
|
||||
id: 'toggle-favorite',
|
||||
label: config.isFavorite ? 'Remove from Favorites' : 'Add to Favorites',
|
||||
shortcut: '⌘D',
|
||||
keywords: ['favorite', 'star', 'bookmark', 'pin'],
|
||||
enabled: config.hasActiveNote && !!config.onToggleFavorite,
|
||||
path: config.activeTabPath,
|
||||
run: (path) => config.onToggleFavorite?.(path),
|
||||
}),
|
||||
createNoteCommand({
|
||||
id: 'toggle-organized',
|
||||
label: config.isOrganized ? 'Mark as Unorganized' : 'Mark as Organized',
|
||||
shortcut: '⌘E',
|
||||
keywords: ['organized', 'inbox', 'triage', 'done'],
|
||||
enabled: config.hasActiveNote && !!config.onToggleOrganized,
|
||||
path: config.activeTabPath,
|
||||
run: (path) => config.onToggleOrganized?.(path),
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
function buildOptionalNoteCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
return [
|
||||
...buildRecoveryCommands(config),
|
||||
...buildRetargetingCommands(config),
|
||||
...buildPresentationCommands(config),
|
||||
]
|
||||
}
|
||||
|
||||
function buildRecoveryCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
return [
|
||||
createNoteCommand({
|
||||
id: 'restore-deleted-note',
|
||||
label: 'Restore Deleted Note',
|
||||
keywords: ['restore', 'deleted', 'undelete', 'git', 'checkout'],
|
||||
enabled: !!config.canRestoreDeletedNote && !!config.onRestoreDeletedNote,
|
||||
execute: () => config.onRestoreDeletedNote?.(),
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
function buildRetargetingCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
return [
|
||||
createNoteCommand({
|
||||
id: 'set-note-icon',
|
||||
label: 'Set Note Icon',
|
||||
keywords: ['icon', 'emoji', 'set', 'add', 'change', 'picker'],
|
||||
enabled: config.hasActiveNote && !!config.onSetNoteIcon,
|
||||
execute: () => config.onSetNoteIcon?.(),
|
||||
}),
|
||||
createNoteCommand({
|
||||
id: 'change-note-type',
|
||||
label: 'Change Note Type…',
|
||||
keywords: ['type', 'change', 'retarget', 'section', 'move'],
|
||||
enabled: config.hasActiveNote && !!config.onChangeNoteType,
|
||||
execute: () => config.onChangeNoteType?.(),
|
||||
}),
|
||||
createNoteCommand({
|
||||
id: 'move-note-to-folder',
|
||||
label: 'Move Note to Folder…',
|
||||
keywords: ['folder', 'move', 'retarget', 'organize'],
|
||||
enabled: config.hasActiveNote && !!config.onMoveNoteToFolder && !!config.canMoveNoteToFolder,
|
||||
execute: () => config.onMoveNoteToFolder?.(),
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
function buildPresentationCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
return [
|
||||
createNoteCommand({
|
||||
id: 'remove-note-icon',
|
||||
label: 'Remove Note Icon',
|
||||
keywords: ['icon', 'emoji', 'remove', 'delete', 'clear'],
|
||||
enabled: config.hasActiveNote && !!config.activeNoteHasIcon && !!config.onRemoveNoteIcon,
|
||||
execute: () => config.onRemoveNoteIcon?.(),
|
||||
}),
|
||||
createNoteCommand({
|
||||
id: 'open-in-new-window',
|
||||
label: 'Open in New Window',
|
||||
shortcut: '⌘⇧O',
|
||||
keywords: ['window', 'new', 'detach', 'pop', 'external', 'separate'],
|
||||
enabled: config.hasActiveNote,
|
||||
execute: () => config.onOpenInNewWindow?.(),
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
export function buildNoteCommands(config: NoteCommandsConfig): CommandAction[] {
|
||||
return [
|
||||
...buildCoreNoteCommands(config),
|
||||
...buildPathNoteCommands(config),
|
||||
...buildOptionalNoteCommands(config),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -80,6 +80,9 @@ interface AppCommandsConfig {
|
||||
onRepairVault?: () => void
|
||||
onSetNoteIcon?: () => void
|
||||
onRemoveNoteIcon?: () => void
|
||||
onChangeNoteType?: () => void
|
||||
onMoveNoteToFolder?: () => void
|
||||
canMoveNoteToFolder?: boolean
|
||||
activeNoteHasIcon?: boolean
|
||||
noteListFilter?: NoteListFilter
|
||||
onSetNoteListFilter?: (filter: NoteListFilter) => void
|
||||
@@ -169,6 +172,9 @@ type CommandRegistryNoteActions = Pick<
|
||||
CommandRegistryConfig,
|
||||
| 'onSetNoteIcon'
|
||||
| 'onRemoveNoteIcon'
|
||||
| 'onChangeNoteType'
|
||||
| 'onMoveNoteToFolder'
|
||||
| 'canMoveNoteToFolder'
|
||||
| 'activeNoteHasIcon'
|
||||
| 'noteListFilter'
|
||||
| 'onSetNoteListFilter'
|
||||
@@ -421,6 +427,9 @@ function createCommandRegistryNoteConfig(
|
||||
return {
|
||||
onSetNoteIcon: config.onSetNoteIcon,
|
||||
onRemoveNoteIcon: config.onRemoveNoteIcon,
|
||||
onChangeNoteType: config.onChangeNoteType,
|
||||
onMoveNoteToFolder: config.onMoveNoteToFolder,
|
||||
canMoveNoteToFolder: config.canMoveNoteToFolder,
|
||||
activeNoteHasIcon: config.activeNoteHasIcon,
|
||||
noteListFilter: config.noteListFilter,
|
||||
onSetNoteListFilter: config.onSetNoteListFilter,
|
||||
|
||||
@@ -152,6 +152,42 @@ describe('useCommandRegistry', () => {
|
||||
expect(onSetNoteIcon).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('includes Change Note Type when the active note can be retargeted', () => {
|
||||
const onChangeNoteType = vi.fn()
|
||||
const config = makeConfig({ onChangeNoteType })
|
||||
const { result } = renderHook(() => useCommandRegistry(config))
|
||||
const cmd = findCommand(result.current, 'change-note-type')
|
||||
|
||||
expect(cmd).toBeDefined()
|
||||
expect(cmd!.enabled).toBe(true)
|
||||
|
||||
cmd!.execute()
|
||||
expect(onChangeNoteType).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('enables Move Note to Folder only when another folder destination exists', () => {
|
||||
const onMoveNoteToFolder = vi.fn()
|
||||
const { result, rerender } = renderHook(
|
||||
(props) => useCommandRegistry(props),
|
||||
{
|
||||
initialProps: makeConfig({
|
||||
onMoveNoteToFolder,
|
||||
canMoveNoteToFolder: true,
|
||||
}),
|
||||
},
|
||||
)
|
||||
|
||||
expect(findCommand(result.current, 'move-note-to-folder')?.enabled).toBe(true)
|
||||
findCommand(result.current, 'move-note-to-folder')!.execute()
|
||||
expect(onMoveNoteToFolder).toHaveBeenCalledOnce()
|
||||
|
||||
rerender(makeConfig({
|
||||
onMoveNoteToFolder,
|
||||
canMoveNoteToFolder: false,
|
||||
}))
|
||||
expect(findCommand(result.current, 'move-note-to-folder')?.enabled).toBe(false)
|
||||
})
|
||||
|
||||
it('includes restore deleted note command when provided', () => {
|
||||
const config = makeConfig({ onRestoreDeletedNote: vi.fn(), canRestoreDeletedNote: true })
|
||||
const { result } = renderHook(() => useCommandRegistry(config))
|
||||
|
||||
@@ -40,6 +40,9 @@ interface CommandRegistryConfig {
|
||||
onRepairVault?: () => void
|
||||
onSetNoteIcon?: () => void
|
||||
onRemoveNoteIcon?: () => void
|
||||
onChangeNoteType?: () => void
|
||||
onMoveNoteToFolder?: () => void
|
||||
canMoveNoteToFolder?: boolean
|
||||
onOpenInNewWindow?: () => void
|
||||
onToggleFavorite?: (path: string) => void
|
||||
onToggleOrganized?: (path: string) => void
|
||||
@@ -109,7 +112,7 @@ export function useCommandRegistry(config: CommandRegistryConfig): import('./com
|
||||
mcpStatus, onInstallMcp, aiAgentsStatus, vaultAiGuidanceStatus,
|
||||
onOpenAiAgents, onRestoreVaultAiGuidance, onSetDefaultAiAgent, selectedAiAgent, onCycleDefaultAiAgent, selectedAiAgentLabel,
|
||||
onReloadVault, onRepairVault,
|
||||
onSetNoteIcon, onRemoveNoteIcon, activeNoteHasIcon,
|
||||
onSetNoteIcon, onRemoveNoteIcon, activeNoteHasIcon, onChangeNoteType, onMoveNoteToFolder, canMoveNoteToFolder,
|
||||
onOpenInNewWindow, onToggleFavorite, onToggleOrganized,
|
||||
onCustomizeNoteListColumns, canCustomizeNoteListColumns,
|
||||
onRestoreDeletedNote, canRestoreDeletedNote,
|
||||
@@ -150,6 +153,7 @@ export function useCommandRegistry(config: CommandRegistryConfig): import('./com
|
||||
hasActiveNote, activeTabPath, isArchived,
|
||||
onCreateNote, onCreateType, onSave,
|
||||
onDeleteNote, onArchiveNote, onUnarchiveNote,
|
||||
onChangeNoteType, onMoveNoteToFolder, canMoveNoteToFolder,
|
||||
onSetNoteIcon, onRemoveNoteIcon, activeNoteHasIcon, onOpenInNewWindow, onToggleFavorite, isFavorite,
|
||||
onToggleOrganized, isOrganized: activeEntry?.organized ?? false,
|
||||
onRestoreDeletedNote, canRestoreDeletedNote,
|
||||
@@ -200,7 +204,7 @@ export function useCommandRegistry(config: CommandRegistryConfig): import('./com
|
||||
mcpStatus, onInstallMcp, aiAgentsStatus, vaultAiGuidanceStatus,
|
||||
onOpenAiAgents, onRestoreVaultAiGuidance, onSetDefaultAiAgent, selectedAiAgent, onCycleDefaultAiAgent, selectedAiAgentLabel,
|
||||
onReloadVault, onRepairVault,
|
||||
onSetNoteIcon, onRemoveNoteIcon, activeNoteHasIcon,
|
||||
onSetNoteIcon, onRemoveNoteIcon, activeNoteHasIcon, onChangeNoteType, onMoveNoteToFolder, canMoveNoteToFolder,
|
||||
isSectionGroup, noteListFilter, onSetNoteListFilter,
|
||||
selection,
|
||||
onOpenInNewWindow, onToggleFavorite, isFavorite,
|
||||
|
||||
@@ -70,18 +70,48 @@ describe('useNoteActions hook', () => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('handleCreateNote calls addEntry and creates correct entry', () => {
|
||||
const { result } = renderHook(() => useNoteActions(makeConfig()))
|
||||
function renderActions(entries: VaultEntry[] = []) {
|
||||
return renderHook(() => useNoteActions(makeConfig(entries)))
|
||||
}
|
||||
|
||||
function createImmediateEntry(type?: string) {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(1700000000000)
|
||||
const { result } = renderActions()
|
||||
act(() => {
|
||||
result.current.handleCreateNoteImmediate(type)
|
||||
})
|
||||
const [createdEntry] = addEntry.mock.calls[0]
|
||||
vi.restoreAllMocks()
|
||||
return createdEntry as VaultEntry
|
||||
}
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'handleCreateNote',
|
||||
run: (result: ReturnType<typeof renderActions>['result']) => result.current.handleCreateNote('Test Note', 'Note'),
|
||||
expectedTitle: 'Test Note',
|
||||
expectedType: 'Note',
|
||||
expectedPathFragment: 'test-note.md',
|
||||
},
|
||||
{
|
||||
name: 'handleCreateType',
|
||||
run: (result: ReturnType<typeof renderActions>['result']) => result.current.handleCreateType('Recipe'),
|
||||
expectedTitle: 'Recipe',
|
||||
expectedType: 'Type',
|
||||
expectedPathFragment: 'recipe.md',
|
||||
},
|
||||
])('$name creates the expected entry', ({ run, expectedTitle, expectedType, expectedPathFragment }) => {
|
||||
const { result } = renderActions()
|
||||
|
||||
act(() => {
|
||||
result.current.handleCreateNote('Test Note', 'Note')
|
||||
run(result)
|
||||
})
|
||||
|
||||
expect(addEntry).toHaveBeenCalledTimes(1)
|
||||
const [createdEntry] = addEntry.mock.calls[0]
|
||||
expect(createdEntry.title).toBe('Test Note')
|
||||
expect(createdEntry.isA).toBe('Note')
|
||||
expect(createdEntry.path).toContain('test-note.md')
|
||||
expect(createdEntry.title).toBe(expectedTitle)
|
||||
expect(createdEntry.isA).toBe(expectedType)
|
||||
expect(createdEntry.path).toContain(expectedPathFragment)
|
||||
})
|
||||
|
||||
it('handleCreateNote opens tab immediately (before addEntry resolves)', () => {
|
||||
@@ -102,19 +132,6 @@ describe('useNoteActions hook', () => {
|
||||
expect(result.current.activeTabPath).toContain('fast-note.md')
|
||||
})
|
||||
|
||||
it('handleCreateType creates type entry', () => {
|
||||
const { result } = renderHook(() => useNoteActions(makeConfig()))
|
||||
|
||||
act(() => {
|
||||
result.current.handleCreateType('Recipe')
|
||||
})
|
||||
|
||||
expect(addEntry).toHaveBeenCalledTimes(1)
|
||||
const [createdEntry] = addEntry.mock.calls[0]
|
||||
expect(createdEntry.isA).toBe('Type')
|
||||
expect(createdEntry.title).toBe('Recipe')
|
||||
})
|
||||
|
||||
it('handleNavigateWikilink finds entry by title', async () => {
|
||||
const target = makeEntry({ title: 'Target Note', path: '/vault/target.md' })
|
||||
|
||||
@@ -178,19 +195,10 @@ describe('useNoteActions hook', () => {
|
||||
})
|
||||
|
||||
it('handleCreateNoteImmediate creates note with timestamp-based title', () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(1700000000000)
|
||||
const { result } = renderHook(() => useNoteActions(makeConfig()))
|
||||
|
||||
act(() => {
|
||||
result.current.handleCreateNoteImmediate()
|
||||
})
|
||||
|
||||
expect(addEntry).toHaveBeenCalledTimes(1)
|
||||
const [createdEntry] = addEntry.mock.calls[0]
|
||||
const createdEntry = createImmediateEntry()
|
||||
expect(createdEntry.title).toBe('Untitled Note 1700000000')
|
||||
expect(createdEntry.filename).toBe('untitled-note-1700000000.md')
|
||||
expect(createdEntry.isA).toBe('Note')
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('handleCreateNoteImmediate generates unique names on rapid calls via timestamp', () => {
|
||||
@@ -217,18 +225,9 @@ describe('useNoteActions hook', () => {
|
||||
})
|
||||
|
||||
it('handleCreateNoteImmediate accepts custom type', () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(1700000000000)
|
||||
const { result } = renderHook(() => useNoteActions(makeConfig()))
|
||||
|
||||
act(() => {
|
||||
result.current.handleCreateNoteImmediate('Project')
|
||||
})
|
||||
|
||||
expect(addEntry).toHaveBeenCalledTimes(1)
|
||||
const [createdEntry] = addEntry.mock.calls[0]
|
||||
const createdEntry = createImmediateEntry('Project')
|
||||
expect(createdEntry.filename).toMatch(/^untitled-project-\d+\.md$/)
|
||||
expect(createdEntry.isA).toBe('Project')
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('handleCreateNote uses default template for Project type', () => {
|
||||
@@ -435,7 +434,11 @@ describe('useNoteActions hook', () => {
|
||||
|
||||
expect(addEntry).toHaveBeenCalledTimes(1)
|
||||
expect(removeEntry).toHaveBeenCalledWith(expect.stringContaining(pathFragment))
|
||||
expect(setToastMessage).toHaveBeenCalledWith('Failed to create note — disk write error')
|
||||
expect(setToastMessage).toHaveBeenCalledWith(
|
||||
type === 'Type'
|
||||
? 'Failed to create type — disk write error'
|
||||
: 'Failed to create note — disk write error',
|
||||
)
|
||||
})
|
||||
|
||||
it('does not revert when disk write succeeds', async () => {
|
||||
|
||||
@@ -343,5 +343,6 @@ export function useNoteActions(config: NoteActionsConfig) {
|
||||
handleAddProperty: frontmatterActions.handleAddProperty,
|
||||
handleRenameNote: rename.handleRenameNote,
|
||||
handleRenameFilename: rename.handleRenameFilename,
|
||||
handleMoveNoteToFolder: rename.handleMoveNoteToFolder,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,6 +348,21 @@ describe('useNoteCreation hook', () => {
|
||||
expect(addEntry.mock.calls[0][0].title).toBe('Recipe')
|
||||
})
|
||||
|
||||
it('handleCreateType blocks when a non-type file already uses the target filename', async () => {
|
||||
const existing = makeEntry({ path: '/test/vault/briefing.md', filename: 'briefing.md', title: 'Briefing', isA: 'Note' })
|
||||
const { result } = renderHook(() => useNoteCreation(makeConfig([existing]), tabDeps))
|
||||
|
||||
let created = true
|
||||
await act(async () => {
|
||||
created = await result.current.handleCreateType('Briefing')
|
||||
})
|
||||
|
||||
expect(created).toBe(false)
|
||||
expect(addEntry).not.toHaveBeenCalled()
|
||||
expect(openTabWithContent).not.toHaveBeenCalled()
|
||||
expect(setToastMessage).toHaveBeenCalledWith('Cannot create type "Briefing" because briefing.md already exists')
|
||||
})
|
||||
|
||||
it('createTypeEntrySilent persists without opening tab', async () => {
|
||||
const { result } = renderHook(() => useNoteCreation(makeConfig(), tabDeps))
|
||||
const entry = await act(async () => result.current.createTypeEntrySilent('Recipe'))
|
||||
@@ -356,6 +371,32 @@ describe('useNoteCreation hook', () => {
|
||||
expect(entry.isA).toBe('Type')
|
||||
})
|
||||
|
||||
it('createTypeEntrySilent reuses an existing slug-equivalent type', async () => {
|
||||
const existing = makeEntry({ path: '/test/vault/briefing.md', filename: 'briefing.md', title: 'Briefing', isA: 'Type' })
|
||||
const { result } = renderHook(() => useNoteCreation(makeConfig([existing]), tabDeps))
|
||||
|
||||
const entry = await act(async () => result.current.createTypeEntrySilent('briefing'))
|
||||
|
||||
expect(entry).toBe(existing)
|
||||
expect(addEntry).not.toHaveBeenCalled()
|
||||
expect(openTabWithContent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('handleCreateNoteForRelationship blocks when the generated filename already exists', async () => {
|
||||
const existing = makeEntry({ path: '/test/vault/briefing.md', filename: 'briefing.md', title: 'Existing Briefing', isA: 'Note' })
|
||||
const { result } = renderHook(() => useNoteCreation(makeConfig([existing]), tabDeps))
|
||||
|
||||
let created = true
|
||||
await act(async () => {
|
||||
created = await result.current.handleCreateNoteForRelationship('Briefing')
|
||||
})
|
||||
|
||||
expect(created).toBe(false)
|
||||
expect(addEntry).not.toHaveBeenCalled()
|
||||
expect(openTabWithContent).not.toHaveBeenCalled()
|
||||
expect(setToastMessage).toHaveBeenCalledWith('Cannot create note "Briefing" because briefing.md already exists')
|
||||
})
|
||||
|
||||
it('reverts optimistic creation when disk write fails (Tauri)', async () => {
|
||||
vi.mocked(isTauri).mockReturnValue(true)
|
||||
vi.mocked(invoke).mockRejectedValueOnce(new Error('disk full'))
|
||||
|
||||
@@ -132,10 +132,104 @@ export function resolveNewType({ typeName, vaultPath }: NewTypeParams): { entry:
|
||||
return { entry, content: `---\ntype: Type\n---\n` }
|
||||
}
|
||||
|
||||
type ResolvedEntry = { entry: VaultEntry; content: string }
|
||||
|
||||
interface BlockedCreationPlan {
|
||||
status: 'blocked'
|
||||
message: string
|
||||
}
|
||||
|
||||
interface ReadyCreationPlan {
|
||||
status: 'create'
|
||||
resolved: ResolvedEntry
|
||||
}
|
||||
|
||||
interface ExistingTypeCreationPlan {
|
||||
status: 'existing'
|
||||
entry: VaultEntry
|
||||
}
|
||||
|
||||
export type NoteCreationPlan = BlockedCreationPlan | ReadyCreationPlan
|
||||
export type TypeCreationPlan = BlockedCreationPlan | ExistingTypeCreationPlan | ReadyCreationPlan
|
||||
|
||||
function normalizeComparablePath(path: string): string {
|
||||
return path.replace(/\\/g, '/').toLocaleLowerCase()
|
||||
}
|
||||
|
||||
function findPathCollision(entries: VaultEntry[], path: string): VaultEntry | undefined {
|
||||
const target = normalizeComparablePath(path)
|
||||
return entries.find((entry) => normalizeComparablePath(entry.path) === target)
|
||||
}
|
||||
|
||||
function buildCreationCollisionMessage({ noun, title, path }: { noun: 'note' | 'type'; title: string; path: string }): string {
|
||||
const filename = path.split('/').pop() ?? path
|
||||
return `Cannot create ${noun} "${title}" because ${filename} already exists`
|
||||
}
|
||||
|
||||
function findEquivalentTypeEntry(entries: VaultEntry[], typeName: string): VaultEntry | undefined {
|
||||
const trimmed = typeName.trim()
|
||||
const targetSlug = slugify(trimmed)
|
||||
return entries.find((entry) =>
|
||||
entry.isA === 'Type' && (entry.title === trimmed || slugify(entry.title) === targetSlug)
|
||||
)
|
||||
}
|
||||
|
||||
export function planNewNoteCreation({
|
||||
entries,
|
||||
title,
|
||||
type,
|
||||
vaultPath,
|
||||
template,
|
||||
}: NewNoteParams & { entries: VaultEntry[] }): NoteCreationPlan {
|
||||
const resolved = resolveNewNote({ title, type, vaultPath, template })
|
||||
const collision = findPathCollision(entries, resolved.entry.path)
|
||||
if (collision) {
|
||||
return {
|
||||
status: 'blocked',
|
||||
message: buildCreationCollisionMessage({ noun: 'note', title, path: resolved.entry.path }),
|
||||
}
|
||||
}
|
||||
return { status: 'create', resolved }
|
||||
}
|
||||
|
||||
export function planNewTypeCreation({
|
||||
entries,
|
||||
typeName,
|
||||
vaultPath,
|
||||
}: NewTypeParams & { entries: VaultEntry[] }): TypeCreationPlan {
|
||||
const existingType = findEquivalentTypeEntry(entries, typeName)
|
||||
if (existingType) return { status: 'existing', entry: existingType }
|
||||
|
||||
const resolved = resolveNewType({ typeName, vaultPath })
|
||||
const collision = findPathCollision(entries, resolved.entry.path)
|
||||
if (collision) {
|
||||
return {
|
||||
status: 'blocked',
|
||||
message: buildCreationCollisionMessage({ noun: 'type', title: typeName, path: resolved.entry.path }),
|
||||
}
|
||||
}
|
||||
return { status: 'create', resolved }
|
||||
}
|
||||
|
||||
function isAlreadyExistsError(error: unknown): boolean {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return /already exists|file exists|eexist/i.test(message)
|
||||
}
|
||||
|
||||
function createPersistFailureMessage(entry: VaultEntry, error: unknown): string {
|
||||
if (isAlreadyExistsError(error)) {
|
||||
const noun = entry.isA === 'Type' ? 'type' : 'note'
|
||||
return buildCreationCollisionMessage({ noun, title: entry.title, path: entry.path })
|
||||
}
|
||||
return entry.isA === 'Type'
|
||||
? 'Failed to create type — disk write error'
|
||||
: 'Failed to create note — disk write error'
|
||||
}
|
||||
|
||||
/** Persist a newly created note to disk. Returns a Promise for error handling. */
|
||||
export function persistNewNote(path: string, content: string): Promise<void> {
|
||||
if (!isTauri()) return Promise.resolve()
|
||||
return invoke<void>('save_note_content', { path, content }).then(() => {})
|
||||
return invoke<void>('create_note_content', { path, content }).then(() => {})
|
||||
}
|
||||
|
||||
// Rapid Cmd+N bursts can outpace the note-list render path on desktop. Keep
|
||||
@@ -156,33 +250,125 @@ function signalFocusEditor(opts?: { selectTitle?: boolean; path?: string }): voi
|
||||
}
|
||||
|
||||
interface PersistCallbacks {
|
||||
onFail: (p: string) => void
|
||||
onStart?: (p: string) => void
|
||||
onEnd?: (p: string) => void
|
||||
onPersisted?: () => void
|
||||
}
|
||||
|
||||
/** Persist to disk; track pending state via onStart/onEnd; revert on failure. */
|
||||
function persistOptimistic(path: string, content: string, cbs: PersistCallbacks): void {
|
||||
/** Persist to disk; track pending state via onStart/onEnd. */
|
||||
async function persistOptimistic(path: string, content: string, cbs: PersistCallbacks): Promise<void> {
|
||||
cbs.onStart?.(path)
|
||||
persistNewNote(path, content)
|
||||
.then(() => { cbs.onEnd?.(path); cbs.onPersisted?.() })
|
||||
.catch(() => { cbs.onEnd?.(path); cbs.onFail(path) })
|
||||
try {
|
||||
await persistNewNote(path, content)
|
||||
cbs.onPersisted?.()
|
||||
} finally {
|
||||
cbs.onEnd?.(path)
|
||||
}
|
||||
}
|
||||
|
||||
type ResolvedNote = { entry: VaultEntry; content: string }
|
||||
type PersistFn = (resolved: ResolvedNote) => void
|
||||
interface PersistResolvedOptions {
|
||||
openTab?: boolean
|
||||
}
|
||||
|
||||
/** Optimistically open note, add entry to vault, and persist to disk. */
|
||||
function createAndPersist(
|
||||
resolved: ResolvedNote,
|
||||
addFn: (e: VaultEntry) => void,
|
||||
openTab: (e: VaultEntry, c: string) => void,
|
||||
cbs: PersistCallbacks,
|
||||
): void {
|
||||
openTab(resolved.entry, resolved.content)
|
||||
addEntryWithMock(resolved.entry, resolved.content, addFn)
|
||||
persistOptimistic(resolved.entry.path, resolved.content, cbs)
|
||||
type PersistResolvedEntryFn = (
|
||||
resolved: ResolvedEntry,
|
||||
options?: PersistResolvedOptions,
|
||||
) => Promise<void>
|
||||
|
||||
interface CreationDeps {
|
||||
entries: VaultEntry[]
|
||||
vaultPath: string
|
||||
setToastMessage: (msg: string | null) => void
|
||||
persistResolvedEntry: PersistResolvedEntryFn
|
||||
}
|
||||
|
||||
interface NoteCreationRequest extends CreationDeps {
|
||||
title: string
|
||||
type: string
|
||||
creationPath?: 'plus_button'
|
||||
}
|
||||
|
||||
async function createNamedNote({
|
||||
entries,
|
||||
title,
|
||||
type,
|
||||
vaultPath,
|
||||
setToastMessage,
|
||||
persistResolvedEntry,
|
||||
creationPath,
|
||||
}: NoteCreationRequest): Promise<boolean> {
|
||||
const template = resolveTemplate({ entries, typeName: type })
|
||||
const plan = planNewNoteCreation({ entries, title, type, vaultPath, template })
|
||||
if (plan.status === 'blocked') {
|
||||
setToastMessage(plan.message)
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
await persistResolvedEntry(plan.resolved)
|
||||
if (creationPath) {
|
||||
trackEvent('note_created', { has_type: type !== 'Note' ? 1 : 0, creation_path: creationPath })
|
||||
}
|
||||
return true
|
||||
} catch (error) {
|
||||
setToastMessage(createPersistFailureMessage(plan.resolved.entry, error))
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
interface TypeCreationRequest extends CreationDeps {
|
||||
typeName: string
|
||||
}
|
||||
|
||||
async function createTypeFromName({
|
||||
entries,
|
||||
typeName,
|
||||
vaultPath,
|
||||
setToastMessage,
|
||||
persistResolvedEntry,
|
||||
}: TypeCreationRequest): Promise<boolean> {
|
||||
const plan = planNewTypeCreation({ entries, typeName, vaultPath })
|
||||
if (plan.status === 'existing') {
|
||||
setToastMessage(`Type "${plan.entry.title}" already exists`)
|
||||
return false
|
||||
}
|
||||
if (plan.status === 'blocked') {
|
||||
setToastMessage(plan.message)
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
await persistResolvedEntry(plan.resolved)
|
||||
trackEvent('type_created')
|
||||
return true
|
||||
} catch (error) {
|
||||
setToastMessage(createPersistFailureMessage(plan.resolved.entry, error))
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function createTypeSilently({
|
||||
entries,
|
||||
typeName,
|
||||
vaultPath,
|
||||
setToastMessage,
|
||||
persistResolvedEntry,
|
||||
}: TypeCreationRequest): Promise<VaultEntry> {
|
||||
const plan = planNewTypeCreation({ entries, typeName, vaultPath })
|
||||
if (plan.status === 'existing') return plan.entry
|
||||
if (plan.status === 'blocked') {
|
||||
setToastMessage(plan.message)
|
||||
throw new Error(plan.message)
|
||||
}
|
||||
|
||||
try {
|
||||
await persistResolvedEntry(plan.resolved, { openTab: false })
|
||||
return plan.resolved.entry
|
||||
} catch (error) {
|
||||
const message = createPersistFailureMessage(plan.resolved.entry, error)
|
||||
setToastMessage(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
}
|
||||
|
||||
interface ImmediateCreateDeps {
|
||||
@@ -318,30 +504,6 @@ function useImmediateCreateQueue(config: ImmediateCreateQueueConfig): (type?: st
|
||||
}, [syncDeps, executeRequest, scheduleQueuedBurst])
|
||||
}
|
||||
|
||||
interface RelationshipCreateDeps {
|
||||
entries: VaultEntry[]
|
||||
vaultPath: string
|
||||
openTabWithContent: (entry: VaultEntry, content: string) => void
|
||||
addEntry: (entry: VaultEntry) => void
|
||||
removeEntry: (path: string) => void
|
||||
setToastMessage: (msg: string | null) => void
|
||||
onNewNotePersisted?: () => void
|
||||
}
|
||||
|
||||
/** Create a note for a relationship link; persist in background. */
|
||||
function createNoteForRelationship(deps: RelationshipCreateDeps, title: string): void {
|
||||
const template = resolveTemplate({ entries: deps.entries, typeName: 'Note' })
|
||||
const resolved = resolveNewNote({ title, type: 'Note', vaultPath: deps.vaultPath, template })
|
||||
deps.openTabWithContent(resolved.entry, resolved.content)
|
||||
addEntryWithMock(resolved.entry, resolved.content, deps.addEntry)
|
||||
persistNewNote(resolved.entry.path, resolved.content)
|
||||
.then(() => deps.onNewNotePersisted?.())
|
||||
.catch(() => {
|
||||
deps.removeEntry(resolved.entry.path)
|
||||
deps.setToastMessage('Failed to create note — disk write error')
|
||||
})
|
||||
}
|
||||
|
||||
export interface NoteCreationConfig {
|
||||
addEntry: (entry: VaultEntry) => void
|
||||
removeEntry: (path: string) => void
|
||||
@@ -362,60 +524,59 @@ interface CreationTabDeps {
|
||||
}
|
||||
|
||||
export function useNoteCreation(config: NoteCreationConfig, tabDeps: CreationTabDeps) {
|
||||
const { addEntry, removeEntry, entries, setToastMessage, addPendingSave, removePendingSave } = config
|
||||
const { addEntry, removeEntry, entries, setToastMessage, addPendingSave, removePendingSave, vaultPath } = config
|
||||
const { openTabWithContent } = tabDeps
|
||||
|
||||
const revertOptimisticNote = useCallback((path: string) => {
|
||||
removeEntry(path)
|
||||
setToastMessage('Failed to create note — disk write error')
|
||||
}, [removeEntry, setToastMessage])
|
||||
const persistResolvedEntry = useCallback(async (
|
||||
resolved: ResolvedEntry,
|
||||
options?: PersistResolvedOptions,
|
||||
): Promise<void> => {
|
||||
if (options?.openTab !== false) openTabWithContent(resolved.entry, resolved.content)
|
||||
addEntryWithMock(resolved.entry, resolved.content, addEntry)
|
||||
try {
|
||||
await persistOptimistic(resolved.entry.path, resolved.content, {
|
||||
onStart: addPendingSave,
|
||||
onEnd: removePendingSave,
|
||||
onPersisted: config.onNewNotePersisted,
|
||||
})
|
||||
} catch (error) {
|
||||
removeEntry(resolved.entry.path)
|
||||
throw error
|
||||
}
|
||||
}, [openTabWithContent, addEntry, addPendingSave, removePendingSave, config.onNewNotePersisted, removeEntry])
|
||||
|
||||
const persistNew: PersistFn = useCallback(
|
||||
(resolved) => createAndPersist(resolved, addEntry, openTabWithContent, {
|
||||
onFail: revertOptimisticNote,
|
||||
onStart: addPendingSave,
|
||||
onEnd: removePendingSave,
|
||||
onPersisted: config.onNewNotePersisted,
|
||||
}),
|
||||
[openTabWithContent, addEntry, revertOptimisticNote, addPendingSave, removePendingSave, config.onNewNotePersisted],
|
||||
)
|
||||
const creationDeps = {
|
||||
entries,
|
||||
vaultPath,
|
||||
setToastMessage,
|
||||
persistResolvedEntry,
|
||||
}
|
||||
|
||||
const handleCreateNote = useCallback((title: string, type: string): Promise<boolean> =>
|
||||
createNamedNote({ ...creationDeps, title, type, creationPath: 'plus_button' }),
|
||||
[creationDeps])
|
||||
|
||||
const handleCreateType = useCallback((typeName: string): Promise<boolean> =>
|
||||
createTypeFromName({ ...creationDeps, typeName }),
|
||||
[creationDeps])
|
||||
|
||||
const createTypeEntrySilent = useCallback((typeName: string): Promise<VaultEntry> =>
|
||||
createTypeSilently({ ...creationDeps, typeName }),
|
||||
[creationDeps])
|
||||
|
||||
const handleCreateNoteForRelationship = useCallback((title: string): Promise<boolean> =>
|
||||
createNamedNote({ ...creationDeps, title, type: 'Note' }),
|
||||
[creationDeps])
|
||||
|
||||
const handleCreateNoteImmediate = useImmediateCreateQueue({
|
||||
entries,
|
||||
vaultPath: config.vaultPath,
|
||||
vaultPath,
|
||||
addEntry,
|
||||
openTabWithContent,
|
||||
trackUnsaved: config.trackUnsaved,
|
||||
markContentPending: config.markContentPending,
|
||||
})
|
||||
|
||||
const handleCreateNote = useCallback((title: string, type: string) => {
|
||||
const template = resolveTemplate({ entries, typeName: type })
|
||||
persistNew(resolveNewNote({ title, type, vaultPath: config.vaultPath, template }))
|
||||
trackEvent('note_created', { has_type: type !== 'Note' ? 1 : 0, creation_path: 'plus_button' })
|
||||
}, [entries, persistNew, config.vaultPath])
|
||||
|
||||
const handleCreateNoteForRelationship = useCallback((title: string): Promise<boolean> => {
|
||||
createNoteForRelationship({
|
||||
entries, vaultPath: config.vaultPath, openTabWithContent, addEntry,
|
||||
removeEntry, setToastMessage, onNewNotePersisted: config.onNewNotePersisted,
|
||||
}, title)
|
||||
return Promise.resolve(true)
|
||||
}, [entries, openTabWithContent, addEntry, removeEntry, setToastMessage, config.vaultPath, config.onNewNotePersisted])
|
||||
|
||||
const handleCreateType = useCallback((typeName: string) => {
|
||||
persistNew(resolveNewType({ typeName, vaultPath: config.vaultPath }))
|
||||
trackEvent('type_created')
|
||||
}, [persistNew, config.vaultPath])
|
||||
|
||||
/** Create a Type entry file silently (no tab opened). Adds to state and persists to disk. */
|
||||
const createTypeEntrySilent = useCallback(async (typeName: string): Promise<VaultEntry> => {
|
||||
const resolved = resolveNewType({ typeName, vaultPath: config.vaultPath })
|
||||
addEntryWithMock(resolved.entry, resolved.content, addEntry)
|
||||
await persistNewNote(resolved.entry.path, resolved.content)
|
||||
return resolved.entry
|
||||
}, [addEntry, config.vaultPath])
|
||||
|
||||
return {
|
||||
handleCreateNote,
|
||||
handleCreateNoteImmediate,
|
||||
|
||||
@@ -248,4 +248,44 @@ describe('useNoteRename hook', () => {
|
||||
|
||||
expect(setToastMessage).toHaveBeenCalledWith('A note with that name already exists')
|
||||
})
|
||||
|
||||
it('handleMoveNoteToFolder moves the note and keeps its title intact', async () => {
|
||||
const entry = makeEntry({ path: '/vault/notes/project-kickoff.md', filename: 'project-kickoff.md', title: 'Project Kickoff' })
|
||||
vi.mocked(mockInvoke).mockImplementation(async (cmd: string) => {
|
||||
if (cmd === 'move_note_to_folder') {
|
||||
return {
|
||||
new_path: '/vault/projects/project-kickoff.md',
|
||||
updated_files: 1,
|
||||
failed_updates: 0,
|
||||
}
|
||||
}
|
||||
if (cmd === 'get_note_content') return '# Project Kickoff\n'
|
||||
return ''
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useNoteRename(
|
||||
{ entries: [entry], setToastMessage },
|
||||
{ tabs: [], setTabs, activeTabPathRef, handleSwitchTab, updateTabContent },
|
||||
))
|
||||
|
||||
const onEntryRenamed = vi.fn()
|
||||
await act(async () => {
|
||||
await result.current.handleMoveNoteToFolder('/vault/notes/project-kickoff.md', 'projects', '/vault', onEntryRenamed)
|
||||
})
|
||||
|
||||
expect(mockInvoke).toHaveBeenCalledWith('move_note_to_folder', expect.objectContaining({
|
||||
old_path: '/vault/notes/project-kickoff.md',
|
||||
folder_path: 'projects',
|
||||
}))
|
||||
expect(onEntryRenamed).toHaveBeenCalledWith(
|
||||
'/vault/notes/project-kickoff.md',
|
||||
expect.objectContaining({
|
||||
path: '/vault/projects/project-kickoff.md',
|
||||
filename: 'project-kickoff.md',
|
||||
title: 'Project Kickoff',
|
||||
}),
|
||||
'# Project Kickoff\n',
|
||||
)
|
||||
expect(setToastMessage).toHaveBeenCalledWith('Moved to "projects" and updated 1 note')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -25,6 +25,12 @@ interface FilenameRenameRequest {
|
||||
vaultPath: string
|
||||
}
|
||||
|
||||
interface FolderMoveRequest {
|
||||
path: string
|
||||
folderPath: string
|
||||
vaultPath: string
|
||||
}
|
||||
|
||||
interface LoadNoteContentRequest {
|
||||
path: string
|
||||
}
|
||||
@@ -34,6 +40,8 @@ interface ReloadTabsAfterRenameRequest {
|
||||
updateTabContent: (path: string, content: string) => void
|
||||
}
|
||||
|
||||
type RenameCommand = 'rename_note' | 'rename_note_filename' | 'move_note_to_folder'
|
||||
|
||||
/** Check if a note's filename doesn't match the slug of its current title. */
|
||||
export function needsRenameOnSave(title: string, filename: string): boolean {
|
||||
if (!filename.toLowerCase().endsWith('.md')) return false
|
||||
@@ -46,10 +54,23 @@ export async function performRename({
|
||||
vaultPath,
|
||||
oldTitle,
|
||||
}: RenameRequest): Promise<RenameResult> {
|
||||
if (isTauri()) {
|
||||
return invoke<RenameResult>('rename_note', { vaultPath, oldPath: path, newTitle, oldTitle: oldTitle ?? null })
|
||||
}
|
||||
return mockInvoke<RenameResult>('rename_note', { vault_path: vaultPath, old_path: path, new_title: newTitle, old_title: oldTitle ?? null })
|
||||
return invokeRenameCommand({
|
||||
command: 'rename_note',
|
||||
tauriArgs: { vaultPath, oldPath: path, newTitle, oldTitle: oldTitle ?? null },
|
||||
mockArgs: { vault_path: vaultPath, old_path: path, new_title: newTitle, old_title: oldTitle ?? null },
|
||||
})
|
||||
}
|
||||
|
||||
function invokeRenameCommand(
|
||||
params: {
|
||||
command: RenameCommand
|
||||
tauriArgs: Record<string, unknown>
|
||||
mockArgs: Record<string, unknown>
|
||||
},
|
||||
): Promise<RenameResult> {
|
||||
return isTauri()
|
||||
? invoke<RenameResult>(params.command, params.tauriArgs)
|
||||
: mockInvoke<RenameResult>(params.command, params.mockArgs)
|
||||
}
|
||||
|
||||
export async function performFilenameRename({
|
||||
@@ -57,17 +78,22 @@ export async function performFilenameRename({
|
||||
newFilenameStem,
|
||||
vaultPath,
|
||||
}: FilenameRenameRequest): Promise<RenameResult> {
|
||||
if (isTauri()) {
|
||||
return invoke<RenameResult>('rename_note_filename', {
|
||||
vaultPath,
|
||||
oldPath: path,
|
||||
newFilenameStem,
|
||||
})
|
||||
}
|
||||
return mockInvoke<RenameResult>('rename_note_filename', {
|
||||
vault_path: vaultPath,
|
||||
old_path: path,
|
||||
new_filename_stem: newFilenameStem,
|
||||
return invokeRenameCommand({
|
||||
command: 'rename_note_filename',
|
||||
tauriArgs: { vaultPath, oldPath: path, newFilenameStem },
|
||||
mockArgs: { vault_path: vaultPath, old_path: path, new_filename_stem: newFilenameStem },
|
||||
})
|
||||
}
|
||||
|
||||
export async function performMoveNoteToFolder({
|
||||
path,
|
||||
folderPath,
|
||||
vaultPath,
|
||||
}: FolderMoveRequest): Promise<RenameResult> {
|
||||
return invokeRenameCommand({
|
||||
command: 'move_note_to_folder',
|
||||
tauriArgs: { vaultPath, oldPath: path, folderPath },
|
||||
mockArgs: { vault_path: vaultPath, old_path: path, folder_path: folderPath },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -87,16 +113,59 @@ export async function loadNoteContent({ path }: LoadNoteContentRequest): Promise
|
||||
: mockInvoke<string>('get_note_content', { path })
|
||||
}
|
||||
|
||||
export function renameToastMessage(updatedFiles: number, failedUpdates = 0): string {
|
||||
function rewriteSummaryLabel(params: { updatedFiles: number }): string {
|
||||
return params.updatedFiles === 1 ? 'Updated 1 note' : `Updated ${params.updatedFiles} notes`
|
||||
}
|
||||
|
||||
function manualUpdateWarning(params: { failedUpdates: number }): string {
|
||||
const { failedUpdates } = params
|
||||
return `${failedUpdates} linked note${failedUpdates > 1 ? 's' : ''} need${failedUpdates === 1 ? 's' : ''} manual updates`
|
||||
}
|
||||
|
||||
function formatRewriteToast(
|
||||
params: {
|
||||
action: string
|
||||
updatedFiles: number
|
||||
failedUpdates?: number
|
||||
preferBareUpdate?: boolean
|
||||
},
|
||||
): string {
|
||||
const {
|
||||
action,
|
||||
updatedFiles,
|
||||
failedUpdates = 0,
|
||||
preferBareUpdate = false,
|
||||
} = params
|
||||
if (failedUpdates > 0) {
|
||||
const noteLabel = `${failedUpdates} linked note${failedUpdates > 1 ? 's' : ''}`
|
||||
if (updatedFiles === 0) {
|
||||
return `Renamed, but ${noteLabel} need${failedUpdates === 1 ? 's' : ''} manual updates`
|
||||
return `${action}, but ${manualUpdateWarning({ failedUpdates })}`
|
||||
}
|
||||
return `Updated ${updatedFiles} note${updatedFiles > 1 ? 's' : ''}, but ${noteLabel} need${failedUpdates === 1 ? 's' : ''} manual updates`
|
||||
if (preferBareUpdate) {
|
||||
return `${rewriteSummaryLabel({ updatedFiles })}, but ${manualUpdateWarning({ failedUpdates })}`
|
||||
}
|
||||
return `${action} and ${rewriteSummaryLabel({ updatedFiles }).toLowerCase()}, but ${manualUpdateWarning({ failedUpdates })}`
|
||||
}
|
||||
if (updatedFiles === 0) return 'Renamed'
|
||||
return `Updated ${updatedFiles} note${updatedFiles > 1 ? 's' : ''}`
|
||||
if (updatedFiles === 0) return action
|
||||
return preferBareUpdate
|
||||
? rewriteSummaryLabel({ updatedFiles })
|
||||
: `${action} and ${rewriteSummaryLabel({ updatedFiles }).toLowerCase()}`
|
||||
}
|
||||
|
||||
export function renameToastMessage(updatedFiles: number, failedUpdates = 0): string {
|
||||
return formatRewriteToast({ action: 'Renamed', updatedFiles, failedUpdates, preferBareUpdate: true })
|
||||
}
|
||||
|
||||
function folderLabel(params: { folderPath: string }): string {
|
||||
const trimmed = params.folderPath.trim().replace(/^\/+|\/+$/g, '')
|
||||
return trimmed.split('/').filter(Boolean).at(-1) ?? trimmed
|
||||
}
|
||||
|
||||
function moveToastMessage(folderPath: string, updatedFiles: number, failedUpdates = 0): string {
|
||||
return formatRewriteToast({
|
||||
action: `Moved to "${folderLabel({ folderPath })}"`,
|
||||
updatedFiles,
|
||||
failedUpdates,
|
||||
})
|
||||
}
|
||||
|
||||
export async function reloadVaultAfterRename(reloadVault?: () => Promise<unknown>): Promise<void> {
|
||||
@@ -137,6 +206,15 @@ function renameErrorMessage(err: unknown): string {
|
||||
return 'Failed to rename note'
|
||||
}
|
||||
|
||||
function moveNoteErrorMessage(err: unknown): string {
|
||||
const message = typeof err === 'string'
|
||||
? err.trim()
|
||||
: err instanceof Error
|
||||
? err.message.trim()
|
||||
: ''
|
||||
return message || 'Failed to move note'
|
||||
}
|
||||
|
||||
export interface NoteRenameConfig {
|
||||
entries: VaultEntry[]
|
||||
setToastMessage: (msg: string | null) => void
|
||||
@@ -151,7 +229,14 @@ interface RenameTabDeps {
|
||||
updateTabContent: (path: string, content: string) => void
|
||||
}
|
||||
|
||||
export function useNoteRename(config: NoteRenameConfig, tabDeps: RenameTabDeps) {
|
||||
interface ApplyRenameOptions {
|
||||
successMessage?: (result: RenameResult) => string
|
||||
}
|
||||
|
||||
function useRenameResultApplier(
|
||||
config: NoteRenameConfig,
|
||||
tabDeps: RenameTabDeps,
|
||||
) {
|
||||
const { entries, setToastMessage, reloadVault } = config
|
||||
const { setTabs, activeTabPathRef, handleSwitchTab, updateTabContent } = tabDeps
|
||||
|
||||
@@ -164,6 +249,7 @@ export function useNoteRename(config: NoteRenameConfig, tabDeps: RenameTabDeps)
|
||||
result: RenameResult,
|
||||
buildEntry: (entry: VaultEntry | undefined, newPath: string) => VaultEntry,
|
||||
onEntryRenamed: (oldPath: string, newEntry: Partial<VaultEntry> & { path: string }, newContent: string) => void,
|
||||
options?: ApplyRenameOptions,
|
||||
) => {
|
||||
const entry = entries.find((item) => item.path === oldPath)
|
||||
const newContent = await loadNoteContent({ path: result.new_path })
|
||||
@@ -174,26 +260,79 @@ export function useNoteRename(config: NoteRenameConfig, tabDeps: RenameTabDeps)
|
||||
onEntryRenamed(oldPath, newEntry, newContent)
|
||||
await reloadTabsAfterRename({ tabPaths: otherTabPaths, updateTabContent })
|
||||
await reloadVaultAfterRename(reloadVault)
|
||||
setToastMessage(renameToastMessage(result.updated_files, result.failed_updates ?? 0))
|
||||
const successMessage = options?.successMessage
|
||||
? options.successMessage(result)
|
||||
: renameToastMessage(result.updated_files, result.failed_updates ?? 0)
|
||||
setToastMessage(successMessage)
|
||||
return result
|
||||
}, [entries, setTabs, activeTabPathRef, handleSwitchTab, updateTabContent, reloadVault, setToastMessage])
|
||||
|
||||
return {
|
||||
tabsRef,
|
||||
applyRenameResult,
|
||||
}
|
||||
}
|
||||
|
||||
async function runRenameAction({
|
||||
path,
|
||||
perform,
|
||||
applyRenameResult,
|
||||
buildEntry,
|
||||
onEntryRenamed,
|
||||
setToastMessage,
|
||||
errorMessage,
|
||||
logLabel,
|
||||
successMessage,
|
||||
allowUnchangedResult = false,
|
||||
}: {
|
||||
path: string
|
||||
perform: () => Promise<RenameResult>
|
||||
applyRenameResult: (
|
||||
oldPath: string,
|
||||
result: RenameResult,
|
||||
buildEntry: (entry: VaultEntry | undefined, newPath: string) => VaultEntry,
|
||||
onEntryRenamed: (oldPath: string, newEntry: Partial<VaultEntry> & { path: string }, newContent: string) => void,
|
||||
options?: ApplyRenameOptions,
|
||||
) => Promise<RenameResult>
|
||||
buildEntry: (entry: VaultEntry | undefined, newPath: string) => VaultEntry
|
||||
onEntryRenamed: (oldPath: string, newEntry: Partial<VaultEntry> & { path: string }, newContent: string) => void
|
||||
setToastMessage: (message: string | null) => void
|
||||
errorMessage: (err: unknown) => string
|
||||
logLabel: string
|
||||
successMessage?: (result: RenameResult) => string
|
||||
allowUnchangedResult?: boolean
|
||||
}): Promise<RenameResult | null> {
|
||||
try {
|
||||
const result = await perform()
|
||||
if (allowUnchangedResult && result.new_path === path) return result
|
||||
await applyRenameResult(path, result, buildEntry, onEntryRenamed, { successMessage })
|
||||
return result
|
||||
} catch (err) {
|
||||
console.error(`${logLabel}:`, err)
|
||||
setToastMessage(errorMessage(err))
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function useNoteRename(config: NoteRenameConfig, tabDeps: RenameTabDeps) {
|
||||
const { entries, setToastMessage } = config
|
||||
const { tabsRef, applyRenameResult } = useRenameResultApplier(config, tabDeps)
|
||||
|
||||
const handleRenameNote = useCallback(async (
|
||||
path: string, newTitle: string, vaultPath: string,
|
||||
onEntryRenamed: (oldPath: string, newEntry: Partial<VaultEntry> & { path: string }, newContent: string) => void,
|
||||
) => {
|
||||
try {
|
||||
const entry = entries.find((e) => e.path === path)
|
||||
const result = await performRename({ path, newTitle, vaultPath, oldTitle: entry?.title })
|
||||
await applyRenameResult(
|
||||
path,
|
||||
result,
|
||||
(currentEntry, newPath) => buildRenamedEntry(currentEntry ?? {} as VaultEntry, newTitle, newPath),
|
||||
onEntryRenamed,
|
||||
)
|
||||
} catch (err) {
|
||||
console.error('Failed to rename note:', err)
|
||||
setToastMessage(renameErrorMessage(err))
|
||||
}
|
||||
const entry = entries.find((e) => e.path === path)
|
||||
await runRenameAction({
|
||||
path,
|
||||
perform: () => performRename({ path, newTitle, vaultPath, oldTitle: entry?.title }),
|
||||
applyRenameResult,
|
||||
buildEntry: (currentEntry, newPath) => buildRenamedEntry(currentEntry ?? {} as VaultEntry, newTitle, newPath),
|
||||
onEntryRenamed,
|
||||
setToastMessage,
|
||||
errorMessage: renameErrorMessage,
|
||||
logLabel: 'Failed to rename note',
|
||||
})
|
||||
}, [entries, applyRenameResult, setToastMessage])
|
||||
|
||||
const handleRenameFilename = useCallback(async (
|
||||
@@ -202,19 +341,42 @@ export function useNoteRename(config: NoteRenameConfig, tabDeps: RenameTabDeps)
|
||||
vaultPath: string,
|
||||
onEntryRenamed: (oldPath: string, newEntry: Partial<VaultEntry> & { path: string }, newContent: string) => void,
|
||||
) => {
|
||||
try {
|
||||
const result = await performFilenameRename({ path, newFilenameStem, vaultPath })
|
||||
await applyRenameResult(
|
||||
path,
|
||||
result,
|
||||
(currentEntry, newPath) => buildFilenameRenamedEntry(currentEntry ?? {} as VaultEntry, newPath),
|
||||
onEntryRenamed,
|
||||
)
|
||||
} catch (err) {
|
||||
console.error('Failed to rename note filename:', err)
|
||||
setToastMessage(renameErrorMessage(err))
|
||||
}
|
||||
await runRenameAction({
|
||||
path,
|
||||
perform: () => performFilenameRename({ path, newFilenameStem, vaultPath }),
|
||||
applyRenameResult,
|
||||
buildEntry: (currentEntry, newPath) => buildFilenameRenamedEntry(currentEntry ?? {} as VaultEntry, newPath),
|
||||
onEntryRenamed,
|
||||
setToastMessage,
|
||||
errorMessage: renameErrorMessage,
|
||||
logLabel: 'Failed to rename note filename',
|
||||
})
|
||||
}, [applyRenameResult, setToastMessage])
|
||||
|
||||
return { handleRenameNote, handleRenameFilename, tabsRef }
|
||||
const handleMoveNoteToFolder = useCallback(async (
|
||||
path: string,
|
||||
folderPath: string,
|
||||
vaultPath: string,
|
||||
onEntryRenamed: (oldPath: string, newEntry: Partial<VaultEntry> & { path: string }, newContent: string) => void,
|
||||
) => {
|
||||
const normalizedFolderPath = folderPath.trim().replace(/^\/+|\/+$/g, '')
|
||||
return runRenameAction({
|
||||
path,
|
||||
perform: () => performMoveNoteToFolder({ path, folderPath: normalizedFolderPath, vaultPath }),
|
||||
applyRenameResult,
|
||||
buildEntry: (currentEntry, newPath) => buildFilenameRenamedEntry(currentEntry ?? {} as VaultEntry, newPath),
|
||||
onEntryRenamed,
|
||||
setToastMessage,
|
||||
errorMessage: moveNoteErrorMessage,
|
||||
logLabel: 'Failed to move note to folder',
|
||||
successMessage: (result) => moveToastMessage(
|
||||
normalizedFolderPath,
|
||||
result.updated_files,
|
||||
result.failed_updates ?? 0,
|
||||
),
|
||||
allowUnchangedResult: true,
|
||||
})
|
||||
}, [applyRenameResult, setToastMessage])
|
||||
|
||||
return { handleRenameNote, handleRenameFilename, handleMoveNoteToFolder, tabsRef }
|
||||
}
|
||||
|
||||
132
src/hooks/useNoteRetargeting.test.ts
Normal file
132
src/hooks/useNoteRetargeting.test.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { FolderNode, SidebarSelection, VaultEntry } from '../types'
|
||||
import { useNoteRetargeting } from './useNoteRetargeting'
|
||||
|
||||
const makeEntry = (overrides: Partial<VaultEntry> = {}): VaultEntry => ({
|
||||
path: '/vault/notes/alpha.md',
|
||||
filename: 'alpha.md',
|
||||
title: 'Alpha',
|
||||
isA: 'Note',
|
||||
aliases: [],
|
||||
belongsTo: [],
|
||||
relatedTo: [],
|
||||
status: 'Active',
|
||||
archived: false,
|
||||
modifiedAt: 1700000000,
|
||||
createdAt: 1700000000,
|
||||
fileSize: 10,
|
||||
snippet: '',
|
||||
wordCount: 0,
|
||||
relationships: {},
|
||||
icon: null,
|
||||
color: null,
|
||||
order: null,
|
||||
outgoingLinks: [],
|
||||
template: null,
|
||||
sort: null,
|
||||
sidebarLabel: null,
|
||||
view: null,
|
||||
visible: null,
|
||||
properties: {},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const folders: FolderNode[] = [
|
||||
{ name: 'notes', path: 'notes', children: [] },
|
||||
{ name: 'projects', path: 'projects', children: [] },
|
||||
]
|
||||
|
||||
describe('useNoteRetargeting', () => {
|
||||
const setSelection = vi.fn()
|
||||
const setToastMessage = vi.fn()
|
||||
const updateFrontmatter = vi.fn()
|
||||
const moveNoteToFolder = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
function renderUseNoteRetargeting(
|
||||
selection: SidebarSelection,
|
||||
entries: VaultEntry[] = [
|
||||
makeEntry(),
|
||||
makeEntry({ path: '/vault/type/project.md', filename: 'project.md', title: 'Project', isA: 'Type' }),
|
||||
],
|
||||
) {
|
||||
return renderHook(() => useNoteRetargeting({
|
||||
entries,
|
||||
folders,
|
||||
selection,
|
||||
setSelection,
|
||||
setToastMessage,
|
||||
vaultPath: '/vault',
|
||||
updateFrontmatter,
|
||||
moveNoteToFolder,
|
||||
}))
|
||||
}
|
||||
|
||||
it('rejects dropping a note onto its current type and allows other types', () => {
|
||||
const { result } = renderUseNoteRetargeting({ kind: 'filter', filter: 'all' })
|
||||
|
||||
expect(result.current.canDropNoteOnType('/vault/notes/alpha.md', 'Note')).toBe(false)
|
||||
expect(result.current.canDropNoteOnType('/vault/notes/alpha.md', 'Type')).toBe(true)
|
||||
})
|
||||
|
||||
it('changes the note type, updates entity selection, and shows a toast', async () => {
|
||||
updateFrontmatter.mockResolvedValue(undefined)
|
||||
const selection: SidebarSelection = { kind: 'entity', entry: makeEntry() }
|
||||
const { result } = renderUseNoteRetargeting(selection)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.changeNoteType('/vault/notes/alpha.md', 'Type')
|
||||
})
|
||||
|
||||
expect(updateFrontmatter).toHaveBeenCalledWith(
|
||||
'/vault/notes/alpha.md',
|
||||
'type',
|
||||
'Type',
|
||||
{ silent: true },
|
||||
)
|
||||
expect(setSelection).toHaveBeenCalledWith({
|
||||
kind: 'entity',
|
||||
entry: expect.objectContaining({
|
||||
path: '/vault/notes/alpha.md',
|
||||
isA: 'Type',
|
||||
}),
|
||||
})
|
||||
expect(setToastMessage).toHaveBeenCalledWith('Type set to "Type"')
|
||||
})
|
||||
|
||||
it('moves the note into another folder and updates the selected entity path', async () => {
|
||||
const selection: SidebarSelection = { kind: 'entity', entry: makeEntry() }
|
||||
moveNoteToFolder.mockImplementation(async (
|
||||
path: string,
|
||||
folderPath: string,
|
||||
vaultPath: string,
|
||||
onEntryRenamed: (oldPath: string, newEntry: Partial<VaultEntry> & { path: string }) => void,
|
||||
) => {
|
||||
onEntryRenamed(path, { path: '/vault/projects/alpha.md', filename: 'alpha.md' })
|
||||
return { new_path: '/vault/projects/alpha.md' }
|
||||
})
|
||||
const { result } = renderUseNoteRetargeting(selection)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.moveIntoFolder('/vault/notes/alpha.md', 'projects')
|
||||
})
|
||||
|
||||
expect(moveNoteToFolder).toHaveBeenCalledWith(
|
||||
'/vault/notes/alpha.md',
|
||||
'projects',
|
||||
'/vault',
|
||||
expect.any(Function),
|
||||
)
|
||||
expect(setSelection).toHaveBeenCalledWith({
|
||||
kind: 'entity',
|
||||
entry: expect.objectContaining({
|
||||
path: '/vault/projects/alpha.md',
|
||||
filename: 'alpha.md',
|
||||
}),
|
||||
})
|
||||
})
|
||||
})
|
||||
241
src/hooks/useNoteRetargeting.ts
Normal file
241
src/hooks/useNoteRetargeting.ts
Normal file
@@ -0,0 +1,241 @@
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import type { FolderNode, SidebarSelection, VaultEntry } from '../types'
|
||||
import type { FrontmatterOpOptions } from './frontmatterOps'
|
||||
import { extractVaultTypes } from '../utils/vaultTypes'
|
||||
|
||||
type RetargetResult = 'updated' | 'noop' | 'error'
|
||||
|
||||
export interface RetargetFolderOption {
|
||||
path: string
|
||||
label: string
|
||||
}
|
||||
|
||||
interface NoteRetargetingInput {
|
||||
entries: VaultEntry[]
|
||||
folders: FolderNode[]
|
||||
selection: SidebarSelection
|
||||
setSelection: (selection: SidebarSelection) => void
|
||||
setToastMessage: (message: string | null) => void
|
||||
vaultPath: string
|
||||
updateFrontmatter: (
|
||||
path: string,
|
||||
key: string,
|
||||
value: string,
|
||||
options?: FrontmatterOpOptions,
|
||||
) => Promise<void>
|
||||
moveNoteToFolder: (
|
||||
path: string,
|
||||
folderPath: string,
|
||||
vaultPath: string,
|
||||
onEntryRenamed: (
|
||||
oldPath: string,
|
||||
newEntry: Partial<VaultEntry> & { path: string },
|
||||
newContent: string,
|
||||
) => void,
|
||||
) => Promise<{ new_path: string } | null>
|
||||
}
|
||||
|
||||
function normalizeFolderPath(params: { folderPath: string }): string {
|
||||
return params.folderPath.trim().replace(/^\/+|\/+$/g, '')
|
||||
}
|
||||
|
||||
function folderPathForEntry(params: { entry: VaultEntry; vaultPath: string }): string {
|
||||
const normalizedVaultPath = params.vaultPath.replace(/\/+$/, '')
|
||||
const relativePath = params.entry.path.startsWith(`${normalizedVaultPath}/`)
|
||||
? params.entry.path.slice(normalizedVaultPath.length + 1)
|
||||
: params.entry.filename
|
||||
const lastSlashIndex = relativePath.lastIndexOf('/')
|
||||
return lastSlashIndex >= 0 ? relativePath.slice(0, lastSlashIndex) : ''
|
||||
}
|
||||
|
||||
function flattenFolders(nodes: FolderNode[]): RetargetFolderOption[] {
|
||||
return nodes.flatMap((node) => [
|
||||
{ path: node.path, label: node.name },
|
||||
...flattenFolders(node.children),
|
||||
])
|
||||
}
|
||||
|
||||
function entryByPath(params: { entries: VaultEntry[]; notePath: string }): VaultEntry | undefined {
|
||||
return params.entries.find((entry) => entry.path === params.notePath)
|
||||
}
|
||||
|
||||
function canRetargetEntryToType(params: { entry: VaultEntry | undefined; type: string }): boolean {
|
||||
return !!params.entry && params.entry.isA !== params.type
|
||||
}
|
||||
|
||||
function canRetargetEntryToFolder(
|
||||
params: {
|
||||
entry: VaultEntry | undefined
|
||||
folderPath: string
|
||||
vaultPath: string
|
||||
},
|
||||
): boolean {
|
||||
if (!params.entry) return false
|
||||
return folderPathForEntry({ entry: params.entry, vaultPath: params.vaultPath })
|
||||
!== normalizeFolderPath({ folderPath: params.folderPath })
|
||||
}
|
||||
|
||||
function updateEntitySelection(
|
||||
selection: SidebarSelection,
|
||||
setSelection: (selection: SidebarSelection) => void,
|
||||
notePath: string,
|
||||
patch: Partial<VaultEntry> & { path: string },
|
||||
) {
|
||||
if (selection.kind !== 'entity' || selection.entry.path !== notePath) return
|
||||
setSelection({
|
||||
kind: 'entity',
|
||||
entry: {
|
||||
...selection.entry,
|
||||
...patch,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function changeEntryType({
|
||||
entry,
|
||||
notePath,
|
||||
nextType,
|
||||
selection,
|
||||
setSelection,
|
||||
setToastMessage,
|
||||
updateFrontmatter,
|
||||
}: {
|
||||
entry: VaultEntry | undefined
|
||||
notePath: string
|
||||
nextType: string
|
||||
selection: SidebarSelection
|
||||
setSelection: (selection: SidebarSelection) => void
|
||||
setToastMessage: (message: string | null) => void
|
||||
updateFrontmatter: (
|
||||
path: string,
|
||||
key: string,
|
||||
value: string,
|
||||
options?: FrontmatterOpOptions,
|
||||
) => Promise<void>
|
||||
}): Promise<RetargetResult> {
|
||||
const normalizedType = nextType.trim()
|
||||
if (!entry || !normalizedType) return 'error'
|
||||
if (entry.isA === normalizedType) return 'noop'
|
||||
|
||||
try {
|
||||
await updateFrontmatter(notePath, 'type', normalizedType, { silent: true })
|
||||
updateEntitySelection(selection, setSelection, notePath, { path: notePath, isA: normalizedType })
|
||||
setToastMessage(`Type set to "${normalizedType}"`)
|
||||
return 'updated'
|
||||
} catch (error) {
|
||||
console.error('Failed to change note type:', error)
|
||||
setToastMessage(typeof error === 'string' ? error : 'Failed to change note type')
|
||||
return 'error'
|
||||
}
|
||||
}
|
||||
|
||||
async function moveEntryToFolder({
|
||||
entry,
|
||||
notePath,
|
||||
folderPath,
|
||||
vaultPath,
|
||||
selection,
|
||||
setSelection,
|
||||
moveNoteToFolder,
|
||||
}: {
|
||||
entry: VaultEntry | undefined
|
||||
notePath: string
|
||||
folderPath: string
|
||||
vaultPath: string
|
||||
selection: SidebarSelection
|
||||
setSelection: (selection: SidebarSelection) => void
|
||||
moveNoteToFolder: (
|
||||
path: string,
|
||||
folderPath: string,
|
||||
vaultPath: string,
|
||||
onEntryRenamed: (
|
||||
oldPath: string,
|
||||
newEntry: Partial<VaultEntry> & { path: string },
|
||||
newContent: string,
|
||||
) => void,
|
||||
) => Promise<{ new_path: string } | null>
|
||||
}): Promise<RetargetResult> {
|
||||
const normalizedFolderPath = normalizeFolderPath({ folderPath })
|
||||
if (!entry || !normalizedFolderPath) return 'error'
|
||||
if (folderPathForEntry({ entry, vaultPath }) === normalizedFolderPath) return 'noop'
|
||||
|
||||
const result = await moveNoteToFolder(
|
||||
notePath,
|
||||
normalizedFolderPath,
|
||||
vaultPath,
|
||||
(oldPath, newEntry) => updateEntitySelection(selection, setSelection, oldPath, newEntry),
|
||||
)
|
||||
if (!result) return 'error'
|
||||
return result.new_path === notePath ? 'noop' : 'updated'
|
||||
}
|
||||
|
||||
export function useNoteRetargeting({
|
||||
entries,
|
||||
folders,
|
||||
selection,
|
||||
setSelection,
|
||||
setToastMessage,
|
||||
vaultPath,
|
||||
updateFrontmatter,
|
||||
moveNoteToFolder,
|
||||
}: NoteRetargetingInput) {
|
||||
const availableTypes = useMemo(
|
||||
() => extractVaultTypes(entries).sort((left, right) => left.localeCompare(right)),
|
||||
[entries],
|
||||
)
|
||||
const availableFolders = useMemo(() => flattenFolders(folders), [folders])
|
||||
|
||||
const canDropNoteOnType = useCallback((notePath: string, type: string) => {
|
||||
return canRetargetEntryToType({
|
||||
entry: entryByPath({ entries, notePath }),
|
||||
type,
|
||||
})
|
||||
}, [entries])
|
||||
|
||||
const canDropNoteOnFolder = useCallback((notePath: string, folderPath: string) => {
|
||||
return canRetargetEntryToFolder({
|
||||
entry: entryByPath({ entries, notePath }),
|
||||
folderPath,
|
||||
vaultPath,
|
||||
})
|
||||
}, [entries, vaultPath])
|
||||
|
||||
const changeNoteType = useCallback(async (
|
||||
notePath: string,
|
||||
nextType: string,
|
||||
): Promise<RetargetResult> => {
|
||||
return changeEntryType({
|
||||
entry: entryByPath({ entries, notePath }),
|
||||
notePath,
|
||||
nextType,
|
||||
selection,
|
||||
setSelection,
|
||||
setToastMessage,
|
||||
updateFrontmatter,
|
||||
})
|
||||
}, [entries, selection, setSelection, setToastMessage, updateFrontmatter])
|
||||
|
||||
const moveIntoFolder = useCallback(async (
|
||||
notePath: string,
|
||||
folderPath: string,
|
||||
): Promise<RetargetResult> => {
|
||||
return moveEntryToFolder({
|
||||
entry: entryByPath({ entries, notePath }),
|
||||
notePath,
|
||||
folderPath,
|
||||
vaultPath,
|
||||
selection,
|
||||
setSelection,
|
||||
moveNoteToFolder,
|
||||
})
|
||||
}, [entries, moveNoteToFolder, selection, setSelection, vaultPath])
|
||||
|
||||
return {
|
||||
availableTypes,
|
||||
availableFolders,
|
||||
canDropNoteOnType,
|
||||
canDropNoteOnFolder,
|
||||
changeNoteType,
|
||||
moveIntoFolder,
|
||||
}
|
||||
}
|
||||
249
src/hooks/useNoteRetargetingUi.ts
Normal file
249
src/hooks/useNoteRetargetingUi.ts
Normal file
@@ -0,0 +1,249 @@
|
||||
import { useCallback, useMemo, useState, type Dispatch, type SetStateAction } from 'react'
|
||||
import type { NoteRetargetingContextValue } from '../components/note-retargeting/noteRetargetingContext'
|
||||
import type { RetargetOption } from '../components/note-retargeting/RetargetNoteDialog'
|
||||
import type { FolderNode, SidebarSelection, VaultEntry } from '../types'
|
||||
import type { FrontmatterOpOptions } from './frontmatterOps'
|
||||
import { useNoteRetargeting } from './useNoteRetargeting'
|
||||
|
||||
type DialogState =
|
||||
| { kind: 'type'; notePath: string }
|
||||
| { kind: 'folder'; notePath: string }
|
||||
| null
|
||||
|
||||
interface NoteRetargetingUiInput {
|
||||
activeEntry: VaultEntry | null
|
||||
activeNoteBlocked: boolean
|
||||
entries: VaultEntry[]
|
||||
folders: FolderNode[]
|
||||
selection: SidebarSelection
|
||||
setSelection: (selection: SidebarSelection) => void
|
||||
setToastMessage: (message: string | null) => void
|
||||
vaultPath: string
|
||||
updateFrontmatter: (
|
||||
path: string,
|
||||
key: string,
|
||||
value: string,
|
||||
options?: FrontmatterOpOptions,
|
||||
) => Promise<void>
|
||||
moveNoteToFolder: (
|
||||
path: string,
|
||||
folderPath: string,
|
||||
vaultPath: string,
|
||||
onEntryRenamed: (
|
||||
oldPath: string,
|
||||
newEntry: Partial<VaultEntry> & { path: string },
|
||||
newContent: string,
|
||||
) => void,
|
||||
) => Promise<{ new_path: string } | null>
|
||||
}
|
||||
|
||||
function folderPathForNote(notePath: string, vaultPath: string): string {
|
||||
const normalizedVaultPath = vaultPath.replace(/\/+$/, '')
|
||||
const relativePath = notePath.startsWith(`${normalizedVaultPath}/`)
|
||||
? notePath.slice(normalizedVaultPath.length + 1)
|
||||
: notePath
|
||||
const lastSlashIndex = relativePath.lastIndexOf('/')
|
||||
return lastSlashIndex >= 0 ? relativePath.slice(0, lastSlashIndex) : ''
|
||||
}
|
||||
|
||||
function buildTypeOptions(types: string[], entry: VaultEntry | null): RetargetOption[] {
|
||||
if (!entry) return []
|
||||
return types.map((type) => ({
|
||||
id: type,
|
||||
label: type,
|
||||
current: entry.isA === type,
|
||||
}))
|
||||
}
|
||||
|
||||
function buildFolderOptions(
|
||||
folders: Array<{ path: string; label: string }>,
|
||||
entry: VaultEntry | null,
|
||||
vaultPath: string,
|
||||
): RetargetOption[] {
|
||||
if (!entry) return []
|
||||
|
||||
const currentFolderPath = folderPathForNote(entry.path, vaultPath)
|
||||
return folders.map((folder) => ({
|
||||
id: folder.path,
|
||||
label: folder.label,
|
||||
detail: folder.path === folder.label ? undefined : folder.path,
|
||||
current: folder.path === currentFolderPath,
|
||||
}))
|
||||
}
|
||||
|
||||
function resolveDialogEntry(
|
||||
dialogState: DialogState,
|
||||
entries: VaultEntry[],
|
||||
activeEntry: VaultEntry | null,
|
||||
): VaultEntry | null {
|
||||
if (!dialogState) return null
|
||||
return entries.find((entry) => entry.path === dialogState.notePath)
|
||||
?? (activeEntry?.path === dialogState.notePath ? activeEntry : null)
|
||||
}
|
||||
|
||||
function hasTypeRetargetDestination(activeEntry: VaultEntry | null, activeNoteBlocked: boolean, types: string[]): boolean {
|
||||
return !!activeEntry && !activeNoteBlocked && types.some((type) => type !== activeEntry.isA)
|
||||
}
|
||||
|
||||
function hasFolderRetargetDestination(
|
||||
activeEntry: VaultEntry | null,
|
||||
activeNoteBlocked: boolean,
|
||||
folders: Array<{ path: string; label: string }>,
|
||||
canDropNoteOnFolder: (notePath: string, folderPath: string) => boolean,
|
||||
): boolean {
|
||||
return !!activeEntry
|
||||
&& !activeNoteBlocked
|
||||
&& folders.some((folder) => canDropNoteOnFolder(activeEntry.path, folder.path))
|
||||
}
|
||||
|
||||
function openDialogForActiveEntry(
|
||||
setDialogState: Dispatch<SetStateAction<DialogState>>,
|
||||
activeEntry: VaultEntry | null,
|
||||
enabled: boolean,
|
||||
kind: 'type' | 'folder',
|
||||
) {
|
||||
if (!activeEntry || !enabled) return
|
||||
setDialogState({ kind, notePath: activeEntry.path })
|
||||
}
|
||||
|
||||
async function selectFromDialogState(
|
||||
dialogState: DialogState,
|
||||
kind: 'type' | 'folder',
|
||||
value: string,
|
||||
runSelection: (notePath: string, value: string) => Promise<'updated' | 'noop' | 'error'>,
|
||||
): Promise<boolean> {
|
||||
if (!dialogState || dialogState.kind !== kind) return false
|
||||
const result = await runSelection(dialogState.notePath, value)
|
||||
return result !== 'error'
|
||||
}
|
||||
|
||||
function useNoteRetargetDialogState({
|
||||
activeEntry,
|
||||
canChangeActiveNoteType,
|
||||
canMoveActiveNoteToFolder,
|
||||
changeNoteType,
|
||||
moveIntoFolder,
|
||||
}: {
|
||||
activeEntry: VaultEntry | null
|
||||
canChangeActiveNoteType: boolean
|
||||
canMoveActiveNoteToFolder: boolean
|
||||
changeNoteType: (notePath: string, type: string) => Promise<'updated' | 'noop' | 'error'>
|
||||
moveIntoFolder: (notePath: string, folderPath: string) => Promise<'updated' | 'noop' | 'error'>
|
||||
}) {
|
||||
const [dialogState, setDialogState] = useState<DialogState>(null)
|
||||
|
||||
const openChangeNoteTypeDialog = useCallback(() => {
|
||||
openDialogForActiveEntry(setDialogState, activeEntry, canChangeActiveNoteType, 'type')
|
||||
}, [activeEntry, canChangeActiveNoteType])
|
||||
|
||||
const openMoveNoteToFolderDialog = useCallback(() => {
|
||||
openDialogForActiveEntry(setDialogState, activeEntry, canMoveActiveNoteToFolder, 'folder')
|
||||
}, [activeEntry, canMoveActiveNoteToFolder])
|
||||
|
||||
const closeDialog = useCallback(() => {
|
||||
setDialogState(null)
|
||||
}, [])
|
||||
|
||||
const selectType = useCallback(async (type: string) => {
|
||||
return selectFromDialogState(dialogState, 'type', type, changeNoteType)
|
||||
}, [changeNoteType, dialogState])
|
||||
|
||||
const selectFolder = useCallback(async (folderPath: string) => {
|
||||
return selectFromDialogState(dialogState, 'folder', folderPath, moveIntoFolder)
|
||||
}, [dialogState, moveIntoFolder])
|
||||
|
||||
return {
|
||||
dialogState,
|
||||
openChangeNoteTypeDialog,
|
||||
openMoveNoteToFolderDialog,
|
||||
closeDialog,
|
||||
selectType,
|
||||
selectFolder,
|
||||
}
|
||||
}
|
||||
|
||||
function useRetargetContextValue({
|
||||
canDropNoteOnType,
|
||||
changeNoteType,
|
||||
canDropNoteOnFolder,
|
||||
moveIntoFolder,
|
||||
}: {
|
||||
canDropNoteOnType: (notePath: string, type: string) => boolean
|
||||
changeNoteType: (notePath: string, type: string) => Promise<'updated' | 'noop' | 'error'>
|
||||
canDropNoteOnFolder: (notePath: string, folderPath: string) => boolean
|
||||
moveIntoFolder: (notePath: string, folderPath: string) => Promise<'updated' | 'noop' | 'error'>
|
||||
}) {
|
||||
return useMemo<NoteRetargetingContextValue>(() => ({
|
||||
canDropNoteOnType,
|
||||
dropNoteOnType: async (notePath, type) => {
|
||||
await changeNoteType(notePath, type)
|
||||
},
|
||||
canDropNoteOnFolder,
|
||||
dropNoteOnFolder: async (notePath, folderPath) => {
|
||||
await moveIntoFolder(notePath, folderPath)
|
||||
},
|
||||
}), [canDropNoteOnFolder, canDropNoteOnType, changeNoteType, moveIntoFolder])
|
||||
}
|
||||
|
||||
function buildDialogOptions(
|
||||
availableTypes: string[],
|
||||
availableFolders: Array<{ path: string; label: string }>,
|
||||
dialogEntry: VaultEntry | null,
|
||||
vaultPath: string,
|
||||
) {
|
||||
return {
|
||||
typeOptions: buildTypeOptions(availableTypes, dialogEntry),
|
||||
folderOptions: buildFolderOptions(availableFolders, dialogEntry, vaultPath),
|
||||
}
|
||||
}
|
||||
|
||||
function buildNoteRetargetingUiState(params: {
|
||||
contextValue: NoteRetargetingContextValue
|
||||
dialogState: DialogState
|
||||
dialogEntry: VaultEntry | null
|
||||
canChangeActiveNoteType: boolean
|
||||
canMoveActiveNoteToFolder: boolean
|
||||
openChangeNoteTypeDialog: () => void
|
||||
openMoveNoteToFolderDialog: () => void
|
||||
typeOptions: RetargetOption[]
|
||||
folderOptions: RetargetOption[]
|
||||
closeDialog: () => void
|
||||
selectType: (type: string) => Promise<boolean>
|
||||
selectFolder: (folderPath: string) => Promise<boolean>
|
||||
}) {
|
||||
return {
|
||||
contextValue: params.contextValue,
|
||||
isDialogOpen: params.dialogState !== null,
|
||||
dialogState: params.dialogState,
|
||||
dialogEntry: params.dialogEntry,
|
||||
canChangeActiveNoteType: params.canChangeActiveNoteType,
|
||||
canMoveActiveNoteToFolder: params.canMoveActiveNoteToFolder,
|
||||
openChangeNoteTypeDialog: params.openChangeNoteTypeDialog,
|
||||
openMoveNoteToFolderDialog: params.openMoveNoteToFolderDialog,
|
||||
typeOptions: params.typeOptions,
|
||||
folderOptions: params.folderOptions,
|
||||
closeDialog: params.closeDialog,
|
||||
selectType: params.selectType,
|
||||
selectFolder: params.selectFolder,
|
||||
}
|
||||
}
|
||||
|
||||
export function useNoteRetargetingUi({
|
||||
activeEntry, activeNoteBlocked, entries, folders, selection, setSelection, setToastMessage, vaultPath, updateFrontmatter, moveNoteToFolder,
|
||||
}: NoteRetargetingUiInput) {
|
||||
const {
|
||||
availableTypes, availableFolders, canDropNoteOnType, canDropNoteOnFolder, changeNoteType, moveIntoFolder,
|
||||
} = useNoteRetargeting({ entries, folders, selection, setSelection, setToastMessage, vaultPath, updateFrontmatter, moveNoteToFolder })
|
||||
const canChangeActiveNoteType = hasTypeRetargetDestination(activeEntry, activeNoteBlocked, availableTypes)
|
||||
const canMoveActiveNoteToFolder = hasFolderRetargetDestination(activeEntry, activeNoteBlocked, availableFolders, canDropNoteOnFolder)
|
||||
const { dialogState, openChangeNoteTypeDialog, openMoveNoteToFolderDialog, closeDialog, selectType, selectFolder } = useNoteRetargetDialogState({
|
||||
activeEntry, canChangeActiveNoteType, canMoveActiveNoteToFolder, changeNoteType, moveIntoFolder,
|
||||
})
|
||||
const dialogEntry = useMemo(() => resolveDialogEntry(dialogState, entries, activeEntry), [activeEntry, dialogState, entries])
|
||||
const contextValue = useRetargetContextValue({ canDropNoteOnType, changeNoteType, canDropNoteOnFolder, moveIntoFolder })
|
||||
const { typeOptions, folderOptions } = buildDialogOptions(availableTypes, availableFolders, dialogEntry, vaultPath)
|
||||
return buildNoteRetargetingUiState({
|
||||
contextValue, dialogState, dialogEntry, canChangeActiveNoteType, canMoveActiveNoteToFolder,
|
||||
openChangeNoteTypeDialog, openMoveNoteToFolderDialog, typeOptions, folderOptions, closeDialog, selectType, selectFolder,
|
||||
})
|
||||
}
|
||||
@@ -269,6 +269,42 @@ function handleRenameNoteFilename(args: {
|
||||
return { new_path: newPath, updated_files: updatedFiles, failed_updates: 0 }
|
||||
}
|
||||
|
||||
function handleMoveNoteToFolder(args: {
|
||||
vault_path: string
|
||||
old_path: string
|
||||
folder_path: string
|
||||
}) {
|
||||
const oldEntry = MOCK_ENTRIES.find(e => e.path === args.old_path)
|
||||
const oldContent = MOCK_CONTENT[args.old_path] ?? ''
|
||||
const oldTitle = oldEntry?.title ?? ''
|
||||
const oldFilename = args.old_path.split('/').pop() ?? ''
|
||||
const normalizedFolderPath = args.folder_path.trim().replace(/^\/+|\/+$/g, '')
|
||||
|
||||
if (!normalizedFolderPath) {
|
||||
throw new Error('Folder path cannot be empty')
|
||||
}
|
||||
|
||||
const vaultRoot = args.vault_path.replace(/\/+$/, '')
|
||||
const newPath = `${vaultRoot}/${normalizedFolderPath}/${oldFilename}`
|
||||
if (newPath === args.old_path) {
|
||||
return { new_path: args.old_path, updated_files: 0, failed_updates: 0 }
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(MOCK_CONTENT, newPath)) {
|
||||
throw new Error('A note with that name already exists')
|
||||
}
|
||||
|
||||
delete MOCK_CONTENT[args.old_path]
|
||||
MOCK_CONTENT[newPath] = oldContent
|
||||
|
||||
const oldPathStem = relativePathStem({ path: args.old_path, vaultPath: args.vault_path })
|
||||
const newPathStem = relativePathStem({ path: newPath, vaultPath: args.vault_path })
|
||||
const oldTargets = canonicalRenameTargets({ oldTitle, oldPathStem })
|
||||
const updatedFiles = updateMockRenameReferences({ newPath, newPathStem, oldTargets })
|
||||
|
||||
syncWindowContent()
|
||||
return { new_path: newPath, updated_files: updatedFiles, failed_updates: 0 }
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock handler map accepts heterogeneous arg types
|
||||
export const mockHandlers: Record<string, (args: any) => any> = {
|
||||
list_vault: () => MOCK_ENTRIES,
|
||||
@@ -386,6 +422,7 @@ export const mockHandlers: Record<string, (args: any) => any> = {
|
||||
save_vault_list: (args: { list: typeof mockVaultList }) => { mockVaultList = { ...args.list }; return null },
|
||||
rename_note: handleRenameNote,
|
||||
rename_note_filename: handleRenameNoteFilename,
|
||||
move_note_to_folder: handleMoveNoteToFolder,
|
||||
clone_repo: (args: { url: string; localPath?: string; local_path?: string }) => {
|
||||
const localPath = args.localPath ?? args.local_path ?? ''
|
||||
setMockRemoteState(localPath, true)
|
||||
|
||||
@@ -62,6 +62,16 @@ const VAULT_API_COMMANDS: Record<string, (args: Record<string, unknown>) => Vaul
|
||||
new_filename_stem: args.new_filename_stem,
|
||||
},
|
||||
} : null,
|
||||
move_note_to_folder: (args) =>
|
||||
args.old_path && args.folder_path ? {
|
||||
url: '/api/vault/move-to-folder',
|
||||
method: 'POST',
|
||||
body: {
|
||||
vault_path: args.vault_path,
|
||||
old_path: args.old_path,
|
||||
folder_path: args.folder_path,
|
||||
},
|
||||
} : null,
|
||||
delete_note: (args) =>
|
||||
args.path ? { url: '/api/vault/delete', method: 'POST', body: { path: args.path } } : null,
|
||||
search_vault: (args) => {
|
||||
|
||||
85
tests/smoke/collision-create-flows.spec.ts
Normal file
85
tests/smoke/collision-create-flows.spec.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { createFixtureVaultCopy, openFixtureVaultDesktopHarness, removeFixtureVaultCopy } from '../helpers/fixtureVault'
|
||||
import { sendShortcut } from './helpers'
|
||||
|
||||
let tempVaultDir: string
|
||||
|
||||
function writeFixtureNote(vaultPath: string, filename: string, content: string): string {
|
||||
const notePath = path.join(vaultPath, filename)
|
||||
fs.writeFileSync(notePath, content)
|
||||
return notePath
|
||||
}
|
||||
|
||||
function toast(page: import('@playwright/test').Page) {
|
||||
return page.locator('.fixed.bottom-8')
|
||||
}
|
||||
|
||||
test.describe('Collision-safe create flows', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
tempVaultDir = createFixtureVaultCopy()
|
||||
await page.setViewportSize({ width: 1600, height: 900 })
|
||||
})
|
||||
|
||||
test.afterEach(() => {
|
||||
removeFixtureVaultCopy(tempVaultDir)
|
||||
})
|
||||
|
||||
test('missing-type creation keeps the dialog open when a root filename already exists', async ({ page }) => {
|
||||
const collidingPath = writeFixtureNote(
|
||||
tempVaultDir,
|
||||
'hotel.md',
|
||||
'---\ntype: Note\n---\n# Existing Hotel Note\n',
|
||||
)
|
||||
writeFixtureNote(
|
||||
tempVaultDir,
|
||||
'hotel-guide.md',
|
||||
'---\ntype: Hotel\nstatus: Active\n---\n# Hotel Guide\n',
|
||||
)
|
||||
|
||||
await openFixtureVaultDesktopHarness(page, tempVaultDir)
|
||||
await page.getByText('Hotel Guide', { exact: true }).click()
|
||||
await sendShortcut(page, 'i', ['Control', 'Shift'])
|
||||
|
||||
const warning = page.getByTestId('missing-type-warning')
|
||||
await expect(warning).toBeVisible()
|
||||
await warning.focus()
|
||||
await page.keyboard.press('Enter')
|
||||
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
await expect(dialog.getByPlaceholder('e.g. Recipe, Book, Habit...')).toHaveValue('Hotel')
|
||||
await page.keyboard.press('Enter')
|
||||
|
||||
await expect(dialog).toBeVisible()
|
||||
await expect(toast(page)).toContainText('Cannot create type "Hotel" because hotel.md already exists')
|
||||
expect(fs.readFileSync(collidingPath, 'utf8')).toContain('# Existing Hotel Note')
|
||||
})
|
||||
|
||||
test('relationship create-and-open keeps the inline input active on filename collision', async ({ page }) => {
|
||||
const collidingPath = writeFixtureNote(
|
||||
tempVaultDir,
|
||||
'briefing.md',
|
||||
'---\ntype: Note\n---\n# Weekly Sync\n',
|
||||
)
|
||||
|
||||
await openFixtureVaultDesktopHarness(page, tempVaultDir)
|
||||
await page.getByText('Team Meeting', { exact: true }).click()
|
||||
await sendShortcut(page, 'i', ['Control', 'Shift'])
|
||||
|
||||
const addButton = page.getByTestId('add-relation-ref').first()
|
||||
await expect(addButton).toBeVisible()
|
||||
await addButton.click()
|
||||
const input = page.getByTestId('add-relation-ref-input')
|
||||
await expect(input).toBeVisible()
|
||||
await input.fill('Briefing!')
|
||||
await page.waitForTimeout(300)
|
||||
|
||||
await page.getByTestId('create-and-open-option').click()
|
||||
|
||||
await expect(input).toBeVisible()
|
||||
await expect(toast(page)).toContainText('Cannot create note "Briefing!" because briefing.md already exists')
|
||||
expect(fs.readFileSync(collidingPath, 'utf8')).toContain('# Weekly Sync')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user