Version 9.9.6

This commit is contained in:
maru21 2023-10-14 17:21:05 +02:00
parent cfe7e209b0
commit c67aee4876
16 changed files with 3603 additions and 3309 deletions

View File

@ -1,76 +0,0 @@
import { retrieveData } from "./storage.js";
import sha256 from "./sha256.min.js";
import XORCipher from "./xorc.js";
import getBrowserFingerprint from "./identify.js"
export const passwordHash = {
toString: () => {
let fp = getBrowserFingerprint( { hardwareOnly: true } );
let data;
try {
data = window.sessionStorage.getItem(sha256(fp));
} catch (e) {
return "none";
}
if (data === null) return "none";
return XORCipher.decode(fp, data);
},
set: (pw) => {
let fp = getBrowserFingerprint( { hardwareOnly: true } );
window.sessionStorage.setItem(sha256(fp), XORCipher.encode(fp, pw));
}
}
function setPassword() {
let x = document.getElementById("loginForm");
let pw = x.elements[0].value;
if (pw != "" || pw !== "undefined") {
let pwOld = pw;
passwordHash.set(sha256(pw));
let templateFiles = retrieveData("templateFiles");
if (templateFiles != "") {
try {
JSON.parse(templateFiles);
} catch (e) {
document.getElementById("wrongPWAlert").style.display = "block";
const alertTimeout = setTimeout(() => {
document.getElementById("wrongPWAlert").style.display = "none";
}, 5000);
passwordHash.set(pwOld);
x.elements[0].value = "";
return;
}
}
//user logged in
document.getElementById("login").style.display = "none";
window.sessionStorage.setItem(sha256("verified"), XORCipher.encode(sha256("passwordHash"), passwordHash));
}
}
export function getUsrId() {
const fingerprint = getBrowserFingerprint( { hardwareOnly: true } );
return cyrb53(fingerprint + passwordHash);
}
const cyrb53 = (str, seed = 21) => {
let h1 = 0xdeadbeef ^ seed,
h2 = 0x41c6ce57 ^ seed;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};
export default setPassword;

View File

@ -1,393 +1,405 @@
import { getFileName } from "./storage.js"; import { getFileName } from "./storage.js";
function transformTemplateObject(objects) { function transformTemplateObject(objects) {
let form = document.createElement("FORM"); let form = document.createElement("FORM");
form.setAttribute("method", "post"); form.setAttribute("method", "post");
form.setAttribute("action", "javascript:void(0)"); form.setAttribute("action", "javascript:void(0)");
form.setAttribute("id", "mainFormObj"); form.setAttribute("id", "mainFormObj");
form.classList.add("w3-row"); form.classList.add("w3-row");
let sidebarList = document.createElement("ul"); let sidebarList = document.createElement("ul");
sidebarList.classList.add("w3-ul"); sidebarList.classList.add("w3-ul");
for (let i = 0; i < objects.length; i++) { for (let i = 0; i < objects.length; i++) {
buildField(objects[i], form, sidebarList); buildField(objects[i], form, sidebarList);
} }
//console.log(objects); //console.log(objects);
//create sidebar submit button //create sidebar submit button
let sidebarSubmitButton = document.createElement("li"); let sidebarSubmitButton = document.createElement("li");
sidebarSubmitButton.classList.add( sidebarSubmitButton.classList.add(
"w3-bar-item", "w3-bar-item",
"w3-padding-large", "w3-padding-large",
"w3-button" "w3-button"
); );
sidebarSubmitButton.style.borderTop = "2px solid #ddd"; sidebarSubmitButton.style.borderTop = "2px solid #ddd";
sidebarSubmitButton.id = "sb-submit"; sidebarSubmitButton.id = "sb-submit";
sidebarSubmitButton.innerHTML = "Save & Copy"; sidebarSubmitButton.innerHTML = "Save & Copy";
sidebarList.appendChild(sidebarSubmitButton); sidebarList.appendChild(sidebarSubmitButton);
//add sidebar elemnts to sidebar //add sidebar elemnts to sidebar
document.getElementById("sidebar").appendChild(sidebarList); document.getElementById("sidebar").appendChild(sidebarList);
//add form to mainForm Div //add form to mainForm Div
document.getElementById("mainForm").appendChild(form); document.getElementById("mainForm").appendChild(form);
//create username and append field to site //create username and append field to site
let fileName = getFileName(); let fileName = getFileName();
document.getElementById("submitContainer").appendChild(userFileNameDiv(fileName)); document.getElementById("submitContainer").appendChild(userFileNameDiv(fileName));
// create a Save button // create a Save button
let saveBtn = document.createElement("input"); let saveBtn = document.createElement("input");
saveBtn.setAttribute("type", "submit"); saveBtn.setAttribute("type", "submit");
saveBtn.setAttribute("value", "Save"); saveBtn.setAttribute("value", "Save");
saveBtn.classList.add("w3-button"); saveBtn.classList.add("w3-button");
saveBtn.classList.add("w3-grey"); saveBtn.classList.add("w3-grey");
saveBtn.style.margin = "20px"; saveBtn.style.margin = "20px";
//append submit button to submitContainer //append submit button to submitContainer
document.getElementById("submitContainer").appendChild(saveBtn); document.getElementById("submitContainer").appendChild(saveBtn);
// create a Copy button // create a Copy button
let copyBtn = document.createElement("input"); let copyBtn = document.createElement("input");
copyBtn.setAttribute("type", "submit"); copyBtn.setAttribute("type", "submit");
copyBtn.setAttribute("value", "Copy"); copyBtn.setAttribute("value", "Copy");
copyBtn.classList.add("w3-button"); copyBtn.classList.add("w3-button");
copyBtn.classList.add("w3-grey"); copyBtn.classList.add("w3-grey");
copyBtn.style.margin = "20px 0px"; copyBtn.style.margin = "20px 0px";
//append submit button to submitContainer //append submit button to submitContainer
document.getElementById("submitContainer").appendChild(copyBtn); document.getElementById("submitContainer").appendChild(copyBtn);
} }
function buildField(obj, form, sidebarList) { function buildField(obj, form, sidebarList) {
//create template Input fields //create template Input fields
let divContainer = document.createElement("DIV"); let divContainer = document.createElement("DIV");
divContainer.classList.add("w3-half"); divContainer.classList.add("w3-half");
divContainer.classList.add("w3-container"); divContainer.classList.add("w3-container");
let div = document.createElement("DIV"); let div = document.createElement("DIV");
div.classList.add("w3-section"); div.classList.add("w3-section");
div.classList.add("w3-flat-silver"); div.classList.add("w3-left-align");
div.setAttribute("style", "padding: 10px"); div.setAttribute("style", "padding: 10px");
let label = document.createElement("LABEL"); let label = document.createElement("LABEL");
label.style.display = "inline-block";
let connectedListsArray = []; label.style.width = "100%";
label.style.paddingBottom = "5px";
let ltPlaceholder; label.style.borderBottom = "thin solid #9e9e9e";
label.style.fontWeight = "800";
//check for longtext:!li and convert it to standard longText
if (obj.type.indexOf("longText") !== -1) { let connectedListsArray = [];
if (obj.type.indexOf(":") !== -1) {
ltPlaceholder = obj.type.split(":")[1]; let ltPlaceholder;
if (ltPlaceholder !== undefined) {
let textarea = document.createElement("textarea"); //check for longtext:!li and convert it to standard longText
textarea.setAttribute("name", obj.word.replace(/ /g, "_")); if (obj.type.indexOf("longText") !== -1) {
textarea.setAttribute("id", obj.word.replace(/ /g, "_")); if (obj.type.indexOf(":") !== -1) {
textarea.setAttribute("cols", "100"); ltPlaceholder = obj.type.split(":")[1];
textarea.setAttribute("rows", "15"); if (ltPlaceholder !== undefined) {
textarea.classList.add("w3-input"); let textarea = document.createElement("textarea");
textarea.id = obj.word.replace(/ /g, "_"); textarea.setAttribute("name", obj.word.replace(/ /g, "_"));
divContainer.classList.remove("w3-half"); textarea.setAttribute("id", obj.word.replace(/ /g, "_"));
divContainer.classList.add("w3-center"); textarea.setAttribute("cols", "100");
label.innerHTML = obj.word; textarea.setAttribute("rows", "15");
div.appendChild(label); textarea.classList.add("w3-input");
div.appendChild(textarea); textarea.id = obj.word.replace(/ /g, "_");
} divContainer.classList.remove("w3-half");
} divContainer.classList.add("w3-center");
} label.innerHTML = obj.word;
div.appendChild(label);
div.appendChild(textarea);
if (obj.type.indexOf("simpleInput") !== -1) { }
if (obj.type.indexOf(":") !== -1) { }
ltPlaceholder = obj.type.split(":")[1]; }
if (ltPlaceholder !== undefined) {
let input = document.createElement("input");
input.setAttribute("type", "text"); if (obj.type.indexOf("simpleInput") !== -1) {
input.setAttribute("name", obj.word.replace(/ /g, "_")); if (obj.type.indexOf(":") !== -1) {
input.setAttribute("id", obj.word.replace(/ /g, "_")); ltPlaceholder = obj.type.split(":")[1];
input.classList.add("w3-input"); if (ltPlaceholder !== undefined) {
input.id = obj.word.replace(/ /g, "_"); let input = document.createElement("input");
label.innerHTML = obj.word; input.setAttribute("type", "text");
div.appendChild(label); input.setAttribute("name", obj.word.replace(/ /g, "_"));
div.appendChild(input); input.setAttribute("id", obj.word.replace(/ /g, "_"));
} input.classList.add("w3-input");
} input.id = obj.word.replace(/ /g, "_");
} label.innerHTML = obj.word;
div.appendChild(label);
//check for markup:title and display it as none div.appendChild(input);
if (obj.type.indexOf("markup") !== -1) { }
if (obj.type.indexOf(":") !== -1) { }
ltPlaceholder = obj.type.split(":")[1]; }
if (ltPlaceholder !== undefined) {
divContainer.classList.add("hidden"); //check for markup:title and display it as none
let input = document.createElement("input"); if (obj.type.indexOf("markup") !== -1) {
input.setAttribute("type", "text"); if (obj.type.indexOf(":") !== -1) {
input.setAttribute("name", obj.word.replace(/ /g, "_")); ltPlaceholder = obj.type.split(":")[1];
input.id = obj.word.replace(/ /g, "_"); if (ltPlaceholder !== undefined) {
input.value = obj.word; divContainer.classList.add("hidden");
divContainer.style.display = "none"; let input = document.createElement("input");
label.innerHTML = obj.word; input.setAttribute("type", "text");
div.appendChild(label); input.setAttribute("name", obj.word.replace(/ /g, "_"));
div.appendChild(input); input.id = obj.word.replace(/ /g, "_");
} input.value = obj.word;
} divContainer.style.display = "none";
} label.innerHTML = obj.word;
div.appendChild(label);
div.appendChild(input);
switch (obj.type) { }
case "genderSpecific": }
let select = document.createElement("select"); }
select.setAttribute("name", obj.word.replace(/ /g, "_"));
select.id = obj.word.replace(/ /g, "_");
select.classList.add("w3-select"); switch (obj.type) {
if (typeof obj.m !== "undefined") { case "genderSpecific":
let optionM = document.createElement("option"); let select = document.createElement("select");
optionM.value = obj.m; select.setAttribute("name", obj.word.replace(/ /g, "_"));
optionM.text = obj.m; select.id = obj.word.replace(/ /g, "_");
select.appendChild(optionM); select.classList.add("w3-select");
} if (typeof obj.m !== "undefined") {
if (typeof obj.w !== "undefined") { let optionM = document.createElement("option");
let optionW = document.createElement("option"); optionM.value = obj.m;
optionW.value = obj.w; optionM.text = obj.m;
optionW.text = obj.w; select.appendChild(optionM);
select.appendChild(optionW); }
} if (typeof obj.w !== "undefined") {
if (typeof obj.d !== "undefined") { let optionW = document.createElement("option");
let optionD = document.createElement("option"); optionW.value = obj.w;
optionD.value = obj.d; optionW.text = obj.w;
optionD.text = obj.d; select.appendChild(optionW);
select.appendChild(optionD); }
} if (typeof obj.d !== "undefined") {
label.innerHTML = obj.word; let optionD = document.createElement("option");
div.appendChild(label); optionD.value = obj.d;
div.appendChild(select); optionD.text = obj.d;
break; select.appendChild(optionD);
}
case "list": label.innerHTML = obj.word;
let select2 = document.createElement("select"); div.appendChild(label);
select2.setAttribute("name", obj.word.replace(/ /g, "_")); div.appendChild(select);
select2.classList.add("w3-select"); break;
select2.id = obj.word.replace(/ /g, "_");
select2.setAttribute("id", obj.word.replace(/ /g, "_")); case "list":
let select2 = document.createElement("select");
for (let listItem = 0; listItem < obj.listCount + 1; listItem++) { select2.setAttribute("name", obj.word.replace(/ /g, "_"));
//console.log(obj[listItem]); select2.classList.add("w3-select");
if (typeof obj[listItem] !== "undefined") { select2.id = obj.word.replace(/ /g, "_");
let optionL = document.createElement("option"); select2.setAttribute("id", obj.word.replace(/ /g, "_"));
optionL.value = obj[listItem];
optionL.text = obj[listItem]; for (let listItem = 0; listItem < obj.listCount + 1; listItem++) {
select2.appendChild(optionL); //console.log(obj[listItem]);
} if (typeof obj[listItem] !== "undefined") {
} let optionL = document.createElement("option");
label.innerHTML = obj.word; optionL.value = obj[listItem];
div.appendChild(label); optionL.text = obj[listItem];
div.appendChild(select2); select2.appendChild(optionL);
break; }
}
case "conList": label.innerHTML = obj.word;
let select3 = document.createElement("select"); div.appendChild(label);
select3.setAttribute("name", "clM-"+obj.word.replace(/ /g, "_")); div.appendChild(select2);
select3.classList.add("w3-select"); break;
select3.id = obj.word.replace(/ /g, "_");
let optionDefault = document.createElement("option"); case "conList":
optionDefault.value = "!none"; let select3 = document.createElement("select");
optionDefault.text = "Choose one"; select3.setAttribute("name", "clM-"+obj.word.replace(/ /g, "_"));
select3.appendChild(optionDefault); select3.classList.add("w3-select");
select3.id = obj.word.replace(/ /g, "_");
let optionDefault = document.createElement("option");
for (let listItem = 0; listItem < obj.listCount + 1; listItem++) { optionDefault.value = "!none";
//console.log(obj[listItem]); optionDefault.text = "Choose one";
if (typeof obj[listItem] !== "undefined") { select3.appendChild(optionDefault);
let optionL = document.createElement("option");
let item = obj[listItem];
optionL.value = item; for (let listItem = 0; listItem < obj.listCount + 1; listItem++) {
optionL.text = item; //console.log(obj[listItem]);
select3.appendChild(optionL); if (typeof obj[listItem] !== "undefined") {
connectedListsArray.push({ let optionL = document.createElement("option");
word: item, let item = obj[listItem];
type: obj["clType-"+item], optionL.value = item;
cl: obj.word optionL.text = item;
}); select3.appendChild(optionL);
} connectedListsArray.push({
} word: item,
label.innerHTML = obj.word; type: obj["clType-"+item],
cl: obj.word
if (obj.listCount == 0) { });
select3 = document.createElement("button"); }
select3.setAttribute("value", "!none"); }
select3.classList.add("w3-button", "w3-grey", "w3-left-align"); label.innerHTML = obj.word;
select3.id = obj.word.replace(/ /g, "_");
select3.innerHTML = "Show"; if (obj.listCount == 0) {
select3.setAttribute("name", "clM-"+obj.word.replace(/ /g, "_")); select3 = document.createElement("button");
select3.setAttribute("data-word", connectedListsArray[0].word); select3.setAttribute("value", "!none");
} select3.classList.add("w3-button", "w3-grey", "w3-left-align", "w3-padding-16");
select3.id = obj.word.replace(/ /g, "_");
div.appendChild(label); select3.innerHTML = connectedListsArray[0].word;
div.appendChild(document.createElement("br")); select3.setAttribute("name", "clM-"+obj.word.replace(/ /g, "_"));
select3.setAttribute("data-word", connectedListsArray[0].word);
div.appendChild(select3); label = document.createElement("LABEL");
label.innerHTML = '';
//div.classList.add("w3-center");
break; div.classList.replace("w3-flat-silver", "w3-flat-clouds");
div.appendChild(label);
case "simpleInput": div.appendChild(select3);
let input = document.createElement("input"); } else {
input.setAttribute("type", "text"); div.appendChild(label);
input.setAttribute("name", obj.word.replace(/ /g, "_")); div.appendChild(document.createElement("br"));
input.classList.add("w3-input"); div.appendChild(select3);
input.id = obj.word.replace(/ /g, "_"); }
label.innerHTML = obj.word;
div.appendChild(label);
div.appendChild(input);
break; break;
case "longText":
let textarea = document.createElement("textarea"); case "simpleInput":
textarea.setAttribute("name", obj.word.replace(/ /g, "_")); let input = document.createElement("input");
textarea.setAttribute("cols", "100"); input.setAttribute("type", "text");
textarea.setAttribute("rows", "15"); input.setAttribute("name", obj.word.replace(/ /g, "_"));
textarea.classList.add("w3-input"); input.classList.add("w3-input");
textarea.id = obj.word.replace(/ /g, "_"); input.id = obj.word.replace(/ /g, "_");
label.innerHTML = obj.word; label.innerHTML = obj.word;
divContainer.classList.remove("w3-half"); div.appendChild(label);
divContainer.classList.add("w3-center"); div.appendChild(input);
div.appendChild(label); break;
div.appendChild(textarea); case "longText":
break; let textarea = document.createElement("textarea");
case "current_time": textarea.setAttribute("name", obj.word.replace(/ /g, "_"));
let input2 = document.createElement("input"); textarea.setAttribute("cols", "100");
let today = new Date(); textarea.setAttribute("rows", "15");
let currentTime = textarea.classList.add("w3-input");
today.getHours() + ":" + ("0" + today.getMinutes()).slice(-2); textarea.id = obj.word.replace(/ /g, "_");
//console.log(currentTime); label.innerHTML = obj.word;
input2.setAttribute("type", "text"); divContainer.classList.remove("w3-half");
input2.setAttribute("name", obj.word.replace(/ /g, "_")); divContainer.classList.add("w3-center");
input2.setAttribute("value", currentTime); div.appendChild(label);
input2.id = obj.word.replace(/ /g, "_"); div.appendChild(textarea);
div.setAttribute("style", "display: none;"); break;
input2.classList.add("w3-input"); case "current_time":
label.innerHTML = obj.word; let input2 = document.createElement("input");
div.appendChild(label); let today = new Date();
div.appendChild(input2); let currentTime =
break; today.getHours() + ":" + ("0" + today.getMinutes()).slice(-2);
case "current_date": //console.log(currentTime);
let input3 = document.createElement("input"); input2.setAttribute("type", "text");
var today2 = new Date(); input2.setAttribute("name", obj.word.replace(/ /g, "_"));
var dd = String(today2.getDate()).padStart(2, "0"); input2.setAttribute("value", currentTime);
var mm = String(today2.getMonth() + 1).padStart(2, "0"); //January is 0! input2.id = obj.word.replace(/ /g, "_");
var yyyy = today2.getFullYear(); div.setAttribute("style", "display: none;");
currentDate = dd + "." + mm + "." + yyyy; input2.classList.add("w3-input");
input3.setAttribute("type", "text"); label.innerHTML = obj.word;
input3.setAttribute("name", obj.word.replace(/ /g, "_")); div.appendChild(label);
input3.setAttribute("value", currentDate); div.appendChild(input2);
input3.id = obj.word.replace(/ /g, "_"); break;
div.setAttribute("style", "display: none;"); case "current_date":
input3.classList.add("w3-input"); let input3 = document.createElement("input");
label.innerHTML = obj.word; var today2 = new Date();
div.appendChild(label); var dd = String(today2.getDate()).padStart(2, "0");
div.appendChild(input3); var mm = String(today2.getMonth() + 1).padStart(2, "0"); //January is 0!
break; var yyyy = today2.getFullYear();
} currentDate = dd + "." + mm + "." + yyyy;
input3.setAttribute("type", "text");
//check if item is connected list item cl input3.setAttribute("name", obj.word.replace(/ /g, "_"));
if (obj.cl !== undefined) divContainer.classList.add("hidden"); input3.setAttribute("value", currentDate);
if (obj.cl !== undefined) { input3.id = obj.word.replace(/ /g, "_");
div.lastChild.setAttribute("name", div.setAttribute("style", "display: none;");
(ltPlaceholder !== undefined) ? "cl-"+obj.word.replace(/ /g, "_") +":"+ltPlaceholder : "cl-"+obj.word.replace(/ /g, "_")); input3.classList.add("w3-input");
} label.innerHTML = obj.word;
div.appendChild(label);
//append field to wrapper and add to mainForm div.appendChild(input3);
divContainer.appendChild(div); break;
form.appendChild(divContainer); }
buildSidebarList(obj, sidebarList) //check if item is connected list item cl
if (obj.cl !== undefined) divContainer.classList.add("hidden");
//handle conList items if (obj.cl !== undefined) {
if (obj.type == "conList") { div.lastChild.setAttribute("name",
//build connected list fields according to obj (ltPlaceholder !== undefined) ? "cl-"+obj.word.replace(/ /g, "_") +":"+ltPlaceholder : "cl-"+obj.word.replace(/ /g, "_"));
for (let conObj of connectedListsArray) { divContainer.classList.add("w3-animate-opacity")
buildField(conObj, form, sidebarList); }
}
//append field to wrapper and add to mainForm
//set formEvent for selection detection to mainForm divContainer.appendChild(div);
if (obj.listCount == 0) { form.appendChild(divContainer);
document.getElementById("mainForm").addEventListener("click", (e) => {
if (e.target && e.target.matches("button#"+obj.word.replace(/ /g, "_"))) { buildSidebarList(obj, sidebarList)
let button = document.getElementById(obj.word.replace(/ /g, "_"));
let con = button.dataset.word; //handle conList items
let conElement = document.getElementById(con); if (obj.type == "conList") {
if (conElement.parentElement.parentElement.classList.contains("hidden")) { //build connected list fields according to obj
conElement.parentElement.parentElement.classList.remove("hidden"); for (let conObj of connectedListsArray) {
button.value = "!selected"; buildField(conObj, form, sidebarList);
} else { }
conElement.parentElement.parentElement.classList.add("hidden");
button.value = "!none"; //set formEvent for selection detection to mainForm
} if (obj.listCount == 0) {
} document.getElementById("mainForm").addEventListener("click", (e) => {
}); if (e.target && e.target.matches("button#"+obj.word.replace(/ /g, "_"))) {
} else { let button = document.getElementById(obj.word.replace(/ /g, "_"));
document.getElementById("mainForm").addEventListener("change", (e) => { let con = button.dataset.word;
if (e.target && e.target.matches("select#"+obj.word.replace(/ /g, "_"))) { let conElement = document.getElementById(con);
let select = document.getElementById(obj.word.replace(/ /g, "_")); if (conElement.parentElement.parentElement.classList.contains("hidden")) {
for (let opt of select.options) { conElement.parentElement.parentElement.classList.remove("hidden");
if (opt.value == "!none") continue; button.value = "!selected";
if (opt.innerHTML != select.value) { } else {
document.getElementById(opt.innerHTML.replace(/ /g, "_")).parentElement.parentElement.classList.add("hidden"); conElement.parentElement.parentElement.classList.add("hidden");
} else { button.value = "!none";
document.getElementById(select.value.replace(/ /g, "_")).parentElement.parentElement.classList.remove("hidden"); }
} }
} });
for (let hiddenItems of document.getElementsByClassName("cl")) { } else {
if (hiddenItems.innerHTML != select.value) { document.getElementById("mainForm").addEventListener("change", (e) => {
hiddenItems.classList.add("hidden"); if (e.target && e.target.matches("select#"+obj.word.replace(/ /g, "_"))) {
} else { let select = document.getElementById(obj.word.replace(/ /g, "_"));
hiddenItems.classList.remove("hidden"); for (let opt of select.options) {
} if (opt.value == "!none") continue;
} if (opt.innerHTML != select.value) {
} document.getElementById(opt.innerHTML.replace(/ /g, "_")).parentElement.parentElement.classList.add("hidden");
}); } else {
} document.getElementById(select.value.replace(/ /g, "_")).parentElement.parentElement.classList.remove("hidden");
} }
} }
for (let hiddenItems of document.getElementsByClassName("cl")) {
function buildSidebarList(obj, sidebarList) { if (hiddenItems.innerHTML != select.value) {
//build sidebarlist item and append hiddenItems.classList.add("hidden");
let sidebarListItem = document.createElement("li"); } else {
sidebarListItem.classList.add( hiddenItems.classList.remove("hidden");
"w3-bar-item", }
"w3-padding-large", }
"w3-button", }
"sb-item" });
); }
if (obj.cl !== undefined) sidebarListItem.classList.add("hidden", "cl"); }
sidebarListItem.style.borderBottom = "1px solid #ddd"; }
sidebarListItem.id = "sb-item";
sidebarListItem.setAttribute("data-item", obj.word.replace(/ /g, "_")); function buildSidebarList(obj, sidebarList) {
sidebarListItem.innerHTML = obj.word; //build sidebarlist item and append
sidebarListItem; let sidebarListItem = document.createElement("li");
sidebarList.appendChild(sidebarListItem); sidebarListItem.classList.add(
} "w3-bar-item",
"w3-padding-large",
function userFileNameDiv(fileName) { "w3-button",
let divContainer = document.createElement("DIV"); "sb-item"
divContainer.classList.add("w3-third", "w3-container"); );
divContainer.setAttribute("style", "padding: 0px"); if (obj.cl !== undefined) sidebarListItem.classList.add("hidden", "cl");
let div = document.createElement("DIV"); sidebarListItem.style.borderBottom = "1px solid #ddd";
div.classList.add("w3-section", "w3-flat-silver"); sidebarListItem.id = "sb-item";
div.setAttribute("style", "padding: 5px"); sidebarListItem.setAttribute("data-item", obj.word.replace(/ /g, "_"));
let userFileNameInput = document.createElement("input"); sidebarListItem.innerHTML = obj.word;
userFileNameInput.setAttribute("type", "text"); sidebarListItem;
userFileNameInput.setAttribute("name", "userFileName"); sidebarList.appendChild(sidebarListItem);
userFileNameInput.setAttribute("placeholder", fileName); }
userFileNameInput.classList.add("w3-input");
userFileNameInput.id = "userFileName"; function userFileNameDiv(fileName) {
div.appendChild(userFileNameInput); let divContainer = document.createElement("DIV");
divContainer.appendChild(div); divContainer.classList.add("w3-third", "w3-container");
return divContainer; divContainer.setAttribute("style", "padding: 0px");
} let div = document.createElement("DIV");
div.classList.add("w3-section", "w3-flat-silver");
export default transformTemplateObject; div.setAttribute("style", "padding: 5px");
let userFileNameInput = document.createElement("input");
userFileNameInput.setAttribute("type", "text");
userFileNameInput.setAttribute("name", "userFileName");
userFileNameInput.setAttribute("placeholder", fileName);
userFileNameInput.classList.add("w3-input");
userFileNameInput.id = "userFileName";
div.appendChild(userFileNameInput);
divContainer.appendChild(div);
return divContainer;
}
export default transformTemplateObject;

