From c440214466683f464c3cbb8318fe4fc5877a6fba Mon Sep 17 00:00:00 2001 From: "matth@ultra" Date: Mon, 2 Sep 2024 13:27:03 +0200 Subject: [PATCH] add load/save --- src/config.html | 3 +++ src/config.js | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/config.html b/src/config.html index 9ee97e5..4100c1d 100644 --- a/src/config.html +++ b/src/config.html @@ -27,6 +27,9 @@ +

Save / Load

+ +
diff --git a/src/config.js b/src/config.js index 2afd963..ff16aea 100644 --- a/src/config.js +++ b/src/config.js @@ -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();