WebOrbiton
v1.5.0

AtheraStudio Code

426 lines · 14.4 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var util = A.util;
  6. ​
  7. var BINARY = ["png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "ico", "svgz", "woff", "woff2", "ttf", "otf", "eot",
  8. "mp3", "mp4", "webm", "ogg", "wav", "m4a", "mov", "zip", "rar", "7z", "gz", "pdf", "exe", "dll", "psd"];
  9. var IMAGE = ["png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "ico", "svg"];
  10. var MIME = {
  11. png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif",
  12. bmp: "image/bmp", ico: "image/x-icon", svg: "image/svg+xml", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf",
  13. otf: "font/otf", mp3: "audio/mpeg", mp4: "video/mp4", webm: "video/webm", ogg: "audio/ogg", wav: "audio/wav",
  14. css: "text/css", js: "text/javascript", html: "text/html", json: "application/json", txt: "text/plain"
  15. };
  16. ​
  17. function exists(path) { return new Error(A.t("fs.exists", { path: path })); }
  18. function notFound(path) { return new Error(A.t("fs.not_found", { path: path })); }
  19. ​
  20. var collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
  21. var HIDDEN_DIRS = [".git", "node_modules", ".backups"];
  22. var HIDDEN_FILES = [".DS_Store", "Thumbs.db"];
  23. ​
  24. function sortEntries(list) {
  25. return list.sort(function (a, b) {
  26. if (a.kind !== b.kind) return a.kind === "dir" ? -1 : 1;
  27. return collator.compare(a.name, b.name);
  28. });
  29. }
  30. ​
  31. function splitPath(path) {
  32. return path ? path.split("/") : [];
  33. }
  34. ​
  35. function DiskProvider(root) {
  36. this.root = root;
  37. this.name = root.name || "Folder";
  38. this.kind = "disk";
  39. }
  40. ​
  41. DiskProvider.prototype._dir = async function (path, create) {
  42. var dir = this.root;
  43. for (var seg of splitPath(path)) dir = await dir.getDirectoryHandle(seg, { create: !!create });
  44. return dir;
  45. };
  46. ​
  47. DiskProvider.prototype._file = async function (path, create) {
  48. var dir = await this._dir(util.dirname(path), create);
  49. return dir.getFileHandle(util.basename(path), { create: !!create });
  50. };
  51. ​
  52. DiskProvider.prototype._handle = async function (path, kind) {
  53. if (!path) return this.root;
  54. return kind === "dir" ? this._dir(path) : this._file(path);
  55. };
  56. ​
  57. DiskProvider.prototype.list = async function (path) {
  58. var dir = await this._dir(path);
  59. var out = [];
  60. for await (var h of dir.values()) out.push({ name: h.name, kind: h.kind === "directory" ? "dir" : "file" });
  61. return sortEntries(out);
  62. };
  63. ​
  64. DiskProvider.prototype.readFile = async function (path) {
  65. try {
  66. return await (await this._file(path)).getFile();
  67. } catch (e) {
  68. if (e.name === "NotFoundError" || e.name === "TypeMismatchError") throw notFound(path);
  69. throw e;
  70. }
  71. };
  72. ​
  73. DiskProvider.prototype.readText = async function (path) {
  74. return (await this.readFile(path)).text();
  75. };
  76. ​
  77. DiskProvider.prototype.write = async function (path, data) {
  78. var fh = await this._file(path, true);
  79. var w = await fh.createWritable();
  80. try {
  81. await w.write(data);
  82. await w.close();
  83. } catch (e) {
  84. try { await w.abort(); } catch (x) { }
  85. throw e;
  86. }
  87. };
  88. ​
  89. DiskProvider.prototype.exists = async function (path) {
  90. try { await this._file(path); return true; } catch (e) { }
  91. try { await this._dir(path); return true; } catch (e) { return false; }
  92. };
  93. ​
  94. DiskProvider.prototype.createFile = async function (path, text) {
  95. if (await this.exists(path)) throw exists(path);
  96. await this.write(path, text || "");
  97. };
  98. ​
  99. DiskProvider.prototype.createDir = async function (path) {
  100. if (await this.exists(path)) throw exists(path);
  101. await this._dir(path, true);
  102. };
  103. ​
  104. DiskProvider.prototype.remove = async function (path) {
  105. var parent = await this._dir(util.dirname(path));
  106. await parent.removeEntry(util.basename(path), { recursive: true });
  107. };
  108. ​
  109. DiskProvider.prototype._copy = async function (from, to, kind) {
  110. if (kind === "file") return this.write(to, await this.readFile(from));
  111. await this._dir(to, true);
  112. for (var e of await this.list(from)) await this._copy(util.join(from, e.name), util.join(to, e.name), e.kind);
  113. };
  114. ​
  115. DiskProvider.prototype.rename = async function (path, newName, kind) {
  116. var target = util.join(util.dirname(path), newName);
  117. if (target === path) return target;
  118. if (target.toLowerCase() !== path.toLowerCase() && await this.exists(target)) throw exists(target);
  119. var h = await this._handle(path, kind);
  120. if (typeof h.move === "function") {
  121. try { await h.move(newName); return target; } catch (e) { }
  122. }
  123. await this._copy(path, target, kind);
  124. await this.remove(path);
  125. return target;
  126. };
  127. ​
  128. DiskProvider.prototype.move = async function (path, destDir, kind) {
  129. var target = util.join(destDir, util.basename(path));
  130. if (target === path) return target;
  131. if (await this.exists(target)) throw exists(target);
  132. var h = await this._handle(path, kind);
  133. if (typeof h.move === "function") {
  134. try {
  135. await h.move(await this._dir(destDir));
  136. if (await this.exists(target)) return target;
  137. } catch (e) { }
  138. }
  139. await this._copy(path, target, kind);
  140. await this.remove(path);
  141. return target;
  142. };
  143. ​
  144. function MemoryProvider(name, files) {
  145. this.name = name;
  146. this.kind = "memory";
  147. this.files = new Map();
  148. this.dirs = new Set();
  149. var self = this;
  150. (files || []).forEach(function (f) {
  151. var rel = (f.webkitRelativePath || f.name).split("/").slice(f.webkitRelativePath ? 1 : 0).join("/");
  152. self.files.set(rel, { file: f, text: null });
  153. self._addDirs(util.dirname(rel));
  154. });
  155. }
  156. ​
  157. MemoryProvider.prototype._addDirs = function (dir) {
  158. this._tree = null;
  159. while (dir) { this.dirs.add(dir); dir = util.dirname(dir); }
  160. };
  161. ​
  162. MemoryProvider.prototype._buildTree = function () {
  163. var tree = new Map();
  164. function add(path, kind) {
  165. var dir = util.dirname(path);
  166. if (!tree.has(dir)) tree.set(dir, new Map());
  167. tree.get(dir).set(util.basename(path), kind);
  168. }
  169. this.dirs.forEach(function (d) { add(d, "dir"); });
  170. this.files.forEach(function (v, p) { add(p, "file"); });
  171. this._tree = tree;
  172. return tree;
  173. };
  174. ​
  175. MemoryProvider.prototype.list = async function (path) {
  176. var children = (this._tree || this._buildTree()).get(path || "");
  177. var out = [];
  178. if (children) children.forEach(function (kind, name) { out.push({ name: name, kind: kind }); });
  179. return sortEntries(out);
  180. };
  181. ​
  182. MemoryProvider.prototype.readFile = async function (path) {
  183. var e = this.files.get(path);
  184. if (!e) throw notFound(path);
  185. if (e.text != null) return new File([e.text], util.basename(path), { type: MIME[util.ext(path)] || "text/plain" });
  186. return e.file;
  187. };
  188. ​
  189. MemoryProvider.prototype.readText = async function (path) {
  190. var e = this.files.get(path);
  191. if (!e) throw notFound(path);
  192. return e.text != null ? e.text : e.file.text();
  193. };
  194. ​
  195. MemoryProvider.prototype.write = async function (path, text) {
  196. this._tree = null;
  197. this.files.set(path, { file: null, text: text });
  198. this._addDirs(util.dirname(path));
  199. };
  200. ​
  201. MemoryProvider.prototype.exists = async function (path) {
  202. return this.files.has(path) || this.dirs.has(path);
  203. };
  204. ​
  205. MemoryProvider.prototype.createFile = async function (path, text) {
  206. if (await this.exists(path)) throw exists(path);
  207. await this.write(path, text || "");
  208. };
  209. ​
  210. MemoryProvider.prototype.createDir = async function (path) {
  211. if (await this.exists(path)) throw exists(path);
  212. this._addDirs(path);
  213. };
  214. ​
  215. MemoryProvider.prototype._move = function (path, target) {
  216. var self = this, prefix = path + "/";
  217. this._tree = null;
  218. if (this.files.has(path)) {
  219. if (target) this.files.set(target, this.files.get(path));
  220. this.files.delete(path);
  221. }
  222. Array.from(this.files.keys()).forEach(function (p) {
  223. if (p.indexOf(prefix) !== 0) return;
  224. if (target) self.files.set(target + "/" + p.slice(prefix.length), self.files.get(p));
  225. self.files.delete(p);
  226. });
  227. Array.from(this.dirs).forEach(function (d) {
  228. if (d !== path && d.indexOf(prefix) !== 0) return;
  229. self.dirs.delete(d);
  230. if (target) self.dirs.add(target + d.slice(path.length));
  231. });
  232. };
  233. ​
  234. MemoryProvider.prototype.remove = async function (path) {
  235. this._move(path, null);
  236. };
  237. ​
  238. MemoryProvider.prototype.rename = async function (path, newName) {
  239. var target = util.join(util.dirname(path), newName);
  240. if (target !== path && await this.exists(target)) throw exists(target);
  241. this._move(path, target);
  242. return target;
  243. };
  244. ​
  245. MemoryProvider.prototype.move = async function (path, destDir) {
  246. var target = util.join(destDir, util.basename(path));
  247. if (target === path) return target;
  248. if (await this.exists(target)) throw exists(target);
  249. this._move(path, target);
  250. this._addDirs(destDir);
  251. return target;
  252. };
  253. ​
  254. var fs = (A.fs = {
  255. provider: null,
  256. supported: typeof window.showDirectoryPicker === "function",
  257. canSaveAs: typeof window.showSaveFilePicker === "function",
  258. isBinary: function (name) { return BINARY.indexOf(util.ext(name)) >= 0; },
  259. isImage: function (name) { return IMAGE.indexOf(util.ext(name)) >= 0; },
  260. mime: function (name) { return MIME[util.ext(name)] || "application/octet-stream"; },
  261. DiskProvider: DiskProvider,
  262. MemoryProvider: MemoryProvider
  263. });
  264. ​
  265. var allFiles = null;
  266. ​
  267. function walkAll(provider, max) {
  268. return new Promise(function (resolve) {
  269. var out = [], queue = [""], active = 0, done = false;
  270. function finish() {
  271. if (done) return;
  272. done = true;
  273. resolve(out.sort(collator.compare));
  274. }
  275. function visit(dir) {
  276. active++;
  277. provider.list(dir).then(function (entries) {
  278. entries.forEach(function (e) {
  279. if (e.kind === "dir") {
  280. if (!dir && e.name === fs.PRIVATE_DIR && !fs.includePrivate()) return;
  281. if (HIDDEN_DIRS.indexOf(e.name) < 0) queue.push(util.join(dir, e.name));
  282. } else if (HIDDEN_FILES.indexOf(e.name) < 0 && out.length < max) {
  283. out.push(util.join(dir, e.name));
  284. }
  285. });
  286. }, function () { }).then(function () {
  287. active--;
  288. pump();
  289. });
  290. }
  291. function pump() {
  292. while (active < 3 && queue.length && out.length < max) visit(queue.shift());
  293. if (!active && (!queue.length || out.length >= max)) finish();
  294. }
  295. pump();
  296. });
  297. }
  298. ​
  299. fs.allFiles = function () {
  300. var provider = fs.provider;
  301. if (!provider) return Promise.resolve([]);
  302. if (!allFiles || allFiles.provider !== provider) {
  303. var promise = walkAll(provider, 50000);
  304. allFiles = { provider: provider, promise: promise };
  305. }
  306. return allFiles.promise;
  307. };
  308. ​
  309. fs.invalidateIndex = function () {
  310. allFiles = null;
  311. };
  312. ​
  313. fs.HIDDEN_DIRS = HIDDEN_DIRS;
  314. fs.HIDDEN_FILES = HIDDEN_FILES;
  315. fs.PRIVATE_DIR = ".private";
  316. fs.includePrivate = function () { return false; };
  317. ​
  318. A.on("files-changed", fs.invalidateIndex);
  319. ​
  320. fs.setProvider = function (provider) {
  321. fs.provider = provider;
  322. allFiles = null;
  323. if (provider) setTimeout(function () { if (fs.provider === provider) fs.allFiles(); }, 1500);
  324. if (provider && provider.kind === "disk") A.idb.set("lastRoot", provider.root);
  325. A.emit("workspace", provider);
  326. };
  327. ​
  328. fs.pickFolder = async function () {
  329. if (fs.supported) {
  330. try {
  331. return new DiskProvider(await window.showDirectoryPicker({ id: "athera-root", mode: "readwrite" }));
  332. } catch (e) {
  333. if (e.name === "AbortError") return null;
  334. throw e;
  335. }
  336. }
  337. var files = await pickFiles({ directory: true });
  338. if (!files.length) return null;
  339. var rootName = (files[0].webkitRelativePath || "").split("/")[0] || "Folder";
  340. return new MemoryProvider(rootName, files);
  341. };
  342. ​
  343. fs.lastFolder = async function () {
  344. if (!fs.supported) return null;
  345. var h = await A.idb.get("lastRoot");
  346. return h && h.kind === "directory" ? h : null;
  347. };
  348. ​
  349. fs.grant = async function (handle) {
  350. var opts = { mode: "readwrite" };
  351. if ((await handle.queryPermission(opts)) === "granted") return true;
  352. return (await handle.requestPermission(opts)) === "granted";
  353. };
  354. ​
  355. fs.openFiles = async function () {
  356. if (typeof window.showOpenFilePicker === "function") {
  357. var handles;
  358. try {
  359. handles = await window.showOpenFilePicker({ multiple: true, id: "athera-files" });
  360. } catch (e) {
  361. if (e.name === "AbortError") return [];
  362. throw e;
  363. }
  364. return Promise.all(handles.map(async function (h) {
  365. return { name: h.name, handle: h, file: await h.getFile() };
  366. }));
  367. }
  368. return (await pickFiles({ multiple: true })).map(function (f) { return { name: f.name, handle: null, file: f }; });
  369. };
  370. ​
  371. fs.writeHandle = async function (handle, text) {
  372. if (handle.requestPermission && (await handle.requestPermission({ mode: "readwrite" })) !== "granted") {
  373. throw new Error(A.t("fs.no_permission"));
  374. }
  375. var w = await handle.createWritable();
  376. await w.write(text);
  377. await w.close();
  378. };
  379. ​
  380. fs.saveAs = async function (name, text) {
  381. if (fs.canSaveAs) {
  382. try {
  383. var h = await window.showSaveFilePicker({ suggestedName: name, id: "athera-save" });
  384. await fs.writeHandle(h, text);
  385. return h;
  386. } catch (e) {
  387. if (e.name === "AbortError") return undefined;
  388. throw e;
  389. }
  390. }
  391. fs.download(name, text);
  392. return null;
  393. };
  394. ​
  395. fs.download = function (name, data, type) {
  396. var blob = data instanceof Blob ? data : new Blob([data], { type: type || "text/plain;charset=utf-8" });
  397. var url = URL.createObjectURL(blob);
  398. var a = util.el("a", { href: url, download: name });
  399. document.body.appendChild(a);
  400. a.click();
  401. a.remove();
  402. setTimeout(function () { URL.revokeObjectURL(url); }, 2000);
  403. };
  404. ​
  405. fs.pickFiles = pickFiles;
  406. ​
  407. function pickFiles(opts) {
  408. return new Promise(function (resolve) {
  409. var input = util.el("input", { type: "file", accept: opts.accept || null, style: "display:none" });
  410. input.multiple = !!(opts.multiple || opts.directory);
  411. if (opts.directory) input.webkitdirectory = true;
  412. var settled = false;
  413. function finish(list) {
  414. if (settled) return;
  415. settled = true;
  416. input.remove();
  417. resolve(list);
  418. }
  419. input.addEventListener("change", function () { finish(Array.from(input.files || [])); });
  420. input.addEventListener("cancel", function () { finish([]); });
  421. document.body.appendChild(input);
  422. input.click();
  423. });
  424. }
  425. })();
  426. ​