View File

@ -1,209 +1,200 @@
import {setNewTemplate, loadTemplate} from "./web.js"; import {setNewTemplate, loadTemplate} from "./web.js";
import { retrieveData } from "./storage.js"; import { retrieveData } from "./storage.js";
import { hideMenus, modalNotifier } from "./evts.js"; import { hideMenus, modalNotifier } from "./evts.js";
function createTemplate(template = false) { function createTemplate(template = false) {
//set current page value in activeState object //set current page value in activeState object
activeState.activePage = "createTemplate"; activeState.activePage = "createTemplate";
//check if user is authenticated and templateFilesArray is decryptable
let tF = retrieveData("templateFiles"); if (screen.width > 992) {
if (tF != "") { document.getElementById("siteTitle").innerHTML = "Manage templates";
try { } else {
tF = JSON.parse(tF); document.getElementById("siteTitle").innerHTML = "TG";
} catch (e) { }
alert("Decryption failed; are you authenticated?");
window.location.reload(); //hide set Form button
return; document.getElementById("setFormButton").style.display = "none";
}
} if (template) {
document.getElementById("templateInput").value = loadTemplate(template, false, "createTemplate");
return;
if (screen.width > 992) { }
document.getElementById("siteTitle").innerHTML = "Manage templates";
} else { //reset page and event listeners
document.getElementById("siteTitle").innerHTML = "TG";
} hideMenus();
//hide set Form button let mainFormDiv = document.getElementById("mainForm");
document.getElementById("setFormButton").style.display = "none"; let outputDiv = document.getElementById("output");
let submitContainerDiv = document.getElementById("submitContainer");
if (template) { let sidebarDiv = document.getElementById("sidebar");
document.getElementById("templateInput").value = loadTemplate(template, false, "createTemplate");
return; mainFormDiv.innerHTML = "";
} mainFormDiv.replaceWith(mainFormDiv.cloneNode(true));
outputDiv.innerHTML = "";
//reset page and event listeners outputDiv.replaceWith(outputDiv.cloneNode(true));
submitContainerDiv.innerHTML = "";
hideMenus(); submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true));
sidebarDiv.innerHTML = "";
let mainFormDiv = document.getElementById("mainForm"); sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));
let outputDiv = document.getElementById("output");
let submitContainerDiv = document.getElementById("submitContainer"); document.getElementById("mainForm").appendChild(createTemplateInput());
let sidebarDiv = document.getElementById("sidebar"); document.getElementById("sidebar").appendChild(loadTemplateSidebar(activeState.templates));
mainFormDiv.innerHTML = ""; //add events
mainFormDiv.replaceWith(mainFormDiv.cloneNode(true)); if (!template) formEvts();
outputDiv.innerHTML = ""; }
outputDiv.replaceWith(outputDiv.cloneNode(true));
submitContainerDiv.innerHTML = ""; function createTemplateCallBack(fileName, data) {
submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true));
sidebarDiv.innerHTML = ""; document.getElementById("templateInput").value = data;
sidebarDiv.replaceWith(sidebarDiv.cloneNode(true)); document.getElementById("userFileName").setAttribute("placeholder", fileName);
}
document.getElementById("mainForm").appendChild(createTemplateInput());
document.getElementById("sidebar").appendChild(loadTemplateSidebar(activeState.templates)); function loadTemplateSidebar(templates) {
let sidebarList = document.createElement("ul");
//add events sidebarList.classList.add("w3-ul");
if (!template) formEvts(); if (!templates.includes('_textBlocks')) {
} templates.push('_textBlocks');
}
function createTemplateCallBack(fileName, data) {
document.getElementById("templateInput").value = data; for (let template of templates) {
document.getElementById("userFileName").setAttribute("placeholder", fileName); let sidebarListItem = document.createElement("li");
}
sidebarListItem.classList.add(
function loadTemplateSidebar(templates) { "w3-bar-item",
let sidebarList = document.createElement("ul"); "w3-padding-large",
sidebarList.classList.add("w3-ul"); "w3-button"
);
sidebarListItem.style.borderBottom = "1px solid #ddd";
for (let template of templates) { sidebarListItem.id = "sb-item";
let sidebarListItem = document.createElement("li"); sidebarListItem.setAttribute("data-template", template);
sidebarListItem.innerHTML = template.replace(/_/g, " ");
sidebarListItem.classList.add( sidebarList.appendChild(sidebarListItem);
"w3-bar-item", }
"w3-padding-large",
"w3-button" return sidebarList;
);
sidebarListItem.style.borderBottom = "1px solid #ddd"; }
sidebarListItem.id = "sb-item";
sidebarListItem.setAttribute("data-template", template); function createTemplateInput() {
sidebarListItem.innerHTML = template.replace(/_/g, " ");
sidebarList.appendChild(sidebarListItem); let createTemplateDisplay = document.createElement("DIV");
} createTemplateDisplay.classList.add(
"w3-row-padding",
return sidebarList; "w3-padding-24",
"w3-container",
} "w3-flat-clouds"
);
function createTemplateInput() { createTemplateDisplay.id = "createTemplateDisplayWrapper";
let createTemplateDisplay = document.createElement("DIV");
createTemplateDisplay.classList.add( //start building submitContainer with save and filename
"w3-row-padding",
"w3-padding-24",
"w3-container", document.getElementById("submitContainer").appendChild(userFileNameDiv());
"w3-flat-clouds"
); let saveButton = document.createElement("input");
createTemplateDisplay.id = "createTemplateDisplayWrapper"; saveButton.setAttribute("type", "submit");
saveButton.setAttribute("value", "Save");
saveButton.classList.add("w3-button");
//start building submitContainer with save and filename saveButton.classList.add("w3-grey");
saveButton.style.margin = "20px";
document.getElementById("submitContainer").appendChild(saveButton);
document.getElementById("submitContainer").appendChild(userFileNameDiv());
let saveButton = document.createElement("input");
saveButton.setAttribute("type", "submit"); let divContainer = document.createElement("DIV");
saveButton.setAttribute("value", "Save"); divContainer.classList.add("w3-container", "w3-center");
saveButton.classList.add("w3-button");
saveButton.classList.add("w3-grey"); let div = document.createElement("DIV");
saveButton.style.margin = "20px"; div.classList.add("w3-section");
document.getElementById("submitContainer").appendChild(saveButton); div.classList.add("w3-flat-silver");
div.setAttribute("style", "padding: 10px");
let divContainer = document.createElement("DIV");
divContainer.classList.add("w3-container", "w3-center");
let textarea = document.createElement("textarea");
let div = document.createElement("DIV"); textarea.setAttribute("name", "templateInput");
div.classList.add("w3-section"); textarea.setAttribute("id", "templateInput");
div.classList.add("w3-flat-silver"); textarea.setAttribute("cols", "100");
textarea.setAttribute("rows", "30");
div.setAttribute("style", "padding: 10px"); textarea.classList.add("w3-input");
div.appendChild(textarea);
let textarea = document.createElement("textarea"); divContainer.appendChild(div);
textarea.setAttribute("name", "templateInput");
textarea.setAttribute("id", "templateInput");
textarea.setAttribute("cols", "100"); createTemplateDisplay.appendChild(divContainer);
textarea.setAttribute("rows", "30"); return createTemplateDisplay;
textarea.classList.add("w3-input");
}
div.appendChild(textarea);
divContainer.appendChild(div); function formEvts() {
//add event listener to submitContainer
document.getElementById("submitContainer").addEventListener("click", (e) => {
createTemplateDisplay.appendChild(divContainer); if (e.target && e.target.tagName === "INPUT") {
return createTemplateDisplay; switch (e.target.value) {
case "Save":
} let fileName;
let userFileNameField = document.getElementById("userFileName");
let userFileName = userFileNameField.value;
function formEvts() { let userFileNamePH = userFileNameField.getAttribute("placeholder");
//add event listener to submitContainer if (userFileName.length != 0) {
document.getElementById("submitContainer").addEventListener("click", (e) => { fileName = userFileName;
if (e.target && e.target.tagName === "INPUT") { //clear old data as file switches to new filename
switch (e.target.value) { } else if (userFileNamePH.length != 0) {
case "Save": fileName = userFileNamePH;
let fileName; }
let userFileNameField = document.getElementById("userFileName"); let data = document.getElementById("templateInput").value;
let userFileName = userFileNameField.value; setNewTemplate(fileName, data);
let userFileNamePH = userFileNameField.getAttribute("placeholder"); modalNotifier(fileName+" saved!", 1);
if (userFileName.length != 0) { e.target.className = e.target.className.replace(" w3-grey", " w3-flat-nephritis");
fileName = userFileName; e.target.style.pointerEvents = "none";
//clear old data as file switches to new filename const timeoutSave = setTimeout(() => {
} else if (userFileNamePH.length != 0) { e.target.className = e.target.className.replace(" w3-flat-nephritis"," w3-grey");
fileName = userFileNamePH; e.target.style.pointerEvents = "auto";
} }, 250);
let data = document.getElementById("templateInput").value; e.preventDefault;
setNewTemplate(fileName, data); break;
modalNotifier(fileName+" saved!", 1); default:
e.target.className = e.target.className.replace(" w3-grey", " w3-flat-nephritis"); e.preventDefault;
e.target.style.pointerEvents = "none"; }
const timeoutSave = setTimeout(() => { }
e.target.className = e.target.className.replace(" w3-flat-nephritis"," w3-grey"); });
e.target.style.pointerEvents = "auto"; document.getElementById("sidebar").addEventListener("click", (e) => {
}, 250); if (e.target && e.target.matches("li.w3-bar-item")) {
e.preventDefault; let template = e.target.dataset.template;
break; createTemplate(template);
default: }
e.preventDefault; });
} }
}
});
document.getElementById("sidebar").addEventListener("click", (e) => {
if (e.target && e.target.matches("li.w3-bar-item")) { function userFileNameDiv() {
let template = e.target.dataset.template; let divContainer = document.createElement("DIV");
createTemplate(template); divContainer.classList.add("w3-third", "w3-container");
} divContainer.setAttribute("style", "padding: 0px");
}); let div = document.createElement("DIV");
} div.classList.add("w3-section", "w3-flat-silver", "w3-margin-left");
div.setAttribute("style", "padding: 5px");
let userFileNameInput = document.createElement("input");
userFileNameInput.setAttribute("type", "text");
function userFileNameDiv() { userFileNameInput.setAttribute("name", "userFileName");
let divContainer = document.createElement("DIV"); userFileNameInput.setAttribute("placeholder", "Enter a filename");
divContainer.classList.add("w3-third", "w3-container"); userFileNameInput.classList.add("w3-input");
divContainer.setAttribute("style", "padding: 0px"); userFileNameInput.id = "userFileName";
let div = document.createElement("DIV"); div.appendChild(userFileNameInput);
div.classList.add("w3-section", "w3-flat-silver", "w3-margin-left"); divContainer.appendChild(div);
div.setAttribute("style", "padding: 5px"); return divContainer;
let userFileNameInput = document.createElement("input"); }
userFileNameInput.setAttribute("type", "text");
userFileNameInput.setAttribute("name", "userFileName");
userFileNameInput.setAttribute("placeholder", "Enter a filename");
userFileNameInput.classList.add("w3-input");
userFileNameInput.id = "userFileName";
div.appendChild(userFileNameInput);
divContainer.appendChild(div);
return divContainer;
}
export {createTemplate, createTemplateCallBack}; export {createTemplate, createTemplateCallBack};

View File

@ -1,193 +1,220 @@
import { import {
clearData, clearData,
createStorageObj, createStorageObj,
createBookShelf, createBookShelf,
importBookShelf, importBookShelf,
} from "./storage.js"; } from "./storage.js";
import { import {
loadTemplate, loadTemplate,
storeFilesToServer, storeFilesToServer,
setTemplatePreset, setTemplatePreset,
checkForStoredDataOnServer, checkForStoredDataOnServer,
delStoredDataOnServer delStoredDataOnServer
} from "./web.js"; } from "./web.js";
import parseFormOnSubmit from "./parseForm.js"; import parseFormOnSubmit from "./parseForm.js";
import { getUsrId } from "./scripts.js"; import { getUsrId } from "./scripts.js";
function showMenu() { function showMenu() {
var x = document.getElementById("navMob"); var x = document.getElementById("navMob");
if (x.className.indexOf("w3-show") == -1) { if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show"; x.className += " w3-show";
} else { } else {
x.className = x.className.replace(" w3-show", ""); x.className = x.className.replace(" w3-show", "");
} }
if (screen.width < 993) { if (screen.width < 993) {
let sidebar = document.getElementById("sidebar"); let sidebar = document.getElementById("sidebar");
sidebar.style.display = "none"; sidebar.style.display = "none";
} }
} }
function showSidebar() { function showSidebar() {
let sidebar = document.getElementById("sidebar"); let sidebar = document.getElementById("sidebar");
if (getComputedStyle(sidebar).display === "none") { if (getComputedStyle(sidebar).display === "none") {
sidebar.style.display = "block"; sidebar.style.display = "block";
sidebar.style.marginTop = "35px"; sidebar.style.marginTop = "35px";
} else { } else {
sidebar.style.display = "none"; sidebar.style.display = "none";
} }
if (screen.width < 993) { if (screen.width < 993) {
let navBar = document.getElementById("navMob"); let navBar = document.getElementById("navMob");
navBar.className = navBar.className.replace(" w3-show", ""); navBar.className = navBar.className.replace(" w3-show", "");
} }
} }
function showTextBlocks() { function showTextBlocks() {
var x = document.getElementById("navTb"); var x = document.getElementById("navTb");
if (x.className.indexOf("w3-show") == -1) { if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show"; x.className += " w3-show";
} else { } else {
x.className = x.className.replace(" w3-show", ""); x.className = x.className.replace(" w3-show", "");
} }
if (screen.width < 993) { if (screen.width < 993) {
let sidebar = document.getElementById("sidebar"); let sidebar = document.getElementById("sidebar");
sidebar.style.display = "none"; sidebar.style.display = "none";
} }
} }
function insertTextBlocks(t) { function insertTextBlocks(t) {
let insert = "!" + t.innerText.split(":")[0] + " "; let insert = "!" + t.innerText.split(":")[0] + " ";
let id = activeState.lastElement; let id = activeState.lastElement;
let element = document.getElementById(id); let element = document.getElementById(id);
if (element === null) { if (element === null) {
return; return;
} }
element.value += insert; element.value += insert;
let tB = document.getElementById("navTb"); let tB = document.getElementById("navTb");
tB.className.replace(" w3-show", ""); tB.className.replace(" w3-show", "");
element.focus(); element.focus();
} }
function handleOnBlur(t) { function handleOnBlur(t) {
activeState.lastElement = t.id; activeState.lastElement = t.id;
createStorageObj(); createStorageObj();
} }
function clickClearForm() { function clickClearForm() {
//document.activeElement.blur(); //document.activeElement.blur();
//document.getElementById("sidebar").focus(); //document.getElementById("sidebar").focus();
clearData("userInput"); clearData("userInput");
let lT = activeState.loadedTemplate; let lT = activeState.loadedTemplate;
loadTemplate(lT); loadTemplate(lT);
} }
function hideMenus() { function hideMenus() {
let sidebar = document.getElementById("sidebar"); let sidebar = document.getElementById("sidebar");
sidebar.style.display = "none"; sidebar.style.display = "none";
let navBar = document.getElementById("navMob"); let navBar = document.getElementById("navMob");
navBar.className = navBar.className.replace(" w3-show", ""); navBar.className = navBar.className.replace(" w3-show", "");
let tbBar = document.getElementById("navTb"); let tbBar = document.getElementById("navTb");
tbBar.className = tbBar.className.replace(" w3-show", ""); tbBar.className = tbBar.className.replace(" w3-show", "");
} }
function modalNotifier(msg, timeout) { function modalNotifier(msg, timeout) {
let modalElement = document.getElementById("modalNotifier"); let modalElement = document.getElementById("modalNotifier");
let msgElement = document.getElementById("modalMsg"); let msgElement = document.getElementById("modalMsg");
modalElement.style.display = "block"; modalElement.style.display = "block";
msgElement.innerHTML = msg; msgElement.innerHTML = msg;
if (timeout === undefined) { if (timeout === undefined) {
const run = setTimeout(() => (modalElement.style.display = "none"), 5000); const run = setTimeout(() => (modalElement.style.display = "none"), 5000);
} else if (timeout >= 1) { } else if (timeout >= 1) {
const run = setTimeout( const run = setTimeout(
() => (modalElement.style.display = "none"), () => (modalElement.style.display = "none"),
timeout * 1000 timeout * 1000
); );
} }
} }
function clickSetForm(e) { function clickSetForm(e) {
e.preventDefault; e.preventDefault;
let dataArray = parseFormOnSubmit(true); let dataArray = parseFormOnSubmit(true);
let lT = activeState.loadedTemplate; let lT = activeState.loadedTemplate;
setTemplatePreset(lT, JSON.stringify(dataArray)); setTemplatePreset(lT, JSON.stringify(dataArray));
modalNotifier("Form Saved", 2); modalNotifier("Form Saved", 2);
} }
function clickImportFiles() { function clickImportFiles() {
checkForStoredDataOnServer(); if (activeState.localOnly) {
document.getElementById("modalMsg").addEventListener("click", (e) => { createBookShelfDownload();
if (e.target && e.target.tagName === "BUTTON") { return;
let modal = document.getElementById("modalNotifier"); }
switch (e.target.innerHTML) { checkForStoredDataOnServer();
case "Import": document.getElementById("modalMsg").addEventListener("click", (e) => {
modal.replaceWith(modal.cloneNode(true)); if (e.target && e.target.tagName === "BUTTON") {
document.getElementById("modalMsg").addEventListener("click", (e) => { let modal = document.getElementById("modalNotifier");
if (e.target && e.target.tagName === "BUTTON") { switch (e.target.innerHTML) {
let modal = document.getElementById("modalNotifier"); case "Import":
modal.replaceWith(modal.cloneNode(true));
switch (e.target.innerHTML) { document.getElementById("modalMsg").addEventListener("click", (e) => {
case "Yes": if (e.target && e.target.tagName === "BUTTON") {
importBookShelf(); let modal = document.getElementById("modalNotifier");
modal.replaceWith(modal.cloneNode(true));
modalNotifier("Imported!", 2); switch (e.target.innerHTML) {
break; case "Yes":
case "Cancel": importBookShelf();
modal.replaceWith(modal.cloneNode(true)); modal.replaceWith(modal.cloneNode(true));
document.getElementById("modalNotifier").style.display = "none"; modalNotifier("Imported!", 2);
break; break;
default: case "Cancel":
e.preventDefault; modal.replaceWith(modal.cloneNode(true));
} document.getElementById("modalNotifier").style.display = "none";
} break;
}) default:
modalNotifier( e.preventDefault;
"<div class='w3-container'> \ }
Would you like to import the backup created on: "+activeState.serverFilesTs.replace("_", " - ")+ "<br><br> \ }
<button class='w3-button w3-border w3-flat-wet-asphalt' >Yes</button> \ })
<button class='w3-button w3-border w3-flat-wet-asphalt' >Cancel</button></div>", modalNotifier(
0); "<div class='w3-container'> \
break; Would you like to import the backup created on: "+activeState.serverFilesTs.replace("_", " - ")+ "<br><br> \
case "Save": <button class='w3-button w3-border w3-flat-wet-asphalt' >Yes</button> \
storeFilesToServer(createBookShelf()); <button class='w3-button w3-border w3-flat-wet-asphalt' >Cancel</button></div>",
modal.replaceWith(modal.cloneNode(true)); 0);
modalNotifier( break;
"Files saved to server <br><br> would you like to <a href='/storage/" + case "Save":
getUsrId() + storeFilesToServer(createBookShelf());
".txt' style='text-decoration: underline;' download>download</a> them?" modal.replaceWith(modal.cloneNode(true));
); modalNotifier(
break; "Files saved to server <br><br> would you like to <a href='/storage/" +
case "Delete": getUsrId() +
delStoredDataOnServer(); ".txt' style='text-decoration: underline;' download>download</a> them?"
break; ,0);
break;
default: case "Delete":
e.preventDefault; delStoredDataOnServer();
} break;
}
}); default:
modalNotifier( e.preventDefault;
"Here you can manage if your files should be saved on the server \ }
<br> If there are stored files already on the server you can inport them \ }
It will overwrite any saved documents <br><br> \ });
<div class='w3-container'> \ modalNotifier(
<button style='display: none;' id='importModalBtn' class='w3-button w3-border w3-flat-wet-asphalt' >Import</button> \ "Here you can manage if your files should be saved on the server \
<button class='w3-button w3-border w3-flat-wet-asphalt' >Save</button> \ <br> If there are stored files already on the server you can inport them \
<button class='w3-button w3-border w3-flat-pomegranate' >Delete</button></div>", It will overwrite any saved documents <br><br> \
0); <div class='w3-container'> \
<button style='display: none;' id='importModalBtn' class='w3-button w3-border w3-flat-wet-asphalt' >Import</button> \
} <button class='w3-button w3-border w3-flat-wet-asphalt' >Save</button> \
<button class='w3-button w3-border w3-flat-pomegranate' >Delete</button></div>",
export { 0);
hideMenus,
showMenu, }
showSidebar,
showTextBlocks, function createBookShelfDownload() {
insertTextBlocks, let data = createBookShelf();
handleOnBlur, let filename = data[0]['data'] + ".txt";
clickClearForm, document.getElementById("modalMsg").addEventListener("click", (e) => {
modalNotifier, if (e.target && e.target.tagName === "BUTTON") {
clickSetForm, var element = document.createElement('a');
clickImportFiles, element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data)));
}; element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
});
modalNotifier(
"Since you are in local only mode you can only export a backup of your files \
<br><br> \
<div class='w3-container'> \
<button class='w3-button w3-border w3-flat-wet-asphalt' >Export</button></div>"
,0);
}
export {
hideMenus,
showMenu,
showSidebar,
showTextBlocks,
insertTextBlocks,
handleOnBlur,
clickClearForm,
modalNotifier,
clickSetForm,
clickImportFiles
};

