Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions wled00/data/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,16 +137,26 @@ function showToast(text, error = false) {
x.style.animation = 'none';
timeout = setTimeout(function(){ x.className = x.className.replace("show", ""); }, 2900);
}
function uploadFile(fileObj, name) {
async function uploadFile(fileObj, name, callback) {
let file = fileObj.files?.[0]; // get first file, "?"" = optional chaining in case no file is selected
if (!file) { callback?.(false); return; }
if (/\.json$/i.test(name)) { // same as name.toLowerCase().endsWith('.json')
try {
const minified = JSON.stringify(JSON.parse(await file.text())); // validate and minify JSON
file = new Blob([minified], { type: file.type || "application/json" });
} catch (err) {
if (!confirm("JSON invalid. Continue?")) { callback?.(false); return; }
// proceed with original file if invalid but user confirms
}
}
var req = new XMLHttpRequest();
req.addEventListener('load', function(){showToast(this.responseText,this.status >= 400)});
req.addEventListener('error', function(e){showToast(e.stack,true);});
req.addEventListener('load', function(){showToast(this.responseText,this.status >= 400); if(callback) callback(this.status < 400);});
req.addEventListener('error', function(e){showToast(e.stack,true); if(callback) callback(false);});
req.open("POST", "/upload");
var formData = new FormData();
formData.append("data", fileObj.files[0], name);
formData.append("data", file, name);
req.send(formData);
fileObj.value = '';
return false;
}
// connect to WebSocket, use parent WS or open new, callback function gets passed the new WS object
function connectWs(onOpen) {
Expand Down
44 changes: 23 additions & 21 deletions wled00/data/edit.htm
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@
<meta name="author" content="DedeHai, based on editor by Me-No-Dev">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"><!-- prevent too much scaling on mobile -->
<link rel="shortcut icon" href="favicon.ico">
<link href="style.css" rel="stylesheet">
<!-- Optional lightweight JSON editor - fallback to textarea if CDN is unavailable -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.4/ace.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.4/mode-json.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.4/theme-monokai.min.js"></script>
<script src="common.js"></script>
<style>
/* Editor-specific styles */
body {
Expand Down Expand Up @@ -113,6 +111,15 @@
@keyframes spin { to { transform: rotate(360deg); } }
</style>
<script>
// load common.js with retry on error
(function loadFiles() {
const l = document.createElement('script');
l.src = 'common.js';
l.onload = () => loadResources(['style.css'], S); // load style.css then call S()
l.onerror = () => setTimeout(loadFiles, 100);
document.head.appendChild(l);
})();

var QueuedRequester = function(){ this.q=[]; this.r=false; this.x=null; }
QueuedRequester.prototype = {
_request: function(req){
Expand Down Expand Up @@ -411,7 +418,7 @@
// Check filename from text field or current file
var pathField = gId("filepath");
var filename = (pathField && pathField.value) ? pathField.value : currentFile;
aceEditor.session.setMode(filename && filename.toLowerCase().endsWith('.json') ? "ace/mode/json" : "ace/mode/text");
aceEditor.session.setMode(filename && (/\.json$/i.test(filename)) ? "ace/mode/json" : "ace/mode/text"); // same as filename.toLowerCase().endsWith('.json')
}

// Try to initialize Ace editor if available
Expand Down Expand Up @@ -467,7 +474,7 @@
var filename = pathField ? pathField.value : currentFile;
var border = "2px solid #333";

if (filename && filename.toLowerCase().endsWith('.json')) {
if (filename && (/\.json$/i.test(filename))) { // same as filename.toLowerCase().endsWith('.json')
try {
JSON.parse(ta.value);
} catch(e) {
Expand All @@ -478,23 +485,19 @@
};

function saveFile(filename,data){
var finalData = data;
// Minify JSON files before upload
if (filename.toLowerCase().endsWith('.json')) {
var outdata = data;
if (/\.json$/i.test(filename)) { // same as filename.toLowerCase().endsWith('.json')
try {
finalData = JSON.stringify(JSON.parse(data));
outdata = JSON.stringify(JSON.parse(data)); // validate and minify
} catch(e) {
alert("Invalid JSON! Please fix syntax.");
alert("Invalid JSON! Please fix.");
return;
}
}
var fd=new FormData();
fd.append("file",new Blob([finalData],{type:"text/plain"}),filename);
req.add("POST","/upload",fd,function(st,resp){
if (st!=200) alert("ERROR "+st+": "+resp);
else {
showToast("File saved");
uploadFile({files: [new Blob([outdata], {type:"text/plain"})]}, filename, function(s) {
if(s) {
refreshTree();
loadFile(filename); // (re)load if saved successfully to update formating or show file content
}
});
}
Expand All @@ -505,9 +508,9 @@
gId("preview").style.display="none";
gId("editor").style.display="flex";
if (st==200) {
if (filename.toLowerCase().endsWith('.json')) {
if ((/\.json$/i.test(filename))) { // same as filename.toLowerCase().endsWith('.json')
try {
setContent(filename.toLowerCase().includes('ledmap') ? prettyLedmap(resp) : JSON.stringify(JSON.parse(resp), null, 2));
setContent(/ledmap/i.test(filename) ? prettyLedmap(resp) : JSON.stringify(JSON.parse(resp), null, 2)); // pretty-print ledmap files (i.e. if file name includes "ledmap" case-insensitive)
} catch(e) {
setContent(resp);
}
Expand All @@ -534,8 +537,7 @@
}
if (!fn.startsWith("/")) fn = "/" + fn;
currentFile = fn; // Update current file
saveFile(fn, getContent());
loadFile(fn);
saveFile(fn, getContent())
},
loadText:function(fn){
currentFile=fn;
Expand All @@ -558,7 +560,7 @@
};
}

function onBodyLoad(){
function S(){
var vars={};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,k,v){
vars[decodeURIComponent(k)]=decodeURIComponent(v);
Expand All @@ -577,7 +579,7 @@
}
</script>
</head>
<body onload="onBodyLoad()">
<body>
<div id="toast"></div>
<div id="loader"><div class="loader"></div></div>
<div id="top"></div>
Expand Down