Compare commits

..
1 Commits
Author SHA1 Message Date
Yuri Karamian 46f4b6e7bc v1.0.0 - Initial release 2026-02-09 01:47:56 +01:00
27 changed files with 364 additions and 2734 deletions
+11 -31
View File
@@ -1,33 +1,18 @@
# HelixNotes
A local markdown note-taking app built with Tauri, SvelteKit, and Rust.
A local-first markdown note-taking app built with Tauri, SvelteKit, and Rust.
Your notes are stored as standard Markdown files on your local filesystem.
No cloud, no lock-in.
Your notes are stored as standard Markdown files on your local filesystem. No cloud, no lock-in.
## Download
### Linux
| Platform | Download |
|----------|----------|
| Linux | [HelixNotes_1.0.0_amd64.AppImage](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.0.0/HelixNotes_1.0.0_amd64.AppImage) |
| Windows | Coming soon |
| macOS | Coming soon |
#### Arch / Manjaro / Fedora / openSUSE
[Download AppImage](https://download.helixnotes.com/releases/v1.1.1/HelixNotes_1.1.1_amd64.AppImage)
#### Debian / Ubuntu / Mint
[Download .deb](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.1.1/HelixNotes_1.1.1_amd64.deb) — Ubuntu 22.04+
### Windows
[Download Installer](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.1.1/HelixNotes_1.1.1_x64-setup.exe) — Windows 10/11
### macOS
[Download .dmg](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.1.1/HelixNotes_1.1.1_x64.dmg) — macOS 12+ (Intel, runs on Apple Silicon via Rosetta)
---
All releases: [codeberg.org/ArkHost/HelixNotes/releases](https://codeberg.org/ArkHost/HelixNotes/releases)
See all releases: [codeberg.org/ArkHost/HelixNotes/releases](https://codeberg.org/ArkHost/HelixNotes/releases)
## Features
@@ -35,25 +20,20 @@ All releases: [codeberg.org/ArkHost/HelixNotes/releases](https://codeberg.org/Ar
- **Wiki-links** — link notes with `[[Note Title]]` syntax
- **Graph view** — visualize connections between your notes
- **Full-text search** powered by Tantivy
- **Math support** — KaTeX rendering for inline and block equations
- **Daily notes** — one-click button to create or open today's note
- **AI writing tools** — improve, summarize, translate, and more (Anthropic / OpenAI)
- **Version history** — per-note snapshots with diff view
- **Backups** — automatic zip-based vault backups
- **PDF preview** — inline rendering of embedded PDFs
- **Tag management** — organize notes with tags, bulk edit from context menu
- **Drag-and-drop** — move notes between notebooks, reorganize notebooks by dragging
- **Obsidian import** — convert Obsidian wiki-links to standard markdown
- **Themes** — light/dark mode with customizable accent colors and fonts
- **Focus mode** — distraction-free writing
- **View mode** — read-only toggle for distraction-free reading
- **Local** — everything stays on your machine
- **Local-first** — everything stays on your machine
## Tech Stack
- **Frontend**: SvelteKit (Svelte 5) + TailwindCSS v4 + TipTap v3
- **Backend**: Rust (Tauri 2.0) + Tantivy (search) + Notify (file watcher)
- **Platforms**: Linux (AppImage), Windows, macOS
- **Platforms**: Linux (AppImage, .deb, .rpm), Windows, macOS
## Building from Source
@@ -79,4 +59,4 @@ pnpm tauri build
## License
[AGPL-3.0](https://codeberg.org/ArkHost/HelixNotes/src/branch/main/LICENSE)
[AGPL-3.0](LICENSE)
+1 -3
View File
@@ -2,7 +2,7 @@
"name": "helixnotes",
"private": true,
"license": "AGPL-3.0-or-later",
"version": "1.1.2",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite dev",
@@ -57,9 +57,7 @@
"@tiptap/extension-underline": "^3.19.0",
"@tiptap/pm": "^3.19.0",
"@tiptap/starter-kit": "^3.19.0",
"@types/katex": "^0.16.8",
"@types/markdown-it": "^14.1.2",
"katex": "^0.16.28",
"lowlight": "^3.3.0",
"markdown-it": "^14.1.0",
"markdown-it-mark": "^4.0.0",
-25
View File
@@ -89,15 +89,9 @@ importers:
'@tiptap/starter-kit':
specifier: ^3.19.0
version: 3.19.0
'@types/katex':
specifier: ^0.16.8
version: 0.16.8
'@types/markdown-it':
specifier: ^14.1.2
version: 14.1.2
katex:
specifier: ^0.16.28
version: 0.16.28
lowlight:
specifier: ^3.3.0
version: 3.3.0
@@ -942,9 +936,6 @@ packages:
'@types/hast@3.0.4':
resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
'@types/katex@0.16.8':
resolution: {integrity: sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==}
'@types/linkify-it@5.0.0':
resolution: {integrity: sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==}
@@ -981,10 +972,6 @@ packages:
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
engines: {node: '>=6'}
commander@8.3.0:
resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==}
engines: {node: '>= 12'}
cookie@0.6.0:
resolution: {integrity: sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==}
engines: {node: '>= 0.6'}
@@ -1061,10 +1048,6 @@ packages:
resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==}
hasBin: true
katex@0.16.28:
resolution: {integrity: sha512-YHzO7721WbmAL6Ov1uzN/l5mY5WWWhJBSW+jq4tkfZfsxmo1hu6frS0EOswvjBUnWE6NtjEs48SFn5CQESRLZg==}
hasBin: true
kleur@4.1.5:
resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
engines: {node: '>=6'}
@@ -1989,8 +1972,6 @@ snapshots:
dependencies:
'@types/unist': 3.0.3
'@types/katex@0.16.8': {}
'@types/linkify-it@5.0.0': {}
'@types/markdown-it@14.1.2':
@@ -2016,8 +1997,6 @@ snapshots:
clsx@2.1.1: {}
commander@8.3.0: {}
cookie@0.6.0: {}
crelt@1.0.6: {}
@@ -2095,10 +2074,6 @@ snapshots:
jiti@2.6.1: {}
katex@0.16.28:
dependencies:
commander: 8.3.0
kleur@4.1.5: {}
lightningcss-android-arm64@1.30.2:
+1 -17
View File
@@ -1778,7 +1778,7 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "helixnotes"
version = "1.1.2"
version = "1.0.0"
dependencies = [
"chrono",
"dirs",
@@ -1799,7 +1799,6 @@ dependencies = [
"tauri-plugin-fs",
"tauri-plugin-log",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
"tokio",
"uuid",
@@ -5082,21 +5081,6 @@ dependencies = [
"zbus",
]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc61e4822b8f74d68278e09161d3e3fdd1b14b9eb781e24edccaabf10c420e8c"
dependencies = [
"serde",
"serde_json",
"tauri",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.60.2",
"zbus",
]
[[package]]
name = "tauri-plugin-updater"
version = "2.10.0"
+2 -3
View File
@@ -1,7 +1,7 @@
[package]
name = "helixnotes"
version = "1.1.2"
description = "Local markdown note-taking app"
version = "1.0.0"
description = "Local-first markdown note-taking app"
authors = ["HelixNotes"]
license = "AGPL-3.0-or-later"
edition = "2021"
@@ -38,4 +38,3 @@ zip = { version = "2", default-features = false, features = ["deflate"] }
reqwest = { version = "0.12", features = ["json", "stream"] }
futures = "0.3"
rayon = "1"
tauri-plugin-single-instance = "2"
+2 -159
View File
@@ -2,7 +2,6 @@ use crate::search::SearchIndex;
use crate::state::AppState;
use crate::types::*;
use crate::vault::{operations, watcher};
use std::path::Path;
use tauri::{AppHandle, Manager, State};
// ── Vault Management ──
@@ -102,77 +101,6 @@ pub fn rename_notebook(path: String, new_name: String) -> Result<String, String>
operations::rename_notebook(&path, &new_name)
}
#[tauri::command]
pub fn move_notebook(
state: State<'_, AppState>,
notebook_path: String,
dest_parent: String,
) -> Result<String, String> {
let config = state.config.lock().map_err(|e| e.to_string())?;
let vault_path = config.active_vault.as_ref().ok_or("No active vault")?;
let old_relative = Path::new(&notebook_path)
.strip_prefix(vault_path.as_str())
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
let new_full_path = operations::move_notebook(&notebook_path, &dest_parent)?;
let new_relative = Path::new(&new_full_path)
.strip_prefix(vault_path.as_str())
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
// Update Quick Access paths for all notes inside the moved notebook
if let Ok(mut qa) = operations::load_quick_access(vault_path) {
let old_prefix = format!("{}/", old_relative);
let mut changed = false;
for path in qa.iter_mut() {
if path.starts_with(&old_prefix) {
*path = format!("{}/{}", new_relative, &path[old_prefix.len()..]);
changed = true;
}
}
if changed {
let _ = operations::save_quick_access(vault_path, &qa);
}
}
// Update notebook icon mappings
if let Ok(icons) = operations::load_notebook_icons(vault_path) {
let old_prefix = format!("{}/", old_relative);
let mut new_icons = std::collections::HashMap::new();
let mut changed = false;
for (key, value) in &icons {
if *key == old_relative {
new_icons.insert(new_relative.clone(), value.clone());
changed = true;
} else if key.starts_with(&old_prefix) {
let new_key = format!("{}/{}", new_relative, &key[old_prefix.len()..]);
new_icons.insert(new_key, value.clone());
changed = true;
} else {
new_icons.insert(key.clone(), value.clone());
}
}
if changed {
let icons_path = operations::helixnotes_dir(vault_path).join("notebook_icons.json");
if let Ok(data) = serde_json::to_string_pretty(&new_icons) {
let _ = std::fs::write(&icons_path, data);
}
}
}
// Rebuild search index (paths changed for all contained notes)
if let Ok(search_guard) = state.search_index.lock() {
if let Some(ref search) = *search_guard {
let _ = search.rebuild(vault_path);
}
}
Ok(new_full_path)
}
#[tauri::command]
pub fn delete_notebook(state: State<'_, AppState>, path: String) -> Result<(), String> {
let config = state.config.lock().map_err(|e| e.to_string())?;
@@ -245,21 +173,6 @@ pub fn create_note(
Ok(entry)
}
#[tauri::command]
pub fn create_daily_note(state: State<'_, AppState>) -> Result<NoteEntry, String> {
let config = state.config.lock().map_err(|e| e.to_string())?;
let vault_path = config.active_vault.as_ref().ok_or("No active vault")?;
let entry = operations::create_daily_note(vault_path)?;
if let Ok(search_guard) = state.search_index.lock() {
if let Some(ref search) = *search_guard {
let _ = search.index_note(&entry.path);
}
}
Ok(entry)
}
#[tauri::command]
pub fn rename_note(path: String, new_title: String) -> Result<String, String> {
operations::rename_note(&path, &new_title)
@@ -282,39 +195,8 @@ pub fn delete_note(state: State<'_, AppState>, path: String) -> Result<(), Strin
}
#[tauri::command]
pub fn move_note(
state: State<'_, AppState>,
note_path: String,
dest_notebook: String,
) -> Result<String, String> {
let config = state.config.lock().map_err(|e| e.to_string())?;
let vault_path = config.active_vault.as_ref().ok_or("No active vault")?;
// Compute old relative path before move
let old_relative = Path::new(&note_path)
.strip_prefix(vault_path)
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
let new_full_path = operations::move_note(&note_path, &dest_notebook)?;
// Update quick access if the moved note was in it
if !old_relative.is_empty() {
if let Ok(mut qa) = operations::load_quick_access(vault_path) {
if let Some(pos) = qa.iter().position(|p| *p == old_relative) {
let new_relative = Path::new(&new_full_path)
.strip_prefix(vault_path)
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();
if !new_relative.is_empty() {
qa[pos] = new_relative;
let _ = operations::save_quick_access(vault_path, &qa);
}
}
}
}
Ok(new_full_path)
pub fn move_note(note_path: String, dest_notebook: String) -> Result<String, String> {
operations::move_note(&note_path, &dest_notebook)
}
// ── Tags ──
@@ -507,10 +389,8 @@ pub fn set_general_settings(
pdf_height: u32,
title_mode: String,
hide_title_in_body: bool,
show_line_numbers: bool,
default_view_mode: bool,
show_tray_icon: bool,
close_to_tray: bool,
enable_wiki_links: bool,
) -> Result<(), String> {
let mut config = state.config.lock().map_err(|e| e.to_string())?;
@@ -522,10 +402,8 @@ pub fn set_general_settings(
config.pdf_height = pdf_height;
config.title_mode = title_mode;
config.hide_title_in_body = hide_title_in_body;
config.show_line_numbers = show_line_numbers;
config.default_view_mode = default_view_mode;
config.show_tray_icon = show_tray_icon;
config.close_to_tray = close_to_tray;
config.enable_wiki_links = enable_wiki_links;
save_app_config(&config)?;
Ok(())
@@ -557,13 +435,6 @@ pub fn remove_quick_access(
operations::remove_quick_access(vault_path, &note_relative)
}
#[tauri::command]
pub fn reorder_quick_access(state: State<'_, AppState>, paths: Vec<String>) -> Result<(), String> {
let config = state.config.lock().map_err(|e| e.to_string())?;
let vault_path = config.active_vault.as_ref().ok_or("No active vault")?;
operations::save_quick_access(vault_path, &paths)
}
#[tauri::command]
pub fn get_vault_stats(state: State<'_, AppState>) -> Result<VaultStats, String> {
let config = state.config.lock().map_err(|e| e.to_string())?;
@@ -1099,9 +970,6 @@ fn resolve_wiki_ref(
reference: &str,
) -> String {
let reference = reference.trim();
// Strip Obsidian heading anchors (#) and block references (^) before lookup
let reference = reference.split('#').next().unwrap_or(reference).trim();
let reference = reference.split('^').next().unwrap_or(reference).trim();
// Direct match by filename
if let Some(rel) = file_index.get(reference) {
return rel.clone();
@@ -1471,28 +1339,3 @@ fn save_app_config(config: &AppConfig) -> Result<(), String> {
std::fs::write(path, data).map_err(|e| e.to_string())?;
Ok(())
}
// ── Install Type Detection ──
#[tauri::command]
pub fn get_install_type() -> String {
if cfg!(target_os = "macos") {
"macos".to_string()
} else if cfg!(target_os = "windows") {
"windows".to_string()
} else if std::path::Path::new("/var/lib/dpkg/info/helix-notes.list").exists() {
"deb".to_string()
} else if std::path::Path::new("/var/lib/pacman/local").exists()
&& std::process::Command::new("pacman")
.args(["-Q", "helixnotes"])
.output()
.map(|o| o.status.success())
.unwrap_or(false)
{
"aur".to_string()
} else if std::env::var("APPIMAGE").is_ok() {
"appimage".to_string()
} else {
"native".to_string()
}
}
+2 -25
View File
@@ -19,17 +19,9 @@ use tauri::{
pub fn run() {
let config = commands::load_app_config();
let show_tray = config.show_tray_icon;
let close_to_tray = config.close_to_tray && show_tray;
let app_state = AppState::new(config);
let mut builder = tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
}))
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_opener::init())
@@ -61,12 +53,10 @@ pub fn run() {
commands::create_notebook,
commands::rename_notebook,
commands::delete_notebook,
commands::move_notebook,
commands::get_notes,
commands::read_note,
commands::save_note,
commands::create_note,
commands::create_daily_note,
commands::rename_note,
commands::delete_note,
commands::move_note,
@@ -88,7 +78,6 @@ pub fn run() {
commands::get_quick_access,
commands::add_quick_access,
commands::remove_quick_access,
commands::reorder_quick_access,
commands::get_vault_stats,
commands::import_obsidian,
commands::open_file,
@@ -104,19 +93,7 @@ pub fn run() {
commands::set_ai_settings,
commands::test_ai_connection,
commands::ai_ask,
commands::get_install_type,
]);
if close_to_tray {
builder = builder.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
let _ = window.hide();
}
});
}
builder
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
-6
View File
@@ -70,8 +70,6 @@ pub struct AppConfig {
#[serde(default)]
pub hide_title_in_body: bool,
#[serde(default)]
pub show_line_numbers: bool,
#[serde(default)]
pub backup_enabled: bool,
#[serde(default = "default_backup_frequency")]
pub backup_frequency: String,
@@ -99,8 +97,6 @@ pub struct AppConfig {
pub default_view_mode: bool,
#[serde(default)]
pub show_tray_icon: bool,
#[serde(default)]
pub close_to_tray: bool,
#[serde(default = "default_true")]
pub enable_wiki_links: bool,
}
@@ -150,7 +146,6 @@ impl Default for AppConfig {
pdf_height: 600,
title_mode: "input".to_string(),
hide_title_in_body: false,
show_line_numbers: false,
backup_enabled: false,
backup_frequency: "24h".to_string(),
backup_max_count: 10,
@@ -165,7 +160,6 @@ impl Default for AppConfig {
ai_writing_style: None,
default_view_mode: false,
show_tray_icon: false,
close_to_tray: false,
enable_wiki_links: true,
}
}
+5 -90
View File
@@ -1,8 +1,9 @@
use crate::types::NoteMeta;
use chrono::{NaiveDate, NaiveDateTime, Utc};
use chrono::Utc;
use gray_matter::engine::YAML;
use gray_matter::Matter;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize, Default)]
struct RawFrontmatter {
@@ -14,32 +15,6 @@ struct RawFrontmatter {
modified: Option<String>,
}
/// Try to parse a date string in multiple common formats.
fn parse_date_flexible(s: &str) -> Option<chrono::DateTime<Utc>> {
let s = s.trim();
// RFC 3339 / ISO 8601 with timezone (e.g. 2024-01-15T10:30:00+00:00)
if let Ok(dt) = s.parse::<chrono::DateTime<Utc>>() {
return Some(dt);
}
// Try parsing as DateTime with fixed offset then convert
if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
return Some(dt.with_timezone(&Utc));
}
// YYYY-MM-DD HH:MM:SS (no timezone)
if let Ok(ndt) = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
return Some(ndt.and_utc());
}
// YYYY-MM-DDTHH:MM:SS (no timezone, with T separator)
if let Ok(ndt) = NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") {
return Some(ndt.and_utc());
}
// YYYY-MM-DD (date only)
if let Ok(nd) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
return nd.and_hms_opt(0, 0, 0).map(|ndt| ndt.and_utc());
}
None
}
pub fn parse_note(raw: &str, filename: &str) -> (NoteMeta, String) {
let matter = Matter::<YAML>::new();
let result = matter.parse(raw);
@@ -53,16 +28,15 @@ pub fn parse_note(raw: &str, filename: &str) -> (NoteMeta, String) {
let created = fm
.created
.and_then(|s| parse_date_flexible(&s))
.and_then(|s| s.parse().ok())
.unwrap_or_else(Utc::now);
let modified = fm
.modified
.and_then(|s| parse_date_flexible(&s))
.and_then(|s| s.parse().ok())
.unwrap_or_else(Utc::now);
// Don't generate UUID on read — empty string signals "no ID yet"
let id = fm.id.unwrap_or_default();
let id = fm.id.unwrap_or_else(|| Uuid::new_v4().to_string());
let meta = NoteMeta {
id,
@@ -107,65 +81,6 @@ pub fn update_note_raw(meta: &NoteMeta, body: &str) -> String {
format!("{}{}", fm, body)
}
/// Merge NoteMeta fields into existing frontmatter, preserving unknown YAML keys.
/// Falls back to serialize_frontmatter() if the original has no frontmatter.
pub fn merge_frontmatter(original_raw: &str, meta: &NoteMeta, body: &str) -> String {
let matter = Matter::<YAML>::new();
let parsed = matter.parse(original_raw);
// If original had no frontmatter, use the simple serializer
if parsed.matter.trim().is_empty() {
return update_note_raw(meta, body);
}
// Parse existing YAML into a Mapping to preserve all keys
let mut mapping: serde_yaml::Mapping = match serde_yaml::from_str(&parsed.matter) {
Ok(m) => m,
Err(_) => return update_note_raw(meta, body), // unparseable YAML, fall back
};
// Update only our known fields
if !meta.id.is_empty() {
mapping.insert(
serde_yaml::Value::String("id".into()),
serde_yaml::Value::String(meta.id.clone()),
);
}
mapping.insert(
serde_yaml::Value::String("title".into()),
serde_yaml::Value::String(meta.title.clone()),
);
mapping.insert(
serde_yaml::Value::String("tags".into()),
serde_yaml::Value::Sequence(
meta.tags
.iter()
.map(|t| serde_yaml::Value::String(t.clone()))
.collect(),
),
);
mapping.insert(
serde_yaml::Value::String("pinned".into()),
serde_yaml::Value::Bool(meta.pinned),
);
mapping.insert(
serde_yaml::Value::String("created".into()),
serde_yaml::Value::String(meta.created.to_rfc3339()),
);
mapping.insert(
serde_yaml::Value::String("modified".into()),
serde_yaml::Value::String(meta.modified.to_rfc3339()),
);
// Serialize the mapping back to YAML
let yaml_str = match serde_yaml::to_string(&serde_yaml::Value::Mapping(mapping)) {
Ok(s) => s,
Err(_) => return update_note_raw(meta, body),
};
format!("---\n{}---\n{}", yaml_str, body)
}
fn filename_to_title(filename: &str) -> String {
let stem = filename.trim_end_matches(".md");
// Only replace dashes/underscores acting as word separators (between non-space chars).
+8 -104
View File
@@ -1,6 +1,6 @@
use crate::types::{NoteContent, NoteEntry, NoteMeta, NotebookEntry, VaultState};
use crate::vault::frontmatter;
use chrono::{Local, Utc};
use chrono::Utc;
use rayon::prelude::*;
use std::fs;
use std::io::Read;
@@ -184,19 +184,13 @@ fn read_note_entry_from_str(
let (mut meta, content) = frontmatter::parse_note(raw, &filename);
// Use filesystem times only if frontmatter didn't have created/modified fields
let has_created = raw.contains("\ncreated:") || raw.starts_with("created:");
let has_modified = raw.contains("\nmodified:") || raw.starts_with("modified:");
// Use filesystem times if frontmatter didn't have them
if let Ok(fs_meta) = fs::metadata(path) {
if !has_modified {
if let Ok(modified) = fs_meta.modified() {
meta.modified = modified.into();
}
if let Ok(modified) = fs_meta.modified() {
meta.modified = modified.into();
}
if !has_created {
if let Ok(created) = fs_meta.created() {
meta.created = created.into();
}
if let Ok(created) = fs_meta.created() {
meta.created = created.into();
}
}
@@ -239,19 +233,7 @@ pub fn save_note(path: &str, meta: &NoteMeta, body: &str) -> Result<(), String>
let mut updated_meta = meta.clone();
updated_meta.modified = Utc::now();
// Generate UUID on first save if note didn't have one
if updated_meta.id.is_empty() {
updated_meta.id = Uuid::new_v4().to_string();
}
// Read existing file to preserve unknown frontmatter fields
let existing = fs::read_to_string(path).unwrap_or_default();
let raw = if existing.is_empty() {
frontmatter::update_note_raw(&updated_meta, body)
} else {
frontmatter::merge_frontmatter(&existing, &updated_meta, body)
};
let raw = frontmatter::update_note_raw(&updated_meta, body);
fs::write(path, raw).map_err(|e| e.to_string())?;
Ok(())
}
@@ -308,49 +290,6 @@ pub fn create_note(
})
}
pub fn create_daily_note(vault_path: &str) -> Result<NoteEntry, String> {
let today = Local::now();
let date_str = today.format("%Y-%m-%d").to_string();
let title = today.format("%B %d, %Y").to_string();
let dir = Path::new(vault_path).join("Daily");
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let file_path = dir.join(format!("{}.md", date_str));
let vault_root = Path::new(vault_path);
// If today's note already exists, return it
if file_path.exists() {
return read_note_entry(&file_path, vault_root);
}
let now = Utc::now();
let meta = NoteMeta {
id: Uuid::new_v4().to_string(),
title,
tags: vec!["daily".to_string()],
pinned: false,
created: now,
modified: now,
};
let raw = frontmatter::update_note_raw(&meta, "\n");
fs::write(&file_path, raw).map_err(|e| e.to_string())?;
let relative = file_path
.strip_prefix(vault_root)
.unwrap_or(&file_path)
.to_string_lossy()
.to_string();
Ok(NoteEntry {
path: file_path.to_string_lossy().to_string(),
relative_path: relative,
meta,
preview: String::new(),
})
}
pub fn create_notebook(
vault_path: &str,
parent_relative: Option<&str>,
@@ -446,10 +385,7 @@ pub fn rename_note(path: &str, new_title: &str) -> Result<String, String> {
let (mut meta, content) = frontmatter::parse_note(&raw, &filename);
meta.title = new_title.to_string();
meta.modified = Utc::now();
if meta.id.is_empty() {
meta.id = Uuid::new_v4().to_string();
}
let updated = frontmatter::merge_frontmatter(&raw, &meta, &content);
let updated = frontmatter::update_note_raw(&meta, &content);
// Rename file
let new_filename = sanitize_filename(new_title);
@@ -496,38 +432,6 @@ pub fn move_note(note_path: &str, dest_notebook: &str) -> Result<String, String>
Ok(dest.to_string_lossy().to_string())
}
pub fn move_notebook(notebook_path: &str, dest_parent: &str) -> Result<String, String> {
let src = Path::new(notebook_path);
if !src.exists() || !src.is_dir() {
return Err("Notebook does not exist".to_string());
}
let dest_parent_path = Path::new(dest_parent);
if !dest_parent_path.is_dir() {
return Err("Destination does not exist".to_string());
}
// No-op if already in that parent
if src.parent() == Some(dest_parent_path) {
return Err("Notebook is already in that location".to_string());
}
let dir_name = src.file_name().unwrap_or_default();
let dest = dest_parent_path.join(dir_name);
// Prevent moving into itself or a descendant
if dest.starts_with(src) {
return Err("Cannot move a notebook into itself or its descendants".to_string());
}
if dest.exists() {
return Err("A notebook with that name already exists in the destination".to_string());
}
fs::rename(src, &dest).map_err(|e| e.to_string())?;
Ok(dest.to_string_lossy().to_string())
}
pub fn get_trash_notes(vault_path: &str) -> Result<Vec<NoteEntry>, String> {
let trash_dir = helixnotes_dir(vault_path).join("trash");
if !trash_dir.exists() {
+2 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "HelixNotes",
"version": "1.1.2",
"version": "1.0.0",
"identifier": "com.helixnotes.app",
"build": {
"frontendDist": "../build",
@@ -24,7 +24,7 @@
}
],
"security": {
"csp": "default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' asset: http://asset.localhost blob: data:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-src 'self' asset: http://asset.localhost",
"csp": "default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' asset: http://asset.localhost blob: data:; font-src 'self' data:; style-src 'self' 'unsafe-inline'",
"assetProtocol": {
"enable": true,
"scope": ["**/*", "/**", "**/.helixnotes/**"]
-16
View File
@@ -1,16 +0,0 @@
{
"app": {
"windows": [
{
"label": "main",
"decorations": true,
"titleBarStyle": "Overlay",
"hiddenTitle": true,
"trafficLightPosition": {
"x": 12,
"y": 10
}
}
]
}
}
+1 -10
View File
@@ -31,7 +31,7 @@
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);
--sidebar-width: 220px;
--notelist-width: 280px;
--panel-resize-handle: 3px;
--panel-resize-handle: 4px;
}
:root.dark {
@@ -149,12 +149,3 @@ body {
.resize-handle.active {
background: var(--accent);
}
body.resizing .ProseMirror {
pointer-events: none;
contain: strict;
}
body.resizing {
user-select: none;
}
-23
View File
@@ -60,13 +60,6 @@ export async function deleteNotebook(path: string): Promise<void> {
return invoke("delete_notebook", { path });
}
export async function moveNotebook(
notebookPath: string,
destParent: string,
): Promise<string> {
return invoke("move_notebook", { notebookPath, destParent });
}
export async function getNotes(
notebookPath: string | null,
): Promise<NoteEntry[]> {
@@ -92,10 +85,6 @@ export async function createNote(
return invoke("create_note", { notebookRelative, title });
}
export async function createDailyNote(): Promise<NoteEntry> {
return invoke("create_daily_note");
}
export async function renameNote(
path: string,
newTitle: string,
@@ -191,10 +180,8 @@ export async function setGeneralSettings(
pdfHeight: number,
titleMode: string,
hideTitleInBody: boolean,
showLineNumbers: boolean,
defaultViewMode: boolean,
showTrayIcon: boolean,
closeToTray: boolean,
enableWikiLinks: boolean,
): Promise<void> {
return invoke("set_general_settings", {
@@ -206,10 +193,8 @@ export async function setGeneralSettings(
pdfHeight,
titleMode,
hideTitleInBody,
showLineNumbers,
defaultViewMode,
showTrayIcon,
closeToTray,
enableWikiLinks,
});
}
@@ -226,10 +211,6 @@ export async function removeQuickAccess(noteRelative: string): Promise<void> {
return invoke("remove_quick_access", { noteRelative });
}
export async function reorderQuickAccess(paths: string[]): Promise<void> {
return invoke("reorder_quick_access", { paths });
}
export async function getVaultStats(): Promise<VaultStats> {
return invoke("get_vault_stats");
}
@@ -326,7 +307,3 @@ export async function aiAsk(
): Promise<void> {
return invoke("ai_ask", { action, text, customPrompt, requestId });
}
export async function getInstallType(): Promise<string> {
return invoke("get_install_type");
}
+11 -116
View File
@@ -20,18 +20,11 @@
showCommandPalette,
theme,
focusMode,
readOnly,
activeNote,
activeNotePath,
editorDirty,
showInfo,
showSettings,
sourceMode
activeNote
} from '$lib/stores/app';
const appWindow = getCurrentWindow();
const isMac = navigator.platform.startsWith('Mac');
import { loadVaultState, saveVaultState, readNote, createDailyNote } from '$lib/api';
import { loadVaultState, saveVaultState } from '$lib/api';
import { debounce } from '$lib/utils/debounce';
import type { VaultState, FileEvent } from '$lib/types';
@@ -39,39 +32,6 @@
let noteList: NoteList;
let editor: Editor;
let unlistenFileChange: (() => void) | null = null;
let navigatingFromHistory = false;
let noteHistory: string[] = [];
let noteHistoryIndex = -1;
// Track note navigation in history stack
$effect(() => {
const path = $activeNotePath;
if (navigatingFromHistory) {
navigatingFromHistory = false;
return;
}
if (path) {
// Trim forward history and push
noteHistory = [...noteHistory.slice(0, noteHistoryIndex + 1), path];
noteHistoryIndex = noteHistory.length - 1;
}
});
function navigateHistory(direction: -1 | 1) {
const newIndex = noteHistoryIndex + direction;
if (newIndex < 0 || newIndex >= noteHistory.length) return;
const path = noteHistory[newIndex];
noteHistoryIndex = newIndex;
navigatingFromHistory = true;
readNote(path).then((content) => {
$activeNote = content;
$activeNotePath = path;
$editorDirty = false;
editor?.loadNote(path, content.content);
}).catch(() => {
// Note may have been deleted, ignore
});
}
const persistState = debounce(async () => {
const state: VaultState = {
@@ -109,75 +69,28 @@
editor?.focusTitle();
}
async function handleDailyNote() {
try {
const entry = await createDailyNote();
const content = await readNote(entry.path);
$activeNote = content;
$activeNotePath = entry.path;
$editorDirty = false;
editor?.loadNote(entry.path, content.content);
noteList?.refresh();
sidebar?.refresh();
} catch (e) {
console.error('Failed to create/open daily note:', e);
}
}
function handleMouseDown(e: MouseEvent) {
if (e.button === 3) { e.preventDefault(); navigateHistory(-1); }
if (e.button === 4) { e.preventDefault(); navigateHistory(1); }
}
function handleKeydown(e: KeyboardEvent) {
const mod = e.ctrlKey || e.metaKey;
if (e.altKey && e.key === 'ArrowLeft') {
e.preventDefault();
navigateHistory(-1);
return;
}
if (e.altKey && e.key === 'ArrowRight') {
e.preventDefault();
navigateHistory(1);
return;
}
if (mod && !e.shiftKey && e.key === 'n') {
if (e.ctrlKey && !e.shiftKey && e.key === 'n') {
e.preventDefault();
createAndFocusNote();
}
if (mod && e.shiftKey && e.key === 'N') {
if (e.ctrlKey && e.shiftKey && e.key === 'N') {
e.preventDefault();
}
if (mod && e.shiftKey && e.key === 'F') {
if (e.ctrlKey && e.key === 'f') {
e.preventDefault();
$showSearch = true;
return;
}
if (mod && !e.shiftKey && e.key === 'f') {
e.preventDefault();
if ($activeNotePath) {
editor?.openNoteSearch();
} else {
$showSearch = true;
}
return;
}
if (mod && e.key === 'p') {
if (e.ctrlKey && e.key === 'p') {
e.preventDefault();
$showCommandPalette = true;
}
if (mod && e.key === 's') {
if (e.ctrlKey && e.key === 's') {
e.preventDefault();
editor?.forceSave();
}
if (mod && e.shiftKey && e.key === 'M') {
e.preventDefault();
$sourceMode = !$sourceMode;
}
if (e.key === 'Escape') {
if ($showSettings) $showSettings = false;
else if ($showInfo) $showInfo = false;
else if ($focusMode) $focusMode = false;
if ($focusMode) $focusMode = false;
else if ($showSearch) $showSearch = false;
else if ($showCommandPalette) $showCommandPalette = false;
}
@@ -229,12 +142,12 @@
});
</script>
<svelte:window onkeydown={handleKeydown} onmousedown={handleMouseDown} />
<svelte:window onkeydown={handleKeydown} />
<div class="app-shell">
{#if $focusMode}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="focus-topbar" class:macos={isMac} onmousedown={(e) => { if (!(e.target as HTMLElement).closest('button')) appWindow.startDragging(); }}>
<div class="focus-topbar" onmousedown={(e) => { if (!(e.target as HTMLElement).closest('button')) appWindow.startDragging(); }}>
<span class="focus-title">{$activeNote?.meta.title || 'Untitled'}</span>
<div class="focus-controls">
<button class="focus-btn focus-active" onclick={() => ($focusMode = false)} title="Exit focus mode (Escape)">
@@ -242,19 +155,6 @@
<path d="M8 3v3a2 2 0 01-2 2H3m18 0h-3a2 2 0 01-2-2V3m0 18v-3a2 2 0 012-2h3M3 16h3a2 2 0 012 2v3"/>
</svg>
</button>
<button class="focus-btn" class:focus-active={$readOnly} onclick={() => ($readOnly = !$readOnly)} title={$readOnly ? 'Switch to Edit Mode' : 'Switch to View Mode'}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
{#if $readOnly}
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
{:else}
<path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94" />
<path d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19" />
<line x1="1" y1="1" x2="23" y2="23" />
{/if}
</svg>
</button>
{#if !isMac}
<button class="focus-btn" onmousedown={(e) => e.stopPropagation()} onclick={() => appWindow.minimize()} title="Minimize">
<svg width="10" height="10" viewBox="0 0 10 10"><line x1="1" y1="5" x2="9" y2="5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>
</button>
@@ -264,11 +164,10 @@
<button class="focus-btn focus-close" onmousedown={(e) => e.stopPropagation()} onclick={() => appWindow.close()} title="Close">
<svg width="10" height="10" viewBox="0 0 10 10"><line x1="1.5" y1="1.5" x2="8.5" y2="8.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/><line x1="8.5" y1="1.5" x2="1.5" y2="8.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>
</button>
{/if}
</div>
</div>
{:else}
<TitleBar onNewNote={createAndFocusNote} onDailyNote={handleDailyNote} />
<TitleBar onNewNote={createAndFocusNote} />
{/if}
<div class="app-layout">
{#if !$focusMode}
@@ -386,8 +285,4 @@
background: #e81123;
color: white;
}
.focus-topbar.macos {
padding-left: 78px;
}
</style>
+1 -3
View File
@@ -9,8 +9,6 @@
action: () => void;
}
const modKey = navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl';
let query = $state('');
let selectedIndex = $state(0);
let inputEl = $state<HTMLInputElement>(null!);
@@ -19,7 +17,7 @@
{
id: 'search',
label: 'Search Notes',
shortcut: `${modKey}+F`,
shortcut: 'Ctrl+F',
action: () => {
$showCommandPalette = false;
$showSearch = true;
File diff suppressed because it is too large Load Diff
+55 -157
View File
@@ -20,17 +20,16 @@
y: number;
vx: number;
vy: number;
links: string[]; // titles this note links to
}
interface GraphEdge {
sourceIdx: number;
targetIdx: number;
source: string;
target: string;
}
let nodes: GraphNode[] = [];
let edges: GraphEdge[] = [];
let nodeIndexMap: Map<string, number> = new Map();
let connectedSet: Set<number> = new Set();
let animFrame = 0;
let pan = { x: 0, y: 0 };
let zoom = 1;
@@ -40,7 +39,6 @@
let panning = false;
let panStart = { x: 0, y: 0 };
let hoveredNode: GraphNode | null = null;
let glowPhase = 0;
const wikiLinkRegex = /\[\[([^\]]+)\]\]/g;
@@ -56,7 +54,7 @@
// Create nodes
const w = canvas?.width ?? 800;
const h = canvas?.height ?? 600;
nodes = titles.map((t) => ({
nodes = titles.map((t, i) => ({
id: t.title.toLowerCase(),
title: t.title,
path: t.path,
@@ -64,50 +62,33 @@
y: h / 2 + (Math.random() - 0.5) * Math.min(w, h) * 0.6,
vx: 0,
vy: 0,
links: [],
}));
// Build index map for O(1) lookups
nodeIndexMap = new Map();
for (let i = 0; i < nodes.length; i++) {
nodeIndexMap.set(nodes[i].id, i);
}
const nodeMap = new Map<string, GraphNode>();
for (const n of nodes) nodeMap.set(n.id, n);
// Read all notes in parallel (batched) to extract [[wiki-links]]
// Read each note to extract [[wiki-links]]
const edgeSet = new Set<string>();
edges = [];
const BATCH_SIZE = 20;
for (let b = 0; b < nodes.length; b += BATCH_SIZE) {
const batch = nodes.slice(b, b + BATCH_SIZE);
const results = await Promise.allSettled(
batch.map(async (node) => {
const content = await readNote(node.path);
return { node, body: content.content || '' };
})
);
for (const result of results) {
if (result.status !== 'fulfilled') continue;
const { node, body } = result.value;
const nodeIdx = nodeIndexMap.get(node.id)!;
for (const node of nodes) {
try {
const content = await readNote(node.path);
const body = content.content || '';
let match;
wikiLinkRegex.lastIndex = 0;
while ((match = wikiLinkRegex.exec(body)) !== null) {
// Handle Obsidian syntax: strip |alias, #heading, ^block
let rawLink = match[1].trim();
const pipeIdx = rawLink.indexOf('|');
if (pipeIdx >= 0) rawLink = rawLink.slice(0, pipeIdx).trim();
rawLink = rawLink.replace(/#.*$/, '').replace(/\^.*$/, '').trim();
const linkTitle = rawLink.toLowerCase();
const targetIdx = nodeIndexMap.get(linkTitle);
if (linkTitle !== node.id && targetIdx !== undefined) {
const edgeKey = nodeIdx < targetIdx ? `${nodeIdx}|${targetIdx}` : `${targetIdx}|${nodeIdx}`;
const linkTitle = match[1].trim().toLowerCase();
if (linkTitle !== node.id && nodeMap.has(linkTitle)) {
node.links.push(linkTitle);
const edgeKey = [node.id, linkTitle].sort().join('|');
if (!edgeSet.has(edgeKey)) {
edgeSet.add(edgeKey);
edges.push({ sourceIdx: nodeIdx, targetIdx });
connectedSet.add(nodeIdx);
connectedSet.add(targetIdx);
edges.push({ source: node.id, target: linkTitle });
}
}
}
} catch {
// Skip notes that can't be read
}
}
} catch (e) {
@@ -117,57 +98,13 @@
startSimulation();
}
function centerOnActiveNote() {
if (!canvas || nodes.length === 0) return;
const activePath = $activeNotePath || '';
const activeNode = nodes.find(n => n.path === activePath);
// Only center on active note if it has connections
if (!activeNode) return;
const activeIdx = nodeIndexMap.get(activeNode.id);
if (activeIdx === undefined || !connectedSet.has(activeIdx)) return;
// Gather the active node and its direct neighbors
const neighborhood: GraphNode[] = [activeNode];
for (const edge of edges) {
if (edge.sourceIdx === activeIdx) neighborhood.push(nodes[edge.targetIdx]);
else if (edge.targetIdx === activeIdx) neighborhood.push(nodes[edge.sourceIdx]);
}
const w = canvas.width;
const h = canvas.height;
const padding = 80;
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const n of neighborhood) {
if (n.x < minX) minX = n.x;
if (n.y < minY) minY = n.y;
if (n.x > maxX) maxX = n.x;
if (n.y > maxY) maxY = n.y;
}
const graphW = maxX - minX || 1;
const graphH = maxY - minY || 1;
const centerX = (minX + maxX) / 2;
const centerY = (minY + maxY) / 2;
zoom = Math.min(
(w - padding * 2) / graphW,
(h - padding * 2) / graphH,
1.8
);
zoom = Math.max(zoom, 0.5);
pan.x = w / 2 - centerX * zoom;
pan.y = h / 2 - centerY * zoom;
}
function fitToView() {
if (!canvas || nodes.length === 0) return;
const w = canvas.width;
const h = canvas.height;
const padding = 60;
// Compute bounding box of all nodes
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const node of nodes) {
if (node.x < minX) minX = node.x;
@@ -181,49 +118,36 @@
const centerGraphX = (minX + maxX) / 2;
const centerGraphY = (minY + maxY) / 2;
// Compute zoom to fit
zoom = Math.min(
(w - padding * 2) / graphW,
(h - padding * 2) / graphH,
2
2 // max zoom
);
zoom = Math.max(zoom, 0.2);
// Center the graph
pan.x = w / 2 - centerGraphX * zoom;
pan.y = h / 2 - centerGraphY * zoom;
}
function startSimulation() {
if (animFrame) cancelAnimationFrame(animFrame);
let iterations = 0;
const maxIterations = 300;
// Run physics synchronously — no need to animate the settling
for (let i = 0; i < 300; i++) {
function tick() {
if (iterations >= maxIterations) {
fitToView();
draw();
return;
}
simulate();
}
// Center on active note if it has links, otherwise fit all
const activePath = $activeNotePath || '';
const activeNode = nodes.find(n => n.path === activePath);
const activeIdx = activeNode ? nodeIndexMap.get(activeNode.id) : undefined;
if (activeIdx !== undefined && connectedSet.has(activeIdx)) {
centerOnActiveNote();
} else {
fitToView();
}
draw();
startGlowLoop();
}
let glowFrame = 0;
function startGlowLoop() {
if (glowFrame) cancelAnimationFrame(glowFrame);
function loop() {
glowPhase += 0.04;
draw();
glowFrame = requestAnimationFrame(loop);
iterations++;
animFrame = requestAnimationFrame(tick);
}
glowFrame = requestAnimationFrame(loop);
animFrame = requestAnimationFrame(tick);
}
function simulate() {
@@ -237,14 +161,13 @@
// Repulsion between all nodes
for (let i = 0; i < nodeCount; i++) {
const a = nodes[i];
for (let j = i + 1; j < nodeCount; j++) {
const a = nodes[i];
const b = nodes[j];
const dx = b.x - a.x;
const dy = b.y - a.y;
const distSq = dx * dx + dy * dy || 1;
const force = 800 / distSq;
const dist = Math.sqrt(distSq);
let dx = b.x - a.x;
let dy = b.y - a.y;
let dist = Math.sqrt(dx * dx + dy * dy) || 1;
const force = 800 / (dist * dist);
const fx = (dx / dist) * force;
const fy = (dy / dist) * force;
a.vx -= fx;
@@ -254,13 +177,14 @@
}
}
// Attraction along edges (indexed lookups)
// Attraction along edges
for (const edge of edges) {
const a = nodes[edge.sourceIdx];
const b = nodes[edge.targetIdx];
const dx = b.x - a.x;
const dy = b.y - a.y;
const dist = Math.sqrt(dx * dx + dy * dy) || 1;
const a = nodes.find(n => n.id === edge.source);
const b = nodes.find(n => n.id === edge.target);
if (!a || !b) continue;
let dx = b.x - a.x;
let dy = b.y - a.y;
let dist = Math.sqrt(dx * dx + dy * dy) || 1;
const force = (dist - 100) * 0.01;
const fx = (dx / dist) * force;
const fy = (dy / dist) * force;
@@ -303,14 +227,16 @@
const textColor = style.getPropertyValue('--text-primary').trim() || '#eee';
const textSecondary = style.getPropertyValue('--text-tertiary').trim() || '#888';
const accent = style.getPropertyValue('--accent').trim() || '#7b9bd4';
const accentLight = style.getPropertyValue('--accent-light').trim() || 'rgba(123,155,212,0.15)';
// Draw edges
ctx.strokeStyle = borderColor;
ctx.lineWidth = 1;
ctx.globalAlpha = 0.4;
for (const edge of edges) {
const a = nodes[edge.sourceIdx];
const b = nodes[edge.targetIdx];
const a = nodes.find(n => n.id === edge.source);
const b = nodes.find(n => n.id === edge.target);
if (!a || !b) continue;
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
@@ -322,27 +248,11 @@
const activePath = $activeNotePath || '';
// Draw nodes
const pulse = 0.5 + 0.5 * Math.sin(glowPhase);
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
for (const node of nodes) {
const isActive = node.path === activePath;
const isHovered = node === hoveredNode;
const hasLinks = connectedSet.has(i);
const baseRadius = isActive ? 9 : hasLinks ? 5 : 3.5;
const radius = isActive ? baseRadius + pulse * 2 : baseRadius;
// Active node glow
if (isActive) {
const glowRadius = radius + 10 + pulse * 6;
const glow = ctx.createRadialGradient(node.x, node.y, radius, node.x, node.y, glowRadius);
glow.addColorStop(0, accent + '60');
glow.addColorStop(1, accent + '00');
ctx.beginPath();
ctx.arc(node.x, node.y, glowRadius, 0, Math.PI * 2);
ctx.fillStyle = glow;
ctx.fill();
}
const hasLinks = node.links.length > 0 || edges.some(e => e.source === node.id || e.target === node.id);
const radius = isActive ? 7 : hasLinks ? 5 : 3.5;
// Node circle
ctx.beginPath();
@@ -358,23 +268,12 @@
}
ctx.fill();
// Active node ring
if (isActive) {
ctx.beginPath();
ctx.arc(node.x, node.y, radius + 3, 0, Math.PI * 2);
ctx.strokeStyle = accent;
ctx.lineWidth = 1.5;
ctx.globalAlpha = 0.4 + pulse * 0.3;
ctx.stroke();
ctx.globalAlpha = 1;
}
// Label
if (isActive || isHovered || hasLinks) {
ctx.font = `${isActive ? 'bold 13' : isHovered ? '12' : '10'}px -apple-system, BlinkMacSystemFont, sans-serif`;
ctx.font = `${isActive || isHovered ? '12' : '10'}px -apple-system, BlinkMacSystemFont, sans-serif`;
ctx.fillStyle = isActive || isHovered ? textColor : textSecondary;
ctx.textAlign = 'center';
ctx.fillText(node.title, node.x, node.y - radius - 6);
ctx.fillText(node.title, node.x, node.y - radius - 5);
}
}
@@ -478,7 +377,6 @@
onDestroy(() => {
if (animFrame) cancelAnimationFrame(animFrame);
if (glowFrame) cancelAnimationFrame(glowFrame);
});
</script>
+11 -20
View File
@@ -2,16 +2,10 @@
import { showInfo, appConfig } from '$lib/stores/app';
import { getVaultStats } from '$lib/api';
import { openUrl } from '@tauri-apps/plugin-opener';
import { getVersion } from '@tauri-apps/api/app';
import type { VaultStats } from '$lib/types';
const modKey = navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl';
let stats = $state<VaultStats | null>(null);
let activeTab = $state<'about' | 'shortcuts'>('shortcuts');
let appVersion = $state('...');
getVersion().then(v => appVersion = v).catch(() => appVersion = '0.0.0');
function close() {
$showInfo = false;
@@ -72,8 +66,8 @@
</svg>
</div>
<h3 class="app-name">HelixNotes</h3>
<p class="app-version">v{appVersion}</p>
<p class="app-description">A local markdown note-taking app.</p>
<p class="app-version">v1.0.0</p>
<p class="app-description">A local-first markdown note-taking app.</p>
{#if stats}
<div class="info-stats">
@@ -114,18 +108,15 @@
{:else}
<div class="shortcuts-section">
<h4 class="shortcuts-group-title">Keyboard Shortcuts</h4>
<div class="shortcut-row"><span class="shortcut-desc">New note</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>N</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Quick open</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>P</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Find in note</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>F</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Search vault</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Save</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>S</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Bold</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>B</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Italic</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>I</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Underline</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>U</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Undo</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Redo</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Go back</span><span class="shortcut-keys"><kbd>Alt</kbd>+<kbd></kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Go forward</span><span class="shortcut-keys"><kbd>Alt</kbd>+<kbd></kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">New note</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>N</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Quick open</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>P</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Search</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>F</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Save</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>S</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Bold</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>B</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Italic</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>I</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Underline</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>U</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Undo</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Redo</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Exit focus mode</span><span class="shortcut-keys"><kbd>Esc</kbd></span></div>
<h4 class="shortcuts-group-title">Editor Commands</h4>
+9 -351
View File
@@ -11,8 +11,7 @@
editorDirty,
quickAccessPaths,
appConfig,
notebooks,
tags
notebooks
} from '$lib/stores/app';
import {
getNotes,
@@ -27,9 +26,7 @@
getQuickAccess,
addQuickAccess,
removeQuickAccess,
reorderQuickAccess,
moveNote,
getAllTags
moveNote
} from '$lib/api';
import { formatRelativeTime } from '$lib/utils/time';
import type { NoteEntry, SortMode } from '$lib/types';
@@ -39,47 +36,17 @@
onNoteMoved?: () => void;
} = $props();
const modKey = navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl';
let compact = $derived($appConfig?.compact_notes ?? false);
let contextMenu = $state<{ x: number; y: number; note: NoteEntry } | null>(null);
let sortMenu = $state<{ x: number; y: number } | null>(null);
let editingNote = $state<string | null>(null);
let editValue = $state('');
let movePickerNote = $state<NoteEntry | null>(null);
let tagEditNote = $state<NoteEntry | null>(null);
let tagEditValue = $state('');
let tagEditTags = $state<string[]>([]);
// Multi-select
let selectedPaths = $state<Set<string>>(new Set());
let lastClickedPath = $state<string | null>(null);
let batchMovePicker = $state(false);
let batchTagEdit = $state(false);
// Quick Access drag-to-reorder
let qaDragFrom = $state<number | null>(null);
let qaDragOver = $state<number | null>(null);
let qaDragHalf = $state<'top' | 'bottom'>('bottom');
// Virtual scroll
let listContainer = $state<HTMLDivElement>(null!);
let scrollTop = $state(0);
let containerHeight = $state(600);
let itemHeight = $derived(compact ? 33 : 62);
const BUFFER = 10;
let totalHeight = $derived($sortedNotes.length * itemHeight);
let startIndex = $derived(Math.max(0, Math.floor(scrollTop / itemHeight) - BUFFER));
let endIndex = $derived(Math.min($sortedNotes.length, Math.ceil((scrollTop + containerHeight) / itemHeight) + BUFFER));
let visibleNotes = $derived($sortedNotes.slice(startIndex, endIndex));
let topPad = $derived(startIndex * itemHeight);
let bottomPad = $derived(Math.max(0, ($sortedNotes.length - endIndex) * itemHeight));
function onListScroll(e: Event) {
const el = e.currentTarget as HTMLDivElement;
scrollTop = el.scrollTop;
}
function clearSelection() {
selectedPaths = new Set();
@@ -87,22 +54,10 @@
batchMovePicker = false;
}
// Clear selection and reset scroll when view/notebook changes
// Clear selection when view/notebook changes
$effect(() => {
const _ = [$viewMode, $activeNotebook, $activeTag];
clearSelection();
scrollTop = 0;
if (listContainer) listContainer.scrollTop = 0;
});
// Track container height via ResizeObserver
$effect(() => {
if (!listContainer) return;
const ro = new ResizeObserver((entries) => {
containerHeight = entries[0].contentRect.height;
});
ro.observe(listContainer);
return () => ro.disconnect();
});
interface FlatNotebook { name: string; path: string; depth: number; }
@@ -288,102 +243,6 @@
}
}
function openTagEdit(note: NoteEntry) {
tagEditNote = note;
tagEditTags = [...note.meta.tags];
tagEditValue = '';
}
async function addTagToNote(tag: string) {
if (!tagEditNote || !tag.trim()) return;
const cleaned = tag.trim().toLowerCase();
if (tagEditTags.includes(cleaned)) return;
tagEditTags = [...tagEditTags, cleaned];
tagEditValue = '';
await saveTagsForNote(tagEditNote, tagEditTags);
}
async function removeTagFromNote(tag: string) {
if (!tagEditNote) return;
tagEditTags = tagEditTags.filter(t => t !== tag);
await saveTagsForNote(tagEditNote, tagEditTags);
}
async function saveTagsForNote(note: NoteEntry, newTags: string[]) {
try {
const content = await readNote(note.path);
content.meta.tags = newTags;
await saveNote(note.path, content.meta, content.content);
$notes = $notes.map(n =>
n.path === note.path ? { ...n, meta: { ...n.meta, tags: newTags } } : n
);
if ($activeNotePath === note.path && $activeNote) {
$activeNote = { ...$activeNote, meta: { ...$activeNote.meta, tags: newTags } };
}
$tags = await getAllTags();
} catch (e) {
console.error('Failed to save tags:', e);
}
}
function openBatchTagEdit() {
batchTagEdit = true;
tagEditValue = '';
// Show tags common to ALL selected notes
const selectedNotes = $notes.filter(n => selectedPaths.has(n.path));
if (selectedNotes.length === 0) { tagEditTags = []; return; }
tagEditTags = selectedNotes[0].meta.tags.filter(t =>
selectedNotes.every(n => n.meta.tags.includes(t))
);
}
async function addTagToBatch(tag: string) {
if (!tag.trim()) return;
const cleaned = tag.trim().toLowerCase();
tagEditValue = '';
if (!tagEditTags.includes(cleaned)) tagEditTags = [...tagEditTags, cleaned];
try {
for (const path of selectedPaths) {
const content = await readNote(path);
if (!content.meta.tags.includes(cleaned)) {
content.meta.tags = [...content.meta.tags, cleaned];
await saveNote(path, content.meta, content.content);
$notes = $notes.map(n =>
n.path === path ? { ...n, meta: { ...n.meta, tags: content.meta.tags } } : n
);
if ($activeNotePath === path) {
$activeNote = content;
}
}
}
$tags = await getAllTags();
} catch (e) {
console.error('Failed to add tag to batch:', e);
}
}
async function removeTagFromBatch(tag: string) {
tagEditTags = tagEditTags.filter(t => t !== tag);
try {
for (const path of selectedPaths) {
const content = await readNote(path);
if (content.meta.tags.includes(tag)) {
content.meta.tags = content.meta.tags.filter((t: string) => t !== tag);
await saveNote(path, content.meta, content.content);
$notes = $notes.map(n =>
n.path === path ? { ...n, meta: { ...n.meta, tags: content.meta.tags } } : n
);
if ($activeNotePath === path) {
$activeNote = content;
}
}
}
$tags = await getAllTags();
} catch (e) {
console.error('Failed to remove tag from batch:', e);
}
}
async function handleAddQuickAccess(note: NoteEntry) {
contextMenu = null;
try {
@@ -401,33 +260,12 @@
await removeQuickAccess(note.relative_path);
const qaNotes = await getQuickAccess();
$quickAccessPaths = qaNotes.map(n => n.relative_path);
if ($viewMode === 'quickaccess') await refresh(true);
if ($viewMode === 'quickaccess') await refresh();
} catch (e) {
console.error('Failed to remove from quick access:', e);
}
}
async function handleQaDrop(targetIndex: number) {
if (qaDragFrom === null) { qaDragFrom = null; qaDragOver = null; return; }
// Compute the actual insert position based on which half we're hovering
let insertAt = qaDragHalf === 'bottom' ? targetIndex + 1 : targetIndex;
if (qaDragFrom === insertAt || qaDragFrom + 1 === insertAt) {
qaDragFrom = null; qaDragOver = null; return;
}
const arr = [...$sortedNotes];
const [moved] = arr.splice(qaDragFrom, 1);
if (insertAt > qaDragFrom) insertAt--;
arr.splice(insertAt, 0, moved);
$notes = arr;
qaDragFrom = null;
qaDragOver = null;
try {
await reorderQuickAccess(arr.map(n => n.relative_path));
} catch (e) {
console.error('Failed to reorder quick access:', e);
}
}
async function handleMoveNote(note: NoteEntry, destPath: string) {
contextMenu = null;
movePickerNote = null;
@@ -545,7 +383,7 @@
}
function handleWindowClick() {
if (contextMenu) { contextMenu = null; movePickerNote = null; tagEditNote = null; batchTagEdit = false; }
if (contextMenu) { contextMenu = null; movePickerNote = null; }
if (sortMenu) sortMenu = null;
}
@@ -585,7 +423,7 @@
</svg>
</button>
{#if $viewMode !== 'trash'}
<button class="icon-btn" onclick={handleCreateNote} title={`New note (${modKey}+N)`}>
<button class="icon-btn" onclick={handleCreateNote} title="New note (Ctrl+N)">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
@@ -641,7 +479,7 @@
</div>
{/if}
<div class="list-content" bind:this={listContainer} onscroll={onListScroll}>
<div class="list-content">
{#if $sortedNotes.length === 0}
<div class="empty-state">
{#if $viewMode === 'trash'}
@@ -653,9 +491,7 @@
</div>
{/if}
<div style="height: {topPad}px"></div>
{#each visibleNotes as note, i (note.path)}
{@const noteIndex = startIndex + i}
{#each $sortedNotes as note (note.path)}
{#if editingNote === note.path}
<div class="note-item active">
<input
@@ -676,8 +512,6 @@
class:selected={selectedPaths.has(note.path)}
class:pinned={note.meta.pinned}
class:compact={compact}
class:qa-drag-above={$viewMode === 'quickaccess' && qaDragOver === noteIndex && qaDragFrom !== null && qaDragHalf === 'top'}
class:qa-drag-below={$viewMode === 'quickaccess' && qaDragOver === noteIndex && qaDragFrom !== null && qaDragHalf === 'bottom'}
onclick={(e) => handleNoteClick(e, note)}
oncontextmenu={(e) => {
e.preventDefault();
@@ -694,12 +528,6 @@
}}
draggable="true"
ondragstart={(e) => {
if ($viewMode === 'quickaccess') {
qaDragFrom = noteIndex;
e.dataTransfer!.setData('text/plain', note.path);
e.dataTransfer!.effectAllowed = 'move';
return;
}
if (selectedPaths.size > 1 && selectedPaths.has(note.path)) {
e.dataTransfer!.setData('text/plain', [...selectedPaths].join('\n'));
} else {
@@ -707,25 +535,6 @@
}
e.dataTransfer!.effectAllowed = 'move';
}}
ondragover={(e) => {
if ($viewMode === 'quickaccess' && qaDragFrom !== null) {
e.preventDefault();
e.dataTransfer!.dropEffect = 'move';
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
qaDragHalf = e.clientY < rect.top + rect.height / 2 ? 'top' : 'bottom';
qaDragOver = noteIndex;
}
}}
ondragleave={() => {
if (qaDragOver === noteIndex) qaDragOver = null;
}}
ondrop={(e) => {
if ($viewMode === 'quickaccess' && qaDragFrom !== null) {
e.preventDefault();
handleQaDrop(noteIndex);
}
}}
ondragend={() => { qaDragFrom = null; qaDragOver = null; }}
>
{#if compact}
<div class="note-compact-row">
@@ -763,7 +572,6 @@
</button>
{/if}
{/each}
<div style="height: {bottomPad}px"></div>
</div>
</div>
@@ -778,50 +586,7 @@
<button class="danger" onclick={() => { contextMenu = null; handleBatchPermanentDelete(); }}>
Delete {selectedPaths.size} permanently
</button>
{:else if batchTagEdit}
<button class="move-back" onclick={() => batchTagEdit = false}>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="15 18 9 12 15 6"/>
</svg>
Tags for {selectedPaths.size} notes
</button>
<div class="context-sep"></div>
<div class="tag-edit-section">
<div class="tag-edit-input-row">
<input
type="text"
class="tag-edit-input"
placeholder="Add tag to all..."
bind:value={tagEditValue}
onkeydown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); addTagToBatch(tagEditValue); }
if (e.key === 'Escape') { e.preventDefault(); batchTagEdit = false; }
}}
autofocus
/>
</div>
{#if tagEditTags.length > 0}
<div class="tag-edit-list">
{#each tagEditTags as tag}
<div class="tag-edit-item">
<span class="tag-edit-name">#{tag}</span>
<button class="tag-edit-remove" onclick={() => removeTagFromBatch(tag)} title="Remove from all">
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
{/each}
</div>
{:else}
<div class="context-empty">No common tags</div>
{/if}
</div>
{:else}
<button onclick={() => openBatchTagEdit()}>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/>
</svg>
Tags...
</button>
<button onclick={() => { contextMenu = null; batchMovePicker = true; }}>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z"/>
@@ -835,43 +600,6 @@
{:else if $viewMode === 'trash'}
<button onclick={() => handleRestore(contextMenu!.note)}>Restore</button>
<button class="danger" onclick={() => handlePermanentDelete(contextMenu!.note)}>Delete Permanently</button>
{:else if tagEditNote}
<button class="move-back" onclick={() => tagEditNote = null}>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="15 18 9 12 15 6"/>
</svg>
Tags
</button>
<div class="context-sep"></div>
<div class="tag-edit-section">
<div class="tag-edit-input-row">
<input
type="text"
class="tag-edit-input"
placeholder="Add tag..."
bind:value={tagEditValue}
onkeydown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); addTagToNote(tagEditValue); }
if (e.key === 'Escape') { e.preventDefault(); tagEditNote = null; }
}}
autofocus
/>
</div>
{#if tagEditTags.length > 0}
<div class="tag-edit-list">
{#each tagEditTags as tag}
<div class="tag-edit-item">
<span class="tag-edit-name">#{tag}</span>
<button class="tag-edit-remove" onclick={() => removeTagFromNote(tag)} title="Remove tag">
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
{/each}
</div>
{:else}
<div class="context-empty">No tags</div>
{/if}
</div>
{:else if movePickerNote}
<button class="move-back" onclick={() => movePickerNote = null}>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@@ -901,12 +629,6 @@
</svg>
{contextMenu.note.meta.pinned ? 'Unpin Note' : 'Pin Note'}
</button>
<button onclick={() => openTagEdit(contextMenu!.note)}>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/>
</svg>
Tags...
</button>
{#if $quickAccessPaths.includes(contextMenu.note.relative_path)}
<button onclick={() => handleRemoveQuickAccess(contextMenu!.note)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@@ -1039,8 +761,8 @@
border-radius: 6px;
cursor: pointer;
text-align: left;
transition: background 0.1s;
margin-bottom: 1px;
contain: content;
}
.note-item:hover {
@@ -1363,62 +1085,6 @@
border-radius: 2px;
}
.tag-edit-section {
padding: 4px 0;
}
.tag-edit-input-row {
padding: 2px 8px 4px;
}
.tag-edit-input {
width: 100%;
padding: 4px 8px;
border: 1px solid var(--border-color);
border-radius: 4px;
background: var(--bg-secondary);
color: var(--text-primary);
font-size: 12px;
outline: none;
}
.tag-edit-input:focus {
border-color: var(--accent);
}
.tag-edit-list {
max-height: 160px;
overflow-y: auto;
}
.tag-edit-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 3px 12px;
font-size: 12px;
}
.tag-edit-name {
color: var(--text-secondary);
}
.tag-edit-remove {
background: none;
border: none;
color: var(--text-tertiary);
cursor: pointer;
padding: 2px;
border-radius: 3px;
display: flex;
align-items: center;
}
.tag-edit-remove:hover {
color: var(--danger, #e53e3e);
background: color-mix(in srgb, var(--danger, #e53e3e) 10%, transparent);
}
.sort-menu {
position: fixed;
background: var(--bg-primary);
@@ -1467,12 +1133,4 @@
color: var(--accent);
font-size: 14px;
}
.note-item.qa-drag-above {
border-top: 2px solid var(--accent);
}
.note-item.qa-drag-below {
border-bottom: 2px solid var(--accent);
}
</style>
+2 -14
View File
@@ -2,35 +2,23 @@
let { onResize }: { onResize: (delta: number) => void } = $props();
let active = $state(false);
let startX = 0;
let rafId = 0;
let pendingDelta = 0;
function onMouseDown(e: MouseEvent) {
e.preventDefault();
active = true;
startX = e.clientX;
document.body.classList.add('resizing');
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
}
function onMouseMove(e: MouseEvent) {
pendingDelta += e.clientX - startX;
const delta = e.clientX - startX;
startX = e.clientX;
if (!rafId) {
rafId = requestAnimationFrame(() => {
onResize(pendingDelta);
pendingDelta = 0;
rafId = 0;
});
}
onResize(delta);
}
function onMouseUp() {
active = false;
document.body.classList.remove('resizing');
if (rafId) { cancelAnimationFrame(rafId); rafId = 0; }
if (pendingDelta) { onResize(pendingDelta); pendingDelta = 0; }
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
}
+3 -90
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { showSettings, theme, appConfig, updateAvailable as globalUpdateAvailable, updateObj as globalUpdateObj, installType, settingsTab } from '$lib/stores/app';
import { showSettings, theme, appConfig } from '$lib/stores/app';
import { setTheme, setAccentColor, setFontSize, setFontFamily, setGeneralSettings, importObsidian, createBackup, listBackups, restoreBackup, deleteBackup, setBackupSettings, setAiSettings, testAiConnection } from '$lib/api';
import { open as openDialog } from '@tauri-apps/plugin-dialog';
import { listen } from '@tauri-apps/api/event';
@@ -24,31 +24,6 @@
}
loadAppVersion();
// Switch to requested tab if set externally (e.g. from update badge)
$effect(() => {
const tab = $settingsTab;
if (tab) {
activeTab = tab as Tab;
$settingsTab = null;
}
});
// Pre-populate from global store if update was already detected at startup
$effect(() => {
const global = $globalUpdateAvailable;
if (global && !updateAvailable) {
updateAvailable = { version: global.version, body: global.body };
}
});
// Pre-populate updater object from global store so Download & Install works without manual check
$effect(() => {
const obj = $globalUpdateObj;
if (obj && !updateObj) {
updateObj = obj;
}
});
async function handleCheckUpdate() {
updateChecking = true;
updateMessage = null;
@@ -57,9 +32,7 @@
const update = await checkUpdate();
if (update) {
updateObj = update;
$globalUpdateObj = update;
updateAvailable = { version: update.version, body: update.body, date: update.date };
globalUpdateAvailable.set({ version: update.version, body: update.body });
updateMessage = { type: 'info', text: `Version ${update.version} is available!` };
} else {
updateMessage = { type: 'success', text: 'You are on the latest version.' };
@@ -308,10 +281,8 @@
let pdfHeight = $state($appConfig?.pdf_height ?? 600);
let titleMode = $state($appConfig?.title_mode ?? 'input');
let hideTitleInBody = $state($appConfig?.hide_title_in_body ?? false);
let showLineNumbers = $state($appConfig?.show_line_numbers ?? false);
let defaultViewMode = $state($appConfig?.default_view_mode ?? false);
let showTrayIcon = $state($appConfig?.show_tray_icon ?? false);
let closeToTray = $state($appConfig?.close_to_tray ?? false);
let enableWikiLinks = $state($appConfig?.enable_wiki_links ?? true);
const pdfHeightPresets = [
@@ -361,13 +332,11 @@
$appConfig.pdf_height = pdfHeight;
$appConfig.title_mode = titleMode;
$appConfig.hide_title_in_body = hideTitleInBody;
$appConfig.show_line_numbers = showLineNumbers;
$appConfig.default_view_mode = defaultViewMode;
$appConfig.show_tray_icon = showTrayIcon;
$appConfig.close_to_tray = closeToTray;
$appConfig.enable_wiki_links = enableWikiLinks;
}
setGeneralSettings(compactNotes, timeFormat, gpuAcceleration, autostart, pdfPreview, pdfHeight, titleMode, hideTitleInBody, showLineNumbers, defaultViewMode, showTrayIcon, closeToTray, enableWikiLinks)
setGeneralSettings(compactNotes, timeFormat, gpuAcceleration, autostart, pdfPreview, pdfHeight, titleMode, hideTitleInBody, defaultViewMode, showTrayIcon, enableWikiLinks)
.catch((e) => console.error('Failed to save general settings:', e));
}
@@ -591,21 +560,10 @@
<span class="setting-name">Show in system tray</span>
<span class="setting-desc">Show an icon in the notification area (requires restart)</span>
</span>
<button class="toggle-switch" class:on={showTrayIcon} onclick={() => { showTrayIcon = !showTrayIcon; if (!showTrayIcon) closeToTray = false; saveGeneralSettings(); }}>
<button class="toggle-switch" class:on={showTrayIcon} onclick={() => { showTrayIcon = !showTrayIcon; saveGeneralSettings(); }}>
<span class="toggle-knob"></span>
</button>
</label>
{#if showTrayIcon}
<label class="setting-toggle">
<span class="setting-label">
<span class="setting-name">Close to tray</span>
<span class="setting-desc">Minimize to tray instead of quitting when closing the window (requires restart)</span>
</span>
<button class="toggle-switch" class:on={closeToTray} onclick={() => { closeToTray = !closeToTray; saveGeneralSettings(); }}>
<span class="toggle-knob"></span>
</button>
</label>
{/if}
</div>
</div>
{:else if activeTab === 'editor'}
@@ -627,15 +585,6 @@
<span class="toggle-knob"></span>
</button>
</label>
<label class="setting-toggle" style="margin-top: 12px;">
<span class="setting-label">
<span class="setting-name">Show line numbers</span>
<span class="setting-desc">Display line numbers in the markdown source editor</span>
</span>
<button class="toggle-switch" class:on={showLineNumbers} onclick={() => { showLineNumbers = !showLineNumbers; saveGeneralSettings(); }}>
<span class="toggle-knob"></span>
</button>
</label>
<label class="setting-toggle" style="margin-top: 12px;">
<span class="setting-label">
<span class="setting-name">Open notes in View Mode</span>
@@ -1072,7 +1021,6 @@
<div class="update-notes">{updateAvailable.body}</div>
{/if}
</div>
{#if $installType === 'appimage' || $installType === 'windows' || $installType === 'macos'}
<button class="update-install-btn" onclick={handleDownloadAndInstall} disabled={updateDownloading}>
{#if updateDownloading}
<svg class="spinner-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10" opacity="0.25" /><path d="M12 2a10 10 0 019.95 9" /></svg>
@@ -1089,24 +1037,6 @@
<div class="update-progress-fill" style="width: {updateProgress}%"></div>
</div>
{/if}
{:else if $installType === 'deb'}
<div class="update-apt-info">
<p>Update via your package manager:</p>
<code>sudo apt update && sudo apt upgrade helix-notes</code>
</div>
{:else if $installType === 'aur'}
<div class="update-apt-info">
<p>Update via your AUR helper:</p>
<code>yay -Syu helixnotes</code>
</div>
{:else}
<a class="update-install-btn" href="https://codeberg.org/ArkHost/HelixNotes/releases" target="_blank" rel="noopener">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>
</svg>
Download from Codeberg
</a>
{/if}
</div>
{/if}
@@ -1975,23 +1905,6 @@
cursor: not-allowed;
}
.update-apt-info {
margin-top: 8px;
}
.update-apt-info p {
margin: 0 0 6px 0;
font-size: 13px;
color: var(--text-secondary);
}
.update-apt-info code {
display: block;
padding: 8px 12px;
background: var(--bg-secondary);
border-radius: 6px;
font-size: 12px;
user-select: all;
}
.update-progress-bar {
margin-top: 10px;
height: 6px;
+23 -221
View File
@@ -17,7 +17,7 @@
quickAccessPaths,
collapsedNotebooks
} from '$lib/stores/app';
import { getNotebooks, getAllTags, createNotebook, deleteNotebook, renameNotebook, moveNotebook, getNotebookIcons, setNotebookIcon, saveAttachment, getQuickAccess, addQuickAccess, removeQuickAccess, emptyTrash, moveNote, readNote, getNotes } from '$lib/api';
import { getNotebooks, getAllTags, createNotebook, deleteNotebook, renameNotebook, getNotebookIcons, setNotebookIcon, saveAttachment, getQuickAccess, addQuickAccess, removeQuickAccess, emptyTrash, moveNote, readNote, getNotes } from '$lib/api';
import { open as openDialog } from '@tauri-apps/plugin-dialog';
import { readFile } from '@tauri-apps/plugin-fs';
import { convertFileSrc } from '@tauri-apps/api/core';
@@ -27,18 +27,13 @@
onViewChanged?: () => void;
} = $props();
const modKey = navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl';
let editingNotebook = $state<string | null>(null);
let editValue = $state('');
let newNotebookName = $state('');
let showNewNotebook = $state(false);
let dropTargetPath = $state<string | null>(null);
let draggedNotebookPath = $state<string | null>(null);
let contextMenu = $state<{ x: number; y: number; notebook: NotebookEntry } | null>(null);
let trashContextMenu = $state<{ x: number; y: number } | null>(null);
let tagsCollapsed = $state(true);
let deleteConfirm = $state<NotebookEntry | null>(null);
function toggleCollapse(path: string, e: MouseEvent) {
e.stopPropagation();
if ($collapsedNotebooks.includes(path)) {
@@ -121,22 +116,8 @@
}
}
function countNotesRecursive(nb: NotebookEntry): number {
return nb.note_count + nb.children.reduce((sum, c) => sum + countNotesRecursive(c), 0);
}
function handleDelete(nb: NotebookEntry) {
async function handleDelete(nb: NotebookEntry) {
contextMenu = null;
const total = countNotesRecursive(nb);
if (total > 0) {
deleteConfirm = nb;
} else {
confirmDelete(nb);
}
}
async function confirmDelete(nb: NotebookEntry) {
deleteConfirm = null;
try {
await deleteNotebook(nb.path);
if ($activeNotebook?.path === nb.path) {
@@ -169,43 +150,6 @@
}
}
async function handleNotebookDrop(e: DragEvent, destPath: string) {
e.preventDefault();
dropTargetPath = null;
const srcPath = e.dataTransfer?.getData('text/plain');
if (!srcPath) return;
draggedNotebookPath = null;
// Don't move onto self or descendant
if (destPath === srcPath || destPath.startsWith(srcPath + '/')) return;
// Don't move if already in that parent
const parentDir = srcPath.substring(0, srcPath.lastIndexOf('/'));
if (parentDir === destPath) return;
try {
const oldName = srcPath.split('/').pop() || '';
const newBasePath = destPath + '/' + oldName;
await moveNotebook(srcPath, destPath);
// Update collapsedNotebooks paths
$collapsedNotebooks = $collapsedNotebooks.map(p => {
if (p === srcPath) return newBasePath;
if (p.startsWith(srcPath + '/')) return newBasePath + p.slice(srcPath.length);
return p;
});
// Update active notebook/note if inside the moved notebook
if ($activeNotebook?.path === srcPath || $activeNotebook?.path.startsWith(srcPath + '/')) {
selectAllNotes();
}
if ($activeNotePath && $activeNotePath.startsWith(srcPath + '/')) {
const newNotePath = newBasePath + $activeNotePath.slice(srcPath.length);
$activeNotePath = newNotePath;
$activeNote = await readNote(newNotePath);
}
$notebookIcons = await getNotebookIcons();
await refresh();
} catch (e) {
console.error('Failed to move notebook:', e);
}
}
function startRename(nb: NotebookEntry) {
contextMenu = null;
editingNotebook = nb.path;
@@ -300,7 +244,7 @@
</svg>
</button>
{#if !$sidebarCollapsed}
<button class="icon-btn" onclick={() => ($showSearch = true)} title={`Search (${modKey}+F)`}>
<button class="icon-btn" onclick={() => ($showSearch = true)} title="Search (Ctrl+F)">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" />
<line x1="21" y1="21" x2="16.65" y2="16.65" />
@@ -348,25 +292,7 @@
</nav>
<div class="section">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="section-header"
class:drop-target={dropTargetPath === '__root__'}
ondragover={(e) => {
if (draggedNotebookPath) {
e.preventDefault();
e.dataTransfer!.dropEffect = 'move';
dropTargetPath = '__root__';
}
}}
ondragleave={() => { if (dropTargetPath === '__root__') dropTargetPath = null; }}
ondrop={(e) => {
if (draggedNotebookPath) {
const vaultRoot = $appConfig?.active_vault;
if (vaultRoot) handleNotebookDrop(e, vaultRoot);
}
}}
>
<div class="section-header">
<span class="section-title">Notebooks</span>
<button class="icon-btn-sm" onclick={() => (showNewNotebook = !showNewNotebook)} title="New notebook">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@@ -397,26 +323,23 @@
</div>
{#if $tags.length > 0}
<div class="tags-section">
<button class="section-header" onclick={() => tagsCollapsed = !tagsCollapsed}>
<div class="section">
<div class="section-header">
<span class="section-title">Tags</span>
<span class="tag-count" style="margin-left: auto">{$tags.length}</span>
</button>
{#if !tagsCollapsed}
<div class="tag-list">
{#each $tags as [tag, count]}
<button
class="tag-item"
class:active={$viewMode === 'tag' && $activeTag === tag}
onclick={() => selectTag(tag)}
>
<span class="tag-hash">#</span>
<span class="tag-name">{tag}</span>
<span class="tag-count">{count}</span>
</button>
{/each}
</div>
{/if}
</div>
<div class="tag-list">
{#each $tags as [tag, count]}
<button
class="tag-item"
class:active={$viewMode === 'tag' && $activeTag === tag}
onclick={() => selectTag(tag)}
>
<span class="tag-hash">#</span>
<span class="tag-name">{tag}</span>
<span class="tag-count">{count}</span>
</button>
{/each}
</div>
</div>
{/if}
@@ -477,21 +400,6 @@
</div>
{/if}
{#if deleteConfirm}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="delete-confirm-overlay" onclick={() => deleteConfirm = null}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="delete-confirm" onclick={(e) => e.stopPropagation()}>
<h4>Delete "{deleteConfirm.name}"?</h4>
<p>This notebook contains {countNotesRecursive(deleteConfirm)} note{countNotesRecursive(deleteConfirm) === 1 ? '' : 's'} that will be permanently deleted.</p>
<div class="delete-confirm-actions">
<button class="delete-confirm-cancel" onclick={() => deleteConfirm = null}>Cancel</button>
<button class="delete-confirm-btn" onclick={() => confirmDelete(deleteConfirm!)}>Delete</button>
</div>
</div>
</div>
{/if}
{#snippet notebookItem(nb: NotebookEntry, depth: number)}
{@const hasChildren = nb.children.length > 0}
{@const isCollapsed = $collapsedNotebooks.includes(nb.path)}
@@ -515,34 +423,11 @@
class:active={$viewMode === 'notebook' && $activeNotebook?.path === nb.path}
class:drop-target={dropTargetPath === nb.path}
style="padding-left: {8 + depth * 16}px"
draggable="true"
onclick={() => selectNotebook(nb)}
oncontextmenu={(e) => onContextMenu(e, nb)}
ondragstart={(e) => { draggedNotebookPath = nb.path; e.dataTransfer!.setData('text/plain', nb.path); e.dataTransfer!.effectAllowed = 'move'; }}
ondragend={() => { draggedNotebookPath = null; }}
ondragover={(e) => {
e.preventDefault();
if (draggedNotebookPath) {
// Prevent drop on self or descendant
if (nb.path === draggedNotebookPath || nb.path.startsWith(draggedNotebookPath + '/')) {
e.dataTransfer!.dropEffect = 'none';
return;
}
// Prevent no-op (already in this parent)
const parentDir = draggedNotebookPath.substring(0, draggedNotebookPath.lastIndexOf('/'));
if (parentDir === nb.path) { e.dataTransfer!.dropEffect = 'none'; return; }
}
e.dataTransfer!.dropEffect = 'move';
dropTargetPath = nb.path;
}}
ondragover={(e) => { e.preventDefault(); e.dataTransfer!.dropEffect = 'move'; dropTargetPath = nb.path; }}
ondragleave={() => { if (dropTargetPath === nb.path) dropTargetPath = null; }}
ondrop={(e) => {
if (draggedNotebookPath) {
handleNotebookDrop(e, nb.path);
} else {
handleNoteDrop(e, nb);
}
}}
ondrop={(e) => handleNoteDrop(e, nb)}
>
{#if hasChildren}
<!-- svelte-ignore a11y_no_static_element_interactions -->
@@ -634,26 +519,11 @@
padding: 4px 0;
}
.tags-section {
flex-shrink: 0;
border-top: 1px solid var(--border-light);
padding: 4px 0;
max-height: 30%;
overflow-y: auto;
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px 4px;
width: 100%;
background: none;
border: none;
cursor: pointer;
color: inherit;
font: inherit;
text-align: left;
}
.section-title {
@@ -740,8 +610,7 @@
color: var(--text-accent);
}
.notebook-item.drop-target,
.section-header.drop-target {
.notebook-item.drop-target {
background: color-mix(in srgb, var(--accent) 20%, transparent);
outline: 2px dashed var(--accent);
outline-offset: -2px;
@@ -890,71 +759,4 @@
.context-menu button.danger:hover {
background: color-mix(in srgb, var(--danger) 10%, transparent);
}
.delete-confirm-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.delete-confirm {
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 10px;
padding: 20px 24px;
max-width: 340px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25);
}
.delete-confirm h4 {
margin: 0 0 8px;
font-size: 14px;
color: var(--text-primary);
}
.delete-confirm p {
margin: 0 0 16px;
font-size: 12.5px;
color: var(--text-secondary);
line-height: 1.4;
}
.delete-confirm-actions {
display: flex;
gap: 8px;
justify-content: flex-end;
}
.delete-confirm-cancel {
padding: 6px 14px;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--bg-secondary);
color: var(--text-primary);
font-size: 12px;
cursor: pointer;
}
.delete-confirm-cancel:hover {
background: var(--bg-hover);
}
.delete-confirm-btn {
padding: 6px 14px;
border: none;
border-radius: 6px;
background: var(--danger, #e53e3e);
color: white;
font-size: 12px;
font-weight: 600;
cursor: pointer;
}
.delete-confirm-btn:hover {
opacity: 0.9;
}
</style>
+5 -73
View File
@@ -1,15 +1,12 @@
<script lang="ts">
import { getCurrentWindow } from '@tauri-apps/api/window';
import { vaultReady, focusMode, readOnly, updateAvailable, showSettings, settingsTab } from '$lib/stores/app';
import { vaultReady, focusMode } from '$lib/stores/app';
let { onNewNote = () => {}, onDailyNote = () => {} }: {
let { onNewNote = () => {} }: {
onNewNote?: () => void;
onDailyNote?: () => void;
} = $props();
const appWindow = getCurrentWindow();
const isMac = navigator.platform.startsWith('Mac');
const modKey = isMac ? '⌘' : 'Ctrl';
let maximized = $state(false);
async function checkMaximized() {
@@ -24,19 +21,11 @@
let lastMouseDown = 0;
const RESIZE_EDGE = 6;
function handleMouseDown(e: MouseEvent) {
if (e.button !== 0) return;
const target = e.target as HTMLElement;
if (target.closest('.titlebar-controls') || target.closest('.titlebar-actions')) return;
// Don't start dragging near window edges — let Tauri handle resize
if (!maximized) {
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
if (e.clientY - rect.top < RESIZE_EDGE || e.clientX - rect.left < RESIZE_EDGE) return;
}
const now = Date.now();
if (now - lastMouseDown < 300) {
// Double-click detected — maximize/restore
@@ -62,7 +51,7 @@
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="titlebar" class:macos={isMac} onmousedown={handleMouseDown}>
<div class="titlebar" onmousedown={handleMouseDown}>
<div class="titlebar-brand">
<svg width="18" height="18" viewBox="0 0 48 48" fill="none">
<rect width="48" height="48" rx="12" fill="var(--accent)" />
@@ -74,12 +63,6 @@
<line x1="29" y1="18" x2="19" y2="30" stroke="white" stroke-width="2" stroke-linecap="round" opacity="0.7" />
</svg>
<span class="titlebar-title">HelixNotes</span>
{#if $updateAvailable}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<button class="update-badge" onmousedown={(e) => e.stopPropagation()} onclick={() => { $settingsTab = 'updates'; $showSettings = true; }}>
v{$updateAvailable.version} available
</button>
{/if}
</div>
<div class="titlebar-actions">
<button class="switch-vault-btn" onclick={() => ($vaultReady = false)} title="Switch Vault">
@@ -92,34 +75,13 @@
<path d="M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3"/>
</svg>
</button>
<button class="switch-vault-btn" class:active={$readOnly} onclick={() => ($readOnly = !$readOnly)} title={$readOnly ? 'Switch to Edit Mode' : 'Switch to View Mode'}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
{#if $readOnly}
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
{:else}
<path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94" />
<path d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19" />
<line x1="1" y1="1" x2="23" y2="23" />
{/if}
</svg>
</button>
<button class="switch-vault-btn" onclick={onDailyNote} title="Daily Note">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
<line x1="16" y1="2" x2="16" y2="6" />
<line x1="8" y1="2" x2="8" y2="6" />
<line x1="3" y1="10" x2="21" y2="10" />
</svg>
</button>
<button class="new-note-btn" onclick={onNewNote} title={`New Note (${modKey}+N)`}>
<button class="new-note-btn" onclick={onNewNote} title="New Note (Ctrl+N)">
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
<path d="M7 1v12M1 7h12" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" />
</svg>
New Note
</button>
</div>
{#if !isMac}
<div class="titlebar-controls">
<button class="titlebar-btn" onclick={minimize} title="Minimize">
<svg width="10" height="10" viewBox="0 0 10 10">
@@ -145,7 +107,6 @@
</svg>
</button>
</div>
{/if}
</div>
<style>
@@ -175,25 +136,6 @@
color: var(--text-tertiary);
}
.update-badge {
font-size: 10px;
font-weight: 600;
color: var(--accent);
background: color-mix(in srgb, var(--accent) 12%, transparent);
border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent);
border-radius: 10px;
padding: 1px 8px;
cursor: pointer;
pointer-events: auto;
-webkit-app-region: no-drag;
transition: background 0.15s, border-color 0.15s;
}
.update-badge:hover {
background: color-mix(in srgb, var(--accent) 20%, transparent);
border-color: color-mix(in srgb, var(--accent) 40%, transparent);
}
.titlebar-actions {
display: flex;
align-items: center;
@@ -221,11 +163,6 @@
color: var(--text-primary);
}
.switch-vault-btn.active {
background: color-mix(in srgb, var(--accent) 18%, transparent);
color: var(--accent);
}
.new-note-btn {
display: flex;
align-items: center;
@@ -233,7 +170,7 @@
padding: 4px 12px 4px 10px;
border: none;
border-radius: 7px;
background: color-mix(in srgb, var(--accent) 85%, black);
background: var(--accent);
color: white;
font-size: 11.5px;
font-weight: 600;
@@ -282,9 +219,4 @@
background: #e81123;
color: white;
}
/* macOS: add left padding for native traffic light buttons */
.titlebar.macos .titlebar-brand {
padding-left: 78px;
}
</style>
+1 -1
View File
@@ -57,7 +57,7 @@
</svg>
</div>
<h1>HelixNotes</h1>
<p class="subtitle">Local markdown notes</p>
<p class="subtitle">Local-first markdown notes</p>
<p class="description">Your notes are stored as standard Markdown (.md) files. Pick any folder — existing .md files will be recognized automatically.</p>
{#if error}
+22 -51
View File
@@ -23,7 +23,6 @@ export const searchQuery = writable("");
export const showCommandPalette = writable(false);
export const showSearch = writable(false);
export const showSettings = writable(false);
export const settingsTab = writable<string | null>(null);
export const showInfo = writable(false);
export const notebookIcons = writable<Record<string, string>>({});
export const quickAccessPaths = writable<string[]>([]);
@@ -42,63 +41,35 @@ export const activeTag = writable<string | null>(null);
export const editorDirty = writable(false);
export const sourceMode = writable(false);
export const focusMode = writable(false);
export const readOnly = writable(false);
// Theme
export const theme = writable<string>("system");
// Update state
export const updateAvailable = writable<{
version: string;
body?: string;
} | null>(null);
export const updateObj = writable<any>(null);
export const installType = writable<string>("native");
export async function checkForUpdate() {
try {
const { check } = await import("@tauri-apps/plugin-updater");
const update = await check();
if (update) {
updateAvailable.set({ version: update.version, body: update.body });
updateObj.set(update);
}
} catch {
// Silent fail — don't disrupt app startup
}
}
// Derived
export const sortedNotes = derived(
[notes, sortMode, viewMode],
([$notes, $sortMode, $viewMode]) => {
// Quick Access preserves stored order
if ($viewMode === "quickaccess") return $notes;
export const sortedNotes = derived([notes, sortMode], ([$notes, $sortMode]) => {
const pinned = $notes.filter((n) => n.meta.pinned);
const unpinned = $notes.filter((n) => !n.meta.pinned);
const pinned = $notes.filter((n) => n.meta.pinned);
const unpinned = $notes.filter((n) => !n.meta.pinned);
const sortFn = (a: NoteEntry, b: NoteEntry) => {
switch ($sortMode) {
case "title":
return a.meta.title.localeCompare(b.meta.title);
case "created":
return (
new Date(b.meta.created).getTime() -
new Date(a.meta.created).getTime()
);
case "modified":
default:
return (
new Date(b.meta.modified).getTime() -
new Date(a.meta.modified).getTime()
);
}
};
const sortFn = (a: NoteEntry, b: NoteEntry) => {
switch ($sortMode) {
case "title":
return a.meta.title.localeCompare(b.meta.title);
case "created":
return (
new Date(b.meta.created).getTime() -
new Date(a.meta.created).getTime()
);
case "modified":
default:
return (
new Date(b.meta.modified).getTime() -
new Date(a.meta.modified).getTime()
);
}
};
return [...pinned.sort(sortFn), ...unpinned.sort(sortFn)];
},
);
return [...pinned.sort(sortFn), ...unpinned.sort(sortFn)];
});
export const vaultState = derived(
[
+2 -8
View File
@@ -1,9 +1,9 @@
<script lang="ts">
import { onMount } from 'svelte';
import '../app.css';
import { theme, appConfig, activeNotePath, installType, checkForUpdate } from '$lib/stores/app';
import { theme, appConfig, activeNotePath } from '$lib/stores/app';
import { openUrl } from '@tauri-apps/plugin-opener';
import { openFile, getInstallType } from '$lib/api';
import { openFile } from '$lib/api';
import { get } from 'svelte/store';
let { children } = $props();
@@ -31,12 +31,6 @@
return resolved.join('/');
}
// Detect install type and check for updates on startup
onMount(() => {
getInstallType().then(t => installType.set(t)).catch(() => {});
checkForUpdate();
});
// Intercept all link clicks in capture phase to prevent webview navigation
onMount(() => {
function handleLinkClick(e: MouseEvent) {