View File

@ -1,313 +1,360 @@
import { import {
storeData, storeData,
clearData, clearData,
retrieveData, retrieveData,
createStorageObj, createStorageObj,
} from "./storage.js"; } from "./storage.js";
import { loadTemplate } from "./web.js"; import { loadTemplate } from "./web.js";
import parseFormOnSubmit from "./parseForm.js"; import parseFormOnSubmit from "./parseForm.js";
import { modalNotifier } from "./evts.js";
function buildFile() {
createStorageObj(); function buildFile() {
createStorageObj();
//set current page value in activeState object
activeState.activePage = "files"; //set current page value in activeState object
activeState.activePage = "files";
//check if user is authenticated and templateFilesArray is decryptable
let tF = retrieveData("templateFiles"); //set templateFiles array
if (tF != "") { let tF = JSON.parse(retrieveData("templateFiles"));
try {
tF = JSON.parse(tF); if (tF == null || tF.length == 0) {
} catch (e) { //console.log("none yet");
alert("Decryption failed; are you authenticated?"); modalNotifier("there are no saved texts yet");
window.location.reload(); return;
return; }
}
}
if (screen.width < 993) {
if (tF == null) { document.getElementById("siteTitle").innerHTML = "Saved files";
//console.log("none yet"); } else {
alert("there are no saved texts yet"); document.getElementById("siteTitle").innerHTML = "TG";
return; }
}
//hide set Form button
if (screen.width > 992) { document.getElementById("setFormButton").style.display = "none";
document.getElementById("siteTitle").innerHTML = "Template Gen";
} else { //reset page and event listeners
document.getElementById("siteTitle").innerHTML = "TG"; let mainFormDiv = document.getElementById("mainForm");
} let outputDiv = document.getElementById("output");
let submitContainerDiv = document.getElementById("submitContainer");
//hide set Form button let sidebarDiv = document.getElementById("sidebar");
document.getElementById("setFormButton").style.display = "none";
mainFormDiv.innerHTML = "";
//reset page and event listeners mainFormDiv.replaceWith(mainFormDiv.cloneNode(true));
let mainFormDiv = document.getElementById("mainForm"); outputDiv.innerHTML = "";
let outputDiv = document.getElementById("output"); outputDiv.replaceWith(outputDiv.cloneNode(true));
let submitContainerDiv = document.getElementById("submitContainer"); submitContainerDiv.innerHTML = "";
let sidebarDiv = document.getElementById("sidebar"); submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true));
sidebarDiv.innerHTML = "";
mainFormDiv.innerHTML = ""; sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));
mainFormDiv.replaceWith(mainFormDiv.cloneNode(true));
outputDiv.innerHTML = ""; document.getElementById("mainForm").innerHTML = mainFormPlaceholder();
outputDiv.replaceWith(outputDiv.cloneNode(true));
submitContainerDiv.innerHTML = ""; document.getElementById("sidebar").appendChild(loadFileSidebar(tF));
submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true)); document.getElementById("sidebar").addEventListener("click", (e) => {
sidebarDiv.innerHTML = ""; if (e.target && e.target.matches("li.w3-bar-item")) {
sidebarDiv.replaceWith(sidebarDiv.cloneNode(true)); let fileName = e.target.dataset.file;
let template = e.target.dataset.template;
document.getElementById("mainForm").innerHTML = mainFormPlaceholder(); clickLoadFileDiv(fileName, template);
}
document.getElementById("sidebar").appendChild(loadFileSidebar(tF)); });
document.getElementById("sidebar").addEventListener("click", (e) => { }
if (e.target && e.target.matches("li.w3-bar-item")) {
let fileName = e.target.dataset.file; function loadFileDiv(fileName, template) {
let template = e.target.dataset.template; activeState.fileName = fileName;
clickLoadFileDiv(fileName, template); activeState.loadedTemplate = template;
}
}); storeData("userInputForce", retrieveData(fileName, template));
}
loadTemplate(template, false, true);
function loadFileDiv(fileName, template) { }
activeState.fileName = fileName;
activeState.loadedTemplate = template; function loadFileDivCallBack() {
let tF = JSON.parse(retrieveData("templateFiles"));
storeData("userInputForce", retrieveData(fileName, template)); document.getElementById("sidebar").appendChild(loadFileSidebar(tF));
loadTemplate(template, false, true); let lT = activeState.loadedTemplate;
} let fN = activeState.fileName;
let storageName = fN + "_m21_" + lT;
function loadFileDivCallBack() {
let tF = JSON.parse(retrieveData("templateFiles")); let fileDisplay = document.createElement("DIV");
document.getElementById("sidebar").appendChild(loadFileSidebar(tF)); fileDisplay.classList.add(
"w3-row-padding",
let lT = activeState.loadedTemplate; "w3-padding-24",
let fN = activeState.fileName; "w3-container",
let storageName = fN + "-" + lT; "w3-flat-clouds"
);
let fileDisplay = document.createElement("DIV"); fileDisplay.id = "fileDisplayWrapper";
fileDisplay.classList.add(
"w3-row-padding", //start building submitContainer with edit copy and delete
"w3-padding-24", let editButton = document.createElement("input");
"w3-container", editButton.setAttribute("type", "submit");
"w3-flat-clouds" editButton.setAttribute("value", "Edit");
); editButton.classList.add("w3-button");
fileDisplay.id = "fileDisplayWrapper"; editButton.classList.add("w3-grey");
document.getElementById("submitContainer").appendChild(editButton);
//start building submitContainer with edit copy and delete
let editButton = document.createElement("input"); document
editButton.setAttribute("type", "submit"); .getElementById("submitContainer")
editButton.setAttribute("value", "Edit"); .appendChild(document.createTextNode(" "));
editButton.classList.add("w3-button");
editButton.classList.add("w3-grey"); let copyButton = document.createElement("input");
document.getElementById("submitContainer").appendChild(editButton); copyButton.setAttribute("type", "submit");
copyButton.setAttribute("value", "Copy");
document copyButton.classList.add("w3-button");
.getElementById("submitContainer") copyButton.classList.add("w3-grey");
.appendChild(document.createTextNode(" ")); document.getElementById("submitContainer").appendChild(copyButton);
let copyButton = document.createElement("input"); document
copyButton.setAttribute("type", "submit"); .getElementById("submitContainer")
copyButton.setAttribute("value", "Copy"); .appendChild(document.createTextNode(" "));
copyButton.classList.add("w3-button");
copyButton.classList.add("w3-grey"); let deleteButton = document.createElement("input");
document.getElementById("submitContainer").appendChild(copyButton); deleteButton.setAttribute("type", "submit");
deleteButton.setAttribute("value", "Delete");
document deleteButton.classList.add("w3-button");
.getElementById("submitContainer") deleteButton.classList.add("w3-red");
.appendChild(document.createTextNode(" ")); document.getElementById("submitContainer").appendChild(deleteButton);
let deleteButton = document.createElement("input"); if (screen.width > 992) {
deleteButton.setAttribute("type", "submit"); document.getElementById("siteTitle").innerHTML = lT.replace(/_/g, " ");
deleteButton.setAttribute("value", "Delete"); } else {
deleteButton.classList.add("w3-button"); document.getElementById("siteTitle").innerHTML = "TG";
deleteButton.classList.add("w3-red"); }
document.getElementById("submitContainer").appendChild(deleteButton);
if (screen.width > 992) { let title = document.createElement("div");
document.getElementById("siteTitle").innerHTML = lT.replace(/_/g, " "); title.classList.add("w3-panel");
} else { let titleText = document.createElement("h2");
document.getElementById("siteTitle").innerHTML = "TG"; titleText.innerText = fN.replace(/_/g, " ");
} titleText.style.margin = "0px";
title.appendChild(titleText);
fileDisplay.appendChild(title);
let title = document.createElement("div");
title.classList.add("w3-panel"); let div = document.createElement("div");
let titleText = document.createElement("h2"); div.appendChild(parseFormOnSubmit(false, true));
titleText.innerText = fN.replace(/_/g, " "); fileDisplay.appendChild(div);
titleText.style.margin = "0px"; document.getElementById("mainForm").appendChild(fileDisplay);
title.appendChild(titleText);
fileDisplay.appendChild(title); //add events
formEvts(storageName);
let div = document.createElement("div"); }
div.appendChild(parseFormOnSubmit(false, true));
fileDisplay.appendChild(div); function clickLoadFileDiv(fileName, template) {
document.getElementById("mainForm").appendChild(fileDisplay); if (fileName == "_overflow") return;
//add events if (fileName == "_clearAll") {
formEvts(storageName); clearAllFiles();
} return;
}
function clickLoadFileDiv(fileName, template) {
document.getElementById("mainForm").innerHTML = ""; document.getElementById("mainForm").innerHTML = "";
loadFileDiv(fileName, template); loadFileDiv(fileName, template);
} }
function clearFileData(storData) { function clearFileData(storData) {
let fileName = storData.split("-")[0]; let fileName = storData.split("_m21_")[0];
let tF = JSON.parse(retrieveData("templateFiles")); let tF = JSON.parse(retrieveData("templateFiles"));
let newArray = []; let newArray = [];
for (let obj of tF) { for (let obj of tF) {
if (obj.fileName != fileName) { if (obj.fileName != fileName) {
newArray.push(obj); newArray.push(obj);
} }
} }
storeData("templateFiles", JSON.stringify(newArray)); storeData("templateFiles", JSON.stringify(newArray));
clearData(fileName); clearData(fileName);
clearData("userInput"); clearData("userInput");
document.getElementById("mainForm").innerHTML = ""; document.getElementById("mainForm").innerHTML = "";
document.getElementById("output").innerHTML = ""; document.getElementById("output").innerHTML = "";
document.getElementById("submitContainer").innerHTML = ""; document.getElementById("submitContainer").innerHTML = "";
document.getElementById("sidebar").innerHTML = ""; document.getElementById("sidebar").innerHTML = "";
document.getElementById("mainForm").innerHTML = mainFormPlaceholder(); document.getElementById("mainForm").innerHTML = mainFormPlaceholder();
document.getElementById("sidebar").appendChild(loadFileSidebar(newArray)); document.getElementById("sidebar").appendChild(loadFileSidebar(newArray));
} }
function loadFileSidebar(tF) { function loadFileSidebar(tF) {
let sidebarList = document.createElement("ul"); let sidebarList = document.createElement("ul");
sidebarList.classList.add("w3-ul"); sidebarList.classList.add("w3-ul");
let c = 0;
for (let obj of tF) { let sidebarItemsAmount = 10;
let sidebarListItem = document.createElement("li"); let sidebarListItem;
sidebarListItem.classList.add( for (let obj of tF.reverse()) {
"w3-bar-item", sidebarListItem = document.createElement("li");
"w3-padding-large", sidebarListItem.classList.add(
"w3-button" "w3-bar-item",
); "w3-padding-large",
sidebarListItem.style.borderBottom = "1px solid #ddd"; "w3-button"
sidebarListItem.id = "sb-" + obj.fileName.replace(/:/g, "_"); );
sidebarListItem.innerHTML = sidebarListItem.style.borderBottom = "1px solid #ddd";
obj.fileName.replace(/_/g, " ") + " - " + obj.template.replace(/_/g, " "); sidebarListItem.id = "sb-" + obj.fileName.replace(/:/g, "_");
sidebarListItem.setAttribute("data-file", obj.fileName);
sidebarListItem.setAttribute("data-template", obj.template); if (c > sidebarItemsAmount) {
sidebarList.appendChild(sidebarListItem); sidebarListItem.setAttribute("data-template", '_overflow');
} sidebarListItem.setAttribute("data-file", '_overflow');
return sidebarList; sidebarListItem.classList.add("w3-flat-clouds");
} sidebarListItem.classList.remove("w3-button");
sidebarListItem.style.borderRight = "1px solid rgb(221, 221, 221)"
function mainFormPlaceholder(msg = "Select a file") { sidebarListItem.innerHTML = tF.length - sidebarItemsAmount + " files not shown";
return "<div class='w3-row-padding w3-padding-24 w3-container w3-flat-clouds'><div class='w3-code notranslate w3-border-white' style='font-family: Arial, Helvetica, sans-serif;'><p>" + msg + "</p><br><br><br><br><br><br><br><br><br><br><br></div></div>"; sidebarList.appendChild(sidebarListItem);
} break;
}
function copyFileToClipboard() { sidebarListItem.innerHTML = obj.fileName.replace(/_/g, " ");
const fileDisplay = document.getElementById("fileDisplay"); sidebarListItem.setAttribute("data-file", obj.fileName);
if (fileDisplay != null) { sidebarListItem.setAttribute("data-template", obj.template);
copyToClipBoard(fileDisplay.innerHTML); sidebarList.appendChild(sidebarListItem);
} else { c++;
console.log("error file not found"); }
}
sidebarListItem = document.createElement("li");
} sidebarListItem.classList.add(
"w3-bar-item",
function copyToClipBoard(html) { "w3-padding-large",
// Create an iframe (isolated container) for the HTML "w3-button"
var container = document.createElement("div"); );
container.innerHTML = html; sidebarListItem.style.borderBottom = "1px solid #ddd";
sidebarListItem.setAttribute("data-template", '_clearAll');
// Hide element sidebarListItem.setAttribute("data-file", '_clearAll');
container.style.position = "fixed"; sidebarListItem.classList.add("w3-flat-pomegranate", "w3-bottom");
container.style.pointerEvents = "none"; sidebarListItem.style.borderRight = "1px solid rgb(221, 221, 221)";
container.style.opacity = 0; sidebarListItem.style.width = "300px";
sidebarListItem.innerHTML = "Clear all files";
// Detect all style sheets of the page sidebarList.appendChild(sidebarListItem);
var activeSheets = Array.prototype.slice
.call(document.styleSheets) return sidebarList;
.filter(function (sheet) { }
return !sheet.disabled;
}); function mainFormPlaceholder(msg = "Select a file") {
return "<div class='w3-row-padding w3-padding-24 w3-container w3-flat-clouds'><div class='w3-code notranslate w3-border-white' style='font-family: Arial, Helvetica, sans-serif;'><p>" + msg + "</p><br><br><br><br><br><br><br><br><br><br><br></div></div>";
// Mount the iframe to the DOM to make `contentWindow` available }
document.body.appendChild(container);
function copyFileToClipboard() {
// Copy to clipboard const fileDisplay = document.getElementById("fileDisplay");
window.getSelection().removeAllRanges(); if (fileDisplay != null) {
copyToClipBoard(fileDisplay.innerHTML);
var range = document.createRange(); } else {
range.selectNode(container); console.log("error file not found");
window.getSelection().addRange(range); }
document.execCommand("copy"); }
for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true;
document.execCommand("copy"); function copyToClipBoard(html) {
for (var i = 0; i < activeSheets.length; i++) // Create an iframe (isolated container) for the HTML
activeSheets[i].disabled = false; var container = document.createElement("div");
container.innerHTML = html;
// Remove the iframe
document.body.removeChild(container); // Hide element
} container.style.position = "fixed";
container.style.pointerEvents = "none";
function formEvts(storageName) { container.style.opacity = 0;
//add event listener to submitContainer
document.getElementById("submitContainer").addEventListener("click", (e) => { // Detect all style sheets of the page
if (e.target && e.target.tagName === "INPUT") { var activeSheets = Array.prototype.slice
switch (e.target.value) { .call(document.styleSheets)
case "Edit": .filter(function (sheet) {
loadSpecificTemplate(storageName); return !sheet.disabled;
break; });
case "Copy":
copyFileToClipboard(); // Mount the iframe to the DOM to make `contentWindow` available
e.target.className = e.target.className.replace(" w3-grey", " w3-flat-carrot"); document.body.appendChild(container);
e.target.style.pointerEvents = "none";
const timeoutCopy = setTimeout(() => { // Copy to clipboard
e.target.className = e.target.className.replace(" w3-flat-carrot"," w3-grey"); window.getSelection().removeAllRanges();
e.target.style.pointerEvents = "auto";
}, 250); var range = document.createRange();
break; range.selectNode(container);
case "Delete": window.getSelection().addRange(range);
let previousFile = getPreviousFile(storageName);
clearFileData(storageName); document.execCommand("copy");
document.getElementById("mainForm").innerHTML = ""; for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true;
if (previousFile) { document.execCommand("copy");
loadFileDiv(previousFile.fileName, previousFile.template); for (var i = 0; i < activeSheets.length; i++)
} else { activeSheets[i].disabled = false;
document.getElementById("mainForm").innerHTML = mainFormPlaceholder("No file yet");
} // Remove the iframe
document.body.removeChild(container);
break; }
default:
e.preventDefault; function formEvts(storageName) {
} //add event listener to submitContainer
} document.getElementById("submitContainer").addEventListener("click", (e) => {
}); if (e.target && e.target.tagName === "INPUT") {
} switch (e.target.value) {
case "Edit":
function loadSpecificTemplate(storageName) { loadSpecificTemplate(storageName);
storeData( break;
"userInputForce", case "Copy":
retrieveData(storageName.split("-")[0], storageName.split("-")[1]) copyFileToClipboard();
); e.target.className = e.target.className.replace(" w3-grey", " w3-flat-carrot");
loadTemplate(storageName.split("-")[1]); e.target.style.pointerEvents = "none";
} const timeoutCopy = setTimeout(() => {
e.target.className = e.target.className.replace(" w3-flat-carrot"," w3-grey");
function getPreviousFile(storageName) { e.target.style.pointerEvents = "auto";
}, 250);
let orgFileName = storageName.split("-")[0]; break;
let tF = JSON.parse(retrieveData("templateFiles")); case "Delete":
let i = 0; let previousFile = getPreviousFile(storageName);
let previousFile; clearFileData(storageName);
document.getElementById("mainForm").innerHTML = "";
for (let obj of tF) { if (previousFile) {
if (obj.fileName == orgFileName) { loadFileDiv(previousFile.fileName, previousFile.template);
previousFile = tF[i-1]; } else {
break; document.getElementById("mainForm").innerHTML = mainFormPlaceholder("No file yet");
} }
i++;
} break;
default:
return (previousFile != undefined) ? previousFile : false; e.preventDefault;
} }
}
export { buildFile, loadFileDivCallBack }; });
}
function loadSpecificTemplate(storageName) {
storeData(
"userInputForce",
retrieveData(storageName.split("_m21_")[0], storageName.split("_m21_")[1])
);
//reset sidebar to clear events
let sidebarDiv = document.getElementById("sidebar");
sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));
loadTemplate(storageName.split("_m21_")[1]);
}
function getPreviousFile(storageName) {
let orgFileName = storageName.split("_m21_")[0];
let tF = JSON.parse(retrieveData("templateFiles"));
let i = 0;
let previousFile;
for (let obj of tF) {
if (obj.fileName == orgFileName) {
previousFile = tF[i-1];
if (previousFile === undefined) {
//get the next one if there is no previous one
previousFile = tF[i+1];
}
break;
}
i++;
}
return (previousFile != undefined) ? previousFile : false;
}
function clearAllFiles() {
let tF = JSON.parse(retrieveData("templateFiles"));
if (tF == null || tF.length == 0) {
modalNotifier("there are no saved texts yet");
return;
}
for (let storageName of tF) {
clearFileData(storageName.fileName);
}
}
export { buildFile, loadFileDivCallBack };

View File

