WebOrbiton
v1.5.0

AtheraStudio Code

987 lines · 33.4 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var util = A.util;
  6. var fs = A.fs;
  7. ​
  8. var INVALID = /[\\:*?"<>|]/;
  9. var ROW_H = 26;
  10. var OVERSCAN = 12;
  11. ​
  12. var rows = [];
  13. var spacer = null, win = null, message = null;
  14. var paintQueued = false;
  15. var focusPath = null;
  16. var loading = new Set();
  17. var drag = null;
  18. var dropPath = null;
  19. var hover = { path: null, timer: 0 };
  20. var multi = new Set();
  21. var anchorPath = null;
  22. var nodes = new Map();
  23. var enter = new Map();
  24. var enterUntil = 0;
  25. ​
  26. var ex = (A.explorer = {
  27. el: null,
  28. cache: new Map(),
  29. expanded: new Set(),
  30. selected: null,
  31. busy: null,
  32. ​
  33. init: function (el) {
  34. ex.el = el;
  35. el.innerHTML = "";
  36. spacer = util.el("div", { class: "ath-tree-spacer" });
  37. win = util.el("div", { class: "ath-tree-window" });
  38. message = util.el("div", { class: "ath-tree-message", hidden: true });
  39. spacer.appendChild(win);
  40. el.appendChild(spacer);
  41. el.appendChild(message);
  42. el.addEventListener("scroll", queuePaint, { passive: true });
  43. window.addEventListener("resize", queuePaint);
  44. win.addEventListener("animationend", onAnimEnd);
  45. el.addEventListener("click", onClick);
  46. el.addEventListener("contextmenu", onContext);
  47. el.addEventListener("keydown", onKey);
  48. el.addEventListener("focusin", function (e) {
  49. var row = e.target.closest && e.target.closest(".ath-tree-row");
  50. if (row) focusPath = row.getAttribute("data-path");
  51. });
  52. el.addEventListener("dragstart", onDragStart);
  53. el.addEventListener("dragover", onDragOver);
  54. el.addEventListener("dragleave", onDragLeave);
  55. el.addEventListener("drop", onDrop);
  56. el.addEventListener("dragend", endDrag);
  57. window.addEventListener("dragend", endDrag, true);
  58. window.addEventListener("drop", function () { setTimeout(endDrag, 0); }, true);
  59. A.on("workspace", function () {
  60. ex.cache.clear();
  61. ex.expanded.clear();
  62. loading.clear();
  63. clearNodes();
  64. setSel(null);
  65. focusPath = null;
  66. el.scrollTop = 0;
  67. ex.render();
  68. });
  69. A.on("active-change", function (tab) {
  70. if (tab && tab.path != null && fs.provider) ex.reveal(tab.path);
  71. else paint();
  72. });
  73. A.on("lang", function () { clearNodes(); if (fs.provider) ex.render(); });
  74. },
  75. ​
  76. load: async function (dir) {
  77. if (!ex.cache.has(dir)) {
  78. var entries = (await fs.provider.list(dir)).filter(function (e) {
  79. return e.kind === "dir" ? fs.HIDDEN_DIRS.indexOf(e.name) < 0 : fs.HIDDEN_FILES.indexOf(e.name) < 0;
  80. });
  81. ex.cache.set(dir, entries);
  82. }
  83. return ex.cache.get(dir);
  84. },
  85. ​
  86. refresh: async function (dir) {
  87. A.emit("files-changed");
  88. if (dir == null) ex.cache.clear();
  89. else ex.cache.delete(dir);
  90. await ex.render();
  91. },
  92. ​
  93. render: function () {
  94. ex.busy = (ex.busy || Promise.resolve()).then(draw, draw);
  95. return ex.busy;
  96. },
  97. ​
  98. reveal: async function (path) {
  99. var dir = util.dirname(path), changed = false;
  100. while (dir) {
  101. if (!ex.expanded.has(dir)) { ex.expanded.add(dir); changed = true; }
  102. dir = util.dirname(dir);
  103. }
  104. setSel({ path: path, kind: "file" });
  105. if (changed) await ex.render();
  106. ex.scrollTo(path);
  107. },
  108. ​
  109. scrollTo: function (path) {
  110. var i = indexOf(path);
  111. if (i < 0) return paint();
  112. var el = ex.el, top = i * ROW_H;
  113. if (top < el.scrollTop) el.scrollTop = top;
  114. else if (top + ROW_H > el.scrollTop + el.clientHeight) el.scrollTop = top + ROW_H - el.clientHeight;
  115. paint();
  116. },
  117. ​
  118. rowOf: function (path) {
  119. return win ? win.querySelector('.ath-tree-row[data-path="' + CSS.escape(path) + '"]') : null;
  120. },
  121. ​
  122. markActive: function () {
  123. paint();
  124. },
  125. ​
  126. targetDir: function () {
  127. var s = ex.selected;
  128. if (!s) return "";
  129. return s.kind === "dir" ? s.path : util.dirname(s.path);
  130. },
  131. ​
  132. uniqueName: async function (dir, name) {
  133. var dot = name.lastIndexOf(".");
  134. var stem = dot > 0 ? name.slice(0, dot) : name, ext = dot > 0 ? name.slice(dot) : "";
  135. var candidate = name, i = 2;
  136. while (await fs.provider.exists(util.join(dir, candidate))) candidate = stem + "-" + i++ + ext;
  137. return candidate;
  138. },
  139. ​
  140. newFile: async function (dir) {
  141. if (!fs.provider) return;
  142. dir = dir == null ? ex.targetDir() : dir;
  143. var label = dir ? A.t("explorer.new_file_label_in", { dir: dir }) : A.t("explorer.new_file_label");
  144. var name = await A.ui.prompt(A.t("explorer.new_file"), label, "", A.t("common.create"));
  145. if (!name) return;
  146. if (INVALID.test(name)) return A.ui.toast(A.t("explorer.invalid_name"), "danger");
  147. var path = util.resolve(dir, name);
  148. if (!path) return;
  149. try {
  150. await fs.provider.createFile(path, A.templates.forFile(path));
  151. } catch (e) {
  152. return A.ui.toast(e.message, "danger");
  153. }
  154. await afterCreate(path);
  155. A.tabs.openPath(path);
  156. },
  157. ​
  158. newFolder: async function (dir) {
  159. if (!fs.provider) return;
  160. dir = dir == null ? ex.targetDir() : dir;
  161. var label = dir ? A.t("explorer.new_folder_label_in", { dir: dir }) : A.t("explorer.new_folder_label");
  162. var name = await A.ui.prompt(A.t("explorer.new_folder"), label, "", A.t("common.create"));
  163. if (!name) return;
  164. if (INVALID.test(name)) return A.ui.toast(A.t("explorer.invalid_name"), "danger");
  165. var path = util.resolve(dir, name);
  166. if (!path) return;
  167. try {
  168. await fs.provider.createDir(path);
  169. } catch (e) {
  170. return A.ui.toast(e.message, "danger");
  171. }
  172. ex.expanded.add(path);
  173. await afterCreate(path, "dir");
  174. },
  175. ​
  176. rename: async function (path, kind) {
  177. var name = await A.ui.prompt(A.t("explorer.rename_title"), A.t("explorer.rename_label"), util.basename(path), A.t("common.rename"));
  178. if (!name || name === util.basename(path)) return;
  179. if (INVALID.test(name) || name.indexOf("/") >= 0 || name === "." || name === "..") {
  180. return A.ui.toast(A.t("explorer.invalid_name"), "danger");
  181. }
  182. try {
  183. var target = await fs.provider.rename(path, name, kind);
  184. A.tabs.renamePath(path, target);
  185. if (kind === "dir") remapExpanded(path, target);
  186. setSel({ path: target, kind: kind });
  187. focusPath = target;
  188. await refreshAround([util.dirname(path)], kind === "dir" ? [path] : []);
  189. ex.scrollTo(target);
  190. } catch (e) {
  191. A.ui.toast(A.t("explorer.rename_failed", { error: e.message }), "danger");
  192. }
  193. },
  194. ​
  195. remove: async function (path, kind) {
  196. var msg = A.t(kind === "dir" ? "explorer.delete_folder_confirm" : "explorer.delete_file_confirm", { path: path });
  197. if (!(await A.ui.confirm(A.t("common.delete"), msg, A.t("common.delete"), true))) return;
  198. try {
  199. await fs.provider.remove(path);
  200. A.tabs.removePath(path);
  201. Array.from(ex.expanded).forEach(function (p) {
  202. if (p === path || p.indexOf(path + "/") === 0) ex.expanded.delete(p);
  203. });
  204. setSel(null);
  205. await refreshAround([util.dirname(path)], kind === "dir" ? [path] : []);
  206. } catch (e) {
  207. A.ui.toast(A.t("explorer.delete_failed", { error: e.message }), "danger");
  208. }
  209. },
  210. ​
  211. move: async function (path, kind, destDir) {
  212. try {
  213. var target = await fs.provider.move(path, destDir, kind);
  214. A.tabs.renamePath(path, target);
  215. if (kind === "dir") remapExpanded(path, target);
  216. var dir = destDir;
  217. while (dir) { ex.expanded.add(dir); dir = util.dirname(dir); }
  218. setSel({ path: target, kind: kind });
  219. focusPath = target;
  220. await refreshAround([util.dirname(path), destDir], kind === "dir" ? [path] : []);
  221. ex.scrollTo(target);
  222. A.ui.toast(A.t("explorer.moved", { name: util.basename(path), dir: destDir || fs.provider.name }));
  223. } catch (e) {
  224. A.ui.toast(A.t("explorer.move_failed", { error: e.message }), "danger");
  225. }
  226. },
  227. ​
  228. removeMany: async function (items) {
  229. items = prune(items);
  230. if (items.length < 2) return items[0] ? ex.remove(items[0].path, items[0].kind) : undefined;
  231. if (!(await A.ui.confirm(A.t("common.delete"), A.tn("explorer.delete_many_confirm", items.length), A.t("common.delete"), true))) return;
  232. var errors = [], dirs = [], goneDirs = [];
  233. for (var it of items) {
  234. try {
  235. await fs.provider.remove(it.path);
  236. A.tabs.removePath(it.path);
  237. Array.from(ex.expanded).forEach(function (p) {
  238. if (p === it.path || p.indexOf(it.path + "/") === 0) ex.expanded.delete(p);
  239. });
  240. dirs.push(util.dirname(it.path));
  241. if (it.kind === "dir") goneDirs.push(it.path);
  242. } catch (e) { errors.push(e.message); }
  243. }
  244. setSel(null);
  245. await refreshAround(dirs, goneDirs);
  246. if (errors.length) A.ui.toast(A.t("explorer.delete_failed", { error: errors[0] }), "danger");
  247. },
  248. ​
  249. copyIn: async function (handles, destDir) {
  250. var items = [], emptyDirs = [], topDirs = [], skipped = false;
  251. for (var h of handles) {
  252. if (h.kind === "directory") {
  253. var target = util.join(destDir, h.name);
  254. if (await isInsideWorkspace(h, destDir, target)) { skipped = true; continue; }
  255. await collectDir(h, target, items, emptyDirs);
  256. topDirs.push(target);
  257. } else {
  258. var f = h._file || (await h.getFile());
  259. items.push({ path: util.join(destDir, f.name), file: f });
  260. }
  261. }
  262. if (skipped) A.ui.toast(A.t("explorer.copy_into_self"), "warning");
  263. if (!items.length && !emptyDirs.length) return;
  264. var dirName = destDir || fs.provider.name;
  265. if (!(await yesNo(A.t("explorer.copy_title", { dir: dirName }), A.t("explorer.copy_confirm")))) return;
  266. var clash = new Set();
  267. for (var it of items) {
  268. if (await fs.provider.exists(it.path)) clash.add(it.path);
  269. }
  270. var replace = false;
  271. if (clash.size) replace = await yesNo(A.t("explorer.replace_title"), A.t("explorer.replace_confirm"));
  272. var done = [], errors = [];
  273. for (var item of items) {
  274. var exists = clash.has(item.path);
  275. if (exists && !replace) continue;
  276. try {
  277. await fs.provider.write(item.path, item.file || (await item.handle.getFile()));
  278. done.push(item.path);
  279. if (exists && A.tabs.byPath(item.path)) {
  280. A.tabs.removePath(item.path);
  281. await A.tabs.openPath(item.path);
  282. }
  283. } catch (e) { errors.push(e.message); }
  284. }
  285. for (var d of emptyDirs) {
  286. try {
  287. if (!(await fs.provider.exists(d))) await fs.provider.createDir(d);
  288. } catch (e) { errors.push(e.message); }
  289. }
  290. var dir = destDir;
  291. while (dir) { ex.expanded.add(dir); dir = util.dirname(dir); }
  292. topDirs.forEach(function (p) { ex.expanded.add(p); });
  293. await refreshAround([destDir], topDirs);
  294. var first = topDirs[0] || done[0];
  295. if (first) ex.scrollTo(first);
  296. if (done.length) A.ui.toast(A.tn("explorer.copied_many", done.length, { dir: dirName }), "success");
  297. if (errors.length) A.ui.toast(A.t("explorer.copy_failed", { error: errors[0] }), "danger");
  298. },
  299. ​
  300. moveMany: async function (items, destDir) {
  301. items = prune(items).filter(function (it) { return canDrop(it, destDir); });
  302. if (!items.length) return;
  303. if (items.length === 1) return ex.move(items[0].path, items[0].kind, destDir);
  304. var targets = [], srcDirs = [destDir], goneDirs = [], errors = [];
  305. for (var it of items) {
  306. try {
  307. var target = await fs.provider.move(it.path, destDir, it.kind);
  308. A.tabs.renamePath(it.path, target);
  309. if (it.kind === "dir") { remapExpanded(it.path, target); goneDirs.push(it.path); }
  310. srcDirs.push(util.dirname(it.path));
  311. targets.push({ path: target, kind: it.kind });
  312. } catch (e) { errors.push(e.message); }
  313. }
  314. var dir = destDir;
  315. while (dir) { ex.expanded.add(dir); dir = util.dirname(dir); }
  316. if (targets.length) {
  317. setSel(targets[0]);
  318. targets.forEach(function (t) { multi.add(t.path); });
  319. focusPath = targets[0].path;
  320. }
  321. await refreshAround(srcDirs, goneDirs);
  322. if (targets.length) {
  323. ex.scrollTo(targets[0].path);
  324. A.ui.toast(A.tn("explorer.moved_many", targets.length, { dir: destDir || fs.provider.name }));
  325. }
  326. if (errors.length) A.ui.toast(A.t("explorer.move_failed", { error: errors[0] }), "danger");
  327. },
  328. ​
  329. dragging: function () {
  330. return drag ? dragItems(drag) : null;
  331. },
  332. ​
  333. collapseAll: function () {
  334. ex.expanded.clear();
  335. ex.el.scrollTop = 0;
  336. ex.render();
  337. }
  338. });
  339. ​
  340. async function collectDir(handle, target, items, emptyDirs) {
  341. var count = 0;
  342. for await (var e of handle.values()) {
  343. if (e.kind === "directory") {
  344. if (fs.HIDDEN_DIRS.indexOf(e.name) >= 0) continue;
  345. count++;
  346. await collectDir(e, util.join(target, e.name), items, emptyDirs);
  347. } else {
  348. if (fs.HIDDEN_FILES.indexOf(e.name) >= 0) continue;
  349. count++;
  350. items.push({ path: util.join(target, e.name), handle: e });
  351. }
  352. }
  353. if (!count) emptyDirs.push(target);
  354. }
  355. ​
  356. async function isInsideWorkspace(handle, destDir, target) {
  357. var root = fs.provider && fs.provider.root;
  358. if (!root || typeof root.resolve !== "function") return false;
  359. var rel = null;
  360. try { rel = await root.resolve(handle); } catch (e) { return false; }
  361. if (!rel) return false;
  362. var src = rel.join("/");
  363. if (src === "") return true;
  364. return target === src || destDir === src || destDir.indexOf(src + "/") === 0;
  365. }
  366. ​
  367. function remapExpanded(path, target) {
  368. Array.from(ex.expanded).forEach(function (p) {
  369. if (p === path || p.indexOf(path + "/") === 0) {
  370. ex.expanded.delete(p);
  371. ex.expanded.add(target + p.slice(path.length));
  372. }
  373. });
  374. }
  375. ​
  376. async function refreshAround(dirs, removedDirs) {
  377. A.emit("files-changed");
  378. dirs.forEach(function (d) { ex.cache.delete(d); });
  379. removedDirs.forEach(function (gone) {
  380. Array.from(ex.cache.keys()).forEach(function (k) {
  381. if (k === gone || k.indexOf(gone + "/") === 0) ex.cache.delete(k);
  382. });
  383. });
  384. await ex.render();
  385. }
  386. ​
  387. async function afterCreate(path, kind) {
  388. var dir = util.dirname(path), dirs = [dir];
  389. while (dir) {
  390. ex.expanded.add(dir);
  391. dir = util.dirname(dir);
  392. dirs.push(dir);
  393. }
  394. setSel({ path: path, kind: kind || "file" });
  395. focusPath = path;
  396. await refreshAround(dirs, []);
  397. ex.scrollTo(path);
  398. }
  399. ​
  400. function visibleExpanded() {
  401. var out = [];
  402. function walk(dir) {
  403. var entries = ex.cache.get(dir);
  404. if (!entries) return;
  405. for (var e of entries) {
  406. if (e.kind !== "dir") continue;
  407. var p = util.join(dir, e.name);
  408. if (!ex.expanded.has(p)) continue;
  409. if (ex.cache.has(p)) walk(p);
  410. else out.push(p);
  411. }
  412. }
  413. if (!ex.cache.has("")) out.push("");
  414. else walk("");
  415. return out;
  416. }
  417. ​
  418. function flatten() {
  419. var out = [];
  420. function walk(dir, depth) {
  421. var entries = ex.cache.get(dir);
  422. if (!entries) {
  423. if (loading.has(dir)) out.push({ path: dir + "/\u0000loading", name: "", kind: "loading", depth: depth });
  424. return;
  425. }
  426. for (var e of entries) {
  427. var p = util.join(dir, e.name);
  428. var open = e.kind === "dir" && ex.expanded.has(p);
  429. out.push({ path: p, name: e.name, kind: e.kind, depth: depth, open: open });
  430. if (open) walk(p, depth + 1);
  431. }
  432. }
  433. walk("", 0);
  434. return out;
  435. }
  436. ​
  437. async function draw() {
  438. if (!fs.provider) {
  439. setRows([]);
  440. showMessage("");
  441. paint();
  442. return;
  443. }
  444. var provider = fs.provider;
  445. for (var round = 0; round < 50; round++) {
  446. var missing = visibleExpanded();
  447. if (!missing.length) break;
  448. missing.forEach(function (d) { loading.add(d); });
  449. setRows(flatten());
  450. paint();
  451. var results = await Promise.all(missing.map(function (d) {
  452. return ex.load(d).then(function () { return null; }, function (e) { return { dir: d, error: e }; });
  453. }));
  454. if (provider !== fs.provider) return;
  455. missing.forEach(function (d) { loading.delete(d); });
  456. var rootError = null;
  457. results.forEach(function (r) {
  458. if (!r) return;
  459. if (r.dir === "") rootError = r.error;
  460. else ex.expanded.delete(r.dir);
  461. });
  462. if (rootError) {
  463. setRows([]);
  464. showMessage(A.t("explorer.read_error", { error: rootError.message }), true);
  465. paint();
  466. return;
  467. }
  468. }
  469. setRows(flatten());
  470. showMessage(rows.length ? "" : A.t("explorer.empty"));
  471. paint();
  472. }
  473. ​
  474. function showMessage(text, isError) {
  475. message.hidden = !text;
  476. message.textContent = text;
  477. message.className = "ath-tree-message" + (isError ? " is-error" : "");
  478. }
  479. ​
  480. function indexOf(path) {
  481. for (var i = 0; i < rows.length; i++) if (rows[i].path === path) return i;
  482. return -1;
  483. }
  484. ​
  485. function queuePaint() {
  486. if (paintQueued) return;
  487. paintQueued = true;
  488. requestAnimationFrame(function () {
  489. paintQueued = false;
  490. paint();
  491. });
  492. }
  493. ​
  494. function onAnimEnd(e) {
  495. var t = e.target;
  496. if (e.animationName === "ath-row-in") {
  497. t.classList.remove("is-entering");
  498. t.style.removeProperty("--i");
  499. } else if (e.animationName === "ath-ficon-pop") {
  500. t.classList.remove("is-toggled");
  501. }
  502. }
  503. ​
  504. function setRows(next) {
  505. var prev = new Set(rows.map(function (r) { return r.path; }));
  506. var fresh = new Map(), n = 0;
  507. next.forEach(function (r) {
  508. if (!prev.has(r.path)) fresh.set(r.path, Math.min(n++, 14));
  509. });
  510. enter = fresh;
  511. enterUntil = performance.now() + 600;
  512. rows = next;
  513. }
  514. ​
  515. function clearNodes() {
  516. nodes.forEach(function (n) { n.remove(); });
  517. nodes.clear();
  518. enter = new Map();
  519. }
  520. ​
  521. function buildRow(r) {
  522. var node = document.createElement("div");
  523. node.className = "ath-tree-row";
  524. node.setAttribute("role", "treeitem");
  525. node.setAttribute("tabindex", "-1");
  526. node.setAttribute("draggable", "true");
  527. node.setAttribute("data-path", r.path);
  528. node.setAttribute("data-kind", r.kind);
  529. node.style.setProperty("--depth", r.depth);
  530. if (r.kind === "loading") {
  531. node.classList.add("is-loading");
  532. node.innerHTML = '<span class="ath-tree-chevron"></span><span class="ath-spinner ath-spinner-sm"></span>' +
  533. '<span class="ath-tree-name">' + util.esc(A.t("palette.loading").replace(/…$/, "")) + "…</span>";
  534. return node;
  535. }
  536. node.title = r.path;
  537. if (r.kind === "dir") {
  538. node.classList.add("is-dir");
  539. node.innerHTML = '<span class="ath-tree-chevron">' + A.icon("chevron") + '</span><span class="ath-ficon ath-ficon-dir">' +
  540. A.icon(r.open ? "folderOpen" : "folder") + "</span>" +
  541. '<span class="ath-tree-name">' + util.esc(r.name) + "</span>";
  542. node.setAttribute("aria-expanded", String(!!r.open));
  543. node._open = !!r.open;
  544. } else {
  545. node.innerHTML = '<span class="ath-tree-chevron"></span>' + A.fileBadge(r.name) +
  546. '<span class="ath-tree-name">' + util.esc(r.name) + "</span>";
  547. }
  548. return node;
  549. }
  550. ​
  551. function syncRow(node, r, active) {
  552. if (r.kind === "loading") return;
  553. var c = node.classList;
  554. var dragging = !!drag && dragItems(drag).some(function (it) { return it.path === r.path; });
  555. var sel = multi.has(r.path);
  556. c.toggle("is-open", !!r.open);
  557. c.toggle("is-active", r.path === active);
  558. c.toggle("is-selected", sel);
  559. c.toggle("is-multi", multi.size > 1 && sel);
  560. c.toggle("is-dragging", dragging);
  561. c.toggle("is-drop-target", dropPath === r.path);
  562. if (r.kind === "dir" && node._open !== !!r.open) {
  563. node._open = !!r.open;
  564. node.setAttribute("aria-expanded", String(!!r.open));
  565. var icon = node.querySelector(".ath-ficon-dir");
  566. if (icon) {
  567. icon.innerHTML = A.icon(r.open ? "folderOpen" : "folder");
  568. icon.classList.remove("is-toggled");
  569. void icon.offsetWidth;
  570. icon.classList.add("is-toggled");
  571. }
  572. }
  573. }
  574. ​
  575. function paint() {
  576. if (!win) return;
  577. var el = ex.el;
  578. spacer.style.height = rows.length * ROW_H + "px";
  579. var height = el.clientHeight || 600;
  580. var start = Math.max(0, Math.floor(el.scrollTop / ROW_H) - OVERSCAN);
  581. var end = Math.min(rows.length, Math.ceil((el.scrollTop + height) / ROW_H) + OVERSCAN);
  582. var hadFocus = el.contains(document.activeElement) && document.activeElement !== el;
  583. var active = A.tabs.active && A.tabs.active.path;
  584. var animate = performance.now() < enterUntil;
  585. var seen = new Set(), prevNode = null;
  586. for (var i = start; i < end; i++) {
  587. var r = rows[i];
  588. var node = nodes.get(r.path);
  589. if (node && node.getAttribute("data-kind") !== r.kind) {
  590. node.remove();
  591. nodes.delete(r.path);
  592. node = null;
  593. }
  594. if (!node) {
  595. node = buildRow(r);
  596. nodes.set(r.path, node);
  597. if (animate && enter.has(r.path)) {
  598. node.style.setProperty("--i", enter.get(r.path));
  599. node.classList.add("is-entering");
  600. enter.delete(r.path);
  601. }
  602. }
  603. syncRow(node, r, active);
  604. seen.add(r.path);
  605. var ref = prevNode ? prevNode.nextSibling : win.firstChild;
  606. if (node !== ref) win.insertBefore(node, ref);
  607. prevNode = node;
  608. }
  609. nodes.forEach(function (n, path) {
  610. if (!seen.has(path)) {
  611. n.remove();
  612. nodes.delete(path);
  613. }
  614. });
  615. win.style.transform = "translateY(" + start * ROW_H + "px)";
  616. if (hadFocus && focusPath) {
  617. var row = ex.rowOf(focusPath);
  618. if (row) row.focus({ preventScroll: true });
  619. else el.focus({ preventScroll: true });
  620. }
  621. }
  622. ​
  623. function prune(items) {
  624. return items.filter(function (it) {
  625. return !items.some(function (o) { return o !== it && o.kind === "dir" && it.path.indexOf(o.path + "/") === 0; });
  626. });
  627. }
  628. ​
  629. function selectedItems() {
  630. return rows.filter(function (r) { return r.kind !== "loading" && multi.has(r.path); })
  631. .map(function (r) { return { path: r.path, kind: r.kind }; });
  632. }
  633. ​
  634. function dragItems(d) { return d.items || [d]; }
  635. ​
  636. function canDropAny(d, dest) {
  637. return dragItems(d).some(function (it) { return canDrop(it, dest); });
  638. }
  639. ​
  640. function setSel(d) {
  641. ex.selected = d || null;
  642. multi = new Set(d ? [d.path] : []);
  643. anchorPath = d ? d.path : null;
  644. }
  645. ​
  646. function selectRange(d, additive) {
  647. var b = indexOf(d.path);
  648. var a = anchorPath != null ? indexOf(anchorPath) : -1;
  649. if (a < 0) { anchorPath = d.path; a = b; }
  650. if (b < 0) return;
  651. if (!additive) multi = new Set();
  652. for (var i = Math.min(a, b); i <= Math.max(a, b); i++) {
  653. if (rows[i].kind !== "loading") multi.add(rows[i].path);
  654. }
  655. ex.selected = d;
  656. focusPath = d.path;
  657. paint();
  658. }
  659. ​
  660. function toggleSel(d) {
  661. if (multi.has(d.path)) {
  662. multi.delete(d.path);
  663. if (ex.selected && ex.selected.path === d.path) {
  664. var left = Array.from(multi).pop();
  665. ex.selected = left ? { path: left, kind: (rows[indexOf(left)] || {}).kind || "file" } : null;
  666. }
  667. } else {
  668. multi.add(d.path);
  669. ex.selected = d;
  670. }
  671. anchorPath = d.path;
  672. focusPath = d.path;
  673. paint();
  674. }
  675. ​
  676. function selectAll() {
  677. multi = new Set();
  678. rows.forEach(function (r) { if (r.kind !== "loading") multi.add(r.path); });
  679. if (!ex.selected || !multi.has(ex.selected.path)) {
  680. var i = focusPath ? indexOf(focusPath) : -1;
  681. var d = rowAt(i >= 0 ? i : 0);
  682. if (d) ex.selected = d;
  683. }
  684. if (anchorPath == null) anchorPath = ex.selected ? ex.selected.path : null;
  685. paint();
  686. }
  687. ​
  688. function rowData(row) {
  689. return { path: row.getAttribute("data-path"), kind: row.getAttribute("data-kind") };
  690. }
  691. ​
  692. function rowAt(i) {
  693. return rows[i] ? { path: rows[i].path, kind: rows[i].kind } : null;
  694. }
  695. ​
  696. async function activate(d) {
  697. if (!d || d.kind === "loading") return;
  698. setSel(d);
  699. focusPath = d.path;
  700. if (d.kind === "dir") {
  701. if (ex.expanded.has(d.path)) ex.expanded.delete(d.path);
  702. else ex.expanded.add(d.path);
  703. await ex.render();
  704. } else {
  705. paint();
  706. await A.tabs.openPath(d.path, { focusEditor: false });
  707. }
  708. }
  709. ​
  710. function onClick(e) {
  711. var row = e.target.closest(".ath-tree-row");
  712. if (!row) {
  713. setSel(null);
  714. paint();
  715. return;
  716. }
  717. row.focus({ preventScroll: true });
  718. var d = rowData(row);
  719. if (d.kind === "loading") return;
  720. var mod = e.ctrlKey || e.metaKey;
  721. if (e.shiftKey) return selectRange(d, mod);
  722. if (mod) return toggleSel(d);
  723. activate(d);
  724. }
  725. ​
  726. function onContext(e) {
  727. if (!fs.provider) return;
  728. e.preventDefault();
  729. var row = e.target.closest(".ath-tree-row:not(.is-loading)");
  730. var d = row ? rowData(row) : { path: "", kind: "dir" };
  731. var inMulti = !!row && multi.size > 1 && multi.has(d.path);
  732. if (inMulti) {
  733. focusPath = d.path;
  734. A.ui.contextMenu(e.clientX, e.clientY, [
  735. { label: A.t("common.delete") + " (" + multi.size + ")", icon: "trash", kbd: "Del", danger: true, action: function () { ex.removeMany(selectedItems()); } },
  736. "-",
  737. { label: A.t("explorer.refresh"), icon: "refresh", action: function () { ex.refresh(null); } }
  738. ]);
  739. return;
  740. }
  741. if (row) { setSel(d); focusPath = d.path; paint(); }
  742. var dir = d.kind === "dir" ? d.path : util.dirname(d.path);
  743. var items = [
  744. { label: A.t("explorer.new_file"), icon: "filePlus", kbd: "Alt+N", action: function () { ex.newFile(dir); } },
  745. { label: A.t("explorer.new_folder"), icon: "folderPlus", action: function () { ex.newFolder(dir); } }
  746. ];
  747. if (row) {
  748. items.push("-",
  749. { label: A.t("explorer.rename_title"), icon: "pencil", kbd: "F2", action: function () { ex.rename(d.path, d.kind); } },
  750. { label: A.t("explorer.copy_path"), icon: "copy", action: function () { copy(d.path); } },
  751. "-",
  752. { label: A.t("common.delete"), icon: "trash", kbd: "Del", danger: true, action: function () { ex.remove(d.path, d.kind); } });
  753. }
  754. items.push("-", { label: A.t("explorer.refresh"), icon: "refresh", action: function () { ex.refresh(null); } });
  755. A.ui.contextMenu(e.clientX, e.clientY, items);
  756. }
  757. ​
  758. function copy(text) {
  759. A.ui.copyText(text).then(function () { A.ui.toast(A.t("explorer.copied", { path: text })); }, function () { });
  760. }
  761. ​
  762. function hasFiles(e) {
  763. return !!e.dataTransfer && Array.from(e.dataTransfer.types).indexOf("Files") >= 0;
  764. }
  765. ​
  766. function externalDrop(e) {
  767. return !drag && hasFiles(e) && !!fs.provider && fs.provider.kind === "disk";
  768. }
  769. ​
  770. function yesNo(title, message) {
  771. return A.ui.dialog({
  772. title: title,
  773. body: util.el("p", { class: "ath-dialog-text" }, message),
  774. size: "sm",
  775. actions: [
  776. { label: A.t("common.no"), value: false, kind: "ghost" },
  777. { label: A.t("common.yes"), value: true, kind: "primary" }
  778. ]
  779. }).then(function (r) { return r === true; });
  780. }
  781. ​
  782. function dropDir(e) {
  783. var row = e.target.closest && e.target.closest(".ath-tree-row:not(.is-loading)");
  784. if (!row) return "";
  785. var d = rowData(row);
  786. return d.kind === "dir" ? d.path : util.dirname(d.path);
  787. }
  788. ​
  789. function canDrop(item, dest) {
  790. if (!item || !fs.provider) return false;
  791. if (util.dirname(item.path) === dest) return false;
  792. if (item.kind === "dir" && (dest === item.path || dest.indexOf(item.path + "/") === 0)) return false;
  793. return true;
  794. }
  795. ​
  796. function markDrop(dest) {
  797. var next = dest || null;
  798. ex.el.classList.toggle("is-drop-root", dest === "");
  799. if (next === dropPath) return;
  800. dropPath = next;
  801. win.querySelectorAll(".is-drop-target").forEach(function (r) { r.classList.remove("is-drop-target"); });
  802. if (dropPath) {
  803. var row = ex.rowOf(dropPath);
  804. if (row) row.classList.add("is-drop-target");
  805. }
  806. }
  807. ​
  808. function clearDrop() {
  809. clearTimeout(hover.timer);
  810. hover.path = null;
  811. dropPath = null;
  812. if (!ex.el) return;
  813. ex.el.classList.remove("is-drop-root");
  814. win.querySelectorAll(".is-drop-target").forEach(function (r) { r.classList.remove("is-drop-target"); });
  815. }
  816. ​
  817. function endDrag() {
  818. if (!drag) return;
  819. drag = null;
  820. clearDrop();
  821. win.querySelectorAll(".is-dragging").forEach(function (r) { r.classList.remove("is-dragging"); });
  822. }
  823. ​
  824. function hostPaths(items) {
  825. var desktop = window.atheraDesktop;
  826. var base = fs.provider && fs.provider.root && fs.provider.root._path;
  827. if (!desktop || !desktop.isDesktop || typeof desktop.startDrag !== "function" || !base) return [];
  828. var sep = base.indexOf("\\") >= 0 && base.indexOf("/") < 0 ? "\\" : "/";
  829. return items.filter(function (it) { return it.kind === "file"; }).map(function (it) {
  830. return base.replace(/[\\/]+$/, "") + sep + it.path.split("/").join(sep);
  831. });
  832. }
  833. ​
  834. function onDragStart(e) {
  835. var row = e.target.closest(".ath-tree-row:not(.is-loading)");
  836. if (!row || !fs.provider) return;
  837. A.ui.closeContextMenu();
  838. var started = rowData(row);
  839. if (multi.size > 1 && multi.has(started.path)) started.items = selectedItems();
  840. if (e.altKey) {
  841. var paths = hostPaths(dragItems(started));
  842. if (paths.length) {
  843. e.preventDefault();
  844. window.atheraDesktop.startDrag(paths);
  845. return;
  846. }
  847. }
  848. drag = started;
  849. e.dataTransfer.effectAllowed = "move";
  850. e.dataTransfer.setData("text/plain", drag.path);
  851. requestAnimationFrame(function () {
  852. dragItems(started).forEach(function (it) {
  853. var r = ex.rowOf(it.path);
  854. if (r) r.classList.add("is-dragging");
  855. });
  856. });
  857. }
  858. ​
  859. function onDragOver(e) {
  860. if (externalDrop(e)) {
  861. e.preventDefault();
  862. e.dataTransfer.dropEffect = "copy";
  863. markDrop(dropDir(e));
  864. return;
  865. }
  866. if (!drag) return;
  867. var dest = dropDir(e);
  868. if (!canDropAny(drag, dest)) {
  869. clearDrop();
  870. e.dataTransfer.dropEffect = "none";
  871. return;
  872. }
  873. e.preventDefault();
  874. e.dataTransfer.dropEffect = "move";
  875. markDrop(dest);
  876. var row = e.target.closest(".ath-tree-row");
  877. var d = row && rowData(row);
  878. if (d && d.kind === "dir" && !ex.expanded.has(d.path)) {
  879. if (hover.path !== d.path) {
  880. clearTimeout(hover.timer);
  881. hover.path = d.path;
  882. hover.timer = setTimeout(function () {
  883. if (!drag || hover.path !== d.path) return;
  884. ex.expanded.add(d.path);
  885. ex.render();
  886. }, 650);
  887. }
  888. } else {
  889. clearTimeout(hover.timer);
  890. hover.path = null;
  891. }
  892. }
  893. ​
  894. function onDragLeave(e) {
  895. if (!ex.el.contains(e.relatedTarget)) clearDrop();
  896. }
  897. ​
  898. function onDrop(e) {
  899. if (externalDrop(e)) {
  900. e.preventDefault();
  901. e.athHandled = true;
  902. var target = dropDir(e);
  903. clearDrop();
  904. var jobs = Array.from(e.dataTransfer.items).filter(function (it) { return it.kind === "file"; }).map(function (it) {
  905. if (it.getAsFileSystemHandle) return it.getAsFileSystemHandle();
  906. var f = it.getAsFile();
  907. return Promise.resolve(f ? { kind: "file", _file: f } : null);
  908. });
  909. Promise.all(jobs).then(function (handles) {
  910. return ex.copyIn(handles.filter(Boolean), target);
  911. }).catch(function (err) {
  912. A.ui.toast(A.t("explorer.copy_failed", { error: err.message }), "danger");
  913. });
  914. return;
  915. }
  916. if (!drag) return;
  917. e.preventDefault();
  918. e.stopPropagation();
  919. var d = drag, dest = dropDir(e);
  920. endDrag();
  921. if (d.items) ex.moveMany(d.items, dest);
  922. else if (canDrop(d, dest)) ex.move(d.path, d.kind, dest);
  923. }
  924. ​
  925. function focusIndex(i) {
  926. var d = rowAt(i);
  927. if (!d || d.kind === "loading") return;
  928. focusPath = d.path;
  929. ex.scrollTo(d.path);
  930. var row = ex.rowOf(d.path);
  931. if (row) row.focus({ preventScroll: true });
  932. }
  933. ​
  934. function onKey(e) {
  935. if (!rows.length) return;
  936. if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "a") {
  937. e.preventDefault();
  938. selectAll();
  939. return;
  940. }
  941. if (e.key === "Escape" && multi.size > 1) {
  942. e.preventDefault();
  943. setSel(ex.selected);
  944. paint();
  945. return;
  946. }
  947. var i = focusPath ? indexOf(focusPath) : -1;
  948. if (i < 0) {
  949. if (e.key === "ArrowDown" || e.key === "Home") { e.preventDefault(); focusIndex(0); }
  950. return;
  951. }
  952. var d = rowAt(i);
  953. var page = Math.max(1, Math.floor(ex.el.clientHeight / ROW_H) - 1);
  954. ​
  955. function go(t) {
  956. if (e.shiftKey) {
  957. if (anchorPath == null || indexOf(anchorPath) < 0) anchorPath = d.path;
  958. focusIndex(t);
  959. selectRange(rowAt(t), false);
  960. } else focusIndex(t);
  961. }
  962. switch (e.key) {
  963. case "ArrowDown": e.preventDefault(); go(Math.min(rows.length - 1, i + 1)); break;
  964. case "ArrowUp": e.preventDefault(); go(Math.max(0, i - 1)); break;
  965. case "PageDown": e.preventDefault(); go(Math.min(rows.length - 1, i + page)); break;
  966. case "PageUp": e.preventDefault(); go(Math.max(0, i - page)); break;
  967. case "Home": e.preventDefault(); go(0); break;
  968. case "End": e.preventDefault(); go(rows.length - 1); break;
  969. case "ArrowRight":
  970. if (d.kind === "dir" && !ex.expanded.has(d.path)) { e.preventDefault(); activate(d); }
  971. break;
  972. case "ArrowLeft":
  973. e.preventDefault();
  974. if (d.kind === "dir" && ex.expanded.has(d.path)) activate(d);
  975. else if (util.dirname(d.path)) focusIndex(indexOf(util.dirname(d.path)));
  976. break;
  977. case "Enter": e.preventDefault(); activate(d); break;
  978. case "F2": e.preventDefault(); ex.rename(d.path, d.kind); break;
  979. case "Delete":
  980. e.preventDefault();
  981. if (multi.size > 1) ex.removeMany(selectedItems());
  982. else ex.remove(d.path, d.kind);
  983. break;
  984. }
  985. }
  986. })();
  987. ​