add load/save

This commit is contained in:
matth@ultra 2024-09-02 13:27:03 +02:00
parent b194eef0c5
commit c440214466
2 changed files with 55 additions and 0 deletions

View File

@ -27,6 +27,9 @@
<button type="submit" name="submit">Add</button>
</div>
</form>
<h2>Save / Load</h2>
<button onclick="saveMappings()" id="save-button">Save mappings to file</button>
<button onclick="loadMappings()" id="load-button">Load mappings from file</button>
</div>
<div class="second-box" style="max-height: 100%">

View File

@ -2,6 +2,8 @@
* Handle mappings
* Mappings are stored in local storage as a Map (key: directory)
*/
const invalidFileNameCharsRe =/[^\\\|:\*\?"<>]/; // dont allow \/|:*?<>
const invalidFileNameChars = "\\|:*?<>";
let statusLine = document.getElementById('status');
@ -63,6 +65,56 @@ function addMapping(key, directory) {
renderMappings();
}
/*
* Save/Load from file
*/
function saveMappings() {
const mappings = new Map(JSON.parse(localStorage.getItem('mappings')) || []);
let dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(Array.from(mappings)));
let downloadElement = document.createElement('a');
downloadElement.style = "display: none;";
downloadElement.setAttribute("href", dataStr);
downloadElement.setAttribute("download", "mappings.json");
document.body.appendChild(downloadElement); // required for firefox
downloadElement.click();
downloadElement.remove();
}
function loadMappings() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = async (event) => {
const file = event.target.files[0];
if (!file) {
statusLine.textContent = "No file selected";
return;
}
try {
const fileText = await file.text();
const jsonData = JSON.parse(fileText);
// check is valid
if (typeof jsonData !== 'object' || jsonData === null) {
statusLine.textContent = "Invalid JSON structure";
return;
}
// TODO possibly implement sanity checks
localStorage.setItem('mappings', JSON.stringify(jsonData));
renderMappings();
} catch (error) {
console.error(error);;
statusLine = "Error loading file";
}
};
input.click();
}
// event listener for add mapping form
document.getElementById('addMappingForm').addEventListener('submit', function(event) {
event.preventDefault();