@ -1,296 +1,290 @@
//class Form {
// constructor () { import { storeData, createStorageObj } from "./storage.js";
// this.buildForm = buildForm; import parseInput from "./parseTemplate.js";
// this.retrieveForm = retrieveForm; import transformTemplateObject from "./buildForm.js";
// } import { showSidebar, handleOnBlur, modalNotifier } from "./evts.js";
// import parseFormOnSubmit, { parseTextMarkups } from "./parseForm.js";
//
// function buildForm(templateInput, loadOnly = false) {
//} var wordArray = [];
import { storeData, createStorageObj } from "./storage.js"; //display set Form button
import parseInput from "./parseTemplate.js"; document.getElementById("setFormButton").style.display = "block";
import transformTemplateObject from "./buildForm.js";
import { showSidebar, handleOnBlur } from "./evts.js"; //check for presets in "-form.txt" file; indicated by !JSON_placeholder
import parseFormOnSubmit, { parseTextMarkups } from "./parseForm.js"; if (templateInput.indexOf("!JSON_placeholder:") !== -1) {
let jsonPlaceholder = templateInput.split("!JSON_placeholder:")[1];
function buildForm(templateInput, loadOnly = false) { templateInput = templateInput.split("!JSON_placeholder:")[0];
var wordArray = []; storeData("templatePreset", jsonPlaceholder);
}
//display set Form button //start building wordArray by splitting input by line win/unix and define eol char for recreating templateInput
document.getElementById("setFormButton").style.display = "block"; let eol;
if (templateInput.indexOf("\r\n") !== -1) {
//check for presets in "-form.txt" file; indicated by !JSON_placeholder eol = false;
if (templateInput.indexOf("!JSON_placeholder:") !== -1) { var wordArrayByLine = templateInput.split("\r\n");
let jsonPlaceholder = templateInput.split("!JSON_placeholder:")[1]; } else {
templateInput = templateInput.split("!JSON_placeholder:")[0]; eol = true;
storeData("templatePreset", jsonPlaceholder); var wordArrayByLine = templateInput.split("\n");
} }
//start building wordArray by splitting input by line win/unix and define eol char for recreating templateInput //finish building wordArray by Looping through lines and spliting it into one array of words
let eol; //also create temporary templateInput to exclude comments
if (templateInput.indexOf("\r\n") !== -1) { let templateInputArr = [];
eol = false; for (let wordArrayByLineLine of wordArrayByLine) {
var wordArrayByLine = templateInput.split("\r\n"); //ignore "#" comment lines
} else { if (wordArrayByLineLine.substring(0, 1) == "#") {
eol = true; continue;
var wordArrayByLine = templateInput.split("\n"); }
}
//finish building wordArray by Looping through lines and spliting it into one array of words //add words ob lines to wordArray
//also create temporary templateInput to exclude comments wordArray = wordArray.concat(wordArrayByLineLine.split(" "));
let templateInputArr = []; //add line to temp templatearray
for (let wordArrayByLineLine of wordArrayByLine) { templateInputArr.push(wordArrayByLineLine);
//ignore "#" comment lines }
if (wordArrayByLineLine.substring(0, 1) == "#") {
continue; //create templateInput without comments
} templateInput = templateInputArr.join(eol ? "\n" : "\r\n");
//add words ob lines to wordArray //parse text markups like !l !n in templateInput
wordArray = wordArray.concat(wordArrayByLineLine.split(" ")); templateInput = parseTextMarkups(templateInput);
//add line to temp templatearray
templateInputArr.push(wordArrayByLineLine); //set objects array for parseInput Function
} var objects = [];
//loop through words, parse it individually and add it to objects array
//create templateInput without comments
templateInput = templateInputArr.join(eol ? "\n" : "\r\n");
for (let i = 0; i < wordArray.length; i++) {
//parse text markups like !l !n in templateInput parseInput(wordArray, objects, i);
templateInput = parseTextMarkups(templateInput); //console.log(wordArray[i]);
}
//set objects array for parseInput Function
var objects = []; //set individual positionens of objects in string and add it to objects
//loop through words, parse it individually and add it to objects array setStringPos(objects, templateInput);
//save objects array and template file string for web.js in session storage
for (let i = 0; i < wordArray.length; i++) { window.sessionStorage.setItem("templateObjects", JSON.stringify(objects));
parseInput(wordArray, objects, i); window.sessionStorage.setItem("fullString", templateInput);
//console.log(wordArray[i]);
} //sort objects array by words prio
objects = prioritizeArray(objects);
//set individual positionens of objects in string and add it to objects
setStringPos(objects, templateInput); //remove non display objects and safe it to session storage
let objectsPurified = purifyObjects(objects);
//save objects array and template file string for web.js in session storage window.sessionStorage.setItem(
window.sessionStorage.setItem("templateObjects", JSON.stringify(objects)); "templateObjectsPurified",
window.sessionStorage.setItem("fullString", templateInput); JSON.stringify(objectsPurified)
);
//sort objects array by words prio
objects = prioritizeArray(objects); //reset page and event listeners
let mainFormDiv = document.getElementById("mainForm");
//remove non display objects and safe it to session storage let outputDiv = document.getElementById("output");
let objectsPurified = purifyObjects(objects); let submitContainerDiv = document.getElementById("submitContainer");
window.sessionStorage.setItem( let sidebarDiv = document.getElementById("sidebar");
"templateObjectsPurified", //sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));
JSON.stringify(objectsPurified)
); mainFormDiv.innerHTML = "";
mainFormDiv.replaceWith(mainFormDiv.cloneNode(true));
//reset page and event listeners outputDiv.innerHTML = "";
let mainFormDiv = document.getElementById("mainForm"); outputDiv.replaceWith(outputDiv.cloneNode(true));
let outputDiv = document.getElementById("output"); submitContainerDiv.innerHTML = "";
let submitContainerDiv = document.getElementById("submitContainer"); submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true));
let sidebarDiv = document.getElementById("sidebar"); sidebarDiv.innerHTML = "";
//sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));
//finally build html code for Form and siddebar and add it to dom if needed
mainFormDiv.innerHTML = ""; if (loadOnly) {return};
mainFormDiv.replaceWith(mainFormDiv.cloneNode(true));
outputDiv.innerHTML = ""; transformTemplateObject(objectsPurified);
outputDiv.replaceWith(outputDiv.cloneNode(true)); //add events
submitContainerDiv.innerHTML = ""; formEvts();
submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true)); }
sidebarDiv.innerHTML = "";
function prioritizeArray(objects) {
//finally build html code for Form and siddebar and add it to dom if needed let prioArray = [];
if (loadOnly) {return}; let objects_sorted = [];
transformTemplateObject(objectsPurified); for (let valPreSorted of objects) {
//add events prioArray.push(valPreSorted.prio);
formEvts(); }
} prioArray.sort(function (a, b) {
return a - b;
function prioritizeArray(objects) { });
let prioArray = []; //console.log(prioArray);
let objects_sorted = []; for (let valSorted of prioArray) {
for (let obj of objects) {
for (let valPreSorted of objects) { if (valSorted === obj.prio) {
prioArray.push(valPreSorted.prio); objects_sorted.push(obj);
} if (obj.prio !== 0) {
prioArray.sort(function (a, b) { break;
return a - b; }
}); }
//console.log(prioArray); }
for (let valSorted of prioArray) { }
for (let obj of objects) { return objects_sorted;
if (valSorted === obj.prio) { }
objects_sorted.push(obj);
if (obj.prio !== 0) { function purifyObjects(objects) {
break; let objectsPurified = [];
} let objectsPrePurified = [];
} for (let objPrePurified of objects) {
} if (!objectsPrePurified.includes(objPrePurified.word)) {
} objectsPurified.push(objPrePurified);
return objects_sorted; }
} objectsPrePurified.push(objPrePurified.word);
}
function purifyObjects(objects) { return objectsPurified;
let objectsPurified = []; }
let objectsPrePurified = [];
for (let objPrePurified of objects) { function setStringPos(objects, fullStringMaster) {
if (!objectsPrePurified.includes(objPrePurified.word)) { let stringCursor = 0;
objectsPurified.push(objPrePurified); let startPos = 0;
} let endPos = 0;
objectsPrePurified.push(objPrePurified.word); let fullString = "";
} for (let obj of objects) {
return objectsPurified; fullString = fullStringMaster.substring(stringCursor);
} if (fullString.indexOf("%" + obj.word) !== -1) {
startPos = 0;
function setStringPos(objects, fullStringMaster) { endPos = 0;
let stringCursor = 0; startPos = fullString.indexOf("%" + obj.word) + stringCursor;
let startPos = 0; let objPrioLength = 1;
let endPos = 0; if (obj.prio > 9) {
let fullString = ""; objPrioLength = 2;
for (let obj of objects) { }
fullString = fullStringMaster.substring(stringCursor); if (obj.prio == 0) {
if (fullString.indexOf("%" + obj.word) !== -1) { objPrioLength = 0;
startPos = 0; }
endPos = 0;
startPos = fullString.indexOf("%" + obj.word) + stringCursor; switch (obj.type) {
let objPrioLength = 1; case "simpleInput":
if (obj.prio > 9) { endPos = startPos + 2 + obj.word.length + objPrioLength;
objPrioLength = 2; break;
} case "genderSpecific":
if (obj.prio == 0) { let gSC = 0;
objPrioLength = 0; if (typeof obj.m !== "undefined") {
} gSC = gSC + obj.m.length + 3;
}
switch (obj.type) { if (typeof obj.w !== "undefined") {
case "simpleInput": gSC = gSC + obj.w.length + 3;
endPos = startPos + 2 + obj.word.length + objPrioLength; }
break; if (typeof obj.d !== "undefined") {
case "genderSpecific": gSC = gSC + obj.d.length + 3;
let gSC = 0; }
if (typeof obj.m !== "undefined") { endPos = startPos + 2 + gSC + objPrioLength + obj.word.length + 1;
gSC = gSC + obj.m.length + 3; break;
} case "list":
if (typeof obj.w !== "undefined") { let gSC1 = 0;
gSC = gSC + obj.w.length + 3; for (
} let objListItem = 0;
if (typeof obj.d !== "undefined") { objListItem < obj.listCount + 1;
gSC = gSC + obj.d.length + 3; objListItem++
} ) {
endPos = startPos + 2 + gSC + objPrioLength + obj.word.length + 1; if (typeof obj[objListItem] !== "undefined") {
break; gSC1 = gSC1 + obj[objListItem].length + 3;
case "list": }
let gSC1 = 0; }
for ( endPos = startPos + 2 + gSC1 + objPrioLength + obj.word.length + 1;
let objListItem = 0; break;
objListItem < obj.listCount + 1; case "conList":
objListItem++ let gSC2 = 0;
) { for (
if (typeof obj[objListItem] !== "undefined") { let objListItem = 0;
gSC1 = gSC1 + obj[objListItem].length + 3; objListItem < obj.listCount + 1;
} objListItem++
} ) {
endPos = startPos + 2 + gSC1 + objPrioLength + obj.word.length + 1; if (typeof obj[objListItem] !== "undefined") {
break; gSC2 = gSC2 + obj[objListItem].length + obj["clType-"+obj[objListItem]].length + 4;
case "conList": if (obj["clType-"+obj[objListItem]] == "cl-simpleInput") {
let gSC2 = 0; gSC2 = gSC2 - obj["clType-"+obj[objListItem]].length;
for ( }
let objListItem = 0; }
objListItem < obj.listCount + 1; }
objListItem++ endPos = startPos + 2 + gSC2 + objPrioLength + obj.word.length + 1;
) { break;
if (typeof obj[objListItem] !== "undefined") { default:
gSC2 = gSC2 + obj[objListItem].length + obj["clType-"+obj[objListItem]].length + 4; endPos =
if (obj["clType-"+obj[objListItem]] == "cl-simpleInput") { startPos +
gSC2 = gSC2 - obj["clType-"+obj[objListItem]].length; 2 +
} obj.word.length +
} 1 +
} obj.type.length +
endPos = startPos + 2 + gSC2 + objPrioLength + obj.word.length + 1; objPrioLength;
break; break;
default: }
endPos = obj.spos = startPos;
startPos + obj.epos = endPos;
2 + stringCursor = endPos;
obj.word.length + }
1 + }
obj.type.length + }
objPrioLength;
break; function formEvts() {
} //add event for main copy button
obj.spos = startPos; document.getElementById("submitContainer").addEventListener("click", (e) => {
obj.epos = endPos; if (e.target && e.target.tagName === "INPUT") {
stringCursor = endPos; switch (e.target.value) {
} case "Copy":
} createStorageObj();
} parseFormOnSubmit();
e.target.className = e.target.className.replace(" w3-grey", " w3-flat-carrot");
function formEvts() { e.target.style.pointerEvents = "none";
//add event for main copy button const timeoutCopy = setTimeout(() => {
document.getElementById("submitContainer").addEventListener("click", (e) => { e.target.className = e.target.className.replace(" w3-flat-carrot"," w3-grey");
if (e.target && e.target.tagName === "INPUT") { e.target.style.pointerEvents = "auto";
switch (e.target.value) { }, 250);
case "Copy": break;
createStorageObj(); case "Save":
parseFormOnSubmit(); createStorageObj();
e.target.className = e.target.className.replace(" w3-grey", " w3-flat-carrot"); e.target.className = e.target.className.replace(" w3-grey", " w3-flat-nephritis");
e.target.style.pointerEvents = "none"; e.target.style.pointerEvents = "none";
const timeoutCopy = setTimeout(() => { modalNotifier(activeState.fileName + " saved", 2);
e.target.className = e.target.className.replace(" w3-flat-carrot"," w3-grey"); const timeoutSave = setTimeout(() => {
e.target.style.pointerEvents = "auto"; e.target.className = e.target.className.replace(" w3-flat-nephritis"," w3-grey");
}, 250); e.target.style.pointerEvents = "auto";
break; }, 250);
case "Save": break;
createStorageObj(); default:
e.target.className = e.target.className.replace(" w3-grey", " w3-flat-nephritis"); e.preventDefault;
e.target.style.pointerEvents = "none"; }
const timeoutSave = setTimeout(() => { }
e.target.className = e.target.className.replace(" w3-flat-nephritis"," w3-grey"); });
e.target.style.pointerEvents = "auto";
}, 250); //add sidebar events
break; document.getElementById("sidebar").addEventListener("click", (e) => {
default: if (e.target) {
e.preventDefault; if (e.target.id == "sb-submit") {
} if (screen.width < 993) {
} showSidebar();
}); }
parseFormOnSubmit();
//add sidebar events focusOnField("output");
document.getElementById("sidebar").addEventListener("click", (e) => { }
if (e.target) { if (e.target.id == "sb-item") {
if (e.target.id == "sb-submit") { setTimeout(() => {
if (screen.width < 993) { focusOnField(e.target.dataset.item);
showSidebar(); }, 100);
} }
parseFormOnSubmit(); }
focusOnField("output"); });
}
if (e.target.id == "sb-item") { //add handle on blur event listener to each form object
setTimeout(() => { let mainForm = document.getElementById("mainFormObj");
focusOnField(e.target.dataset.item); for (let formElement of mainForm.children) {
}, 100); let id = formElement.firstChild.lastChild.id;
} document.getElementById(id).addEventListener("blur", (e) => {
} e.preventDefault;
}); handleOnBlur(e.target);
});
//add handle on blur event listener }
document.getElementById("mainForm").addEventListener("click", (e) => { }
if (e.target && e.target.matches("div.w3-section")) {
e.preventDefault; function focusOnField(id) {
handleOnBlur(e.target); let targetElement = document.getElementById(id);
} if (targetElement == null) return;
});
} document.activeElement.blur();
targetElement.focus();
function focusOnField(id) { setTimeout(function () {
let targetElement = document.getElementById(id); let offset = targetElement.offsetTop - 100;
if (targetElement == null) return; window.scrollTo(0, offset);
}, 100);
document.activeElement.blur(); }
targetElement.focus();
setTimeout(function () { export default buildForm;
let offset = targetElement.offsetTop - 100;
window.scrollTo(0, offset);
}, 100);
}
export default buildForm;

View File

