Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
4de427c
feat(filetree): move file tree generation logic to Rust backend
google-labs-jules[bot] Dec 10, 2025
9e0502e
perf: optimize file tree building and sorting in Rust
google-labs-jules[bot] Dec 10, 2025
bc12921
feat(filetree): move generation and sorting to Rust backend
google-labs-jules[bot] Dec 10, 2025
f86735f
fix: don't use rust sort function for subsequent sorts bcuz of latenc…
Keshav-writes-code Dec 10, 2025
cca74c8
refac: remove unwanted legacy functions
Keshav-writes-code Dec 10, 2025
f6f0a33
fix(error): show a toast error if file tree building fails
Keshav-writes-code Dec 10, 2025
c5b6a5c
Update apps/app/src-tauri/src/lib.rs
Keshav-writes-code Dec 10, 2025
ebce40c
Update apps/app/src-tauri/src/lib.rs
Keshav-writes-code Dec 10, 2025
91ebfeb
Update apps/app/src-tauri/src/lib.rs
Keshav-writes-code Dec 10, 2025
1a18293
fix: use inline type modifier for FileNode import for consistency
Copilot Dec 10, 2025
1238767
feat: implement natural/numeric sorting using natord crate
Copilot Dec 10, 2025
6120081
fix: add aria label to icon based buttons
Keshav-writes-code Dec 12, 2025
5a7c7fc
fix(performace): make subtree sorting happen only on rename operation…
Keshav-writes-code Dec 18, 2025
cfe2efc
fix: add sorting when new element gets inserted
Keshav-writes-code Dec 18, 2025
6d8ebd7
refac: remove debugging statementsa
Keshav-writes-code Dec 18, 2025
93e6a5a
refac: remove unwanted vairables
Keshav-writes-code Dec 18, 2025
b11e3c8
chore: update deps
Keshav-writes-code Dec 18, 2025
dbb3fcf
chore: update deps
Keshav-writes-code Dec 19, 2025
342a9df
fix(ui_webkit): fix strange behaviour where a previously selected ite…
Keshav-writes-code Dec 19, 2025
02f93b5
perf(filetree): optimize Android file tree building in Rust
google-labs-jules[bot] Dec 19, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/app/src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions apps/app/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ tauri-plugin-fs = "2"
tauri-plugin-store = "2"
tauri-plugin-dialog = "2"
tauri-plugin-os = "2"
urlencoding = "2"
153 changes: 153 additions & 0 deletions apps/app/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,155 @@
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone)]
pub struct FileNode {
pub name: String,
pub path: String,
pub is_directory: bool,
pub children: Vec<FileNode>,
}

fn sort_nodes(nodes: &mut Vec<FileNode>) {
nodes.sort_by(|a, b| {
if a.is_directory != b.is_directory {
return if a.is_directory {
std::cmp::Ordering::Less
} else {
std::cmp::Ordering::Greater
};
}
a.name.to_lowercase().cmp(&b.name.to_lowercase())
Comment thread
Keshav-writes-code marked this conversation as resolved.
});

for node in nodes {
if !node.children.is_empty() {
sort_nodes(&mut node.children);
}
}
}

#[cfg(not(target_os = "android"))]
fn build_tree_recursive_desktop(path_str: &str) -> std::io::Result<Vec<FileNode>> {
use std::fs;
let mut nodes = Vec::new();
let entries = fs::read_dir(path_str)?;

for entry in entries {
if let Ok(entry) = entry {
if let Ok(metadata) = entry.metadata() {
let file_name = entry.file_name().to_string_lossy().to_string();

let is_directory = metadata.is_dir();
let starts_with_dot = file_name.starts_with('.');
let ends_with_md = file_name.ends_with(".md");

if (is_directory && !starts_with_dot) || ends_with_md {
let path = entry.path().to_string_lossy().to_string();
let mut children = Vec::new();

if is_directory {
if let Ok(sub_children) = build_tree_recursive_desktop(&path) {
children = sub_children;
Comment thread
Keshav-writes-code marked this conversation as resolved.
}
}

nodes.push(FileNode {
name: file_name.trim_end_matches(".md").to_string(),
path,
is_directory,
children,
});
}
}
}
Comment thread
Keshav-writes-code marked this conversation as resolved.
}
Ok(nodes)
}

