index.htm 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <!--
  3. Important:
  4. If you use the gzipped or `INCLUDE_FALLBACK_INDEX_HTM` options, please remember
  5. to rerun the `reduce_index.sh` script located in the `extras` subfolder and recompile
  6. the sketch after each change to this file.
  7. -->
  8. <html lang="en">
  9. <head>
  10. <title>File manager</title>
  11. <style type="text/css" media="screen">
  12. body {
  13. font-size: 12px;
  14. font-family: Verdana, Arial, Sans-serif;
  15. }
  16. .contextMenu {
  17. z-index: 300;
  18. position: absolute;
  19. left: 5px;
  20. border: 1px solid #444;
  21. background-color: #F5F5F5;
  22. display: none;
  23. box-shadow: 0 0 10px rgba( 0, 0, 0, .4 );
  24. font-size: 11px;
  25. font-weight: bold;
  26. }
  27. .contextMenu ul {
  28. list-style: none;
  29. top: 0;
  30. left: 0;
  31. margin: 0;
  32. padding: 0;
  33. }
  34. .contextMenu li {
  35. position: relative;
  36. min-width: 60px;
  37. cursor: pointer;
  38. }
  39. .contextMenu span {
  40. color: #444;
  41. display: inline-block;
  42. padding: 6px;
  43. }
  44. .contextMenu li:hover { background: #444; }
  45. .contextMenu li:hover span { color: #EEE; }
  46. .css-treeview ul, .css-treeview li {
  47. padding: 0;
  48. margin: 0;
  49. list-style: none;
  50. }
  51. .css-treeview input {
  52. position: absolute;
  53. opacity: 0;
  54. }
  55. .css-treeview {
  56. font-size: 11px;
  57. -moz-user-select: none;
  58. -webkit-user-select: none;
  59. user-select: none;
  60. }
  61. .css-treeview span {
  62. color: #00f;
  63. cursor: pointer;
  64. }
  65. .css-treeview span:hover {
  66. text-decoration: underline;
  67. }
  68. .css-treeview input + label + ul {
  69. margin: 0 0 0 22px;
  70. }
  71. .css-treeview input ~ ul {
  72. display: none;
  73. }
  74. .css-treeview label, .css-treeview label::before {
  75. cursor: pointer;
  76. }
  77. .css-treeview input:disabled + label {
  78. cursor: default;
  79. opacity: .6;
  80. }
  81. .css-treeview input:checked:not(:disabled) ~ ul {
  82. display: block;
  83. }
  84. .css-treeview label, .css-treeview span, .css-treeview label::before {
  85. background: url(" data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAACgCAMAAAAy5xwmAAAAb1BMVEVHcEyWm55WW2E6QUdAQEBiaG1jaG7///8vNj3KzM7CxMbm5ufMzc/Y2dqxtLaGio58gYWJjZFRVFZJTE/Lzc+vsbNdXV74+PhvdHlsbW2kp6q7vLzy8vMuNTzf39+ho6UyOUCFhYWUl5nv7+/p6ekQi/GRAAAAAXRSTlMAQObYZgAAASRJREFUSMftk9tywiAQhoUAhVAwJpqDRqfavv8zluNKkurEjrY3+e74JizLn2W1miAKxphOBMeUYq6uH/A3A66YpRBRqJZaMI8iwsV/CdM6A2xj5nIUsK0/iTUPrGNm0MUDIkeG/J54uOiksb9hXh55PhIIjfKgdJTHSEy2/FD06Xmod8NOwrrwFUsQmXZHZhhekHBiByYIoaIJAjP8USWiCA8KhEW8UGT7KPaZExsObHyrUgTkjTz8liPXwzwEB+OPFVxHE8X2ckRByLaVyhVKxP27KN+nAtH7Rvur2Dr621tekMes+WiG86Hr6jKYj+7Q1Kd0PpxI58NsQdN/25zlQDQdKb9AnM6fHSGkPsQaJamIpQzCrywhD1iT2XksLCws/IZv8Zof7t25YlkAAAAASUVORK5CYII=") no-repeat;
  86. }
  87. .css-treeview label, .css-treeview span, .css-treeview label::before, .css-treeview span::before {
  88. display: inline-block;
  89. height: 16px;
  90. line-height: 16px;
  91. vertical-align: middle;
  92. }
  93. .css-treeview label {
  94. background-position: 18px 0; /* folder icon */
  95. }
  96. .css-treeview span {
  97. background-position: 18px -48px; /* generic file icon */
  98. }
  99. .css-treeview span.txt {
  100. background-position: 18px -64px; /* text file icon */
  101. }
  102. .css-treeview span.img {
  103. background-position: 18px -80px; /* image file icon */
  104. }
  105. .css-treeview label::before {
  106. content: "";
  107. width: 16px;
  108. margin: 0 22px 0 0;
  109. vertical-align: middle;
  110. background-position: 0 -32px; /* expand icon */
  111. }
  112. .css-treeview span::before {
  113. content: "";
  114. width: 16px;
  115. margin: 0 22px 0 0;
  116. }
  117. .css-treeview input:checked + label::before {
  118. background-position: 0 -16px; /* collapse icon */
  119. }
  120. /* webkit adjacent element selector bugfix */
  121. @media screen and (-webkit-min-device-pixel-ratio:0)
  122. {
  123. .css-treeview{
  124. -webkit-animation: webkit-adjacent-element-selector-bugfix infinite 1s;
  125. }
  126. @-webkit-keyframes webkit-adjacent-element-selector-bugfix
  127. {
  128. from {
  129. padding: 0;
  130. }
  131. to {
  132. padding: 0;
  133. }
  134. }
  135. }
  136. #header {
  137. position: absolute;
  138. top: 0;
  139. right: 0;
  140. left: 0;
  141. height:24px;
  142. padding: 1px 1px 0px 10px;
  143. background-color: #444;
  144. color:#EEE;
  145. }
  146. #tree {
  147. position: absolute;
  148. top: 25px;
  149. bottom: 0;
  150. left: 0;
  151. width: 20%;
  152. padding: 8px;
  153. }
  154. #editor, #preview {
  155. position: absolute;
  156. top: 25px;
  157. right: 0;
  158. bottom: 0;
  159. left: 20%;
  160. }
  161. #preview {
  162. background-color: #EEE;
  163. padding:5px;
  164. }
  165. #status {
  166. position: absolute;
  167. top: 3px;
  168. right: 10px;
  169. font-size: 15px;
  170. }
  171. #fsMeter {
  172. width:100px;
  173. padding-bottom:2px;
  174. }
  175. #warning {
  176. height:100%;
  177. background-color:orange;
  178. color:black;
  179. }
  180. .tooltip {
  181. position: absolute;
  182. z-index: 2; /* must be above editor which is at 1 */
  183. right:0px;
  184. top:20px;
  185. visibility: hidden;
  186. background-color: white;
  187. color: black;
  188. text-align: center;
  189. border: 1px solid #000;
  190. padding: 3px;
  191. font-size: 10px;
  192. }
  193. #warning:hover .tooltip {
  194. visibility: visible;
  195. }
  196. #loading {
  197. position:absolute;
  198. // note: changing between block and none cancels the opacity anim, so we move it in and out of screen instead by changing the top value
  199. // maybe see https://www.impressivewebs.com/animate-display-block-none/ for another approach
  200. display:block;
  201. top: -100vh;
  202. left: 0;
  203. width: 100vw;
  204. height: 100vh;
  205. z-index: 100;
  206. background-color: rgba(0, 0, 0, 0.5);
  207. opacity: 0;
  208. transition: opacity 500ms ease-in-out;
  209. }
  210. #loading.shown {
  211. top: 0;
  212. opacity: 1;
  213. }
  214. #loading-msg {
  215. display: inline-block;
  216. position: absolute;
  217. top: 0px;
  218. left: 50%;
  219. transform: translateX(-50%);
  220. color:white;
  221. font-size: 32px;
  222. }
  223. @keyframes spinner-anim {
  224. 0% {
  225. transform: rotate(0deg);
  226. }
  227. 100% {
  228. transform: rotate(360deg);
  229. }
  230. }
  231. /* :not(:required) hides this rule from IE9 and below */
  232. .spinner-anim:not(:required) {
  233. display: inline-block;
  234. position: relative;
  235. top: 50%;
  236. left: 50%;
  237. transform: translate(-50%, -50%);
  238. animation: spinner-anim 1s infinite linear;
  239. border: 16px solid #eee;
  240. border-right-color: transparent;
  241. border-radius: 32px;
  242. box-sizing: border-box;
  243. overflow: hidden;
  244. text-indent: -9999px;
  245. width: 64px;
  246. height: 64px;
  247. }
  248. </style>
  249. <script>
  250. var tree; // needed by editor to refresh file size on save
  251. var fsInfo; // needed to change refreshPath behaviour on SPIFFS
  252. /////////////////////////
  253. // UTILS
  254. function setLoading(show, message) {
  255. if (message) console.log(message);
  256. document.getElementById("loading-msg").innerHTML = message?message:"";
  257. if (show) document.getElementById("loading").classList.add("shown");
  258. else document.getElementById("loading").classList.remove("shown");
  259. document.body.style.cursor = show?"wait":"default";
  260. }
  261. function readableSize(bytes) {
  262. if (bytes < 1024) return bytes + " B";
  263. var units = [' KiB', ' MiB', ' GiB', ' TiB', 'PiB'];
  264. var i = -1;
  265. do {
  266. bytes = bytes / 1024;
  267. i++;
  268. } while (bytes > 1024);
  269. return bytes.toFixed(2) + units[i];
  270. }
  271. function refreshStatus(){
  272. document.getElementById("status").innerHTML = "(refreshing...)";
  273. var xmlHttp = new XMLHttpRequest();
  274. xmlHttp.onload = function() {
  275. if (xmlHttp.status != 200) showHttpError(xmlHttp);
  276. else {
  277. fsInfo = JSON.parse(xmlHttp.responseText);
  278. var status = fsInfo.type + " - ";
  279. if (fsInfo.isOk) {
  280. var percent = (1+Math.round(99*fsInfo.usedBytes/fsInfo.totalBytes)); // fake to see the "used" bar in any case
  281. var text = readableSize(fsInfo.totalBytes - fsInfo.usedBytes) + " free of " + readableSize(fsInfo.totalBytes);
  282. status += "<meter id='fsMeter' min='0' optimum='0'low='90' high='95' max='100' value='" + percent + "' title='" + text + "'>" + text + "</meter>"
  283. if (fsInfo.unsupportedFiles) {
  284. status += " <span id='warning'>WARNING<span class='tooltip'>"
  285. + "Filesystem&nbsp;contains&nbsp;unsupported&nbsp;filenames:<br/>"
  286. + fsInfo.unsupportedFiles
  287. + "</span></span>";
  288. }
  289. }
  290. else {
  291. status += "<span style='background-color:red;color:white;font-weight:bold'>INIT ERROR !</span>";
  292. }
  293. document.getElementById("status").innerHTML = status;
  294. if (fsInfo.type != "SPIFFS") {
  295. document.getElementById("mkdir").style.display = "inline";
  296. }
  297. }
  298. };
  299. xmlHttp.open("GET", "/status", true);
  300. xmlHttp.send(null);
  301. }
  302. function showHttpError(request) {
  303. alert("ERROR: [" + request.status+"] " + request.responseText);
  304. }
  305. function canLoadNewContents() {
  306. // The fact the save button is enabled indicates the editor has unsaved changes
  307. if (document.getElementById("saveBtn").disabled) return true;
  308. if (confirm("Changes to your document will be lost if you continue")) {
  309. enableSaveDiscardBtns(false);
  310. return true;
  311. }
  312. return false;
  313. }
  314. function enableSaveDiscardBtns(enabled) {
  315. document.getElementById("saveBtn").disabled = !enabled;
  316. document.getElementById("discardBtn").disabled = !enabled;
  317. }
  318. /*
  319. * Returns the parent folder of a given path
  320. * "" > ""
  321. * "/" > ""
  322. * "a" > ""
  323. * "/a" > ""
  324. * "a/" > ""
  325. * "/a/" > ""
  326. * "a/b" > "/a"
  327. * "/a/b" > "/a"
  328. * "a/b/" > "/a"
  329. * "/a/b/" > "/a"
  330. */
  331. function getParentFolder(path) {
  332. if (!path.startsWith("/")) path = "/" + path;
  333. if (path.endsWith("/")) path = path.slice(0, -1);
  334. return path.substring(0, path.lastIndexOf("/"));
  335. }
  336. /////////////////////////
  337. // HEADER with uploader, buttons ans status
  338. function createHeader(element, tree, editor){
  339. var header = document.getElementById(element);
  340. var xmlHttp;
  341. var fileSelector = document.createElement("input");
  342. fileSelector.type = "file";
  343. fileSelector.multiple = false;
  344. fileSelector.name = "data";
  345. header.appendChild(fileSelector);
  346. var pathInput = document.createElement("input");
  347. pathInput.id = "pathInput";
  348. pathInput.type = "text";
  349. pathInput.name = "path";
  350. pathInput.defaultValue = "/";
  351. header.appendChild(pathInput);
  352. var upload = document.createElement("button");
  353. upload.innerHTML = "Upload";
  354. header.appendChild(upload);
  355. var mkdir = document.createElement("button");
  356. mkdir.id = "mkdir";
  357. mkdir.style.display = "none";
  358. mkdir.innerHTML = "MkDir";
  359. header.appendChild(mkdir);
  360. var mkfile = document.createElement("button");
  361. mkfile.innerHTML = "MkFile";
  362. header.appendChild(mkfile);
  363. var editorButtons = document.createElement("span");
  364. editorButtons.id = "editorButtons";
  365. editorButtons.style.display = "none";
  366. header.appendChild(editorButtons);
  367. var save = document.createElement("button");
  368. save.id = "saveBtn";
  369. save.innerHTML = "Save";
  370. save.style.marginLeft = "30px";
  371. save.disabled = true;
  372. editorButtons.appendChild(save);
  373. var discard = document.createElement("button");
  374. discard.id = "discardBtn";
  375. discard.innerHTML = "Discard";
  376. discard.disabled = true;
  377. editorButtons.appendChild(discard);
  378. var help = document.createElement("button");
  379. help.id = "helpBtn";
  380. help.innerHTML = "?";
  381. editorButtons.appendChild(help);
  382. var status = document.createElement("span");
  383. status.id = "status";
  384. status.innerHTML = "(loading)";
  385. header.appendChild(status);
  386. fileSelector.onchange = function(e){ // A file has been selected
  387. if (fileSelector.files.length === 0) return;
  388. var filename = fileSelector.files[0].name;
  389. if (mustFormat83()) {
  390. filename = to83(filename);
  391. }
  392. if (!pathInput.value.startsWith("/")) pathInput.value = "/" + pathInput.value;
  393. pathInput.value = getParentFolder(pathInput.value) + "/" + filename;
  394. }
  395. upload.onclick = function(e) {
  396. if (fileSelector.files.length === 0) return;
  397. tree.httpUpload(fileSelector.files[0], pathInput.value);
  398. }
  399. function mustFormat83() {
  400. return false; // TODO: if needed, test fsInfo.type (and fatType ?)
  401. }
  402. function to83(filename) {
  403. var ext = /(?:\.([^.]+))?$/.exec(filename)[1];
  404. var name = /(.*)\.[^.]+$/.exec(filename)[1];
  405. if (name !== undefined){
  406. if (name.length > 8) name = name.substring(0, 8);
  407. filename = name;
  408. }
  409. if (ext !== undefined){
  410. if (ext === "html") ext = "htm";
  411. else if (ext === "jpeg") ext = "jpg";
  412. filename = filename + "." + ext;
  413. }
  414. return filename;
  415. }
  416. mkfile.onclick = function(e){
  417. var path = pathInput.value.trim();
  418. if (path === "") alert("A filename must be given");
  419. else if (path.endsWith("/")) alert("Filenames must not end with a '/' character");
  420. else tree.httpCreate(path);
  421. };
  422. mkdir.onclick = function(e){
  423. var path = pathInput.value.trim();
  424. if (path === "") alert("A folder name must be given");
  425. else {
  426. if (!path.endsWith("/")) path = path + "/";
  427. tree.httpCreate(path);
  428. }
  429. };
  430. save.onclick = function(e){
  431. editor.save();
  432. }
  433. discard.onclick = function(e){
  434. editor.discard();
  435. }
  436. help.onclick = function(e){
  437. editor.showShortcuts();
  438. }
  439. }
  440. /////////////////////////
  441. // FILE TREE
  442. function createTree(element, editor){
  443. var preview = document.getElementById("preview");
  444. var treeRoot = document.createElement("div");
  445. treeRoot.className = "css-treeview";
  446. treeRoot.id = "/";
  447. document.getElementById(element).appendChild(treeRoot);
  448. function loadDownload(path){
  449. document.getElementById("download-frame").src = path+"?download=true";
  450. }
  451. function loadImgPreview(path){
  452. document.getElementById("pathInput").value = path;
  453. document.getElementById("editor").style.display = "none";
  454. document.getElementById("editorButtons").style.display = "none";
  455. preview.style.display = "block";
  456. preview.innerHTML = "<img src='"+path+"' style='max-width:100%; max-height:100%; margin:auto; display:block;' />";
  457. }
  458. // Fall back code used when ace.js is not available (neither online or local)
  459. function loadTxtPreview(path){
  460. document.getElementById("pathInput").value = path;
  461. document.getElementById("editor").style.display = "none";
  462. document.getElementById("editorButtons").style.display = "none";
  463. preview.style.display = "block";
  464. preview.innerHTML = "<span style='color:red;'>Ace editor could not be loaded from the internet nor from /edit/ace.js . Defaulting to text viewer...</span><pre id='txtContents' style='overflow: auto;'></pre>";
  465. var xhr = new XMLHttpRequest();
  466. xhr.onload = function () {
  467. document.getElementById('txtContents').textContent = this.responseText;
  468. };
  469. xhr.open('GET', path);
  470. xhr.send();
  471. }
  472. this.clearMainPanel = function() {
  473. document.getElementById("editor").style.display = "none";
  474. document.getElementById("editorButtons").style.display = "none";
  475. preview.style.display = "block";
  476. preview.innerHTML = "<div style='text-align:center'>(file not found or format not supported)</div>";
  477. }
  478. function isTextFile(path){
  479. var ext = /(?:\.([^.]+))?$/.exec(path)[1];
  480. if (ext !== undefined){
  481. switch(ext.toLowerCase()){
  482. case "txt":
  483. case "htm":
  484. case "html":
  485. case "js":
  486. case "json":
  487. case "c":
  488. case "h":
  489. case "cpp":
  490. case "css":
  491. case "xml":
  492. return true;
  493. }
  494. }
  495. return false;
  496. }
  497. function isImageFile(path){
  498. var ext = /(?:\.([^.]+))?$/.exec(path)[1];
  499. if (ext !== undefined){
  500. switch(ext.toLowerCase()){
  501. case "png":
  502. case "jpg":
  503. case "jpeg":
  504. case "gif":
  505. case "ico":
  506. return true;
  507. }
  508. }
  509. return false;
  510. }
  511. function fillFolderMenu(el, path){
  512. var list = document.createElement("ul");
  513. el.appendChild(list);
  514. var action = document.createElement("li");
  515. list.appendChild(action);
  516. var isChecked = document.getElementById(path).childNodes[0].checked;
  517. var expnd = document.createElement("li");
  518. list.appendChild(expnd);
  519. if (isChecked){
  520. expnd.innerHTML = "<span>Collapse</span>";
  521. expnd.onclick = function(e){
  522. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  523. document.getElementById(path).childNodes[0].checked = false;
  524. };
  525. var refrsh = document.createElement("li");
  526. list.appendChild(refrsh);
  527. refrsh.innerHTML = "<span>Refresh</span>";
  528. refrsh.onclick = function(e){
  529. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  530. httpList(path);
  531. };
  532. }
  533. else {
  534. expnd.innerHTML = "<span>Expand</span>";
  535. expnd.onclick = function(e){
  536. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  537. document.getElementById(path).childNodes[0].checked = true;
  538. httpList(path);
  539. };
  540. }
  541. var renFolder = document.createElement("li");
  542. list.appendChild(renFolder);
  543. renFolder.innerHTML = "<span>Rename/Move</span>";
  544. renFolder.onclick = function(e){
  545. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  546. var newPath = prompt("Rename " + path + " to", path);
  547. if (newPath != null && newPath != path) {
  548. httpRename(path, newPath);
  549. }
  550. };
  551. var delFolder = document.createElement("li");
  552. list.appendChild(delFolder);
  553. delFolder.innerHTML = "<span>Delete</span>";
  554. delFolder.onclick = function(e){
  555. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  556. httpDelete(path);
  557. };
  558. }
  559. function fillFileMenu(el, path){
  560. var list = document.createElement("ul");
  561. el.appendChild(list);
  562. var action = document.createElement("li");
  563. list.appendChild(action);
  564. if (isTextFile(path)){
  565. if (typeof ace == "undefined") {
  566. // Could not load editor
  567. action.innerHTML = "<span>View</span>";
  568. action.onclick = function(e){
  569. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  570. if (canLoadNewContents()) loadTxtPreview(path);
  571. };
  572. }
  573. else {
  574. action.innerHTML = "<span>Edit</span>";
  575. action.onclick = function(e){
  576. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  577. if (canLoadNewContents()) editor.loadUrl(path);
  578. };
  579. }
  580. }
  581. else if (isImageFile(path)){
  582. action.innerHTML = "<span>Preview</span>";
  583. action.onclick = function(e){
  584. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  585. if (canLoadNewContents()) loadImgPreview(path);
  586. };
  587. }
  588. var download = document.createElement("li");
  589. list.appendChild(download);
  590. download.innerHTML = "<span>Download</span>";
  591. download.onclick = function(e){
  592. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  593. loadDownload(path);
  594. };
  595. var renFile = document.createElement("li");
  596. list.appendChild(renFile);
  597. renFile.innerHTML = "<span>Rename/Move</span>";
  598. renFile.onclick = function(e){
  599. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  600. var newPath = prompt("Rename " + path + " to", path);
  601. if (newPath != null && newPath != path) {
  602. httpRename(path, newPath);
  603. }
  604. };
  605. var delFile = document.createElement("li");
  606. list.appendChild(delFile);
  607. delFile.innerHTML = "<span>Delete</span>";
  608. delFile.onclick = function(e){
  609. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
  610. httpDelete(path);
  611. };
  612. }
  613. function showContextMenu(e, path, isfile){
  614. var divContext = document.createElement("div");
  615. var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
  616. var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;
  617. var left = e.clientX + scrollLeft;
  618. var top = e.clientY + scrollTop;
  619. divContext.className = 'contextMenu';
  620. divContext.style.display = 'block';
  621. divContext.style.left = left + 'px';
  622. divContext.style.top = top + 'px';
  623. if (isfile) fillFileMenu(divContext, path);
  624. else fillFolderMenu(divContext, path);
  625. document.body.appendChild(divContext);
  626. var width = divContext.offsetWidth;
  627. var height = divContext.offsetHeight;
  628. divContext.onmouseout = function(e){
  629. if (e.clientX < left || e.clientX > (left + width) || e.clientY < top || e.clientY > (top + height)){
  630. if (document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(divContext);
  631. }
  632. };
  633. }
  634. function createTreeLeaf(parentPath, name, size){
  635. var leaf = document.createElement("li");
  636. leaf.id = ((parentPath == "/")?"":parentPath)+"/"+name;
  637. var span = document.createElement("span");
  638. if (isTextFile(name)) span.classList.add("txt");
  639. else if (isImageFile(name)) span.classList.add("img");
  640. span.innerHTML = name + " <i>(" + readableSize(size) + ")</i>";
  641. leaf.appendChild(span);
  642. leaf.onclick = function(e){
  643. attemptLoad(leaf.id);
  644. };
  645. leaf.oncontextmenu = function(e){
  646. e.preventDefault();
  647. e.stopPropagation();
  648. showContextMenu(e, leaf.id, true);
  649. };
  650. return leaf;
  651. }
  652. function createTreeBranch(parentPath, name, disabled){
  653. var leaf = document.createElement("li");
  654. leaf.id = ((parentPath == "/")?"":parentPath)+"/"+name;
  655. var check = document.createElement("input");
  656. check.type = "checkbox";
  657. if (typeof disabled !== "undefined" && disabled) check.disabled = "disabled";
  658. leaf.appendChild(check);
  659. var label = document.createElement("label");
  660. label.textContent = name;
  661. leaf.appendChild(label);
  662. check.onchange = function(e){
  663. if (check.checked){
  664. httpList(leaf.id);
  665. }
  666. };
  667. label.onclick = function(e){
  668. if (!check.checked){
  669. check.checked = true;
  670. httpList(leaf.id);
  671. }
  672. else {
  673. check.checked = false;
  674. }
  675. };
  676. leaf.oncontextmenu = function(e){
  677. e.preventDefault();
  678. e.stopPropagation();
  679. showContextMenu(e, leaf.id, false);
  680. }
  681. return leaf;
  682. }
  683. function addFileNodes(parentPath, items){
  684. items.sort(function(a, b) {
  685. if (a.type == b.type) {
  686. return a.name.localeCompare(b.name); // a before z
  687. }
  688. else {
  689. return a.type.localeCompare(b.type); // dir before file
  690. }
  691. });
  692. var list = document.createElement("ul");
  693. document.getElementById(parentPath).appendChild(list);
  694. var ll = items.length;
  695. for(var i = 0; i < ll; i++){
  696. var item = items[i];
  697. var itemEl;
  698. if (item.type === "file") itemEl = createTreeLeaf(parentPath, item.name, item.size);
  699. else itemEl = createTreeBranch(parentPath, item.name);
  700. list.appendChild(itemEl);
  701. }
  702. }
  703. this.attemptLoad = function(path) {
  704. console.log("Attempting load of '" + path + "'...");
  705. document.getElementById("pathInput").value = path;
  706. if (canLoadNewContents()) {
  707. if (isTextFile(path)) {
  708. if (typeof ace == "undefined") {
  709. loadTxtPreview(path);
  710. }
  711. else {
  712. editor.loadUrl(path);
  713. }
  714. }
  715. else if (isImageFile(path)) loadImgPreview(path);
  716. else clearMainPanel();
  717. }
  718. }
  719. /*
  720. * Refresh the given path, e.g. "/a/b/c/d"
  721. * It means we have to make sure d is already displayed
  722. * If not, we get to its parent first (c), if open, and so on (b, a).
  723. * Once we have found an ancestor, we refresh it, then we must come back to where we started, refreshing nodes on our way down.
  724. * This is done by pushing all paths to be refreshed in an array that will be pop'd in the callback function
  725. */
  726. this.refreshPath = function(path){
  727. if (fsInfo.type == "SPIFFS") {
  728. // on SPIFFS : No parent node => refresh full tree
  729. console.log("Refreshing '/'...");
  730. httpList("/");
  731. }
  732. else {
  733. console.log("Refreshing '" + path + "'...");
  734. if (path.lastIndexOf("/") == -1){
  735. // No "/" => reset the root
  736. httpList("/");
  737. }
  738. else {
  739. var paths = [];
  740. // Climb the tree until we get to an open node, adding paths to the array
  741. var parentPath = path;
  742. while ((parentPath.lastIndexOf("/") != -1) && !document.getElementById(parentPath)) {
  743. paths.push(parentPath);
  744. parentPath = getParentFolder(parentPath);
  745. }
  746. // If we've reached the top
  747. if (parentPath == "") paths.push("/"); // list the root
  748. else paths.push(parentPath); // otherwise list the last folder
  749. // And list it back down by iterating on collected paths
  750. listPaths(paths);
  751. }
  752. }
  753. }
  754. //////////////////////////////
  755. // HTTP OPERATIONS
  756. // Callbacks
  757. function onListReceived(req, parentPath, remainingPaths) {
  758. return function(){
  759. setLoading(false);
  760. if (req.status != 200) showHttpError(req);
  761. else {
  762. // Remove previous child list, if any
  763. var parentEl = document.getElementById(parentPath);
  764. if (parentEl) {
  765. var lastChild = parentEl.lastElementChild;
  766. if (lastChild && lastChild.tagName == "UL") parentEl.removeChild(lastChild);
  767. }
  768. // And reinsert the received ones instead
  769. addFileNodes(parentPath, JSON.parse(req.responseText));
  770. if (document.getElementById(parentPath).childNodes[0].checked !== undefined) {
  771. document.getElementById(parentPath).childNodes[0].checked = true;
  772. }
  773. // If there are more folders to refresh, go ahead
  774. if (remainingPaths && remainingPaths.length) {
  775. listPaths(remainingPaths);
  776. }
  777. }
  778. }
  779. }
  780. /*
  781. * Callback after a FS operation was performed.
  782. * The "req" param is the http request
  783. * The "path" param is the "affected" (created, moved, renamed, delteted) path, of which the parent must be refreshed
  784. * In case of move/delete, the "target" path is returned in the response, so that it can be refreshed too
  785. * Operation | path (file to be loaded) | req.responseText (between brackets if same as parent of path)
  786. * ---------------+--------------------------+--------------------------------------------------------------
  787. * Create file | created file | (parent of created file)
  788. * Create folder | created folder | (parent of created folder)
  789. * Rename file | target file | (parent of source file)
  790. * Move file | target file | parent of source file, or remaining ancestor
  791. ? Rename folder | target folder | (parent of source folder)
  792. ? Move folder | target folder | parent of source folder, or remaining ancestor
  793. * Delete file | | parent of deleted file, or remaining ancestor
  794. * Delete folder | | parent of deleted folder, or remaining ancestor
  795. */
  796. function onOperationComplete(req, path){
  797. return function(){
  798. setLoading(false);
  799. if (req.status != 200) showHttpError(req);
  800. else {
  801. if (path) {
  802. var parentPath = getParentFolder(path);
  803. // Refresh returned path, if requested and different from path
  804. if (req.responseText && req.responseText != parentPath) {
  805. refreshPath(req.responseText);
  806. }
  807. // Refresh original path
  808. refreshPath(parentPath);
  809. // Try to load given path
  810. attemptLoad(path);
  811. }
  812. else {
  813. // Delete, only refresh returned path
  814. refreshPath(req.responseText);
  815. }
  816. }
  817. refreshStatus();
  818. }
  819. }
  820. // Requests
  821. function httpList(parentPath, remainingPaths){
  822. setLoading(true, "Listing '" + parentPath + "'...");
  823. // Fetch an updated list
  824. xmlHttp = new XMLHttpRequest();
  825. xmlHttp.onload = onListReceived(xmlHttp, parentPath, remainingPaths);
  826. xmlHttp.open("GET", "/list?dir="+parentPath, true);
  827. xmlHttp.send(null);
  828. }
  829. function listPaths(paths) {
  830. var path = paths.pop();
  831. if (path) {
  832. httpList(path, paths);
  833. }
  834. }
  835. this.httpUpload = function(file, path) {
  836. setLoading(true, "Uploading '" + path + "'...");
  837. if (!path.startsWith("/")) path = "/" + path;
  838. xmlHttp = new XMLHttpRequest();
  839. xmlHttp.onload = onOperationComplete(xmlHttp, path);
  840. var formData = new FormData();
  841. formData.append("data", file, path);
  842. xmlHttp.open("POST", "/edit");
  843. xmlHttp.send(formData);
  844. };
  845. this.httpCreate = function(path){
  846. setLoading(true, "Creating '" + path + "'...");
  847. if (!path.startsWith("/")) path = "/" + path;
  848. xmlHttp = new XMLHttpRequest();
  849. xmlHttp.onload = onOperationComplete(xmlHttp, path);
  850. var formData = new FormData();
  851. formData.append("path", path);
  852. xmlHttp.open("PUT", "/edit");
  853. xmlHttp.send(formData);
  854. }
  855. function httpRename(srcPath, dstPath){
  856. setLoading(true, "Renaming '" + srcPath + "' to '" + dstPath + "'...");
  857. if (!dstPath.startsWith("/")) dstPath = "/" + dstPath;
  858. xmlHttp = new XMLHttpRequest();
  859. xmlHttp.onload = onOperationComplete(xmlHttp, dstPath);
  860. var formData = new FormData();
  861. formData.append("path", dstPath);
  862. formData.append("src", srcPath);
  863. xmlHttp.open("PUT", "/edit");
  864. xmlHttp.send(formData);
  865. }
  866. function httpDelete(path) {
  867. setLoading(true, "Deleting '" + path + "'...");
  868. xmlHttp = new XMLHttpRequest();
  869. xmlHttp.onload = onOperationComplete(xmlHttp);
  870. var formData = new FormData();
  871. formData.append("path", path);
  872. xmlHttp.open("DELETE", "/edit");
  873. xmlHttp.send(formData);
  874. }
  875. httpList("/");
  876. return this;
  877. }
  878. /////////////////////////
  879. // ACE EDITOR MANAGEMENT
  880. function createEditor(element, file, lang, theme, type){
  881. function getLangFromFilename(filename){
  882. var lang = "plain";
  883. var ext = /(?:\.([^.]+))?$/.exec(filename)[1];
  884. if (ext !== undefined){
  885. switch(ext){
  886. case "txt": lang = "plain"; break;
  887. case "htm": lang = "html"; break;
  888. case "js": lang = "javascript"; break;
  889. case "c": lang = "c_cpp"; break;
  890. case "cpp": lang = "c_cpp"; break;
  891. case "css":
  892. case "scss":
  893. case "php":
  894. case "html":
  895. case "json":
  896. case "xml":
  897. lang = ext;
  898. }
  899. }
  900. return lang;
  901. }
  902. if (typeof file === "undefined") file = "/index.htm";
  903. if (typeof lang === "undefined"){
  904. lang = getLangFromFilename(file);
  905. }
  906. if (typeof theme === "undefined") theme = "textmate";
  907. if (typeof type === "undefined"){
  908. type = "text/"+lang;
  909. if (lang === "c_cpp") type = "text/plain";
  910. }
  911. var xmlHttp = null;
  912. var editor = ace.edit(element);
  913. function filePosted(){
  914. setLoading(false);
  915. if (xmlHttp.status != 200) showHttpError(xmlHttp);
  916. tree.refreshPath(getParentFolder(file)); // to update size in tree
  917. refreshStatus();
  918. }
  919. function postFile(path, data, type){
  920. setLoading(true, "Saving '" + path + "'...");
  921. xmlHttp = new XMLHttpRequest();
  922. xmlHttp.onload = filePosted;
  923. var formData = new FormData();
  924. formData.append("data", new Blob([data], { type: type }), path);
  925. xmlHttp.open("POST", "/edit");
  926. xmlHttp.send(formData);
  927. }
  928. function fileLoaded(){
  929. setLoading(false);
  930. document.getElementById("preview").style.display = "none";
  931. document.getElementById("editor").style.display = "block";
  932. document.getElementById("editorButtons").style.display = "inline";
  933. if (xmlHttp.status == 200) {
  934. editor.setValue(xmlHttp.responseText);
  935. editor.clearSelection();
  936. enableSaveDiscardBtns(false);
  937. }
  938. else tree.clearMainPanel();
  939. }
  940. function loadFile(path){
  941. setLoading(true, "Loading '" + path + "'...");
  942. xmlHttp = new XMLHttpRequest();
  943. xmlHttp.onload = fileLoaded;
  944. xmlHttp.open("GET", path, true);
  945. xmlHttp.send(null);
  946. }
  947. if (lang !== "plain") editor.getSession().setMode("ace/mode/"+lang);
  948. editor.setTheme("ace/theme/"+theme);
  949. editor.$blockScrolling = Infinity;
  950. editor.getSession().setUseSoftTabs(true);
  951. editor.getSession().setTabSize(2);
  952. editor.setHighlightActiveLine(true);
  953. editor.setShowPrintMargin(false);
  954. editor.commands.addCommand({
  955. name: 'save',
  956. bindKey: {win: 'Ctrl-S', mac: 'Command-S'},
  957. exec: function(editor) {
  958. editor.save();
  959. },
  960. readOnly: false
  961. });
  962. editor.commands.addCommand({
  963. name: "showKeyboardShortcuts",
  964. bindKey: {win: "Ctrl-Alt-h", mac: "Command-Alt-h"},
  965. exec: function(editor) {
  966. editor.showShortcuts();
  967. }
  968. })
  969. editor.session.on('change', function(delta) {
  970. enableSaveDiscardBtns(true);
  971. });
  972. editor.loadUrl = function(path){
  973. document.getElementById("pathInput").value = path;
  974. enableSaveDiscardBtns(false);
  975. file = path;
  976. lang = getLangFromFilename(file);
  977. type = "text/"+lang;
  978. if (lang !== "plain") editor.getSession().setMode("ace/mode/"+lang);
  979. loadFile(file);
  980. }
  981. editor.save = function() {
  982. enableSaveDiscardBtns(false);
  983. postFile(file, editor.getValue()+"", type);
  984. }
  985. editor.discard = function() {
  986. editor.loadUrl(file);
  987. enableSaveDiscardBtns(false);
  988. }
  989. editor.showShortcuts = function() {
  990. ace.config.loadModule("ace/ext/keybinding_menu", function(module) {
  991. module.init(editor);
  992. editor.showKeyboardShortcuts()
  993. });
  994. }
  995. loadFile(file);
  996. return editor;
  997. }
  998. /////////////////////////
  999. // MAIN ENTRY POINT
  1000. function onBodyLoad(){
  1001. var vars = {};
  1002. var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
  1003. if (typeof ace != "undefined") {
  1004. var editor = createEditor("editor", vars.file, vars.lang, vars.theme);
  1005. }
  1006. tree = createTree("tree", editor);
  1007. createHeader("header", tree, editor);
  1008. refreshStatus();
  1009. };
  1010. </script>
  1011. <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.9/ace.js" type="text/javascript" charset="utf-8"></script>
  1012. <script>
  1013. if (typeof ace == "undefined") {
  1014. console.log("Cannot load ace.js from the web, trying local copy");
  1015. var script = document.createElement('script');
  1016. script.src = "/edit/ace.js";
  1017. script.async = false;
  1018. document.head.appendChild(script);
  1019. }
  1020. </script>
  1021. </head>
  1022. <body onload="onBodyLoad();">
  1023. <div id="header"></div>
  1024. <div id="tree"></div>
  1025. <div id="editor"></div>
  1026. <div id="preview" style="display:none;"></div>
  1027. <div id="loading"><span id="loading-msg"></span><br/><div class="spinner-anim">Loading...</div></div>
  1028. <iframe id=download-frame style='display:none;'></iframe>
  1029. </body>
  1030. </html>