@ -1,247 +1,247 @@
const getBrowserFingerprint = ({ hardwareOnly = false, enableWebgl = false, debug = false } = {}) => { const getBrowserFingerprint = ({ hardwareOnly = false, enableWebgl = false, debug = false } = {}) => {
const devicePixelRatio = +parseInt(window.devicePixelRatio); const devicePixelRatio = +parseInt(window.devicePixelRatio);
const { const {
appName, appName,
appCodeName, appCodeName,
appVersion, appVersion,
cookieEnabled, cookieEnabled,
deviceMemory, deviceMemory,
doNotTrack, doNotTrack,
hardwareConcurrency, hardwareConcurrency,
language, language,
languages, languages,
maxTouchPoints, maxTouchPoints,
platform, platform,
product, product,
productSub, productSub,
userAgent, userAgent,
vendor, vendor,
vendorSub, vendorSub,
} = window.navigator; } = window.navigator;
const { width, height, colorDepth, pixelDepth } = window.screen; const { width, height, colorDepth, pixelDepth } = window.screen;
const timezoneOffset = new Date().getTimezoneOffset(); const timezoneOffset = new Date().getTimezoneOffset();
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const touchSupport = 'ontouchstart' in window; const touchSupport = 'ontouchstart' in window;
const canvas = getCanvasID(debug); const canvas = getCanvasID(debug);
const webgl = enableWebgl ? getWebglID(debug) : undefined; // undefined will remove this from the stringify down here const webgl = enableWebgl ? getWebglID(debug) : undefined; // undefined will remove this from the stringify down here
const webglInfo = enableWebgl ? getWebglInfo(debug) : undefined; // undefined will remove this from the stringify down here const webglInfo = enableWebgl ? getWebglInfo(debug) : undefined; // undefined will remove this from the stringify down here
const data = hardwareOnly const data = hardwareOnly
? JSON.stringify({ ? JSON.stringify({
canvas, canvas,
colorDepth, colorDepth,
deviceMemory, deviceMemory,
devicePixelRatio, devicePixelRatio,
hardwareConcurrency, hardwareConcurrency,
height, height,
maxTouchPoints, maxTouchPoints,
pixelDepth, pixelDepth,
platform, platform,
touchSupport, touchSupport,
webgl, webgl,
webglInfo, webglInfo,
width, width,
}) })
: JSON.stringify({ : JSON.stringify({
appCodeName, appCodeName,
appName, appName,
appVersion, appVersion,
canvas, canvas,
colorDepth, colorDepth,
cookieEnabled, cookieEnabled,
deviceMemory, deviceMemory,
devicePixelRatio, devicePixelRatio,
doNotTrack, doNotTrack,
hardwareConcurrency, hardwareConcurrency,
height, height,
language, language,
languages, languages,
maxTouchPoints, maxTouchPoints,
pixelDepth, pixelDepth,
platform, platform,
product, product,
productSub, productSub,
timezone, timezone,
timezoneOffset, timezoneOffset,
touchSupport, touchSupport,
userAgent, userAgent,
vendor, vendor,
vendorSub, vendorSub,
webgl, webgl,
webglInfo, webglInfo,
width, width,
}); });
const datastring = JSON.stringify(data, null, 4); const datastring = JSON.stringify(data, null, 4);
if (debug) console.log('fingerprint data', datastring); if (debug) console.log('fingerprint data', datastring);
const result = murmurhash3_32_gc(datastring); const result = murmurhash3_32_gc(datastring);
return result; return result;
}; };
export const getCanvasID = (debug) => { export const getCanvasID = (debug) => {
try { try {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
const text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~1!2@3#4$5%6^7&8*9(0)-_=+[{]}|;:',<.>/?"; const text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~1!2@3#4$5%6^7&8*9(0)-_=+[{]}|;:',<.>/?";
ctx.textBaseline = 'top'; ctx.textBaseline = 'top';
ctx.font = "14px 'Arial'"; ctx.font = "14px 'Arial'";
ctx.textBaseline = 'alphabetic'; ctx.textBaseline = 'alphabetic';
ctx.fillStyle = '#f60'; ctx.fillStyle = '#f60';
ctx.fillRect(125, 1, 62, 20); ctx.fillRect(125, 1, 62, 20);
ctx.fillStyle = '#069'; ctx.fillStyle = '#069';
ctx.fillText(text, 2, 15); ctx.fillText(text, 2, 15);
ctx.fillStyle = 'rgba(102, 204, 0, 0.7)'; ctx.fillStyle = 'rgba(102, 204, 0, 0.7)';
ctx.fillText(text, 4, 17); ctx.fillText(text, 4, 17);
const result = canvas.toDataURL(); const result = canvas.toDataURL();
if (debug) { if (debug) {
document.body.appendChild(canvas); document.body.appendChild(canvas);
} else { } else {
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height);
} }
return murmurhash3_32_gc(result); return murmurhash3_32_gc(result);
} catch { } catch {
return null; return null;
} }
}; };
export const getWebglID = (debug) => { export const getWebglID = (debug) => {
try { try {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const ctx = canvas.getContext('webgl'); const ctx = canvas.getContext('webgl');
canvas.width = 256; canvas.width = 256;
canvas.height = 128; canvas.height = 128;
const f = const f =
'attribute vec2 attrVertex;varying vec2 varyinTexCoordinate;uniform vec2 uniformOffset;void main(){varyinTexCoordinate=attrVertex+uniformOffset;gl_Position=vec4(attrVertex,0,1);}'; 'attribute vec2 attrVertex;varying vec2 varyinTexCoordinate;uniform vec2 uniformOffset;void main(){varyinTexCoordinate=attrVertex+uniformOffset;gl_Position=vec4(attrVertex,0,1);}';
const g = 'precision mediump float;varying vec2 varyinTexCoordinate;void main() {gl_FragColor=vec4(varyinTexCoordinate,0,1);}'; const g = 'precision mediump float;varying vec2 varyinTexCoordinate;void main() {gl_FragColor=vec4(varyinTexCoordinate,0,1);}';
const h = ctx.createBuffer(); const h = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, h); ctx.bindBuffer(ctx.ARRAY_BUFFER, h);
const i = new Float32Array([-0.2, -0.9, 0, 0.4, -0.26, 0, 0, 0.7321, 0]); const i = new Float32Array([-0.2, -0.9, 0, 0.4, -0.26, 0, 0, 0.7321, 0]);
ctx.bufferData(ctx.ARRAY_BUFFER, i, ctx.STATIC_DRAW), (h.itemSize = 3), (h.numItems = 3); ctx.bufferData(ctx.ARRAY_BUFFER, i, ctx.STATIC_DRAW), (h.itemSize = 3), (h.numItems = 3);
const j = ctx.createProgram(); const j = ctx.createProgram();
const k = ctx.createShader(ctx.VERTEX_SHADER); const k = ctx.createShader(ctx.VERTEX_SHADER);
ctx.shaderSource(k, f); ctx.shaderSource(k, f);
ctx.compileShader(k); ctx.compileShader(k);
const l = ctx.createShader(ctx.FRAGMENT_SHADER); const l = ctx.createShader(ctx.FRAGMENT_SHADER);
ctx.shaderSource(l, g); ctx.shaderSource(l, g);
ctx.compileShader(l); ctx.compileShader(l);
ctx.attachShader(j, k); ctx.attachShader(j, k);
ctx.attachShader(j, l); ctx.attachShader(j, l);
ctx.linkProgram(j); ctx.linkProgram(j);
ctx.useProgram(j); ctx.useProgram(j);
j.vertexPosAttrib = ctx.getAttribLocation(j, 'attrVertex'); j.vertexPosAttrib = ctx.getAttribLocation(j, 'attrVertex');
j.offsetUniform = ctx.getUniformLocation(j, 'uniformOffset'); j.offsetUniform = ctx.getUniformLocation(j, 'uniformOffset');
ctx.enableVertexAttribArray(j.vertexPosArray); ctx.enableVertexAttribArray(j.vertexPosArray);
ctx.vertexAttribPointer(j.vertexPosAttrib, h.itemSize, ctx.FLOAT, !1, 0, 0); ctx.vertexAttribPointer(j.vertexPosAttrib, h.itemSize, ctx.FLOAT, !1, 0, 0);
ctx.uniform2f(j.offsetUniform, 1, 1); ctx.uniform2f(j.offsetUniform, 1, 1);
ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, h.numItems); ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, h.numItems);
const n = new Uint8Array(canvas.width * canvas.height * 4); const n = new Uint8Array(canvas.width * canvas.height * 4);
ctx.readPixels(0, 0, canvas.width, canvas.height, ctx.RGBA, ctx.UNSIGNED_BYTE, n); ctx.readPixels(0, 0, canvas.width, canvas.height, ctx.RGBA, ctx.UNSIGNED_BYTE, n);
const result = JSON.stringify(n).replace(/,?"[0-9]+":/g, ''); const result = JSON.stringify(n).replace(/,?"[0-9]+":/g, '');
if (debug) { if (debug) {
document.body.appendChild(canvas); document.body.appendChild(canvas);
} else { } else {
ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT | ctx.STENCIL_BUFFER_BIT); ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT | ctx.STENCIL_BUFFER_BIT);
} }
return murmurhash3_32_gc(result); return murmurhash3_32_gc(result);
} catch { } catch {
return null; return null;
} }
}; };
export const getWebglInfo = () => { export const getWebglInfo = () => {
try { try {
const ctx = document.createElement('canvas').getContext('webgl'); const ctx = document.createElement('canvas').getContext('webgl');
const result = { const result = {
VERSION: ctx.getParameter(ctx.VERSION), VERSION: ctx.getParameter(ctx.VERSION),
SHADING_LANGUAGE_VERSION: ctx.getParameter(ctx.SHADING_LANGUAGE_VERSION), SHADING_LANGUAGE_VERSION: ctx.getParameter(ctx.SHADING_LANGUAGE_VERSION),
VENDOR: ctx.getParameter(ctx.VENDOR), VENDOR: ctx.getParameter(ctx.VENDOR),
SUPORTED_EXTENSIONS: ctx.getSupportedExtensions(), SUPORTED_EXTENSIONS: ctx.getSupportedExtensions(),
}; };
return result; return result;
} catch { } catch {
return null; return null;
} }
}; };
export const murmurhash3_32_gc = (key) => { export const murmurhash3_32_gc = (key) => {
const remainder = key.length & 3; // key.length % 4 const remainder = key.length & 3; // key.length % 4
const bytes = key.length - remainder; const bytes = key.length - remainder;
const c1 = 0xcc9e2d51; const c1 = 0xcc9e2d51;
const c2 = 0x1b873593; const c2 = 0x1b873593;
let h1, h1b, k1; let h1, h1b, k1;
for (let i = 0; i < bytes; i++) { for (let i = 0; i < bytes; i++) {
k1 = (key.charCodeAt(i) & 0xff) | ((key.charCodeAt(++i) & 0xff) << 8) | ((key.charCodeAt(++i) & 0xff) << 16) | ((key.charCodeAt(++i) & 0xff) << 24); k1 = (key.charCodeAt(i) & 0xff) | ((key.charCodeAt(++i) & 0xff) << 8) | ((key.charCodeAt(++i) & 0xff) << 16) | ((key.charCodeAt(++i) & 0xff) << 24);
++i; ++i;
k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1; h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19); h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) & 0xffffffff; h1b = ((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) & 0xffffffff;
h1 = (h1b & 0xffff) + 0x6b64 + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16); h1 = (h1b & 0xffff) + 0x6b64 + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16);
} }
const i = bytes - 1; const i = bytes - 1;
k1 = 0; k1 = 0;
switch (remainder) { switch (remainder) {
case 3: { case 3: {
k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
break; break;
} }
case 2: { case 2: {
k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
break; break;
} }
case 1: { case 1: {
k1 ^= key.charCodeAt(i) & 0xff; k1 ^= key.charCodeAt(i) & 0xff;
break; break;
} }
} }
k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1; h1 ^= k1;
h1 ^= key.length; h1 ^= key.length;
h1 ^= h1 >>> 16; h1 ^= h1 >>> 16;
h1 = ((h1 & 0xffff) * 0x85ebca6b + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; h1 = ((h1 & 0xffff) * 0x85ebca6b + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13; h1 ^= h1 >>> 13;
h1 = ((h1 & 0xffff) * 0xc2b2ae35 + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) & 0xffffffff; h1 = ((h1 & 0xffff) * 0xc2b2ae35 + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 16; h1 ^= h1 >>> 16;
return h1 >>> 0; return h1 >>> 0;
}; };
export default getBrowserFingerprint; export default getBrowserFingerprint;

View File

@ -1,151 +1,160 @@
import { hideMenus, showMenu, showSidebar, showTextBlocks, clickSetForm, clickImportFiles } from "./evts.js"; import { hideMenus, showMenu, showSidebar, showTextBlocks, clickSetForm, clickImportFiles } from "./evts.js";
import { buildFile } from "./files.js"; import { buildFile } from "./files.js";
import setPassword, { passwordHash } from "./scripts.js"; import setPassword, { passwordHash, sessionVerification } from "./scripts.js";
import { getUsrId } from "./scripts.js"; import { getUsrId, logout } from "./scripts.js";
import parseFormOnSubmit from "./parseForm.js"; import parseFormOnSubmit from "./parseForm.js";
import { createStorageObj } from "./storage.js"; import { createStorageObj } from "./storage.js";
import XORCipher from "./xorc.js"; import XORCipher from "./xorc.js";
import sha256 from "./sha256.min.js"; import sha256 from "./sha256.min.js";
import { loadNavBar, initTextBlocks } from "./web.js"; import { loadNavBar, initTextBlocks } from "./web.js";
window.activeState = { window.activeState = {
userId: getUsrId(), userId: getUsrId(),
activePage: "landing", activePage: "landing",
loadedTemplate: "", loadedTemplate: "",
fileName: "", fileName: "",
lastElement: "", lastElement: "",
serverFilesTs: "", serverFilesTs: "",
templates: [], lineBreak: 100,
templateFieldTypes: [ localOnly: true,
"simpleInput", templates: [],
"longText", templateFieldTypes: [
"hiddenField", "simpleInput",
"current_time", "longText",
"current_date", "hiddenField",
"markup", "current_time",
], "current_date",
markups: [ "markup",
"title", ],
"link", markups: [
"italic", "title",
"green_highlighted", "link",
"highlighted", "italic",
] "green_highlighted",
}; "highlighted",
]
};
function init() {
//check if user is logged in function init() {
let verfiedStatus = window.sessionStorage.getItem(sha256("verified"));
if (verfiedStatus != null) { //check if user is logged in
//user logged in sessionVerification();
let verfiedStatus = window.sessionStorage.getItem(sha256("verified"));
//write verifiedStatus content into passwordHash for decode check later if (verfiedStatus != null) {
passwordHash.set(XORCipher.decode(sha256("passwordHash"), verfiedStatus)); //user logged in
document.getElementById("login").style.display = "none";
//write verifiedStatus content into passwordHash for decode check later
} else { passwordHash.set(XORCipher.decode(sha256("passwordHash"), verfiedStatus));
document.getElementById("login").style.display = "block"; document.getElementById("login").style.display = "none";
}
} else {
//load NavigationBar with templates according to server document.getElementById("login").style.display = "block";
loadNavBar(); }
//init Textblocks field with entries according to server //load NavigationBar with templates according to server
initTextBlocks(); loadNavBar();
//add event listeners to document and window //init Textblocks field with entries according to server
eventListeners(); initTextBlocks();
//print current version to footer //add event listeners to document and window
printVersion(); eventListeners();
//adjust title for mobile use //print current version to footer
if (screen.width < 993) { printVersion();
document.getElementById("siteTitle").innerHTML = "TG";
} //add sign out
document
.getElementById("logout")
.addEventListener("click", logout);
}
function eventListeners() { //adjust title for mobile use
if (screen.width < 993) {
//add hideMenu to Body document.getElementById("siteTitle").innerHTML = "TG";
document }
.getElementsByClassName("w3-main")[0]
.addEventListener("click", hideMenus);
//add set Password to loginForm }
document
.getElementById("submitPassword") function eventListeners() {
.addEventListener("click", setPassword);
//add toggle Navigation Menu //add hideMenu to Body
document document
.getElementById("toggleNavigationMenu") .getElementsByClassName("w3-main")[0]
.addEventListener("click", showMenu); .addEventListener("click", hideMenus);
//add loadTemplateBtn event showMenu
document //add set Password to loginForm
.getElementById("loadTemplateBtn") document
.addEventListener("click", showMenu); .getElementById("submitPassword")
//add toggle sideBar Menu .addEventListener("click", setPassword);
document //add toggle Navigation Menu
.getElementById("toggleSidebarMenu") document
.addEventListener("click", showSidebar); .getElementById("toggleNavigationMenu")
//add toggle files Menu and sidebar button .addEventListener("click", showMenu);
document //add loadTemplateBtn event showMenu
.getElementById("toggleFilesMenuSB") document
.addEventListener("click", buildFile); .getElementById("loadTemplateBtn")
document .addEventListener("click", showMenu);
.getElementById("toggleFilesMenu") //add toggle sideBar Menu
.addEventListener("click", buildFile); document
//add load template sidebar entry .getElementById("toggleSidebarMenu")
document .addEventListener("click", showSidebar);
.getElementById("loadTemplateBtn") //add toggle files Menu and sidebar button
.addEventListener("click", showMenu); document
//add toggle textBLocks Menu .getElementById("toggleFilesMenuSB")
document .addEventListener("click", buildFile);
.getElementById("toggleTestBlocksMenu") document
.addEventListener("click", showTextBlocks); .getElementById("toggleFilesMenu")
.addEventListener("click", buildFile);
//add setFormBtn for use in form //add load template sidebar entry
document document
.getElementById("setFormBtn") .getElementById("loadTemplateBtn")
.addEventListener("click", (e) => clickSetForm(e)); .addEventListener("click", showMenu);
//add toggle textBLocks Menu
//add saveFiles to server listener on launch page document
document .getElementById("toggleTestBlocksMenu")
.getElementById("importFilesSB") .addEventListener("click", showTextBlocks);
.addEventListener("click", () => clickImportFiles());
//add setFormBtn for use in form
//add key listener for ctrl s in form mode document
window.addEventListener("keydown", (e) => { .getElementById("setFormBtn")
.addEventListener("click", (e) => clickSetForm(e));
if (e.ctrlKey && e.key == "s") {
if (activeState.activePage == "form"); //add saveFiles to server listener on launch page
createStorageObj(); document
parseFormOnSubmit(); .getElementById("importFilesSB")
e.preventDefault(); .addEventListener("click", () => clickImportFiles());
}
}) //add key listener for ctrl s in form mode
} window.addEventListener("keydown", (e) => {
function printVersion() { if (e.ctrlKey && e.key == "s") {
const scripts = document.getElementsByTagName("script"); if (activeState.activePage == "form");
const versionSpan = document.getElementById("currentVersion").lastChild; createStorageObj();
parseFormOnSubmit();
for (var i=0;i<scripts.length;i++) { e.preventDefault();
if (scripts[i].src) { }
let source = scripts[i].src; })
// js/version/main.js }
let pathVersion = source.split("/");
pathVersion = pathVersion[pathVersion.length-2]; function printVersion() {
//add it to document footer currentVersion const scripts = document.getElementsByTagName("script");
versionSpan.textContent = "version: " + pathVersion; const versionSpan = document.getElementById("currentVersion").lastChild;
}
} for (var i=0;i<scripts.length;i++) {
} if (scripts[i].src) {
let source = scripts[i].src;
export default init; // js/version/main.js
let pathVersion = source.split("/");
pathVersion = pathVersion[pathVersion.length-2];
//add it to document footer currentVersion
versionSpan.textContent = "version: " + pathVersion;
}
}
}
export default init;

View File

@ -1,7 +1,7 @@
import init from "./init.js"; import init from "./init.js";
document.addEventListener("DOMContentLoaded", () => init()); document.addEventListener("DOMContentLoaded", () => init());

View File

@ -1,362 +1,441 @@
import { storeData, clearData, retrieveData } from "./storage.js"; import { storeData, clearData, retrieveData } from "./storage.js";
function parseFormOnSubmit(returnJSON = false, parseOnly = false) { function parseFormOnSubmit(returnJSON = false, parseOnly = false) {
//event.preventDefault; //event.preventDefault;
let dataArray = []; let dataArray = [];
if (parseOnly) { if (parseOnly) {
let lT = activeState.loadedTemplate; let lT = activeState.loadedTemplate;
dataArray = retrieveData("userInputForce", lT); dataArray = retrieveData("userInputForce", lT);
if (dataArray != "") { if (dataArray != "") {
try { try {
dataArray = JSON.parse(dataArray); dataArray = JSON.parse(dataArray);
} catch (e) { } catch (e) {
alert("Decryption failed; are you authenticated?"); return "";
window.location.reload(); }
return; }
} if (dataArray == null) {
} let wrapper = document.createElement("div");
if (dataArray == null) { wrapper.innerHTML = mainFormPlaceholder();
let wrapper = document.createElement("div"); let div = wrapper.firstChild;
wrapper.innerHTML = mainFormPlaceholder(); return div;
let div = wrapper.firstChild; }
return div;
} if (dataArray.length <= 0) {
let wrapper = document.createElement("div");
if (dataArray.length <= 0) { wrapper.innerHTML = mainFormPlaceholder();
let wrapper = document.createElement("div"); let div = wrapper.firstChild;
wrapper.innerHTML = mainFormPlaceholder(); return div;
let div = wrapper.firstChild; }
return div;
} } else {
let x = document.getElementById("mainFormObj");
} else {
let x = document.getElementById("mainFormObj"); if (x != null) {
for (let i = 0; i < x.length; i++) {
if (x != null) { dataArray.push({
for (let i = 0; i < x.length; i++) { value: x.elements[i].value,
dataArray.push({ name: x.elements[i].name,
value: x.elements[i].value, });
name: x.elements[i].name, }
}); }
}
} //set filename to active state according to userFileName field from loadTemplate
let userFileNameField = document.getElementById("userFileName");
//set filename to active state according to userFileName field from loadTemplate let userFileName = userFileNameField.value;
let userFileNameField = document.getElementById("userFileName"); let userFileNamePH = userFileNameField.getAttribute("placeholder");
let userFileName = userFileNameField.value; if (userFileName.length != 0) {
let userFileNamePH = userFileNameField.getAttribute("placeholder"); activeState.fileName = userFileName;
if (userFileName.length != 0) { } else if (userFileNamePH != null) {
activeState.fileName = userFileName; activeState.fileName = userFileNamePH;
} else if (userFileNamePH != null) { }
activeState.fileName = userFileNamePH; }
}
}
//get original objects from sessionstorage gen from loadTemplate
let objects = JSON.parse(window.sessionStorage.getItem("templateObjects"));
//get original objects from sessionstorage gen from loadTemplate
let objects = JSON.parse(window.sessionStorage.getItem("templateObjects")); //get the complete unparsed template string from sessionstorage from loadTemplate
let fullString = window.sessionStorage.getItem("fullString");
//get the complete unparsed template string from sessionstorage from loadTemplate
let fullString = window.sessionStorage.getItem("fullString"); //define output buffer
let b = "";
let b = "";
if (objects == null) {
if (objects == null) { return;
return; }
}
//iterate through templateObjects and look for according formdata
//iterate through templateObjects and look for according formdata for (let obj of objects) {
for (let obj of objects) { //compaire each obj with elements from mainFormObj
for (let data of dataArray) { for (let data of dataArray) {
//convert conList Master name to default name as set flag for appending connected list fields cl-name
let conListFlag = false; //convert conList Master name to default name as set flag for appending connected list fields cl-name
if (data.name.split("-")[0] == "clM") { let conListFlag = false;
if (data.name.substring(4) === obj.word.replace(/ /g, "_") ) { //if obj is the connected list main selector
conListFlag = true; if (data.name.split("-")[0] == "clM") {
data.name = data.name.substring(4); //if connected list main matches current object
if (data.value == "!none") { if (data.name.substring(4) === obj.word.replace(/ /g, "_") ) {
obj.result = ""; //set flag for next iteration of loop
continue; conListFlag = true;
} data.name = data.name.substring(4);
if (data.value == "!selected") {
data.value = obj[0]; //selection is not added to buffer
obj.result = ""; if (data.value == "!none") {
} obj.result = "";
} continue;
} }
if (obj.word.replace(/ /g, "_") === data.name) { if (data.value == "!selected") {
let value = parseDataForResult(obj, data.value); data.value = obj[0];
obj.result = value; obj.result = "";
}
} }
if (conListFlag) { }
if (obj.type == "conList") {
//if field matches current object
//check for button if only one item exists and search conlist item if (obj.word.replace(/ /g, "_") === data.name) {
if (obj.listCount == 0) { let value = parseDataForResult(obj, data.value);
for (let d of dataArray) { obj.result = value;
if (d.name.split(":!")[1] !== undefined) d.placeholder = "!"+d.name.split(":!")[1];
d.name = d.name.split(":!")[0]; }
if ("cl-"+obj[0].replace(/ /g, "_") == d.name && d.value != "") {
//console.log(d, obj[0], data); //handle conlist elements for parsing each element
if (data.value.replace(/ /g, "_") == d.name.substring(3)) { if (conListFlag && obj.type == "conList") {
if (d.hasOwnProperty("placeholder")) d.value = d.placeholder + "\n" + d.value; let value = parseConListForResult(obj, data, dataArray);
let value = parseDataForResult(obj, d.value); obj.result = value;
obj.result = obj.result + "\n" + value; }
} }
} }
}
} else { //console.log(this, dataArray);
//loop through dataArray and look for coresponding conlist items
for (let i = 0; i <= obj.listCount; i++) { b = fullString.substring(0, objects[0].spos);
for (let d of dataArray) { for (let i = 0; i < objects.length; i++) {
if (d.name.split(":!")[1] !== undefined) d.placeholder = "!"+d.name.split(":!")[1]; let j = i + 1;
d.name = d.name.split(":!")[0]; if (objects[j] === undefined) {
if ("cl-"+obj[i].replace(/ /g, "_") == d.name && d.value != "") { b +=
if (data.value.replace(/ /g, "_") == d.name.substring(3)) { objects[i].result +
if (d.hasOwnProperty("placeholder")) d.value = d.placeholder + "\n" + d.value; fullString.substring(objects[i].epos, fullString.length);
let value = parseDataForResult(obj, d.value); } else {
obj.result = obj.result + "\n" + value; b +=
} objects[i].result +
} fullString.substring(objects[i].epos, objects[j].spos);
} }
} }
}
} let bHtml = b.replace(/(?:\r\n|\r|\n)/g, "<br>");
} bHtml = bHtml.replace(/!l /g, " • ");
} bHtml = bHtml.replace(/!ls /g, " ○ ");
} bHtml = bHtml.replace(/ /g, "&nbsp;");
//console.log(this, dataArray); bHtml =
"<div style='font-family: Arial, Helvetica, sans-serif;'>" +
b = fullString.substring(0, objects[0].spos); bHtml +
for (let i = 0; i < objects.length; i++) { "</div>";
let j = i + 1;
if (objects[j] === undefined) { let div = document.createElement("div");
b += div.classList.add("w3-code", "notranslate", "w3-border-white");
objects[i].result + div.id = "fileDisplay";
fullString.substring(objects[i].epos, fullString.length); div.innerHTML = bHtml;
} else {
b += if (parseOnly) {
objects[i].result + return div;
fullString.substring(objects[i].epos, objects[j].spos); }
}
} let p = document.createElement("p");
p.innerHTML = "Copied to Clipboard:";
let bHtml = b.replace(/(?:\r\n|\r|\n)/g, "<br>"); document.getElementById("output").innerHTML = "";
bHtml = bHtml.replace(/!l /g, " • "); document.getElementById("output").appendChild(p);
bHtml = bHtml.replace(/!ls /g, " ○ "); document.getElementById("output").appendChild(div);
bHtml = bHtml.replace(/ /g, "&nbsp;");
storeData("userInput", JSON.stringify(dataArray));
bHtml = clearData("userInput");
"<div style='font-family: Arial, Helvetica, sans-serif;'>" +
bHtml + if (returnJSON) {
"</div>"; return dataArray;
} else {
let div = document.createElement("div"); copyToClipBoard(bHtml);
div.classList.add("w3-code", "notranslate", "w3-border-white"); }
div.id = "fileDisplay"; }
div.innerHTML = bHtml;
function parseDataForResult(obj, value) {
if (parseOnly) { //handle placeholders like title, link, italic
return div; if (obj.hasOwnProperty("placeholder") && value !== "") {
} //console.log(obj.placeholder);
//check for markups
let p = document.createElement("p"); if (activeState.markups.includes(obj.placeholder)) {
p.innerHTML = "Copied to Clipboard:"; value = parseMarkupmarkups(value, obj.placeholder);
document.getElementById("output").innerHTML = ""; } else {
document.getElementById("output").appendChild(p); value = obj.placeholder + "\n" + value;
document.getElementById("output").appendChild(div); }
}
storeData("userInput", JSON.stringify(dataArray));
clearData("userInput"); //Plugin TextBlock Insertion according to file _textblocks.txt
value = parseTextBlocks(value);
if (returnJSON) {
return dataArray;
} else { //handle placeholders like !l or !n and set it to final interpreted string for object
copyToClipBoard(bHtml); value = parseTextMarkups(value);
}
} //parse global linebreak after marked text was already fixed
value = parseGlobalLineBreak(value);
function parseDataForResult(obj, value) {
//handle placeholders like title, link, italic return value;
if (obj.hasOwnProperty("placeholder") && value !== "") { }
//console.log(obj.placeholder);
//check for markups function parseConListForResult(obj, data, dataArray) {
if (activeState.markups.includes(obj.placeholder)) { //check for button if only one item exists and search conlist item
value = parseMarkupmarkups(value, obj.placeholder); if (obj.listCount == 0) {
} else { for (let d of dataArray) {
value = obj.placeholder + "\n" + value; if (d.name.split(":!")[1] !== undefined) d.placeholder = "!"+d.name.split(":!")[1];
} d.name = d.name.split(":!")[0];
} if ("cl-"+obj[0].replace(/ /g, "_") == d.name && d.value != "") {
//console.log(d, obj[0], data);
if (data.value.replace(/ /g, "_") == d.name.substring(3)) {
//Plugin TextBlock Insertion according to file _textblocks.txt if (d.hasOwnProperty("placeholder")) d.value = d.placeholder + "\n" + d.value;
value = parseTextBlocks(value); let value = parseDataForResult(obj, d.value);
return obj.result + "\n" + value;
}
//handle placeholders like !l or !n and set it to final interpreted string for object }
value = parseTextMarkups(value); }
} else {
return value; //loop through dataArray and look for coresponding conlist items
} for (let i = 0; i <= obj.listCount; i++) {
for (let d of dataArray) {
export function parseTextMarkups(data) { if (d.name.split(":!")[1] !== undefined) d.placeholder = "!"+d.name.split(":!")[1];
let dataArray = data.split("\n"); d.name = d.name.split(":!")[0];
let listFlag = false; if ("cl-"+obj[i].replace(/ /g, "_") == d.name && d.value != "") {
let listSubFlag = false; if (data.value.replace(/ /g, "_") == d.name.substring(3)) {
let boldFlag = false; if (d.hasOwnProperty("placeholder")) d.value = d.placeholder + "\n" + d.value;
let listNumberFlag = false; let value = parseDataForResult(obj, d.value);
let listNumberFlagNum = 1; return obj.result + "\n" + value;
for (let i = 0; i < dataArray.length; i++) { }
switch (dataArray[i]) { }
case "!l": }
listFlag = true; }
dataArray.splice(i, 1); }
i = i - 1; }
break;
case "!ls": export function parseTextMarkups(data) {
listSubFlag = true; let dataArray = data.split("\n");
dataArray.splice(i, 1); let listFlag = false;
i = i - 1; let listSubFlag = false;
break; let boldFlag = false;
case "!n": let listNumberFlag = false;
listNumberFlag = true; let listNumberFlagNum = 1;
dataArray.splice(i, 1); for (let i = 0; i < dataArray.length; i++) {
i = i - 1; if (dataArray[i] == "") continue;
break; switch (dataArray[i]) {
case "!b": case "!l":
boldFlag = true; listFlag = true;
dataArray.splice(i, 1); dataArray.splice(i, 1);
i = i - 1; i = i - 1;
break; break;
case "!e": case "!ls":
listFlag = false; listSubFlag = true;
listNumberFlag = false; dataArray.splice(i, 1);
dataArray.splice(i, 1); i = i - 1;
i = i - 1; break;
break; case "!n":
case "!es": listNumberFlag = true;
listSubFlag = false; dataArray.splice(i, 1);
dataArray.splice(i, 1); i = i - 1;
i = i - 1; break;
break; case "!b":
default: boldFlag = true;
if (boldFlag) { dataArray.splice(i, 1);
dataArray[i] = "<b>" + dataArray[i] + "</b>"; i = i - 1;
boldFlag = false; break;
} case "!e":
if (listSubFlag) { listFlag = false;
dataArray[i] = " ○ " + dataArray[i]; listNumberFlag = false;
continue; dataArray.splice(i, 1);
} i = i - 1;
if (listFlag) { break;
dataArray[i] = " • " + dataArray[i]; case "!es":
} listSubFlag = false;
if (listNumberFlag) { dataArray.splice(i, 1);
dataArray[i] = " " + listNumberFlagNum + ". " + dataArray[i]; i = i - 1;
listNumberFlagNum++; break;
} default:
}
} if (boldFlag) {
return dataArray.join("\n"); dataArray[i] = "<b>" + dataArray[i] + "</b>";
} boldFlag = false;
continue;
function parseMarkupmarkups(value, markup) { }
switch (markup) {
case "title": //check if list indicator has been set and adjust userInput accordingly
return "<b>" + value + "</b>"; let listIndicator = "";
break;
case "italic": if (listNumberFlag) {
return "<i>" + value + "</i>"; listIndicator = " " + listNumberFlagNum + ". ";
break; listNumberFlagNum++;
} }
}
if (listSubFlag && listIndicator == "") listIndicator = " ○ ";
function parseTextBlocks(data) {
let textBlocks = loadTextBlocks(); if (listFlag && listIndicator == "") listIndicator = " • ";
let textBlockIds = Object.keys(textBlocks);
for (let i = 0; i < textBlockIds.length; i++) { //handle global linebreak and fit according to indicator according to list indicator
let id = textBlockIds[i];
if (data.indexOf("!" + id) !== -1) { if (listIndicator != "") dataArray[i] = parseLineBreak(listIndicator + dataArray[i], listIndicator.length);
//console.log("found: "+id);
let sPos = data.indexOf("!" + id); }
let ePos = sPos + id.length + 1; }
data = return dataArray.join("\n");
data.substring(0, sPos) + }
textBlocks[id] +
data.substring(ePos, data.length); function parseMarkupmarkups(value, markup) {
} switch (markup) {
} case "title":
return data; return "<b>" + value + "</b>";
} break;
case "italic":
return "<i>" + value + "</i>";
function loadTextBlocks() { break;
let textBlocks = document.getElementById("textBlocks").innerText; }
let textBlocksObject = {}; }
if (textBlocks.indexOf("\r\n") !== -1) {
var wordArrayByLine = textBlocks.split("\r\n"); function parseTextBlocks(data) {
} else { let textBlocks = loadTextBlocks();
var wordArrayByLine = textBlocks.split("\n"); let textBlockIds = Object.keys(textBlocks);
} for (let i = 0; i < textBlockIds.length; i++) {
let id = textBlockIds[i];
for (let i = 0; i < wordArrayByLine.length; i++) { if (data.indexOf("!" + id) !== -1) {
let textBlockId = wordArrayByLine[i].split(":")[0]; //console.log("found: "+id);
let textBlockText = wordArrayByLine[i].substring( let sPos = data.indexOf("!" + id);
textBlockId.length + 2, let ePos = sPos + id.length + 1;
wordArrayByLine[i].length data =
); data.substring(0, sPos) +
if (textBlockId.length < 1) { textBlocks[id] +
continue; data.substring(ePos, data.length);
} }
textBlocksObject[textBlockId.replace(/\s/g, "")] = textBlockText; }
} return data;
return textBlocksObject; }
}
function parseGlobalLineBreak(data) {
function copyToClipBoard(html) { //parse each line of input with parseLineBreak return condensed string with newlines
// Create an iframe (isolated container) for the HTML let parsedData = '';
var container = document.createElement("div"); for (let line of data.split('\n')) {
container.innerHTML = html; let parsedLine = parseLineBreak(line, 0, activeState.lineBreak);
if (parsedData != '') {
// Hide element parsedData = parsedData + '\n' + parsedLine;
container.style.position = "fixed"; } else {
container.style.pointerEvents = "none"; parsedData = parsedLine;
container.style.opacity = 0; }
}
// Detect all style sheets of the page return parsedData
var activeSheets = Array.prototype.slice }
.call(document.styleSheets)
.filter(function (sheet) { function parseLineBreak(line, intendation = 0, lineBreak = activeState.lineBreak - 5) {
return !sheet.disabled; //add 5 chars buffer to fix list intendation issue
}); //each input field gets parsed line by line twice once for list inputs and a second time for each input
let lines;
// Mount the iframe to the DOM to make `contentWindow` available
document.body.appendChild(container); if (line.length > lineBreak) {
//create linebreak in between second to last word
// Copy to clipboard let correctedLineBreak;
window.getSelection().removeAllRanges(); let newLineStart;
let cLBt = lineBreak-(intendation*2)
var range = document.createRange(); //find last space before linebreak
range.selectNode(container); correctedLineBreak = line.substring(0, cLBt).lastIndexOf(" ");
window.getSelection().addRange(range); //and fix the next lines start
newLineStart = correctedLineBreak+1;
document.execCommand("copy"); //add to parsed output
for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true; lines = line.substring(0, correctedLineBreak);
document.execCommand("copy"); //delete first parsed output from inputstring
for (var i = 0; i < activeSheets.length; i++) line = line.substring(newLineStart);
activeSheets[i].disabled = false;
let intendationSpaces = '';
// Remove the iframe //check if an intendation is given if so convert it to correct spaces
document.body.removeChild(container); if (intendation != 0) intendationSpaces = ' '.repeat(intendation+1);
}
//start loop to parse rest of the string
function mainFormPlaceholder() { while(line.length > lineBreak) {
return "<div class='w3-row-padding w3-padding-24 w3-container w3-flat-clouds'><div class='w3-code notranslate w3-border-white' style='font-family: Arial, Helvetica, sans-serif;'><p>Select a file</p><br><br><br><br><br><br><br><br><br><br><br></div></div>"; let cLBt = lineBreak-(intendation*2)
} correctedLineBreak = line.substring(0, cLBt).lastIndexOf(" ");
newLineStart = correctedLineBreak+1;
//add to output with intendation if given
lines += "\n" + intendationSpaces + line.substring(0, correctedLineBreak);
//delete from input
line = line.substring(newLineStart);
}
//process rest of the string with correct intendation
lines += "\n" + intendationSpaces + line;
} else {
//if string is within lineBreak just forward input to output
lines = line;
}
return lines;
}
function loadTextBlocks() {
let textBlocks = document.getElementById("textBlocks").innerText;
let textBlocksObject = {};
if (textBlocks.indexOf("\r\n") !== -1) {
var wordArrayByLine = textBlocks.split("\r\n");
} else {
var wordArrayByLine = textBlocks.split("\n");
}
for (let i = 0; i < wordArrayByLine.length; i++) {
let textBlockId = wordArrayByLine[i].split(":")[0];
let textBlockText = wordArrayByLine[i].substring(
textBlockId.length + 2,
wordArrayByLine[i].length
);
if (textBlockId.length < 1) {
continue;
}
textBlocksObject[textBlockId.replace(/\s/g, "")] = textBlockText;
}
return textBlocksObject;
}
function copyToClipBoard(html) {
// Create an iframe (isolated container) for the HTML
var container = document.createElement("div");
container.innerHTML = html;
// Hide element
container.style.position = "fixed";
container.style.pointerEvents = "none";
container.style.opacity = 0;
// Detect all style sheets of the page
var activeSheets = Array.prototype.slice
.call(document.styleSheets)
.filter(function (sheet) {
return !sheet.disabled;
});
// Mount the iframe to the DOM to make `contentWindow` available
document.body.appendChild(container);
// Copy to clipboard
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(container);
window.getSelection().addRange(range);
document.execCommand("copy");
for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true;
document.execCommand("copy");
for (var i = 0; i < activeSheets.length; i++)
activeSheets[i].disabled = false;
// Remove the iframe
document.body.removeChild(container);
}
function mainFormPlaceholder() {
return "<div class='w3-row-padding w3-padding-24 w3-container w3-flat-clouds'><div class='w3-code notranslate w3-border-white' style='font-family: Arial, Helvetica, sans-serif;'><p>Select a file</p><br><br><br><br><br><br><br><br><br><br><br></div></div>";
}
export default parseFormOnSubmit; export default parseFormOnSubmit;