#[cfg(target_os = "android")]
fn build_tree_recursive_android(
app: tauri::AppHandle,
path: String,
document_top_tree_uri: Option<String>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<FileNode>, String>> + Send>> {
Box::pin(async move {
use tauri_plugin_android_fs::AndroidFsExt;
use tauri_plugin_android_fs::FileUri;

let api = app.android_fs();

let json_obj = serde_json::json!({
"uri": path,
"documentTopTreeUri": document_top_tree_uri
});
let file_uri = FileUri::from_json_str(&json_obj.to_string())
.map_err(|e| format!("Failed to create FileUri: {}", e))?;

let entries = api.read_dir(&file_uri)
.map_err(|e| e.to_string())?;

let mut nodes = Vec::new();
for entry in entries {
let name = entry.name().to_string();
let is_directory = entry.is_dir();

let starts_with_dot = name.starts_with('.');
let ends_with_md = name.ends_with(".md");

if (is_directory && !starts_with_dot) || ends_with_md {
let path_uri = format!("{}%2F{}", path, urlencoding::encode(&name));

let mut children = Vec::new();
if is_directory {
children = build_tree_recursive_android(
Comment thread
Keshav-writes-code marked this conversation as resolved.
Outdated
app.clone(),
path_uri.clone(),
document_top_tree_uri.clone()
).await?;
}

nodes.push(FileNode {
name: name.trim_end_matches(".md").to_string(),
path: path_uri,
is_directory,
children,
});
}
}
Ok(nodes)
})
}

#[tauri::command]
async fn build_file_tree(
_app: tauri::AppHandle,
path: String,
_document_top_tree_uri: Option<String>,
) -> Result<Vec<FileNode>, String> {
let nodes;

#[cfg(target_os = "android")]
{
// On Android, we need the app handle and args.
// But we renamed arguments to start with _.
// We can use them directly.
let mut unsorted_nodes = build_tree_recursive_android(_app, path, _document_top_tree_uri).await?;
Comment thread
Keshav-writes-code marked this conversation as resolved.
Outdated
Comment thread
Keshav-writes-code marked this conversation as resolved.
Outdated
sort_nodes(&mut unsorted_nodes);
nodes = unsorted_nodes;
}

#[cfg(not(target_os = "android"))]
{
nodes = tauri::async_runtime::spawn_blocking(move || {
let mut n = build_tree_recursive_desktop(&path)?;
sort_nodes(&mut n);
Ok(n)
}).await.map_err(|e| e.to_string())?
.map_err(|e: std::io::Error| e.to_string())?;
}

Ok(nodes)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
Expand All @@ -6,6 +158,7 @@ pub fn run() {
.plugin(tauri_plugin_store::Builder::new().build())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_android_fs::init())
.invoke_handler(tauri::generate_handler![build_file_tree])
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
Expand Down
7 changes: 5 additions & 2 deletions apps/app/src/components/sidebar/file_manager/index.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
import {
build_file_tree_from_fs,
move_node,
sort_file_tree,
sort_nodes,
} from '@/lib/file_tree';
import ItemsRender from './items_renderer.svelte';
import { type FileNode, type GenericPath } from '@/types';
import Toolbar from './toolbar.svelte';
import { toast } from 'svelte-sonner';
import { untrack } from 'svelte';
let {
opened_filenode = $bindable(),
root_path = $bindable(),
Expand All @@ -22,8 +23,10 @@
let focused_subtree: FileNode[] | undefined = $derived(file_tree);

$effect(() => {
if (file_tree) sort_file_tree(file_tree);
const subtree = untrack(() => focused_subtree);
if (file_tree && subtree) sort_nodes(subtree);
});
Comment thread
Keshav-writes-code marked this conversation as resolved.

let collapsed_state: boolean = $state(true);
$effect(() => {
if (!root_path) return;
Expand Down
92 changes: 16 additions & 76 deletions apps/app/src/lib/file_tree/builder.ts
Original file line number Diff line number Diff line change
@@ -1,85 +1,25 @@
import { readDir, type DirEntry } from '@tauri-apps/plugin-fs';
import { type FileNode, type GenericPath } from '@/types';
import {
AndroidFs,
type AndroidEntryMetadataWithUri,
} from 'tauri-plugin-android-fs-api';
import { join } from '@tauri-apps/api/path';
import { current_platform } from './utils';
import { invoke } from '@tauri-apps/api/core';
import { toast } from 'svelte-sonner';

export async function build_file_tree_from_fs({
path,
document_top_tree_uri,
}: GenericPath): Promise<FileNode[]> {
let entries: DirEntry[] | AndroidEntryMetadataWithUri[] | undefined;
let base_nodes: FileNode[] | undefined;

if (current_platform == 'android') {
if (!document_top_tree_uri)
throw new Error('Document top tree URI is not set');
entries = await AndroidFs.readDir({
uri: path,
documentTopTreeUri: document_top_tree_uri,
try {
return await invoke('build_file_tree', {
path,
documentTopTreeUri: document_top_tree_uri || null,
});
base_nodes = await transform_android_entries_to_filenode(entries, path);
} else {
entries = await readDir(path);
base_nodes = await transform_entries_to_filenode(entries, path);
} catch (error) {
console.error('Failed to build file tree:', error);
const description =
error instanceof Error
? error.message
: typeof error === 'string'
? error
: JSON.stringify(error);
toast.error('Failed to build file tree', { description });
throw error;
}

const nodes = await Promise.all(
base_nodes.map(async (n) => {
if (!n.is_directory) return n;
const children = await build_file_tree_from_fs({
path: n.path,
document_top_tree_uri,
});
return {
...n,
children,
};
})
);

return nodes;
}
export async function transform_entries_to_filenode(
entries: DirEntry[],
base_dir_path: string
): Promise<FileNode[]> {
const nodes = await Promise.all(
entries
.filter(
(entry) =>
(entry.isDirectory && !entry.name.startsWith('.')) ||
entry.name.endsWith('.md')
)
.map(async (entry) => ({
name: entry.name.replace(/\.md$/, ''),
path: await join(base_dir_path, entry.name),
is_directory: entry.isDirectory,
children: [],
}))
);
return nodes;
}
export async function transform_android_entries_to_filenode(
entries: AndroidEntryMetadataWithUri[],
base_dir_path: string
): Promise<FileNode[]> {
const nodes = await Promise.all(
entries
.filter(
(entry) =>
(entry.type === 'Dir' && !entry.name.startsWith('.')) ||
entry.name.endsWith('.md')
)
.map(async (entry) => ({
name: entry.name.replace(/\.md$/, ''),
path: `${base_dir_path}%2F${encodeURIComponent(entry.name)}`,
is_directory: entry.type === 'Dir',
children: [],
}))
);
return nodes;
}
15 changes: 4 additions & 11 deletions apps/app/src/lib/file_tree/utils/file_tree_utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { type FileNode } from '@/types';
import type { FileNode } from '@/types';
Comment thread
Keshav-writes-code marked this conversation as resolved.
Outdated

export function find_unused_name(
base_name: string,
subtree: FileNode[],
Expand All @@ -11,7 +12,8 @@ export function find_unused_name(
base_name = `Untitled ${++i}`;
return base_name;
}
export function sort_file_tree(nodes: FileNode[]): FileNode[] {

export function sort_nodes(nodes: FileNode[]) {
// Sort array in-place
nodes.sort((a, b) => {
if (a.is_directory !== b.is_directory) return a.is_directory ? -1 : 1;
Expand All @@ -20,13 +22,4 @@ export function sort_file_tree(nodes: FileNode[]): FileNode[] {
sensitivity: 'base',
});
});
Comment thread
Keshav-writes-code marked this conversation as resolved.

// Recursively sort children in-place
for (const node of nodes) {
if (node.children?.length) {
sort_file_tree(node.children);
}
}

return nodes;
}