feature: added ability to open folder and load directory in file tree
mellbacon committed
May 21, 2023 at 14:07 UTC
dad4e93bc1bf764bcdc19cffbaabaf4e12fc1203
1 file changed
+51
-1
src/lib/File.ts
+51
-1
@@ -1,6 +1,7 @@
1
import { dialog, fs, path } from "@tauri-apps/api";
2
-import { get } from 'svelte/store';
2
+import { get, writable } from 'svelte/store';
3
import { tabs, addEditorTab } from "./EditorTabList.svelte";
4
+import { filetree } from "./FileTree.svelte";
5
6
export async function openFile() {
7
let newPath = await dialog.open() as string;
@@ -9,6 +10,55 @@ export async function openFile() {
10
addEditorTab(newPath, filename);
11
}
12
13
+export const workspaceName = writable("Untitled Workspace");
14
+export async function openFolder() {
15
+ let directory = await dialog.open({directory: true}) as string;
16
+ if (!directory) return;
17
+
18
+ let tree = await fs.readDir(directory, {recursive: true});
19
+ if (!tree) {
20
+ console.error("Cannot load directory");
21
+ return;
22
+ }
23
+ let directoryName = directory.split(path.sep).pop();
24
+ tree = [{name: directoryName, path: directory, children: buildTree(sortTree(tree))}];
25
+ filetree.set(tree);
26
+ workspaceName.set(directoryName);
27
+ id = 0;
28
+}
29
+
30
+// Need to add ids to each node for svelte to iterate over them properly
31
+let id = 0;
32
+function buildTree(tree: fs.FileEntry[]) {
33
+ const nodes = [];
34
+ for (const node of tree) {
35
+ const entry = {id: id, name: node.name, path: node.path, children: node.children};
36
+ id++;
37
+ if (node.children) {
38
+ entry.children = buildTree(sortTree(node.children));
39
+ }
40
+ nodes.push(entry);
41
+ }
42
+ return nodes;
43
+}
44
+function sortTree(tree: fs.FileEntry[]) {
45
+ const sortedTree = [];
46
+ let files = [];
47
+ for (const node of tree) {
48
+ if (node.children) {
49
+ sortedTree.push(node)
50
+ sortTree(node.children);
51
+ }
52
+ else {
53
+ files.push(node);
54
+ }
55
+ }
56
+ files.sort();
57
+ sortedTree.sort();
58
+ sortedTree.push(...files);
59
+ return sortedTree;
60
+}
61
+
62
export async function saveFile(saveAs = false) {
63
const tab = get(tabs).find(t => t.active && t.isfile);
64
if (!tab.path.includes(path.sep) || tab.path === "" || saveAs) {