View File

@ -1,374 +1,388 @@
function parseInput(wordArray, objects, i) { function parseInput(wordArray, objects, i) {
let word = wordArray[i]; let word = wordArray[i];
if (word.substring(0, 1) == "%") { if (word.substring(0, 1) == "%") {
//check if regular use of % in text 20% an ignoreCase //check if regular use of % in text 20% an ignoreCase
if (word.substring(0, 2) !== "% ") { if (word.substring(0, 2) !== "% ") {
//found simple input %word / excluding %m: //found simple input %word / excluding %m:
if (word.substring(2, 3) !== ":") { if (word.substring(2, 3) !== ":") {
//init Word Object //init Word Object
var wordObj = {}; var wordObj = {};
let w = word.substring(1);
//for loop to escape spaces in simple input let w = word.substring(1);
for (let j = i + 1; j < wordArray.length; j++) {
w = w + " " + wordArray[j]; //bugfix if the title of an input has no space in it ex: %test=l:first word;l:second word;%1
//invoke look for gender specific template let oneWordFlag = false;
i = findGenderSpecificInput(wordArray, wordObj, j); if (word.substring(0, 1) == "%" && word.indexOf('=') != -1) {
//invoke look for list template oneWordFlag = true;
i = findListInput(wordArray, wordObj, j); }
//invoke connected fields
i = findConnectedListInput(wordArray, wordObj, j); //for loop to escape spaces in simple input
//find end of template string and format it for future handling¨ for (let j = i+1; j < wordArray.length; j++) {
if (w.indexOf("%") !== -1) { //if title has no space then go back one word to include "=" ex:
//found % sign if (oneWordFlag) {
if (w.indexOf("%") !== w.length - 1) { j = i;
//% is not last char of string oneWordFlag = false;
word = "%" + w; } else {
} else { w = w + " " + wordArray[j];
//% is last }
//no prio has been set //invoke look for gender specific template
word = w.slice(0, -1); i = findGenderSpecificInput(wordArray, wordObj, j);
} //invoke look for list template
break; i = findListInput(wordArray, wordObj, j);
} //invoke connected fields
} i = findConnectedListInput(wordArray, wordObj, j);
//find end of template string and format it for future handling¨
if (word.indexOf("\n") !== -1) { if (w.indexOf("%") !== -1) {
if (word.substring(word.indexOf("\n"), 2).indexOf("%") !== -1) { //found % sign
//alert("attention newlineChar in: "+ word.substring(word.indexOf("\n"),2)); if (w.indexOf("%") !== w.length - 1) {
} //% is not last char of string
} word = "%" + w;
//parse priority } else {
if (word.substring(1).indexOf("%") === -1) { //% is last
//object if no prio was set //no prio has been set
wordObj.word = word; word = w.slice(0, -1);
wordObj.arrayPos = objects.length; }
wordObj.prio = 0; break;
} else { }
//handle edgecase if punctuation mark is directly after prio }
let postMarker = word.substring(1).indexOf("%") + 2;
let postMarkerEnd = word.length; if (word.indexOf("\n") !== -1) {
let isPriority = true; if (word.substring(word.indexOf("\n"), 2).indexOf("%") !== -1) {
let i = 0; //alert("attention newlineChar in: "+ word.substring(word.indexOf("\n"),2));
//console.log(word + " * " + word.substring(postMarkerEnd-2, postMarkerEnd) + " - " + postMarker + ":" + postMarkerEnd + " - " + word.length); }
while ( }
!isCharNumber(word.substring(postMarkerEnd - 1, postMarkerEnd)) //parse priority
) { if (word.substring(1).indexOf("%") === -1) {
postMarkerEnd = postMarkerEnd - 1; //object if no prio was set
//if no priority has been set; set flag wordObj.word = word;
//console.log(word.substring(postMarkerEnd-1, postMarkerEnd)); wordObj.arrayPos = objects.length;
wordObj.prio = 0;
if (postMarkerEnd < 1) { } else {
isPriority = false; //handle edgecase if punctuation mark is directly after prio
break; let postMarker = word.substring(1).indexOf("%") + 2;
} let postMarkerEnd = word.length;
let isPriority = true;
i++; let i = 0;
} //console.log(word + " * " + word.substring(postMarkerEnd-2, postMarkerEnd) + " - " + postMarker + ":" + postMarkerEnd + " - " + word.length);
while (
if (isPriority) { !isCharNumber(word.substring(postMarkerEnd - 1, postMarkerEnd))
//console.log(word + " prio: "+isPriority); ) {
//object if prio has been defined postMarkerEnd = postMarkerEnd - 1;
wordObj.word = word.substring(1, postMarker - 1); //if no priority has been set; set flag
wordObj.arrayPos = objects.length; //console.log(word.substring(postMarkerEnd-1, postMarkerEnd));
wordObj.prio = parseInt(
word.substring(postMarker, postMarkerEnd), if (postMarkerEnd < 1) {
10 isPriority = false;
); break;
if (isNaN(wordObj.prio)) { }
alert(
"error in template: %" + i++;
wordObj.word + }
"% there must always a space after the priority number"
); if (isPriority) {
wordObj.prio = 0; //console.log(word + " prio: "+isPriority);
} //object if prio has been defined
} else { wordObj.word = word.substring(1, postMarker - 1);
//object if no prio has been defined wordObj.arrayPos = objects.length;
wordObj.word = word.substring(1, postMarker - 1); wordObj.prio = parseInt(
wordObj.arrayPos = objects.length; word.substring(postMarker, postMarkerEnd),
wordObj.prio = 0; 10
} );
} if (isNaN(wordObj.prio)) {
//check if genderSpecific or list has been found and if so reformat word alert(
//console.log(wordObj); "error in template: %" +
switch (wordObj.type) { wordObj.word +
case "genderSpecific": "% there must always a space after the priority number"
if (word.substring(0, 1) === "%") { );
wordObj.word = word.split("=")[0].substring(1); wordObj.prio = 0;
} else { }
wordObj.word = word.split("=")[0]; } else {
} //object if no prio has been defined
break; wordObj.word = word.substring(1, postMarker - 1);
case "list": wordObj.arrayPos = objects.length;
if (word.substring(0, 1) === "%") { wordObj.prio = 0;
wordObj.word = word.split("=")[0].substring(1); }
} else { }
wordObj.word = word.split("=")[0]; //check if genderSpecific or list has been found and if so reformat word
} //console.log(wordObj);
break; switch (wordObj.type) {
case "conList": case "genderSpecific":
if (word.substring(0, 1) === "%") { if (word.substring(0, 1) === "%") {
wordObj.word = word.split("=")[0].substring(1); wordObj.word = word.split("=")[0].substring(1);
} else { } else {
wordObj.word = word.split("=")[0]; wordObj.word = word.split("=")[0];
} }
//check if format has been given or markup break;
for (let i = 0; i <= wordObj.listCount; i++) { case "list":
let params = wordObj[i].split(":"); if (word.substring(0, 1) === "%") {
if (params[1] !== undefined) { wordObj.word = word.split("=")[0].substring(1);
wordObj[i] = params[0]; } else {
wordObj["clType-"+wordObj[i]] = (params[2] !== undefined) ? params[1]+":"+params[2]: params[1]; wordObj.word = word.split("=")[0];
} else { }
wordObj["clType-"+wordObj[i]] = "cl-simpleInput"; break;
} case "conList":
} if (word.substring(0, 1) === "%") {
break; wordObj.word = word.split("=")[0].substring(1);
default: } else {
wordObj.type = "simpleInput"; wordObj.word = word.split("=")[0];
//check if customTemplate was used set type and format word }
if (word.indexOf("=") !== -1) { //check if format has been given or markup
parseCustomTemplates(wordObj); for (let i = 0; i <= wordObj.listCount; i++) {
} let params = wordObj[i].split(":");
break; if (params[1] !== undefined) {
} wordObj[i] = params[0];
wordObj["clType-"+wordObj[i]] = (params[2] !== undefined) ? params[1]+":"+params[2]: params[1];
objects.push(wordObj); } else {
} wordObj["clType-"+wordObj[i]] = "cl-simpleInput";
} }
} }
} break;
default:
function findGenderSpecificInput(wordArray, wordObj, i) { wordObj.type = "simpleInput";
let word = wordArray[i]; //check if customTemplate was used set type and format word
if (word.indexOf("=m:") !== -1) { if (word.indexOf("=") !== -1) {
wordObj.type = "genderSpecific"; parseCustomTemplates(wordObj);
let mw = word.substring(word.indexOf("=m:") + 3); }
for (let j = i + 1; j < wordArray.length; j++) { break;
mw = mw + " " + wordArray[j]; }
i = j;
if (mw.indexOf(";") !== -1) { objects.push(wordObj);
wordObj.m = mw.slice(0, mw.indexOf(";")); }
//adding length word + 3 = m: ; }
i = parseGenderTemplate(wordArray, wordObj, i); }
break; }
}
} function findGenderSpecificInput(wordArray, wordObj, i) {
} let word = wordArray[i];
if (word.indexOf("=m:") !== -1) {
if (word.indexOf("=w:") !== -1) { wordObj.type = "genderSpecific";
let ww = word.substring(word.indexOf("=w:") + 3); let mw = word.substring(word.indexOf("=m:") + 3);
for (let j = i + 1; j < wordArray.length; j++) { for (let j = i + 1; j < wordArray.length; j++) {
ww = ww + " " + wordArray[j]; mw = mw + " " + wordArray[j];
i = j; i = j;
if (ww.indexOf(";") !== -1) { if (mw.indexOf(";") !== -1) {
wordObj.w = ww.slice(0, ww.indexOf(";")); wordObj.m = mw.slice(0, mw.indexOf(";"));
i = parseGenderTemplate(wordArray, wordObj, i); //adding length word + 3 = m: ;
break; i = parseGenderTemplate(wordArray, wordObj, i);
} break;
} }
} }
}
if (word.indexOf("=d:") !== -1) {
let dw = word.substring(word.indexOf("=d:") + 3); if (word.indexOf("=w:") !== -1) {
for (let j = i + 1; j < wordArray.length; j++) { let ww = word.substring(word.indexOf("=w:") + 3);
dw = dw + " " + wordArray[j]; for (let j = i + 1; j < wordArray.length; j++) {
i = j; ww = ww + " " + wordArray[j];
if (dw.indexOf(";") !== -1) { i = j;
wordObj.d = dw.slice(0, dw.indexOf(";")); if (ww.indexOf(";") !== -1) {
i = parseGenderTemplate(wordArray, wordObj, i); wordObj.w = ww.slice(0, ww.indexOf(";"));
break; i = parseGenderTemplate(wordArray, wordObj, i);
} break;
} }
} }
return i; }
}
if (word.indexOf("=d:") !== -1) {
function parseGenderTemplate(wordArray, wordObj, i) { let dw = word.substring(word.indexOf("=d:") + 3);
let word = wordArray[i]; for (let j = i + 1; j < wordArray.length; j++) {
if (word.indexOf(";m:") !== -1) { dw = dw + " " + wordArray[j];
let mw = word.substring(word.indexOf(";m:") + 3); i = j;
for (let j = i + 1; j < wordArray.length; j++) { if (dw.indexOf(";") !== -1) {
mw = mw + " " + wordArray[j]; wordObj.d = dw.slice(0, dw.indexOf(";"));
i = j; i = parseGenderTemplate(wordArray, wordObj, i);
if (mw.indexOf(";") !== -1) { break;
wordObj.m = mw.slice(0, mw.indexOf(";")); }
i = parseGenderTemplate(wordArray, wordObj, i); }
break; }
} return i;
} }
}
if (word.indexOf(";w:") !== -1) { function parseGenderTemplate(wordArray, wordObj, i) {
let ww = word.substring(word.indexOf(";w:") + 3); let word = wordArray[i];
for (let j = i + 1; j < wordArray.length; j++) { if (word.indexOf(";m:") !== -1) {
ww = ww + " " + wordArray[j]; let mw = word.substring(word.indexOf(";m:") + 3);
i = j; for (let j = i + 1; j < wordArray.length; j++) {
if (ww.indexOf(";") !== -1) { mw = mw + " " + wordArray[j];
wordObj.w = ww.slice(0, ww.indexOf(";")); i = j;
i = parseGenderTemplate(wordArray, wordObj, i); if (mw.indexOf(";") !== -1) {
break; wordObj.m = mw.slice(0, mw.indexOf(";"));
} i = parseGenderTemplate(wordArray, wordObj, i);
} break;
} }
if (word.indexOf(";d:") !== -1) { }
let dw = word.substring(word.indexOf(";d:") + 3); }
for (let j = i + 1; j < wordArray.length; j++) { if (word.indexOf(";w:") !== -1) {
dw = dw + " " + wordArray[j]; let ww = word.substring(word.indexOf(";w:") + 3);
i = j; for (let j = i + 1; j < wordArray.length; j++) {
if (dw.indexOf(";") !== -1) { ww = ww + " " + wordArray[j];
wordObj.d = dw.slice(0, dw.indexOf(";")); i = j;
i = parseGenderTemplate(wordArray, wordObj, i); if (ww.indexOf(";") !== -1) {
break; wordObj.w = ww.slice(0, ww.indexOf(";"));
} i = parseGenderTemplate(wordArray, wordObj, i);
} break;
} }
return i; }
} }
if (word.indexOf(";d:") !== -1) {
function findListInput(wordArray, wordObj, i) { let dw = word.substring(word.indexOf(";d:") + 3);
let word = wordArray[i]; for (let j = i + 1; j < wordArray.length; j++) {
if (word.indexOf("=l:") !== -1) { dw = dw + " " + wordArray[j];
wordObj.type = "list"; i = j;
wordObj.listCount = 0; if (dw.indexOf(";") !== -1) {
let lw = word.substring(word.indexOf("=l:") + 3); wordObj.d = dw.slice(0, dw.indexOf(";"));
//escape if there is no space in listitem i = parseGenderTemplate(wordArray, wordObj, i);
if (lw.indexOf(";") !== -1) { break;
wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); }
//adding length word + 3 = m: ; }
i = parseListTemplate(wordArray, wordObj, i); }
return i; return i;
} }
for (let j = i + 1; j < wordArray.length; j++) {
lw = lw + " " + wordArray[j]; function findListInput(wordArray, wordObj, i) {
i = j; let word = wordArray[i];
if (lw.indexOf(";") !== -1) { if (word.indexOf("=l:") !== -1) {
wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); wordObj.type = "list";
//adding length word + 3 = m: ; wordObj.listCount = 0;
i = parseListTemplate(wordArray, wordObj, i); let lw = word.substring(word.indexOf("=l:") + 3);
break; //escape if there is no space in listitem
} if (lw.indexOf(";") !== -1) {
} wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";"));
} //adding length word + 3 = m: ;
return i; i = parseListTemplate(wordArray, wordObj, i);
} return i;
}
function parseListTemplate(wordArray, wordObj, i) { for (let j = i + 1; j < wordArray.length; j++) {
let word = wordArray[i]; lw = lw + " " + wordArray[j];
if (word.indexOf(";l:") !== -1) { i = j;
let lw = word.substring(word.indexOf(";l:") + 3); if (lw.indexOf(";") !== -1) {
//escape if there is no space in listitem wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";"));
if (lw.indexOf(";") !== -1) { //adding length word + 3 = m: ;
wordObj.listCount++; i = parseListTemplate(wordArray, wordObj, i);
wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); break;
//shorten wordArray and hand it to parseListTemplate: firstItem;l:secondItem;l: to ;l:secondItem;l:third Item }
wordArray[i] = wordArray[i] }
.substring(1) }
.substring(wordArray[i].indexOf(";") + 1); return i;
//advance wordArray i if third Item has a space in it and no ; is found to avoid endless loop }
if (wordArray[i].substring(1).indexOf(";") === -1) {
i++; function parseListTemplate(wordArray, wordObj, i) {
} let word = wordArray[i];
//console.log(wordArray[i].substring(1)); if (word.indexOf(";l:") !== -1) {
i = parseListTemplate(wordArray, wordObj, i); let lw = word.substring(word.indexOf(";l:") + 3);
return i; //escape if there is no space in listitem
} if (lw.indexOf(";") !== -1) {
for (let j = i + 1; j < wordArray.length; j++) { wordObj.listCount++;
lw = lw + " " + wordArray[j]; wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";"));
i = j; //shorten wordArray and hand it to parseListTemplate: firstItem;l:secondItem;l: to ;l:secondItem;l:third Item
if (lw.indexOf(";") !== -1) { wordArray[i] = wordArray[i]
wordObj.listCount++; .substring(1)
wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); .substring(wordArray[i].indexOf(";") + 1);
i = parseListTemplate(wordArray, wordObj, i); //advance wordArray i if third Item has a space in it and no ; is found to avoid endless loop
break; if (wordArray[i].substring(1).indexOf(";") === -1) {
} i++;
} }
} //console.log(wordArray[i].substring(1));
return i; i = parseListTemplate(wordArray, wordObj, i);
} return i;
}
function findConnectedListInput(wordArray, wordObj, i) { for (let j = i + 1; j < wordArray.length; j++) {
let word = wordArray[i]; lw = lw + " " + wordArray[j];
if (word.indexOf("=h:") !== -1) { i = j;
wordObj.type = "conList"; if (lw.indexOf(";") !== -1) {
wordObj.listCount = 0; wordObj.listCount++;
let lw = word.substring(word.indexOf("=h:") + 3); wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";"));
//escape if there is no space in listitem i = parseListTemplate(wordArray, wordObj, i);
if (lw.indexOf(";") !== -1) { break;
wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); }
//adding length word + 3 = m: ; }
i = parseConnectedListTemplate(wordArray, wordObj, i); }
return i; return i;
} }
for (let j = i + 1; j < wordArray.length; j++) {
lw = lw + " " + wordArray[j]; function findConnectedListInput(wordArray, wordObj, i) {
i = j; let word = wordArray[i];
if (lw.indexOf(";") !== -1) { if (word.indexOf("=h:") !== -1) {
wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); wordObj.type = "conList";
//adding length word + 3 = m: ; wordObj.listCount = 0;
i = parseConnectedListTemplate(wordArray, wordObj, i); let lw = word.substring(word.indexOf("=h:") + 3);
break; //escape if there is no space in listitem
} if (lw.indexOf(";") !== -1) {
} wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";"));
} //adding length word + 3 = m: ;
return i; i = parseConnectedListTemplate(wordArray, wordObj, i);
} return i;
}
for (let j = i + 1; j < wordArray.length; j++) {
function parseConnectedListTemplate(wordArray, wordObj, i) { lw = lw + " " + wordArray[j];
let word = wordArray[i]; i = j;
if (word.indexOf(";h:") !== -1) { if (lw.indexOf(";") !== -1) {
let lw = word.substring(word.indexOf(";h:") + 3); wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";"));
//escape if there is no space in listitem //adding length word + 3 = m: ;
if (lw.indexOf(";") !== -1) { i = parseConnectedListTemplate(wordArray, wordObj, i);
wordObj.listCount++; break;
wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); }
//shorten wordArray and hand it to parseListTemplate: firstItem;l:secondItem;l: to ;l:secondItem;l:third Item }
wordArray[i] = wordArray[i] }
.substring(1) return i;
.substring(wordArray[i].indexOf(";") + 1); }
//advance wordArray i if third Item has a space in it and no ; is found to avoid endless loop
if (wordArray[i].substring(1).indexOf(";") === -1) {
i++; function parseConnectedListTemplate(wordArray, wordObj, i) {
} let word = wordArray[i];
//console.log(wordArray[i].substring(1)); if (word.indexOf(";h:") !== -1) {
i = parseConnectedListTemplate(wordArray, wordObj, i); let lw = word.substring(word.indexOf(";h:") + 3);
return i; //escape if there is no space in listitem
} if (lw.indexOf(";") !== -1) {
for (let j = i + 1; j < wordArray.length; j++) { wordObj.listCount++;
lw = lw + " " + wordArray[j]; wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";"));
i = j; //shorten wordArray and hand it to parseListTemplate: firstItem;l:secondItem;l: to ;l:secondItem;l:third Item
if (lw.indexOf(";") !== -1) { wordArray[i] = wordArray[i]
wordObj.listCount++; .substring(1)
wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); .substring(wordArray[i].indexOf(";") + 1);
i = parseConnectedListTemplate(wordArray, wordObj, i); //advance wordArray i if third Item has a space in it and no ; is found to avoid endless loop
break; if (wordArray[i].substring(1).indexOf(";") === -1) {
} i++;
} }
} //console.log(wordArray[i].substring(1));
return i; i = parseConnectedListTemplate(wordArray, wordObj, i);
} return i;
}
function parseCustomTemplates(wordObj) { for (let j = i + 1; j < wordArray.length; j++) {
let word = wordObj.word; lw = lw + " " + wordArray[j];
for (let i = 0; i < activeState.templateFieldTypes.length; i++) { i = j;
if (word.indexOf("=" + activeState.templateFieldTypes[i]) !== -1) { if (lw.indexOf(";") !== -1) {
wordObj.word = word.split("=")[0]; wordObj.listCount++;
wordObj.type = word.split("=")[1]; wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";"));
i = parseConnectedListTemplate(wordArray, wordObj, i);
if (wordObj.type.indexOf(":") !== -1) { break;
let ltPlaceholder = wordObj.type.split(":")[1]; }
if (ltPlaceholder !== "undefined") { }
wordObj.placeholder = ltPlaceholder; }
//wordObj.type = wordObj.type.split(":")[0]; - dont do this return i;
} }
}
} function parseCustomTemplates(wordObj) {
} let word = wordObj.word;
} for (let i = 0; i < activeState.templateFieldTypes.length; i++) {
if (word.indexOf("=" + activeState.templateFieldTypes[i]) !== -1) {
function isCharNumber(c) { wordObj.word = word.split("=")[0];
return c >= "0" && c <= "9"; wordObj.type = word.split("=")[1];
}
if (wordObj.type.indexOf(":") !== -1) {
export default parseInput; let ltPlaceholder = wordObj.type.split(":")[1];
if (ltPlaceholder !== "undefined") {
wordObj.placeholder = ltPlaceholder;
//wordObj.type = wordObj.type.split(":")[0]; - dont do this
}
}
}
}
}
function isCharNumber(c) {
return c >= "0" && c <= "9";
}
export default parseInput;

