forked from iLikeToBeAnonymous/INI_Editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
224 lines (196 loc) · 9.85 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
var jsonString = '';
var rebuiltIni = ''; // For re-exporting the INI file.
var jsonObj = {};
// The promises were copied from "https://codepen.io/Anveio/pen/XzYBzX"
const readUploadedFileAsText = (inputFile) => {
const temporaryFileReader = new FileReader();
return new Promise((resolve, reject) => {
temporaryFileReader.onerror = () => {
temporaryFileReader.abort();
reject(new DOMException("Problem parsing input file."));
};
temporaryFileReader.onload = () => {
resolve(temporaryFileReader.result);
};
temporaryFileReader.readAsText(inputFile);
});
};
const handleUpload = async (event) => {
const file = event.target.files[0];
////const fileContentDiv = document.querySelector('div#fileContentDiv');
//const fileContentDiv = document.querySelector('pre#file-content');
try {
const fileContents = await readUploadedFileAsText(file);
// The iniParser only works correctly if you open a valid INI file...
//fileContentDiv.innerHTML = JSON.stringify(iniParser(fileContents),null,2);
jsonObj = iniParser(fileContents);
blankTheFields(); // Clears fields which should always be blank.
//const jsonString = JSON.stringify(jsonObj,null,2);
/*jsonString = JSON.stringify(jsonObj,null,2);
fileContentDiv.innerHTML = jsonString;*/
displayJson(jsonObj,'pre#file-content');
document.getElementById('saveName').value = file.name;
} catch (e) {
//fileContentDiv.innerHTML = e.message
alert(e.message);
}
}
// The below line MUST go after the rest of the promise stuff, or else it won't work.
document.querySelector('input#fileSelector').addEventListener('change', handleUpload);
//########################################
function iniParser(myInput){
myInput = myInput.replace(/\r+\n|\r+/gm,'\n'); // replace all newline chars the '\n' for consistency
// below splits all lines into separate array elements, frames each with quotes, then replaces the "=" with a ":"
var myStr = myInput.split(/\r?\n|\r/)
.map(eachRow => '"' + eachRow.replace(/\=/g,'": "') + '"')
.map(eachRow => eachRow.replace(/^\"\s*\"/g,'')) //any lines with just quotes get replaced with empty vals
.filter(notEmpty => notEmpty).join(',\n') // empty lines get removed.
.replace(/\]\"\,/g,']": {').replace(/\,\n\"\[/g,'},\n"[')
.replace(/\[|\]/g,''); //removed the brackets to see if it fixes the JSON parser.
try{return JSON.parse('{' + myStr + '}}');}
catch{return '{' + myStr + '}}';}
}
function rowSplitter(indexContent,cellDelim){ //made this just for simple debugging for now.
//indexContent = indexContent.split(cellDelim);
var myRegex = new RegExp(/\[.*\]/g);
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
myRegex.test(indexContent) ? (indexContent = '"' + indexContent + '"')
: (indexContent ='\{"' + indexContent.replace('=','":"') + '"\},');
return indexContent;
};
//########################################
function displayJson (jData,fileContentDivStr) {
try{const fileContentDiv = document.querySelector(fileContentDivStr);
fileContentDiv.innerHTML = JSON.stringify(jData,null,2);}
catch (error) {alert(error.message);}
}
function createTable(tableData) {
var table = document.getElementById('file-content');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
};
/* ##########################################################################
Below only works if the id of the input box matches the target JSON ele name.
If an element doesn't exist, it creates it.
Currently only works on two-level JSON objects like the INI file result.
##########################################################################*/
document.getElementById('fieldsToChange').addEventListener('input', ()=>{
var oldVal;
var jsonAddress = event.target.id.split('.');
//console.log(event.target.id);
try{oldVal = jsonObj[jsonAddress[0]][jsonAddress[1]];} //if it exists, set to old value
catch{jsonObj[jsonAddress[0]]={}; jsonObj[jsonAddress[0]][jsonAddress[1]]='';} // if it doesn't exist, create it with an empty value.
jsonObj[jsonAddress[0]][jsonAddress[1]] = document.getElementById(event.target.id).value; // updates the value in the global JSON object.
displayJson(jsonObj,'pre#file-content'); // updates the displayed JSON.
// console.log('changed from ' + oldVal + ' to ' + jsonObj[jsonAddress[0]][jsonAddress[1]]);
formatToIni(); // <---This function needs revamped.
});
function blankTheFields(){ // just clears fields which should always be blank.
jsonObj.EmailConfig.To = '';
jsonObj.EmailConfig.Cc = '';
jsonObj.EmailConfig.Bcc = '';
jsonObj.EmailConfig.WaTo1 = '';
jsonObj.EmailConfig.WaTo2 = '';
jsonObj.EmailConfig.WaTo3 = '';
}
// ####################################################
function formatToIni(){ // This works, but it's very purpose-built. Can be improved.
//var location= document.getElementById('iniVs').innerHTML;
var location = document.querySelector('#iniVs');
rebuiltIni = '';
/*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
The Object.keys() method returns an array of a given object's own enumerable
property names, iterated in the same order that a normal loop would.*/
for (var iniSection of Object.keys(jsonObj)) { //https://www.codegrepper.com/code-examples/javascript/loop+through+json+object+javascript
//console.log(key);
rebuiltIni += '[' + iniSection + ']\n';
for (var key in jsonObj[iniSection]){
if (jsonObj[iniSection].hasOwnProperty(key)){
rebuiltIni += (key + '=' + jsonObj[iniSection][key] + '\n');
}
}
}
location.innerHTML = '<pre>' + rebuiltIni + '</pre>';
};
/*###################################################################
############## File-save listeners and functions ################
###################################################################*/
// Listener on the Save and Download button + the function triggered by it.
document.querySelector("#saveMyFile").addEventListener("click", function ()
{
//var textToSave = jsonObj; // just the global JSON object
// https://developer.mozilla.org/en-US/docs/Web/API/Blob
//var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsBlob = new Blob([JSON.stringify(jsonObj, null, 2)], {type : 'application/json'});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("saveName").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
//downloadLink.onclick = destroyClickedElement;
/* the .onclick follows this syntax: target.onclick = functionRef;
Instead of actually calling out to a separate function for something
this simple, just use an arrow. */
downloadLink.onclick = (myEvent) => document.body.removeChild(myEvent.target);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
});
/*###################################################################
Needs to have the embedded function split out and called by the listener instead
since it has recycled code from the "save as JSON" event listener.
###################################################################*/
document.querySelector("#saveToIni").addEventListener("click", function ()
{
//var textToSave = jsonObj; // just the global JSON object
// https://developer.mozilla.org/en-US/docs/Web/API/Blob
var textToSaveAsBlob = new Blob([rebuiltIni], {type : 'text/plain'});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("saveName").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
//downloadLink.onclick = destroyClickedElement;
/* the .onclick follows this syntax: target.onclick = functionRef;
Instead of actually calling out to a separate function for something
this simple, just use an arrow. */
downloadLink.onclick = (myEvent) => document.body.removeChild(myEvent.target);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
});
/* ###################################################################
FORM FIELD VALIDATION
###################################################################*/
//
// For some reason, I can't get a query selector to work here????
/*By using 'change' instead of 'input', the test isn't run until the user
shifts focus out of the input box. */
document.getElementById('NetworkConfig.PLC_IP').addEventListener('input', ()=>{
var myTarget = document.getElementById('NetworkConfig.PLC_IP');
var valToCheck = myTarget.value;
//const ipRegEx = /\d{3}\.\d{3}\.\d{1,3}\.\d{1,3}/g;
const ipRegEx = /((\b[1-9][0-9]?\b|\b1[0-9]{1,2}\b|\b2[0-5]{2}\b|\b0\b)\.){3}(\b[1-9][0-9]?\b|\b1[0-9]{1,2}\b|\b2[0-5]{2}\b|\b0\b)/
//console.log(ipRegEx.test(valToCheck));
if(ipRegEx.test(valToCheck)){
myTarget.removeAttribute('style');
}
else{
//alert('Enter a valid IP address');
myTarget.setAttribute('style','background-color:Tomato'); // https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
myTarget.focus();
}
});
// jsonObj[jsonAddress[0]][jsonAddress[1]] = document.getElementById(event.target.id).value;