forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathopenFolder.js
More file actions
1123 lines (985 loc) · 29 KB
/
openFolder.js
File metadata and controls
1123 lines (985 loc) · 29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fsOperation from "fileSystem";
import sidebarApps from "sidebarApps";
import collapsableList from "components/collapsableList";
import FileTree from "components/fileTree";
import Sidebar from "components/sidebar";
import { TerminalManager } from "components/terminal";
import tile from "components/tile";
import toast from "components/toast";
import alert from "dialogs/alert";
import confirm from "dialogs/confirm";
import prompt from "dialogs/prompt";
import select from "dialogs/select";
import escapeStringRegexp from "escape-string-regexp";
import FileBrowser from "pages/fileBrowser";
import helpers from "utils/helpers";
import Path from "utils/Path";
import Uri from "utils/Uri";
import Url from "utils/Url";
import constants from "./constants";
import * as FileList from "./fileList";
import openFile from "./openFile";
import recents from "./recents";
import appSettings from "./settings";
const isTermuxSafUri = (value = "") =>
value.startsWith("content://com.termux.documents/tree/");
const isAcodeTerminalPublicSafUri = (value = "") =>
value.startsWith("content://com.foxdebug.acode.documents/tree/");
const isTerminalSafUri = (value = "") =>
isTermuxSafUri(value) || isAcodeTerminalPublicSafUri(value);
const getTerminalPaths = () => {
const packageName = window.BuildInfo?.packageName || "com.foxdebug.acode";
const dataDir = `/data/user/0/${packageName}`;
const alpineRoot = `${dataDir}/files/alpine`;
const publicDir = `${dataDir}/files/public`;
return { alpineRoot, publicDir, dataDir };
};
const isTerminalAccessiblePath = (url = "") => {
if (isAcodeTerminalPublicSafUri(url)) return true;
const { alpineRoot, publicDir } = getTerminalPaths();
const cleanUrl = url.replace(/^file:\/\//, "");
if (cleanUrl.startsWith(alpineRoot) || cleanUrl.startsWith(publicDir)) {
return true;
}
return false;
};
const convertToProotPath = (url = "") => {
const { alpineRoot, publicDir } = getTerminalPaths();
if (isAcodeTerminalPublicSafUri(url)) {
try {
const { docId } = Uri.parse(url);
const cleanDocId = decodeURIComponent(docId || "");
if (!cleanDocId) return "/public";
if (cleanDocId.startsWith(publicDir)) {
return cleanDocId.replace(publicDir, "/public") || "/public";
}
if (cleanDocId.startsWith("/public")) {
return cleanDocId;
}
if (cleanDocId.startsWith("public:")) {
const relativePath = cleanDocId.slice("public:".length);
return relativePath ? Path.join("/public", relativePath) : "/public";
}
const relativePath = cleanDocId.replace(/^\/+/, "");
return relativePath ? Path.join("/public", relativePath) : "/public";
} catch (error) {
console.warn(
`Failed to parse public SAF URI for terminal conversion: ${url}`,
);
return "/public";
}
}
const cleanUrl = url.replace(/^file:\/\//, "");
if (cleanUrl.startsWith(publicDir)) {
return cleanUrl.replace(publicDir, "/public");
}
if (cleanUrl.startsWith(alpineRoot)) {
return cleanUrl.replace(alpineRoot, "") || "/";
}
console.warn(`Unrecognized path for terminal conversion: ${url}`);
return cleanUrl;
};
/**
* @typedef {import('../components/collapsableList').Collapsible} Collapsible
*/
/**
* @typedef {object} ClipBoard
* @property {string} url
* @property {HTMLElement} $el
* @property {"cut"|"copy"} action
*/
/**
* @typedef {object} Folder
* @property {string} id
* @property {string} url
* @property {string} title
* @property {boolean} listFiles Weather to list all files recursively
* @property {boolean} saveState
* @property {Collapsible} $node
* @property {ClipBoard} clipBoard
* @property {function(): void} remove
* @property {function(): void} reload
* @property {Map<string, boolean>} listState
*/
/**@type {Folder[]} */
export const addedFolder = [];
const ACODE_PLUGIN_MANIFEST_FILE = "plugin.json";
/**
* Open a folder in the sidebar
* @param {string} _path
* @param {object} opts
* @param {string} opts.name
* @param {string} [opts.id]
* @param {boolean} [opts.saveState]
* @param {boolean} [opts.listFiles]
* @param {Map<string, boolean>} [opts.listState]
*/
function openFolder(_path, opts = {}) {
if (addedFolder.find((folder) => folder.url === _path)) {
return;
}
const saveState = opts.saveState ?? true;
const listState = opts.listState || {};
const title = opts.name;
let listFiles = opts.listFiles;
if (!title) {
throw new Error("Folder name is required");
}
const $root = collapsableList(title, "folder", {
allCaps: true,
ontoggle: () => expandList($root),
});
const $text = $root.$title.get(":scope>span.text");
$root.id = "r" + _path.hashCode();
$text.style.overflow = "hidden";
$text.style.whiteSpace = "nowrap";
$text.style.textOverflow = "ellipsis";
$root.$title.dataset.type = "root";
$root.$title.dataset.url = _path;
$root.$title.dataset.name = title;
$root.$ul.onclick =
$root.$ul.oncontextmenu =
$root.$title.onclick =
$root.$title.oncontextmenu =
handleItems;
recents.addFolder(_path, opts);
sidebarApps.get("files").append($root);
const event = {
url: _path,
name: title,
};
const folder = {
title,
remove,
listFiles,
saveState,
listState,
url: _path,
$node: $root,
id: opts.id,
clipBoard: {},
reload() {
$root.collapse();
$root.expand();
},
};
editorManager.emit("update", "add-folder");
editorManager.onupdate("add-folder", event);
editorManager.emit("add-folder", event);
(async () => {
if (typeof listFiles !== "boolean") {
const protocol = Url.getProtocol(_path).slice(0, -1);
const type = /^(content|file)$/.test(protocol) ? "" : ` (${protocol})`;
const message = strings["list files"].replace(
"{name}",
`${title}${type}`,
);
listFiles = await confirm(strings.confirm, message, true);
}
if (listFiles) {
FileList.addRoot({ url: _path, name: title });
}
folder.listFiles = listFiles;
addedFolder.push(folder);
})();
if (listState[_path]) {
$root.expand();
}
function remove(e) {
if (e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
}
if ($root.parentElement) {
$root.remove();
}
const index = addedFolder.findIndex((folder) => folder.url === _path);
if (index !== -1) addedFolder.splice(index, 1);
editorManager.emit("update", "remove-folder");
editorManager.onupdate("remove-folder", event);
editorManager.emit("remove-folder", event);
}
}
/**
* Expand the list
* @param {Collapsible} $list
*/
async function expandList($list) {
const { $ul, $title } = $list;
const { url } = $title.dataset;
const { saveState, listState, $node } = openFolder.find(url);
const startLoading = () => $node.$title.classList.add("loading");
const stopLoading = () => $node.$title.classList.remove("loading");
if (!$ul) return;
// Cleanup existing file tree
if ($ul._fileTree) {
$ul._fileTree.destroy();
$ul._fileTree = null;
}
$ul.innerHTML = "";
if (saveState) listState[url] = $list.unclasped;
if (!$list.unclasped) return;
try {
startLoading();
const fileTree = new FileTree($ul, {
getEntries: (dirUrl) => fsOperation(dirUrl).lsDir(),
expandedState: listState,
onExpandedChange: (folderUrl, isExpanded) => {
if (saveState) listState[folderUrl] = isExpanded;
},
onFileClick: (fileUrl) => {
handleClick("file", fileUrl);
},
onContextMenu: (type, itemUrl, name, $target) => {
handleContextmenu(type, itemUrl, name, $target);
},
});
await fileTree.load(url);
$ul._fileTree = fileTree;
} catch (err) {
$list.collapse();
if (err?.includes?.("Invalid message length")) {
console.error(err);
toast("SFTP connection broken. Restart the app");
return;
}
helpers.error(err);
} finally {
stopLoading();
}
}
/**
* Gets weather the folder is collapsed or not
* @param {HTMLElement} $el
* @param {boolean} isFile
* @returns
*/
function collapsed($el, isFile) {
if (!$el.isConnected) return true;
$el = $el.parentElement;
if (!isFile) {
$el = $el.parentElement;
}
return $el.previousElementSibling.collapsed;
}
/**
* Handle click event
* @param {Event} e
*/
function handleItems(e) {
const mode = e.type;
const $target = e.target;
if (!($target instanceof HTMLElement)) return;
const type = $target.dataset.type;
if (!type) return;
const url = $target.dataset.url;
const name = $target.dataset.name;
if (mode === "click") {
handleClick(type, url, name, $target);
} else if (mode === "contextmenu") {
handleContextmenu(type, url, name, $target);
}
}
/**
* Handle contextmenu
* @param {"file"|"dir"|"root"} type
* @param {string} url
* @param {string} name
* @param {HTMLElement} $target
*/
async function handleContextmenu(type, url, name, $target) {
if (appSettings.value.vibrateOnTap) {
navigator.vibrate(constants.VIBRATION_TIME);
}
const { clipBoard, $node } = openFolder.find(url);
const cancel = `${strings.cancel}${clipBoard ? ` (${strings[clipBoard.action]})` : ""}`;
const COPY = ["copy", strings.copy, "copy"];
const CUT = ["cut", strings.cut, "cut"];
const COPY_RELATIVE_PATH = [
"copy-relative-path",
strings["copy relative path"],
"attach_file",
];
const REMOVE = ["delete", strings.delete, "delete"];
const RENAME = ["rename", strings.rename, "edit"];
const PASTE = ["paste", strings.paste, "paste", !!clipBoard];
const NEW_FILE = ["new file", strings["new file"], "document-add"];
const NEW_FOLDER = ["new folder", strings["new folder"], "folder-add"];
const CANCEL = ["cancel", cancel, "clearclose"];
const OPEN_FOLDER = ["open-folder", strings["open folder"], "folder"];
const INSERT_FILE = ["insert-file", strings["insert file"], "file_copy"];
const CLOSE_FOLDER = ["close", strings["close"], "folder-remove"];
const INSTALL_PLUGIN = [
"install-plugin",
strings["install as plugin"] || "Install as Plugin",
"extension",
];
let options;
if (helpers.isFile(type)) {
options = [COPY, CUT, COPY_RELATIVE_PATH, RENAME, REMOVE];
if (
url.toLowerCase().endsWith(".zip") &&
(await fsOperation(
Url.dirname(url) + ACODE_PLUGIN_MANIFEST_FILE,
).exists())
) {
options.push(INSTALL_PLUGIN);
}
} else if (helpers.isDir(type)) {
options = [COPY, CUT, COPY_RELATIVE_PATH, REMOVE, RENAME];
if (clipBoard.url != null) {
options.push(PASTE);
}
options.push(NEW_FILE, NEW_FOLDER, OPEN_FOLDER, INSERT_FILE);
if (isTerminalAccessiblePath(url)) {
const OPEN_IN_TERMINAL = [
"open-in-terminal",
strings["open in terminal"] || "Open in Terminal",
"terminal",
];
options.push(OPEN_IN_TERMINAL);
}
} else if (type === "root") {
options = [];
if (clipBoard.url != null) {
options.push(PASTE);
}
options.push(NEW_FILE, NEW_FOLDER, INSERT_FILE);
if (isTerminalAccessiblePath(url)) {
const OPEN_IN_TERMINAL = [
"open-in-terminal",
strings["open in terminal"] || "Open in Terminal",
"terminal",
];
options.push(OPEN_IN_TERMINAL);
}
options.push(CLOSE_FOLDER);
}
if (clipBoard.action) options.push(CANCEL);
try {
const option = await select(name, options);
await execOperation(type, option, url, $target, name);
} catch (error) {
console.error(error);
helpers.error(error);
} finally {
$node.$title.classList.remove("loading");
}
}
/**
* @param {"dir"|"file"|"root"} type
* @param {"copy"|"cut"|"delete"|"rename"|"paste"|"new file"|"new folder"|"cancel"|"open-folder"|"install-plugin"} action
* @param {string} url target url
* @param {HTMLElement} $target target element
* @param {string} name Name of file or folder
*/
function execOperation(type, action, url, $target, name) {
const { clipBoard, $node, remove, url: rootUrl } = openFolder.find(url);
const startLoading = () => $node.$title.classList.add("loading");
const stopLoading = () => $node.$title.classList.remove("loading");
switch (action) {
case "copy":
case "cut":
return clipBoardAction();
case "delete":
return deleteFile();
case "rename":
return renameFile();
case "paste":
return paste();
case "new file":
case "new folder":
return createNew();
case "cancel":
return cancelAction();
case "open-folder":
return open();
case "insert-file":
return insertFile();
case "close":
return remove();
case "install-plugin":
return installPlugin();
case "open-in-terminal":
return openInTerminal();
case "copy-relative-path":
return copyRelativePath();
}
async function installPlugin() {
try {
const manifest = JSON.parse(
await fsOperation(
Url.dirname(url) + ACODE_PLUGIN_MANIFEST_FILE,
).readFile("utf8"),
);
const { default: installPlugin } = await import("lib/installPlugin");
await installPlugin(url, manifest.name);
toast(strings["success"], 3000);
} catch (error) {
helpers.error(error);
console.error(error);
}
}
async function copyRelativePath() {
try {
// Validate inputs
if (!url) {
console.error("File path not available");
return;
}
if (!rootUrl) {
console.error("Root folder not found");
return;
}
let relativePath;
// Try using Url.pathname for protocol-based URLs
const rootPath = Url.pathname(rootUrl);
const targetPath = Url.pathname(url);
if (rootPath && targetPath) {
// Both pathnames extracted successfully
relativePath = Path.convertToRelative(rootPath, targetPath);
} else {
// Fallback: Use simple string comparison for URIs where pathname extraction fails
const cleanRoot = rootUrl.endsWith("/")
? rootUrl.slice(0, -1)
: rootUrl;
const cleanTarget = url.endsWith("/") ? url.slice(0, -1) : url;
// Check if target URL starts with root URL
if (cleanTarget.startsWith(cleanRoot)) {
relativePath = cleanTarget.slice(cleanRoot.length + 1);
} else {
// If not a child path, just use basename
relativePath = Url.basename(url);
}
}
if (!relativePath) {
console.error("Unable to calculate relative path");
return;
}
if (cordova.plugins.clipboard) {
cordova.plugins.clipboard.copy(relativePath);
toast(strings.success || "Relative path copied to clipboard");
} else {
console.error("Clipboard not available");
toast("Clipboard not available");
}
} catch (error) {
console.error("Failed to copy relative path:", error);
}
}
async function openInTerminal() {
try {
const prootPath = convertToProotPath(url);
const terminal = await TerminalManager.createTerminal({
name: `Terminal - ${name}`,
render: true,
});
if (terminal?.component) {
const waitForConnection = (timeoutMs = 5000) =>
new Promise((resolve, reject) => {
const startTime = Date.now();
const check = () => {
if (terminal.component.isConnected) {
resolve();
} else if (Date.now() - startTime > timeoutMs) {
reject(new Error("Terminal connection timeout"));
} else {
setTimeout(check, 50);
}
};
check();
});
await waitForConnection();
terminal.component.write(`cd ${JSON.stringify(prootPath)}\n`);
Sidebar.hide();
}
} catch (error) {
console.error("Failed to open terminal:", error);
const errorMsg = error.message || "Unknown error occurred";
toast(`Failed to open terminal: ${errorMsg}`);
}
}
async function deleteFile() {
const msg = strings["delete entry"].replace("{name}", name);
const confirmation = await confirm(strings.warning, msg);
if (!confirmation) return;
startLoading();
if (!(await fsOperation(url).exists())) return;
// await fsOperation(url).delete();
recents.removeFile(url);
if (helpers.isFile(type)) {
await fsOperation(url).delete();
$target.remove();
const file = editorManager.getFile(url, "uri");
if (file) file.uri = null;
editorManager.onupdate("delete-file");
editorManager.emit("update", "delete-file");
} else {
if (isTerminalSafUri(url)) {
const fs = fsOperation(url);
const entries = await fs.lsDir();
if (entries.length === 0) {
await fs.delete();
} else {
const deleteRecursively = async (currentUrl) => {
const currentFs = fsOperation(currentUrl);
const currentEntries = await currentFs.lsDir();
for (const entry of currentEntries) {
if (entry.isDirectory) {
await deleteRecursively(entry.url);
} else {
await fsOperation(entry.url).delete();
}
}
await currentFs.delete();
};
await deleteRecursively(url);
}
} else {
await fsOperation(url).delete();
}
recents.removeFolder(url);
helpers.updateUriOfAllActiveFiles(url, null);
$target.parentElement.remove();
editorManager.onupdate("delete-folder");
editorManager.emit("update", "delete-folder");
}
toast(strings.success);
FileList.remove(url);
}
async function renameFile() {
if (isTermuxSafUri(url) && !helpers.isFile(type)) {
alert(strings.warning, strings["rename not supported"]);
return;
}
let newName = await prompt(strings.rename, name, "text", {
match: constants.FILE_NAME_REGEX,
required: true,
});
newName = helpers.fixFilename(newName);
if (!newName || newName === name) return;
startLoading();
const fs = fsOperation(url);
let newUrl;
if (isTermuxSafUri(url) && helpers.isFile(type)) {
// Special handling for Termux SAF content files
const newFilePath = Url.join(Url.dirname(url), newName);
const content = await fs.readFile();
await fsOperation(Url.dirname(url)).createFile(newName, content);
await fs.delete();
newUrl = newFilePath;
} else {
newUrl = await fs.renameTo(newName);
}
newName = Url.basename(newUrl);
$target.querySelector(":scope>.text").textContent = newName;
$target.dataset.url = newUrl;
$target.dataset.name = newName;
if (helpers.isFile(type)) {
$target.querySelector(":scope>span").className =
helpers.getIconForFile(newName);
let file = editorManager.getFile(url, "uri");
if (file) {
file.uri = newUrl;
file.filename = newName;
}
} else {
helpers.updateUriOfAllActiveFiles(url, newUrl);
//Reloading the folder by collapsing and expanding the folder
$target.click(); //collapse
$target.click(); //expand
}
toast(strings.success);
FileList.rename(url, newUrl);
}
async function createNew() {
const msg =
action === "new file"
? strings["enter file name"]
: strings["enter folder name"];
let newName = await prompt(msg, "", "text", {
match: constants.FILE_NAME_REGEX,
required: true,
});
newName = helpers.fixFilename(newName);
if (!newName) return;
startLoading();
try {
const isNestedPath = newName.split("/").filter(Boolean).length > 1;
let newUrl;
if (action === "new file") {
newUrl = await helpers.createFileStructure(url, newName);
} else {
newUrl = await helpers.createFileStructure(url, newName, false);
}
if (!newUrl.created) return;
if (isNestedPath) {
openFolder.find(url)?.reload();
await FileList.refresh();
toast(strings.success);
return;
}
newName = Url.basename(newUrl.uri);
if ($target.unclasped) {
if (newUrl.type === "file") {
appendTile($target, createFileTile(newName, newUrl.uri));
} else if (newUrl.type === "folder") {
appendList($target, createFolderTile(newName, newUrl.uri));
}
}
FileList.append(url, newUrl.uri);
toast(strings.success);
} catch (error) {
helpers.error(error);
} finally {
stopLoading();
}
}
async function paste() {
if (clipBoard.url == null) {
alert(strings.warning, "Nothing to paste");
return;
}
// Prevent pasting a folder into itself or its subdirectories
if (helpers.isDir(clipBoard.$el.dataset.type)) {
const sourceUrl = Url.parse(clipBoard.url).url;
const targetUrl = Url.parse(url).url;
// Check if trying to paste folder into itself
if (sourceUrl === targetUrl) {
alert(strings.warning, "Cannot paste a folder into itself");
return;
}
// Check if trying to paste folder into one of its subdirectories
if (
targetUrl.startsWith(sourceUrl + "/") ||
targetUrl.startsWith(sourceUrl + "\\")
) {
alert(strings.warning, "Cannot paste a folder into its subdirectory");
return;
}
}
let CASE = "";
const $src = clipBoard.$el;
const srcType = $src.dataset.type;
const IS_FILE = helpers.isFile(srcType);
const IS_DIR = helpers.isDir(srcType);
const srcCollapsed = collapsed($src, IS_FILE);
CASE += IS_FILE ? 1 : 0;
CASE += srcCollapsed ? 1 : 0;
CASE += $target.collapsed ? 1 : 0;
startLoading();
try {
const fs = fsOperation(clipBoard.url);
const itemName = Url.basename(clipBoard.url);
const possibleConflictUrl = Url.join(url, itemName);
const doesExist = await fsOperation(possibleConflictUrl).exists();
if (doesExist) {
let confirmation = await confirm(
strings.warning,
strings["already exists"]
? strings["already exists"].replace("{name}", itemName)
: `"${itemName}" already exists in this location.`,
);
if (!confirmation) return;
}
let newUrl;
if (clipBoard.action === "cut") {
// Special handling for SAF folders backed by terminal providers - move manually due to SAF limitations
if (isTerminalSafUri(clipBoard.url) && IS_DIR) {
const moveRecursively = async (sourceUrl, targetParentUrl) => {
const sourceFs = fsOperation(sourceUrl);
const sourceName = Url.basename(sourceUrl);
const targetUrl = Url.join(targetParentUrl, sourceName);
// Create target folder
await fsOperation(targetParentUrl).createDirectory(sourceName);
// Get all entries in source folder
const entries = await sourceFs.lsDir();
// Move all files and folders recursively
for (const entry of entries) {
if (entry.isDirectory) {
await moveRecursively(entry.url, targetUrl);
} else {
const fileContent = await fsOperation(entry.url).readFile();
const fileName = entry.name || Url.basename(entry.url);
await fsOperation(targetUrl).createFile(fileName, fileContent);
await fsOperation(entry.url).delete();
}
}
// Delete the now-empty source folder
await sourceFs.delete();
return targetUrl;
};
newUrl = await moveRecursively(clipBoard.url, url);
} else {
newUrl = await fs.moveTo(url);
}
} else {
newUrl = await fs.copyTo(url);
}
const { name: newName } = await fsOperation(newUrl).stat();
stopLoading();
/**
* CASES:
* CASE 111: src is file and parent is collapsed where target is also collapsed
* CASE 110: src is file and parent is collapsed where target is unclasped
* CASE 101: src is file and parent is unclasped where target is collapsed
* CASE 100: src is file and parent is unclasped where target is also unclasped
* CASE 011: src is directory and parent is collapsed where target is also collapsed
* CASE 001: src is directory and parent is unclasped where target is also collapsed
* CASE 010: src is directory and parent is collapsed where target is also unclasped
* CASE 000: src is directory and parent is unclasped where target is also unclasped
*/
if (clipBoard.action === "cut") {
//move
if (IS_FILE) {
const file = editorManager.getFile(clipBoard.url, "uri");
if (file) file.uri = newUrl;
} else if (IS_DIR) {
helpers.updateUriOfAllActiveFiles(clipBoard.url, newUrl);
}
switch (CASE) {
case "111":
case "011":
break;
case "110":
appendTile($target, createFileTile(newName, newUrl));
break;
case "101":
$src.remove();
break;
case "100":
appendTile($target, createFileTile(newName, newUrl));
$src.remove();
break;
case "001":
$src.parentElement.remove();
break;
case "010":
appendList($target, createFolderTile(newName, newUrl));
break;
case "000":
appendList($target, createFolderTile(newName, newUrl));
$src.parentElement.remove();
break;
default:
break;
}
FileList.remove(clipBoard.url);
} else {
//copy
switch (CASE) {
case "111":
case "101":
case "011":
case "001":
break;
case "110":
case "100":
appendTile($target, createFileTile(newName, newUrl));
break;
case "010":
case "000":
appendList($target, createFolderTile(newName, newUrl));
break;
default:
break;
}
}
FileList.append(url, newUrl);
toast(strings.success);
clearClipboard();
} catch (error) {
console.error(error);
helpers.error(error);
} finally {
stopLoading();
}
}
async function insertFile() {
startLoading();
try {
const file = await FileBrowser("file", strings["insert file"]);
const sourceFs = fsOperation(file.url);
const data = await sourceFs.readFile();
const sourceStats = await sourceFs.stat();
const insertedFile = await fsOperation(url).createFile(
sourceStats.name,
data,
);
appendTile($target, createFileTile(sourceStats.name, insertedFile));
FileList.append(url, insertedFile);
} catch (error) {
} finally {
stopLoading();
}
}
async function clipBoardAction() {
clipBoard.url = url;
clipBoard.action = action;
clipBoard.$el = $target;
if (action === "cut") $target.classList.add("cut");
else $target.classList.remove("cut");
}
async function open() {
FileBrowser.openFolder({
url,
name,
});
}
function cancelAction() {
clipBoard.$el.classList.remove("cut");
clearClipboard();
}
function clearClipboard() {
clipBoard.$el = null;
clipBoard.url = null;
clipBoard.action = null;
}
}
/**
*
* @param {"file"|"dir"|"root"} type
* @param {string} url
*/
function handleClick(type, uri) {
if (!helpers.isFile(type)) return;
openFile(uri, { render: true });
Sidebar.hide();
}
/**
* Insert a file into the list
* @param {HTMLElement} $target
* @param {HTMLElement} $tile
*/
function appendTile($target, $tile) {
$target = $target.nextElementSibling;
const $firstTile = $target.get(":scope>[type=file]");
if ($firstTile) $target.insertBefore($tile, $firstTile);
else $target.append($tile);
}
/**
* Insert folder into the list
* @param {HTMLElement} $target The target element
* @param {HTMLElement} $list The tile to be inserted
*/
function appendList($target, $list) {
$target = $target.nextElementSibling;
const $firstList = $target.firstElementChild;
if ($firstList) $target.insertBefore($list, $firstList);
else $target.append($list);
}
/**
* Create a folder tile
* @param {string} name
* @param {string} url
* @returns {HTMLElement}
*/
function createFolderTile(name, url) {