167
js/9.9.6/scripts.js Normal file
View File

@ -0,0 +1,167 @@
import { retrieveData } from "./storage.js";
import sha256 from "./sha256.min.js";
import XORCipher from "./xorc.js";
import getBrowserFingerprint from "./identify.js"
export const passwordHash = {
name: "anae3Iegbai1ahLu",
fp: getBrowserFingerprint( { hardwareOnly: true } ),
toString: () => {
let data;
try {
data = window.sessionStorage.getItem(sha256(passwordHash.name));
} catch (e) {
return "none";
}
if (data === null) return "none";
return XORCipher.decode(passwordHash.name, data);
},
getId: () => {
return passwordHash.fp;
},
set: (pw) => {
window.sessionStorage.setItem(sha256(passwordHash.name), XORCipher.encode(passwordHash.name, pw));
}
}
//export const passwordHash = {
// toString: () => {
// let fp = getBrowserFingerprint( { hardwareOnly: true } );
// let data;
// try {
// data = window.sessionStorage.getItem(sha256(fp));
// } catch (e) {
// return "none";
// }
// if (data === null) return "none";
// return XORCipher.decode(fp, data);
// },
//
// set: (pw) => {
// let fp = getBrowserFingerprint( { hardwareOnly: true } );
// window.sessionStorage.setItem(sha256(fp), XORCipher.encode(fp, pw));
// }
//}
function setPassword() {
let x = document.getElementById("loginForm");
let pw = x.elements[0].value;
if (pw != "" || pw !== "undefined") {
let pwOld = pw;
passwordHash.set(sha256(pw));
let templateFiles = retrieveData("templateFiles");
if (templateFiles != "") {
try {
JSON.parse(templateFiles);
} catch (e) {
document.getElementById("wrongPWAlert").style.display = "block";
const alertTimeout = setTimeout(() => {
document.getElementById("wrongPWAlert").style.display = "none";
}, 5000);
passwordHash.set(pwOld);
x.elements[0].value = "";
return;
}
}
//user logged in
document.getElementById("login").style.display = "none";
window.sessionStorage.setItem(sha256("verified"), XORCipher.encode(sha256("passwordHash"), passwordHash));
setCookie(sha256("verified"), XORCipher.encode(sha256("passwordHash"), passwordHash), 10)
}
}
export function getUsrId() {
const fingerprint = getBrowserFingerprint( { hardwareOnly: true } );
return cyrb53(fingerprint + passwordHash);
}
export function sessionVerification() {
//check if cookie exists
if (getCookie(sha256("verified")) != null) {
passwordHash.set(XORCipher.decode(sha256("passwordHash"), getCookie(sha256("verified"))));
window.sessionStorage.setItem(sha256("verified"), XORCipher.encode(sha256("passwordHash"), passwordHash));
}
let verfiedStatus = window.sessionStorage.getItem(sha256("verified"));
let data;
try {
data = window.sessionStorage.getItem(sha256(passwordHash.name));
} catch (e) {
verfiedStatus = null;
}
if (data === null) verfiedStatus = null;
//if (verfiedStatus != data) verfiedStatus = null
let vsString;
let pnString;
try {
vsString = XORCipher.decode(sha256("passwordHash"), verfiedStatus);
pnString = XORCipher.decode(passwordHash.name, data);
if (vsString != pnString) verfiedStatus = null;
} catch (e) {
verfiedStatus = null;
}
let tF = retrieveData("templateFiles");
try {
tF = JSON.parse(tF);
} catch(e) {
//verfiedStatus = null;
}
return (verfiedStatus == null) ? false : true;
}
const cyrb53 = (str, seed = 21) => {
let h1 = 0xdeadbeef ^ seed,
h2 = 0x41c6ce57 ^ seed;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
export function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return null;
}
export function logout() {
let id = sha256("verified");
window.sessionStorage.setItem(id, "");
document.cookie = id + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
sessionVerification();
document.getElementById("passwordField").value = "";
document.getElementById("login").style.display = "block";
}
export default setPassword;

View File

@ -1,3 +1,3 @@
var sha256=function a(b){function c(a,b){return a>>>b|a<<32-b}for(var d,e,f=Math.pow,g=f(2,32),h="length",i="",j=[],k=8*b[h],l=a.h=a.h||[],m=a.k=a.k||[],n=m[h],o={},p=2;64>n;p++)if(!o[p]){for(d=0;313>d;d+=p)o[d]=p;l[n]=f(p,.5)*g|0,m[n++]=f(p,1/3)*g|0}for(b+="\x80";b[h]%64-56;)b+="\x00";for(d=0;d<b[h];d++){if(e=b.charCodeAt(d),e>>8)return;j[d>>2]|=e<<(3-d)%4*8}for(j[j[h]]=k/g|0,j[j[h]]=k,e=0;e<j[h];){var q=j.slice(e,e+=16),r=l;for(l=l.slice(0,8),d=0;64>d;d++){var s=q[d-15],t=q[d-2],u=l[0],v=l[4],w=l[7]+(c(v,6)^c(v,11)^c(v,25))+(v&l[5]^~v&l[6])+m[d]+(q[d]=16>d?q[d]:q[d-16]+(c(s,7)^c(s,18)^s>>>3)+q[d-7]+(c(t,17)^c(t,19)^t>>>10)|0),x=(c(u,2)^c(u,13)^c(u,22))+(u&l[1]^u&l[2]^l[1]&l[2]);l=[w+x|0].concat(l),l[4]=l[4]+w|0}for(d=0;8>d;d++)l[d]=l[d]+r[d]|0}for(d=0;8>d;d++)for(e=3;e+1;e--){var y=l[d]>>8*e&255;i+=(16>y?0:"")+y.toString(16)}return i}; var sha256=function a(b){function c(a,b){return a>>>b|a<<32-b}for(var d,e,f=Math.pow,g=f(2,32),h="length",i="",j=[],k=8*b[h],l=a.h=a.h||[],m=a.k=a.k||[],n=m[h],o={},p=2;64>n;p++)if(!o[p]){for(d=0;313>d;d+=p)o[d]=p;l[n]=f(p,.5)*g|0,m[n++]=f(p,1/3)*g|0}for(b+="\x80";b[h]%64-56;)b+="\x00";for(d=0;d<b[h];d++){if(e=b.charCodeAt(d),e>>8)return;j[d>>2]|=e<<(3-d)%4*8}for(j[j[h]]=k/g|0,j[j[h]]=k,e=0;e<j[h];){var q=j.slice(e,e+=16),r=l;for(l=l.slice(0,8),d=0;64>d;d++){var s=q[d-15],t=q[d-2],u=l[0],v=l[4],w=l[7]+(c(v,6)^c(v,11)^c(v,25))+(v&l[5]^~v&l[6])+m[d]+(q[d]=16>d?q[d]:q[d-16]+(c(s,7)^c(s,18)^s>>>3)+q[d-7]+(c(t,17)^c(t,19)^t>>>10)|0),x=(c(u,2)^c(u,13)^c(u,22))+(u&l[1]^u&l[2]^l[1]&l[2]);l=[w+x|0].concat(l),l[4]=l[4]+w|0}for(d=0;8>d;d++)l[d]=l[d]+r[d]|0}for(d=0;8>d;d++)for(e=3;e+1;e--){var y=l[d]>>8*e&255;i+=(16>y?0:"")+y.toString(16)}return i};
export default sha256; export default sha256;

View File

@ -1,223 +1,225 @@
import XORCipher from "./xorc.js"; import XORCipher from "./xorc.js";
import sha256 from "./sha256.min.js"; import sha256 from "./sha256.min.js";
import { getUsrId, passwordHash } from "./scripts.js"; import { getUsrId, passwordHash } from "./scripts.js";
function createStorageObj() { function createStorageObj() {
let x = document.getElementById("mainFormObj"); let x = document.getElementById("mainFormObj");
let dataArray = []; let dataArray = [];
if (x == null) { if (x == null) {
return; return;
} }
for (let i = 0; i < x.length; i++) { for (let i = 0; i < x.length; i++) {
dataArray.push({ dataArray.push({
value: x.elements[i].value, value: x.elements[i].value,
name: x.elements[i].name, name: x.elements[i].name,
}); });
} }
//console.log(this, dataArray); //console.log(this, dataArray);
let userFileNameField = document.getElementById("userFileName"); let userFileNameField = document.getElementById("userFileName");
let userFileName = userFileNameField.value; let userFileName = userFileNameField.value;
let userFileNamePH = userFileNameField.getAttribute("placeholder"); let userFileNamePH = userFileNameField.getAttribute("placeholder");
if (userFileName.length != 0) { if (userFileName.length != 0) {
activeState.fileName = userFileName; activeState.fileName = userFileName.replace;
//clear old data as file switches to new filename //clear old data as file switches to new filename
if (userFileNamePH.length != 0) { if (userFileNamePH.length != 0) {
clearData(userFileNamePH); clearData(userFileNamePH);
popFromTemplateFiles(userFileNamePH); popFromTemplateFiles(userFileNamePH);
} }
} else if (userFileNamePH.length != 0) { } else if (userFileNamePH.length != 0) {
activeState.fileName = userFileNamePH; activeState.fileName = userFileNamePH;
} }
storeData("userInput", JSON.stringify(dataArray)); storeData("userInput", JSON.stringify(dataArray));
} }
function storeData(name, data) { function storeData(name, data) {
//setCookie(name, btoa(data), 7); //setCookie(name, btoa(data), 7);
if (name == "userInput") { if (name == "userInput") {
name = getFileName(); name = getFileName();
} }
if (name == "userInputForce") { if (name == "userInputForce") {
name = "userInput"; name = "userInput";
} }
let lT = activeState.loadedTemplate; let lT = activeState.loadedTemplate;
let key = sha256(name + "-" + lT); let key = sha256(name + "_m21_" + lT);
if (name == "templateFiles") { if (name == "templateFiles") {
key = sha256(name + "-"); key = sha256(name + "_m21_");
} }
window.localStorage.setItem(key, obfuscate(data)); window.localStorage.setItem(key, obfuscate(data));
} }
function retrieveData(type, template = "none") { function retrieveData(type, template = "none") {
if (type == "userInput") { if (type == "userInput") {
let tF = JSON.parse(retrieveData("templateFiles")); let tF = JSON.parse(retrieveData("templateFiles"));
if (tF == null) { if (tF == null) {
return ""; return "";
} else { } else {
type = tF[tF.length - 1].fileName; type = tF[tF.length - 1].fileName;
} }
} }
if (type == "userInputForce") { if (type == "userInputForce") {
type = "userInput"; type = "userInput";
} }
let cdata; let cdata;
if (template == "none") { if (template == "none") {
let lT = activeState.loadedTemplate; let lT = activeState.loadedTemplate;
let key = sha256(type + "-" + lT); let key = sha256(type + "_m21_" + lT);
if (type == "templateFiles") { if (type == "templateFiles") {
key = sha256(type + "-"); key = sha256(type + "_m21_");
} }
cdata = window.localStorage.getItem(key); cdata = window.localStorage.getItem(key);
} else { } else {
let key = sha256(type + "-" + template); let key = sha256(type + "_m21_" + template);
cdata = window.localStorage.getItem(key); cdata = window.localStorage.getItem(key);
} }
if (cdata != null) { if (cdata != null) {
return obfuscate(cdata, false); return obfuscate(cdata, false);
} else { } else {
return "[]"; return "[]";
} }
} }
function clearData(type, template = "none") { function clearData(type, template = "none") {
let lT; let lT;
let key; let key;
if (template == "none") { if (template == "none") {
lT = activeState.loadedTemplate; lT = activeState.loadedTemplate;
key = sha256(type + "-" + lT); key = sha256(type + "_m21_" + lT);
if (type == "templateFiles") { if (type == "templateFiles") {
key = sha256(type + "-"); key = sha256(type + "_m21_");
} }
} else { } else {
lT = template; lT = template;
key = sha256(type + "-" + template); key = sha256(type + "_m21_" + template);
} }
window.localStorage.removeItem(key); window.localStorage.removeItem(key);
} }
function getFileName() { function getFileName() {
let currentFileName = activeState.fileName; let currentFileName = activeState.fileName;
if (currentFileName == "none" || currentFileName == "") { let lT = activeState.loadedTemplate;
let date = new Date(); if (currentFileName == "none" || currentFileName == "") {
let current_hour = date.getHours(); let date = new Date();
current_hour = current_hour <= 9 ? "0" + current_hour : current_hour; let current_hour = date.getHours();
let current_minute = date.getMinutes(); current_hour = current_hour <= 9 ? "0" + current_hour : current_hour;
current_minute = let current_minute = date.getMinutes();
current_minute <= 9 ? "0" + current_minute : current_minute; current_minute =
let current_month = date.getMonth() + 1; current_minute <= 9 ? "0" + current_minute : current_minute;
current_month = current_month <= 9 ? "0" + current_month : current_month; let current_month = date.getMonth() + 1;
let current_year = date.getDate(); current_month = current_month <= 9 ? "0" + current_month : current_month;
current_year = current_year <= 9 ? "0" + current_year : current_year; let current_year = date.getDate();
current_year = current_year <= 9 ? "0" + current_year : current_year;
let current_time = current_hour + ":" + current_minute;
let current_date = current_year + "." + current_month; let current_time = current_hour + ":" + current_minute;
currentFileName = current_time + "_" + current_date; let current_date = current_year + "." + current_month;
//console.log(currentFileName); currentFileName = current_time + "_" + current_date + " " + lT;
} //console.log(currentFileName);
}
let lT = activeState.loadedTemplate;
let tF = retrieveData("templateFiles"); let tF = null;
if (tF != "") { try {
try { tF = JSON.parse(retrieveData("templateFiles"));
tF = JSON.parse(tF); } catch(e) {
} catch (e) { tF = null;
alert("Decryption failed; are you authenticated?"); }
window.location.reload();
return; if (tF != null) {
} for (let tFi of tF) {
} if (tFi.fileName == currentFileName) {return currentFileName};
if (tF != null) { }
for (let tFi of tF) { tF.push({ fileName: currentFileName, template: lT });
if (tFi.fileName == currentFileName) {return currentFileName}; } else {
} tF = [{ fileName: currentFileName, template: lT }];
tF.push({ fileName: currentFileName, template: lT }); }
} else { storeData("templateFiles", JSON.stringify(tF));
tF = [{ fileName: currentFileName, template: lT }]; activeState.fileName = currentFileName;
} return currentFileName;
storeData("templateFiles", JSON.stringify(tF)); }
activeState.fileName = currentFileName;
return currentFileName; function obfuscate(data, mode = true) {
} if (mode) {
return XORCipher.encode(sha256(passwordHash), data);
function obfuscate(data, mode = true) { } else {
if (mode) { return XORCipher.decode(sha256(passwordHash), data);
return XORCipher.encode(sha256(passwordHash), data); }
} else { }
return XORCipher.decode(sha256(passwordHash), data);
} function popFromTemplateFiles(fileName) {
} let tF = JSON.parse(retrieveData("templateFiles"));
let newArray = [];
function popFromTemplateFiles(fileName) { for (let obj of tF) {
let tF = JSON.parse(retrieveData("templateFiles")); if (obj.fileName != fileName) {
let newArray = []; newArray.push(obj);
for (let obj of tF) { }
if (obj.fileName != fileName) { }
newArray.push(obj); storeData("templateFiles", JSON.stringify(newArray));
} }
}
storeData("templateFiles", JSON.stringify(newArray)); function createBookShelf() {
} let tF = JSON.parse(retrieveData("templateFiles"));
let bookShelf = {};
function createBookShelf() { let date = new Date();
let tF = JSON.parse(retrieveData("templateFiles")); let current_hour = date.getHours();
let bookShelf = {}; current_hour = current_hour <= 9 ? "0" + current_hour : current_hour;
let date = new Date(); let current_minute = date.getMinutes();
let current_hour = date.getHours(); current_minute =
current_hour = current_hour <= 9 ? "0" + current_hour : current_hour; current_minute <= 9 ? "0" + current_minute : current_minute;
let current_minute = date.getMinutes(); let current_month = date.getMonth() + 1;
current_minute = current_month = current_month <= 9 ? "0" + current_month : current_month;
current_minute <= 9 ? "0" + current_minute : current_minute; let current_year = date.getDate();
let current_month = date.getMonth() + 1; current_year = current_year <= 9 ? "0" + current_year : current_year;
current_month = current_month <= 9 ? "0" + current_month : current_month;
let current_year = date.getDate(); let current_time = current_hour + ":" + current_minute;
current_year = current_year <= 9 ? "0" + current_year : current_year; let current_date = current_year + "." + current_month;
let saveFileName = current_time + "_" + current_date;
let current_time = current_hour + ":" + current_minute;
let current_date = current_year + "." + current_month; if (tF != null) {
let saveFileName = current_time + "_" + current_date; bookShelf[0] = {name: "hash", data: getUsrId(), ts: saveFileName};
let i = 1;
if (tF != null) { for (let tFi of tF) {
bookShelf[0] = {name: "hash", data: getUsrId(), ts: saveFileName}; let data = retrieveData(tFi.fileName, tFi.template);
let i = 1; bookShelf[i] = {};
for (let tFi of tF) { bookShelf[i].name = tFi.fileName + "_m21_" + tFi.template;
let data = retrieveData(tFi.fileName, tFi.template); if (activeState.localOnly) {
bookShelf[i] = {}; bookShelf[i].data = data;
bookShelf[i].name = tFi.fileName + "-" + tFi.template; } else {
bookShelf[i].data = obfuscate(data); bookShelf[i].data = obfuscate(data);
i++; }
}
} i++;
return bookShelf; }
} }
return bookShelf;
function importBookShelf() { }
localStorage.clear() function importBookShelf() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () { localStorage.clear()
if (this.readyState == 4 && this.status == 200) { var xhttp = new XMLHttpRequest();
if (this.responseText == "none") { xhttp.onreadystatechange = function () {
console.log("no files saved on server"); if (this.readyState == 4 && this.status == 200) {
} else { if (this.responseText == "none") {
let respText = decodeURIComponent(this.responseText); console.log("no files saved on server");
let mainArray = JSON.parse(respText); } else {
let templateFilesArray = []; let respText = decodeURIComponent(this.responseText);
for (let file of mainArray) { let mainArray = JSON.parse(respText);
if (file.name == "hash") continue; let templateFilesArray = [];
window.localStorage.setItem(sha256(file.name), file.data); for (let file of mainArray) {
templateFilesArray.push({ fileName: file.name.split("-")[0], template: file.name.split("-")[1] }); if (file.name == "hash") continue;
} window.localStorage.setItem(sha256(file.name), file.data);
window.localStorage.setItem(sha256("templateFiles-"), obfuscate(JSON.stringify(templateFilesArray))); templateFilesArray.push({ fileName: file.name.split("_m21_")[0], template: file.name.split("_m21_")[1] });
} }
} window.localStorage.setItem(sha256("templateFiles-"), obfuscate(JSON.stringify(templateFilesArray)));
}; }
xhttp.open("GET", "php/?getStoredFiles="+getUsrId(), true); }
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8'); };
xhttp.send(); xhttp.open("GET", "php/?getStoredFiles="+getUsrId(), true);
} xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhttp.send();
export { createStorageObj, storeData, retrieveData, clearData, getFileName, createBookShelf, importBookShelf}; }
export { createStorageObj, storeData, retrieveData, clearData, getFileName, createBookShelf, importBookShelf};

View File

@ -1,279 +1,307 @@
import buildForm from "./form.js"; import buildForm from "./form.js";
import { loadFileDivCallBack } from "./files.js"; import { loadFileDivCallBack } from "./files.js";
import { retrieveData, clearData, getFileName, importBookShelf } from "./storage.js"; import { retrieveData, clearData, getFileName, importBookShelf } from "./storage.js";
import { insertTextBlocks } from "./evts.js"; import { insertTextBlocks, modalNotifier } from "./evts.js";
import { createTemplate, createTemplateCallBack} from "./createTemplate.js"; import { createTemplate, createTemplateCallBack} from "./createTemplate.js";
import { getUsrId } from "./scripts.js"; import { getUsrId, sessionVerification } from "./scripts.js";
function loadTemplate(template, newFlag = false, loadOnly = false) { function loadTemplate(template, newFlag = false, loadOnly = false) {
document.getElementById("siteTitle").innerHTML = template.replace(/_/g, " "); document.getElementById("siteTitle").innerHTML = template.replace(/_/g, " ");
activeState.loadedTemplate = template; activeState.loadedTemplate = template;
if (newFlag) { if (newFlag) {
activeState.fileName = "none"; activeState.fileName = "none";
} else { } else {
activeState.fileName = getFileName(); activeState.fileName = getFileName();
} }
document.getElementById("navMob").className = document document.getElementById("navMob").className = document
.getElementById("navMob") .getElementById("navMob")
.className.replace(" w3-show", ""); .className.replace(" w3-show", "");
if (screen.width < 993) { if (screen.width < 993) {
let sidebar = document.getElementById("sidebar"); let sidebar = document.getElementById("sidebar");
sidebar.style.display = "none"; sidebar.style.display = "none";
document.getElementById("siteTitle").innerHTML = "TG"; document.getElementById("siteTitle").innerHTML = "TG";
} }
var xhttp = new XMLHttpRequest(); var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () { xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) { if (this.readyState == 4 && this.status == 200) {
let respText = decodeURIComponent(this.responseText); let respText = decodeURIComponent(this.responseText);
if (loadOnly == "createTemplate") { if (loadOnly == "createTemplate") {
createTemplateCallBack(template, respText.split("!JSON_placeholder:")[0]); createTemplateCallBack(template, respText.split("!JSON_placeholder:")[0]);
return; return;
} }
buildForm(respText, loadOnly); buildForm(respText, loadOnly);
if (loadOnly) { if (loadOnly) {
loadFileDivCallBack(); loadFileDivCallBack();
return; return;
} }
//retrieve previos userData / or preset data if newFile is called //retrieve previos userData / or preset data if newFile is called
let cdata; let cdata;
if (newFlag) { if (newFlag) {
cdata = retrieveData("templatePreset", template); cdata = retrieveData("templatePreset", template);
} else { } else {
cdata = retrieveData("userInputForce"); cdata = retrieveData("userInputForce");
} }
if (cdata != "") { if (cdata != "") {
retrieveForm(JSON.parse(cdata)); let res = "";
} try {
res = JSON.parse(cdata);
//select first object and focus on it } catch (e) {
let obj = JSON.parse( console.log("error", cdata);
window.sessionStorage.getItem("templateObjectsPurified") return;
); }
let firstElement = document.getElementById(obj[0].word.replace(/ /g, "_")); retrieveForm(res);
if (firstElement != null) firstElement.focus(); }
} //select first object and focus on it
}; let obj = JSON.parse(
xhttp.open("GET", "php/?template=" + template, true); window.sessionStorage.getItem("templateObjectsPurified")
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8'); );
xhttp.send(); let firstElement = document.getElementById(obj[0].word.replace(/ /g, "_"));
} if (firstElement != null) firstElement.focus();
function loadNewTemplate(template) { }
//set current page value in activeState object };
activeState.activePage = "template"; xhttp.open("GET", "php/?template=" + template, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
let sidebarDiv = document.getElementById("sidebar"); xhttp.send();
sidebarDiv.replaceWith(sidebarDiv.cloneNode(true)); }
clearData("userInput", template); function loadNewTemplate(template) {
loadTemplate(template, true);
} //sessionVerfication check
if (!sessionVerification()) {
function loadNavBar() { modalNotifier("Error: Session is not authenticated...", 0);
var xhttp = new XMLHttpRequest(); }
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) { //set current page value in activeState object
let res = JSON.parse(this.responseText); activeState.activePage = "template";
let divMob = document.getElementById("navMob");
for (let x in res) { let sidebarDiv = document.getElementById("sidebar");
let aMob = document.createElement("a"); sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));
aMob.setAttribute("href", "#"); clearData("userInput", template);
aMob.setAttribute("data-template", res[x][1]); loadTemplate(template, true);
aMob.classList.add("w3-bar-item", "w3-button", "w3-padding-large"); }
aMob.innerHTML = res[x][0];
function loadNavBar() {
divMob.appendChild(aMob); var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
activeState.templates.push(res[x][1]); if (this.readyState == 4 && this.status == 200) {
} let res = "";
let createEntry = document.createElement("a"); try {
createEntry.setAttribute("href", "#"); res = JSON.parse(this.responseText);
createEntry.setAttribute("data-template", "createNew"); } catch (e) {
createEntry.classList.add("w3-bar-item", "w3-button", "w3-padding-large"); console.log("error", this.responseText);
createEntry.innerHTML = "Manage templates"; return;
}
divMob.appendChild(createEntry);
divMob.addEventListener("click", (e) => { let divMob = document.getElementById("navMob");
if (e.target && e.target.matches("a.w3-bar-item")) { for (let x in res) {
let template = e.target.dataset.template; let aMob = document.createElement("a");
if (template == "createNew") {
createTemplate(); aMob.setAttribute("href", "#");
return; aMob.setAttribute("data-template", res[x][1]);
} aMob.classList.add("w3-bar-item", "w3-button", "w3-padding-large");
loadNewTemplate(template); aMob.innerHTML = res[x][0];
}
}); divMob.appendChild(aMob);
}
}; activeState.templates.push(res[x][1]);
xhttp.open("GET", "php/?templates", true); }
xhttp.send(); let createEntry = document.createElement("a");
} createEntry.setAttribute("href", "#");
function initTextBlocks() { createEntry.setAttribute("data-template", "createNew");
var xhttp = new XMLHttpRequest(); createEntry.classList.add("w3-bar-item", "w3-button", "w3-padding-large");
xhttp.onreadystatechange = function () { createEntry.innerHTML = "Manage templates";
if (this.readyState == 4 && this.status == 200) {
let res = JSON.parse(this.responseText); divMob.appendChild(createEntry);
const textBlocksHolder = document.getElementById("textBlocks"); divMob.addEventListener("click", (e) => {
const divReg = document.getElementById("navTb"); if (e.target && e.target.matches("a.w3-bar-item")) {
for (let x in res) { let template = e.target.dataset.template;
let aReg = document.createElement("a"); if (template == "createNew") {
aReg.setAttribute("href", "#"); createTemplate();
aReg.classList.add("w3-bar-item", "w3-hide-small", "w3-padding-small"); return;
let textBlockText = res[x][1]; }
if (res[x][1].length > 80) { loadNewTemplate(template);
textBlockText = res[x][1].substr(0, 80) + "..."; }
} });
aReg.innerHTML = "<b>" + res[x][0] + ":</b> " + textBlockText; }
divReg.appendChild(aReg); };
xhttp.open("GET", "php/?templates", true);
const text = document.createTextNode( xhttp.send();
res[x][0] + ": " + res[x][1] + "\n" }
); function initTextBlocks() {
textBlocksHolder.appendChild(text); var xhttp = new XMLHttpRequest();
} xhttp.onreadystatechange = function () {
divReg.addEventListener("click", (e) => { if (this.readyState == 4 && this.status == 200) {
if (e.target && e.target.matches("a.w3-bar-item")) { let res = "";
insertTextBlocks(e.target); try {
} res = JSON.parse(this.responseText);
}); } catch (e) {
} console.log("error", this.responseText)
}; return;
xhttp.open("GET", "php/?textBlocks", true); }
xhttp.send(); const textBlocksHolder = document.getElementById("textBlocks");
} const divReg = document.getElementById("navTb");
for (let x in res) {
function setTemplatePreset(template, formData) { if (res[x][1].length < 1) continue;
//console.log(template +" : "+ formData);
var xhttp = new XMLHttpRequest(); let aReg = document.createElement("a");
xhttp.open("POST", "php/?setForm"); aReg.setAttribute("href", "#");
xhttp.setRequestHeader("Accept", "application/json"); aReg.classList.add("w3-bar-item", "w3-hide-small", "w3-padding-small");
xhttp.setRequestHeader("Content-Type", "application/json"); let textBlockText = res[x][1];
xhttp.onreadystatechange = function () { if (res[x][1].length > 80) {
if (this.readyState == 4 && this.status == 200) { textBlockText = res[x][1].substr(0, 80) + "...";
//console.log(this.responseText); }
} aReg.innerHTML = "<b>" + res[x][0] + ":</b> " + textBlockText;
}; divReg.appendChild(aReg);
let data = {
template: template, const text = document.createTextNode(
data: formData, res[x][0] + ": " + res[x][1] + "\n"
}; );
textBlocksHolder.appendChild(text);
xhttp.send(JSON.stringify(data)); }
} divReg.addEventListener("click", (e) => {
if (e.target && e.target.matches("a.w3-bar-item")) {
function setNewTemplate(fileName, data) { insertTextBlocks(e.target);
let obj = { }
fileName: fileName, });
data: data, }
}; };
//console.log(template +" : "+ formData); xhttp.open("GET", "php/?textBlocks", true);
var xhttp = new XMLHttpRequest(); xhttp.send();
xhttp.open("POST", "php/?setTemplate"); }
xhttp.setRequestHeader("Accept", "application/json");
xhttp.setRequestHeader("Content-Type", "application/json"); function setTemplatePreset(template, formData) {
xhttp.onreadystatechange = function () { //console.log(template +" : "+ formData);
if (this.readyState == 4 && this.status == 200) { var xhttp = new XMLHttpRequest();
//console.log(this.responseText); xhttp.open("POST", "php/?setForm");
} xhttp.setRequestHeader("Accept", "application/json");
}; xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function () {
xhttp.send(JSON.stringify(obj)); if (this.readyState == 4 && this.status == 200) {
} //console.log(this.responseText);
}
function storeFilesToServer(data) { };
//console.log(template +" : "+ formData); let data = {
var xhttp = new XMLHttpRequest(); template: template,
xhttp.onreadystatechange = function () { data: formData,
if (this.readyState == 4 && this.status == 200) { };
if (this.responseText == "success") {
console.log("files saved"); xhttp.send(JSON.stringify(data));
} }
}
}; function setNewTemplate(fileName, data) {
xhttp.open("POST", "php/?storeFiles", true); let obj = {
xhttp.setRequestHeader("Accept", "application/json"); fileName: fileName,
xhttp.setRequestHeader("Content-Type", "application/json"); data: data,
xhttp.send(JSON.stringify(data)); };
} //console.log(template +" : "+ formData);
var xhttp = new XMLHttpRequest();
function checkForStoredDataOnServer() { xhttp.open("POST", "php/?setTemplate");
var xhttp = new XMLHttpRequest(); xhttp.setRequestHeader("Accept", "application/json");
xhttp.onreadystatechange = function () { xhttp.setRequestHeader("Content-Type", "application/json");
if (this.readyState == 4 && this.status == 200) { xhttp.onreadystatechange = function () {
if (this.responseText == "none") { if (this.readyState == 4 && this.status == 200) {
} else { //console.log(this.responseText);
activeState.serverFilesTs = this.responseText; }
let btn = document.getElementById("importModalBtn"); };
btn.style.display = "";
} xhttp.send(JSON.stringify(obj));
} }
};
xhttp.open("GET", "php/?storedFiles="+getUsrId(), true); function storeFilesToServer(data) {
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8'); //console.log(template +" : "+ formData);
xhttp.send(); var xhttp = new XMLHttpRequest();
} xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
function delStoredDataOnServer() { if (this.responseText == "success") {
var xhttp = new XMLHttpRequest(); console.log("files saved");
xhttp.onreadystatechange = function () { }
if (this.readyState == 4 && this.status == 200) { }
if (this.responseText == "none") { };
let btn = document.getElementById("importModalBtn"); xhttp.open("POST", "php/?storeFiles", true);
btn.style.display = "none"; xhttp.setRequestHeader("Accept", "application/json");
} xhttp.setRequestHeader("Content-Type", "application/json");
} xhttp.send(JSON.stringify(data));
}; }
xhttp.open("GET", "php/?storedFiles="+getUsrId()+"&del", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8'); function checkForStoredDataOnServer() {
xhttp.send(); var xhttp = new XMLHttpRequest();
} xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "none") {
function retrieveForm(arr) { } else {
for (let i = 0; i < arr.length; i++) { activeState.serverFilesTs = this.responseText;
let e = document.getElementById(arr[i].name); let btn = document.getElementById("importModalBtn");
if (e === null) { btn.style.display = "";
e = document.getElementById(arr[i].name.split("cl-")[1]); }
if (e === null) continue; }
} };
xhttp.open("GET", "php/?storedFiles="+getUsrId(), true);
if (e.name.substr(0, 4) == "clM-") continue; xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhttp.send();
switch (e.nodeName) { }
case "TEXTAREA":
e.innerHTML = arr[i].value; function delStoredDataOnServer() {
break; var xhttp = new XMLHttpRequest();
case "INPUT": xhttp.onreadystatechange = function () {
e.value = arr[i].value; if (this.readyState == 4 && this.status == 200) {
break; if (this.responseText == "none") {
case "SELECT": let btn = document.getElementById("importModalBtn");
for (let j = 0; j < e.options.length; j++) { btn.style.display = "none";
if (e.options[j].value == arr[i].value) { }
// Item is found. Set its property and exit }
e.options[j].selected = true; };
break; xhttp.open("GET", "php/?storedFiles="+getUsrId()+"&del", true);
} xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
} xhttp.send();
break; }
default:
e.innerHTML = arr[i].value;
break; function retrieveForm(arr) {
} for (let i = 0; i < arr.length; i++) {
} let e = document.getElementById(arr[i].name);
} if (e === null) {
export { e = document.getElementById(arr[i].name.split("cl-")[1]);
loadTemplate, if (e === null) continue;
loadNavBar, }
initTextBlocks,
loadNewTemplate, if (e.name.substr(0, 4) == "clM-") continue;
setTemplatePreset,
setNewTemplate, switch (e.nodeName) {
storeFilesToServer, case "TEXTAREA":
checkForStoredDataOnServer, e.innerHTML = arr[i].value;
delStoredDataOnServer break;
}; case "INPUT":
e.value = arr[i].value;
break;
case "SELECT":
for (let j = 0; j < e.options.length; j++) {
if (e.options[j].value == arr[i].value) {
// Item is found. Set its property and exit
e.options[j].selected = true;
break;
}
}
break;
default:
e.innerHTML = arr[i].value;
break;
}
}
}
export {
loadTemplate,
loadNavBar,
initTextBlocks,
loadNewTemplate,
setTemplatePreset,
setNewTemplate,
storeFilesToServer,
checkForStoredDataOnServer,
delStoredDataOnServer
};

View File

@ -1,187 +1,187 @@
var XORCipher = { var XORCipher = {
encode: function (key, data, seed) { encode: function (key, data, seed) {
data = xor_encrypt(key, data, seed); data = xor_encrypt(key, data, seed);
return b64_encode(data); return b64_encode(data);
}, },
decode: function (key, data) { decode: function (key, data) {
data = b64_decode(data); data = b64_decode(data);
return xor_decrypt(key, data); return xor_decrypt(key, data);
}, },
seed: function (n) { seed: function (n) {
return randString(n); return randString(n);
}, },
}; };
function stringToUtf8ByteArray(str) { function stringToUtf8ByteArray(str) {
var out = [], var out = [],
p = 0; p = 0;
for (var i = 0; i < str.length; i++) { for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i); var c = str.charCodeAt(i);
if (c < 128) { if (c < 128) {
out[p++] = c; out[p++] = c;
} else if (c < 2048) { } else if (c < 2048) {
out[p++] = (c >> 6) | 192; out[p++] = (c >> 6) | 192;
out[p++] = (c & 63) | 128; out[p++] = (c & 63) | 128;
} else if ( } else if (
(c & 0xfc00) == 0xd800 && (c & 0xfc00) == 0xd800 &&
i + 1 < str.length && i + 1 < str.length &&
(str.charCodeAt(i + 1) & 0xfc00) == 0xdc00 (str.charCodeAt(i + 1) & 0xfc00) == 0xdc00
) { ) {
// Surrogate Pair // Surrogate Pair
c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
out[p++] = (c >> 18) | 240; out[p++] = (c >> 18) | 240;
out[p++] = ((c >> 12) & 63) | 128; out[p++] = ((c >> 12) & 63) | 128;
out[p++] = ((c >> 6) & 63) | 128; out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128; out[p++] = (c & 63) | 128;
} else { } else {
out[p++] = (c >> 12) | 224; out[p++] = (c >> 12) | 224;
out[p++] = ((c >> 6) & 63) | 128; out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128; out[p++] = (c & 63) | 128;
} }
} }
return out; return out;
} }
function utf8ByteArrayToString(bytes) { function utf8ByteArrayToString(bytes) {
// array of bytes // array of bytes
var out = [], var out = [],
pos = 0, pos = 0,
c = 0; c = 0;
while (pos < bytes.length) { while (pos < bytes.length) {
var c1 = bytes[pos++]; var c1 = bytes[pos++];
if (c1 < 128) { if (c1 < 128) {
out[c++] = String.fromCharCode(c1); out[c++] = String.fromCharCode(c1);
} else if (c1 > 191 && c1 < 224) { } else if (c1 > 191 && c1 < 224) {
var c2 = bytes[pos++]; var c2 = bytes[pos++];
out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
} else if (c1 > 239 && c1 < 365) { } else if (c1 > 239 && c1 < 365) {
// Surrogate Pair // Surrogate Pair
var c2 = bytes[pos++]; var c2 = bytes[pos++];
var c3 = bytes[pos++]; var c3 = bytes[pos++];
var c4 = bytes[pos++]; var c4 = bytes[pos++];
var u = var u =
(((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) - (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -
0x10000; 0x10000;
out[c++] = String.fromCharCode(0xd800 + (u >> 10)); out[c++] = String.fromCharCode(0xd800 + (u >> 10));
out[c++] = String.fromCharCode(0xdc00 + (u & 1023)); out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
} else { } else {
var c2 = bytes[pos++]; var c2 = bytes[pos++];
var c3 = bytes[pos++]; var c3 = bytes[pos++];
out[c++] = String.fromCharCode( out[c++] = String.fromCharCode(
((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63) ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
); );
} }
} }
return out.join(""); return out.join("");
} }
var b64_table = var b64_table =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function b64_encode(data) { function b64_encode(data) {
var o1, var o1,
o2, o2,
o3, o3,
h1, h1,
h2, h2,
h3, h3,
h4, h4,
bits, bits,
r, r,
i = 0, i = 0,
enc = ""; enc = "";
if (!data) { if (!data) {
return data; return data;
} }
do { do {
o1 = data[i++]; o1 = data[i++];
o2 = data[i++]; o2 = data[i++];
o3 = data[i++]; o3 = data[i++];
bits = (o1 << 16) | (o2 << 8) | o3; bits = (o1 << 16) | (o2 << 8) | o3;
h1 = (bits >> 18) & 0x3f; h1 = (bits >> 18) & 0x3f;
h2 = (bits >> 12) & 0x3f; h2 = (bits >> 12) & 0x3f;
h3 = (bits >> 6) & 0x3f; h3 = (bits >> 6) & 0x3f;
h4 = bits & 0x3f; h4 = bits & 0x3f;
enc += enc +=
b64_table.charAt(h1) + b64_table.charAt(h1) +
b64_table.charAt(h2) + b64_table.charAt(h2) +
b64_table.charAt(h3) + b64_table.charAt(h3) +
b64_table.charAt(h4); b64_table.charAt(h4);
} while (i < data.length); } while (i < data.length);
r = data.length % 3; r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + "===".slice(r || 3); return (r ? enc.slice(0, r - 3) : enc) + "===".slice(r || 3);
} }
function b64_decode(data) { function b64_decode(data) {
var o1, var o1,
o2, o2,
o3, o3,
h1, h1,
h2, h2,
h3, h3,
h4, h4,
bits, bits,
i = 0, i = 0,
result = []; result = [];
if (!data) { if (!data) {
return data; return data;
} }
data += ""; data += "";
do { do {
h1 = b64_table.indexOf(data.charAt(i++)); h1 = b64_table.indexOf(data.charAt(i++));
h2 = b64_table.indexOf(data.charAt(i++)); h2 = b64_table.indexOf(data.charAt(i++));
h3 = b64_table.indexOf(data.charAt(i++)); h3 = b64_table.indexOf(data.charAt(i++));
h4 = b64_table.indexOf(data.charAt(i++)); h4 = b64_table.indexOf(data.charAt(i++));
bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4; bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4;
o1 = (bits >> 16) & 0xff; o1 = (bits >> 16) & 0xff;
o2 = (bits >> 8) & 0xff; o2 = (bits >> 8) & 0xff;
o3 = bits & 0xff; o3 = bits & 0xff;
result.push(o1); result.push(o1);
if (h3 !== 64) { if (h3 !== 64) {
result.push(o2); result.push(o2);
if (h4 !== 64) { if (h4 !== 64) {
result.push(o3); result.push(o3);
} }
} }
} while (i < data.length); } while (i < data.length);
return result; return result;
} }
function rand(min, max) { function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min; return Math.floor(Math.random() * (max - min + 1)) + min;
} }
function randString(n) { function randString(n) {
var r = ""; var r = "";
for (var i = 0; i < n; i++) r += String.fromCharCode(rand(1, 65535)); for (var i = 0; i < n; i++) r += String.fromCharCode(rand(1, 65535));
return r; return r;
} }
function xor_encrypt(key, data, seed) { function xor_encrypt(key, data, seed) {
if (typeof seed == "undefined") seed = randString(32); if (typeof seed == "undefined") seed = randString(32);
var d = stringToUtf8ByteArray(seed + String.fromCharCode(0) + data), var d = stringToUtf8ByteArray(seed + String.fromCharCode(0) + data),
k = stringToUtf8ByteArray(key), k = stringToUtf8ByteArray(key),
r = []; r = [];
for (var i = 0; i < d.length; i++) for (var i = 0; i < d.length; i++)
r[i] = r[i - 1] ^ d[i] ^ k[Math.floor(i % k.length)]; r[i] = r[i - 1] ^ d[i] ^ k[Math.floor(i % k.length)];
return r; return r;
} }
function xor_decrypt(key, data) { function xor_decrypt(key, data) {
var d = data, var d = data,
k = stringToUtf8ByteArray(key), k = stringToUtf8ByteArray(key),
r = []; r = [];
for (var i = 0; i < d.length; i++) for (var i = 0; i < d.length; i++)
r[i] = d[i - 1] ^ d[i] ^ k[Math.floor(i % k.length)]; r[i] = d[i - 1] ^ d[i] ^ k[Math.floor(i % k.length)];
r.splice(0, r.indexOf(0) + 1); r.splice(0, r.indexOf(0) + 1);
return utf8ByteArrayToString(r); return utf8ByteArrayToString(r);
} }
export default XORCipher; export default XORCipher;