diff --git a/js/9.7/buildForm.js b/js/9.7/buildForm.js new file mode 100644 index 0000000..11cd932 --- /dev/null +++ b/js/9.7/buildForm.js @@ -0,0 +1,393 @@ +import { getFileName } from "./storage.js"; + +function transformTemplateObject(objects) { + let form = document.createElement("FORM"); + form.setAttribute("method", "post"); + form.setAttribute("action", "javascript:void(0)"); + form.setAttribute("id", "mainFormObj"); + form.classList.add("w3-row"); + + let sidebarList = document.createElement("ul"); + sidebarList.classList.add("w3-ul"); + + for (let i = 0; i < objects.length; i++) { + buildField(objects[i], form, sidebarList); + } + + //console.log(objects); + + //create sidebar submit button + let sidebarSubmitButton = document.createElement("li"); + sidebarSubmitButton.classList.add( + "w3-bar-item", + "w3-padding-large", + "w3-button" + ); + sidebarSubmitButton.style.borderTop = "2px solid #ddd"; + sidebarSubmitButton.id = "sb-submit"; + sidebarSubmitButton.innerHTML = "Save & Copy"; + sidebarList.appendChild(sidebarSubmitButton); + + //add sidebar elemnts to sidebar + document.getElementById("sidebar").appendChild(sidebarList); + + //add form to mainForm Div + document.getElementById("mainForm").appendChild(form); + + //create username and append field to site + let fileName = getFileName(); + document.getElementById("submitContainer").appendChild(userFileNameDiv(fileName)); + + // create a Save button + let saveBtn = document.createElement("input"); + saveBtn.setAttribute("type", "submit"); + saveBtn.setAttribute("value", "Save"); + saveBtn.classList.add("w3-button"); + saveBtn.classList.add("w3-grey"); + saveBtn.style.margin = "20px"; + //append submit button to submitContainer + document.getElementById("submitContainer").appendChild(saveBtn); + + // create a Copy button + let copyBtn = document.createElement("input"); + copyBtn.setAttribute("type", "submit"); + copyBtn.setAttribute("value", "Copy"); + copyBtn.classList.add("w3-button"); + copyBtn.classList.add("w3-grey"); + copyBtn.style.margin = "20px 0px"; + //append submit button to submitContainer + document.getElementById("submitContainer").appendChild(copyBtn); + +} + + +function buildField(obj, form, sidebarList) { + //create template Input fields + + let divContainer = document.createElement("DIV"); + divContainer.classList.add("w3-half"); + divContainer.classList.add("w3-container"); + + let div = document.createElement("DIV"); + div.classList.add("w3-section"); + div.classList.add("w3-flat-silver"); + + div.setAttribute("style", "padding: 10px"); + + let label = document.createElement("LABEL"); + + let connectedListsArray = []; + + let ltPlaceholder; + + //check for longtext:!li and convert it to standard longText + if (obj.type.indexOf("longText") !== -1) { + if (obj.type.indexOf(":") !== -1) { + ltPlaceholder = obj.type.split(":")[1]; + if (ltPlaceholder !== undefined) { + let textarea = document.createElement("textarea"); + textarea.setAttribute("name", obj.word.replace(/ /g, "_")); + textarea.setAttribute("id", obj.word.replace(/ /g, "_")); + textarea.setAttribute("cols", "100"); + textarea.setAttribute("rows", "15"); + textarea.classList.add("w3-input"); + 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"); + input.setAttribute("name", obj.word.replace(/ /g, "_")); + 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); + div.appendChild(input); + } + } + } + + //check for markup:title and display it as none + if (obj.type.indexOf("markup") !== -1) { + if (obj.type.indexOf(":") !== -1) { + ltPlaceholder = obj.type.split(":")[1]; + if (ltPlaceholder !== undefined) { + divContainer.classList.add("hidden"); + let input = document.createElement("input"); + input.setAttribute("type", "text"); + input.setAttribute("name", obj.word.replace(/ /g, "_")); + 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"); + if (typeof obj.m !== "undefined") { + let optionM = document.createElement("option"); + optionM.value = obj.m; + optionM.text = obj.m; + select.appendChild(optionM); + } + if (typeof obj.w !== "undefined") { + let optionW = document.createElement("option"); + optionW.value = obj.w; + optionW.text = obj.w; + select.appendChild(optionW); + } + if (typeof obj.d !== "undefined") { + let optionD = document.createElement("option"); + optionD.value = obj.d; + optionD.text = obj.d; + select.appendChild(optionD); + } + label.innerHTML = obj.word; + div.appendChild(label); + div.appendChild(select); + break; + + case "list": + let select2 = document.createElement("select"); + select2.setAttribute("name", obj.word.replace(/ /g, "_")); + select2.classList.add("w3-select"); + select2.id = obj.word.replace(/ /g, "_"); + select2.setAttribute("id", obj.word.replace(/ /g, "_")); + + for (let listItem = 0; listItem < obj.listCount + 1; listItem++) { + //console.log(obj[listItem]); + if (typeof obj[listItem] !== "undefined") { + let optionL = document.createElement("option"); + optionL.value = obj[listItem]; + optionL.text = obj[listItem]; + select2.appendChild(optionL); + } + } + label.innerHTML = obj.word; + div.appendChild(label); + div.appendChild(select2); + break; + + case "conList": + let select3 = document.createElement("select"); + select3.setAttribute("name", "clM-"+obj.word.replace(/ /g, "_")); + select3.classList.add("w3-select"); + select3.id = obj.word.replace(/ /g, "_"); + let optionDefault = document.createElement("option"); + optionDefault.value = "!none"; + optionDefault.text = "Choose one"; + select3.appendChild(optionDefault); + + + for (let listItem = 0; listItem < obj.listCount + 1; listItem++) { + //console.log(obj[listItem]); + if (typeof obj[listItem] !== "undefined") { + let optionL = document.createElement("option"); + let item = obj[listItem]; + optionL.value = item; + optionL.text = item; + select3.appendChild(optionL); + connectedListsArray.push({ + word: item, + type: obj["clType-"+item], + cl: obj.word + }); + } + } + label.innerHTML = obj.word; + + if (obj.listCount == 0) { + select3 = document.createElement("button"); + select3.setAttribute("value", "!none"); + select3.classList.add("w3-button", "w3-grey", "w3-left-align"); + select3.id = obj.word.replace(/ /g, "_"); + select3.innerHTML = "Show"; + select3.setAttribute("name", "clM-"+obj.word.replace(/ /g, "_")); + select3.setAttribute("data-word", connectedListsArray[0].word); + } + + div.appendChild(label); + div.appendChild(document.createElement("br")); + + div.appendChild(select3); + + + break; + + case "simpleInput": + let input = document.createElement("input"); + input.setAttribute("type", "text"); + input.setAttribute("name", obj.word.replace(/ /g, "_")); + input.classList.add("w3-input"); + input.id = obj.word.replace(/ /g, "_"); + label.innerHTML = obj.word; + div.appendChild(label); + div.appendChild(input); + break; + case "longText": + let textarea = document.createElement("textarea"); + textarea.setAttribute("name", obj.word.replace(/ /g, "_")); + textarea.setAttribute("cols", "100"); + textarea.setAttribute("rows", "15"); + textarea.classList.add("w3-input"); + textarea.id = obj.word.replace(/ /g, "_"); + label.innerHTML = obj.word; + divContainer.classList.remove("w3-half"); + divContainer.classList.add("w3-center"); + div.appendChild(label); + div.appendChild(textarea); + break; + case "current_time": + let input2 = document.createElement("input"); + let today = new Date(); + let currentTime = + today.getHours() + ":" + ("0" + today.getMinutes()).slice(-2); + //console.log(currentTime); + input2.setAttribute("type", "text"); + input2.setAttribute("name", obj.word.replace(/ /g, "_")); + input2.setAttribute("value", currentTime); + input2.id = obj.word.replace(/ /g, "_"); + div.setAttribute("style", "display: none;"); + input2.classList.add("w3-input"); + label.innerHTML = obj.word; + div.appendChild(label); + div.appendChild(input2); + break; + case "current_date": + let input3 = document.createElement("input"); + var today2 = new Date(); + var dd = String(today2.getDate()).padStart(2, "0"); + var mm = String(today2.getMonth() + 1).padStart(2, "0"); //January is 0! + var yyyy = today2.getFullYear(); + currentDate = dd + "." + mm + "." + yyyy; + input3.setAttribute("type", "text"); + input3.setAttribute("name", obj.word.replace(/ /g, "_")); + input3.setAttribute("value", currentDate); + input3.id = obj.word.replace(/ /g, "_"); + div.setAttribute("style", "display: none;"); + input3.classList.add("w3-input"); + label.innerHTML = obj.word; + div.appendChild(label); + div.appendChild(input3); + break; + } + + //check if item is connected list item cl + if (obj.cl !== undefined) divContainer.classList.add("hidden"); + if (obj.cl !== undefined) { + div.lastChild.setAttribute("name", + (ltPlaceholder !== undefined) ? "cl-"+obj.word.replace(/ /g, "_") +":"+ltPlaceholder : "cl-"+obj.word.replace(/ /g, "_")); + } + + //append field to wrapper and add to mainForm + divContainer.appendChild(div); + form.appendChild(divContainer); + + buildSidebarList(obj, sidebarList) + + //handle conList items + if (obj.type == "conList") { + //build connected list fields according to obj + for (let conObj of connectedListsArray) { + buildField(conObj, form, sidebarList); + } + + //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, "_"))) { + let button = document.getElementById(obj.word.replace(/ /g, "_")); + let con = button.dataset.word; + let conElement = document.getElementById(con); + if (conElement.parentElement.parentElement.classList.contains("hidden")) { + conElement.parentElement.parentElement.classList.remove("hidden"); + button.value = "!selected"; + } else { + conElement.parentElement.parentElement.classList.add("hidden"); + button.value = "!none"; + } + } + }); + } else { + document.getElementById("mainForm").addEventListener("change", (e) => { + if (e.target && e.target.matches("select#"+obj.word.replace(/ /g, "_"))) { + let select = document.getElementById(obj.word.replace(/ /g, "_")); + 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")) { + if (hiddenItems.innerHTML != select.value) { + hiddenItems.classList.add("hidden"); + } else { + hiddenItems.classList.remove("hidden"); + } + } + } + }); + } + } +} + +function buildSidebarList(obj, sidebarList) { + //build sidebarlist item and append + let sidebarListItem = document.createElement("li"); + sidebarListItem.classList.add( + "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, "_")); + sidebarListItem.innerHTML = obj.word; + sidebarListItem; + sidebarList.appendChild(sidebarListItem); +} + +function userFileNameDiv(fileName) { + let divContainer = document.createElement("DIV"); + 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"); + 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; diff --git a/js/9.7/createTemplate.js b/js/9.7/createTemplate.js new file mode 100644 index 0000000..1b1e05b --- /dev/null +++ b/js/9.7/createTemplate.js @@ -0,0 +1,212 @@ +import {setNewTemplate, loadTemplate} from "./web.js"; +import { retrieveData } from "./storage.js"; +import { hideMenus, modalNotifier } from "./evts.js"; + +function createTemplate(template = false) { + + + //set current page value in activeState object + activeState.activePage = "createTemplate"; + + //check if user is authenticated and templateFilesArray is decryptable + let tF = retrieveData("templateFiles"); + if (tF != "") { + try { + tF = JSON.parse(tF); + } catch (e) { + alert("Decryption failed; are you authenticated?"); + window.location.reload(); + return; + } + } + + + if (screen.width > 992) { + document.getElementById("siteTitle").innerHTML = "Manage templates"; + } else { + document.getElementById("siteTitle").innerHTML = "TG"; + } + + //hide set Form button + document.getElementById("setFormButton").style.display = "none"; + + if (template) { + document.getElementById("templateInput").value = loadTemplate(template, false, "createTemplate"); + return; + } + + //reset page and event listeners + + hideMenus(); + + let mainFormDiv = document.getElementById("mainForm"); + let outputDiv = document.getElementById("output"); + let submitContainerDiv = document.getElementById("submitContainer"); + let sidebarDiv = document.getElementById("sidebar"); + + mainFormDiv.innerHTML = ""; + mainFormDiv.replaceWith(mainFormDiv.cloneNode(true)); + outputDiv.innerHTML = ""; + outputDiv.replaceWith(outputDiv.cloneNode(true)); + submitContainerDiv.innerHTML = ""; + submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true)); + sidebarDiv.innerHTML = ""; + sidebarDiv.replaceWith(sidebarDiv.cloneNode(true)); + + document.getElementById("mainForm").appendChild(createTemplateInput()); + document.getElementById("sidebar").appendChild(loadTemplateSidebar(activeState.templates)); + + //add events + if (!template) formEvts(); + } + + function createTemplateCallBack(fileName, data) { + + document.getElementById("templateInput").value = data; + document.getElementById("userFileName").setAttribute("placeholder", fileName); + } + + function loadTemplateSidebar(templates) { + let sidebarList = document.createElement("ul"); + sidebarList.classList.add("w3-ul"); + if (!templates.includes('_textBlocks')) { + templates.push('_textBlocks'); + } + + + for (let template of templates) { + let sidebarListItem = document.createElement("li"); + + sidebarListItem.classList.add( + "w3-bar-item", + "w3-padding-large", + "w3-button" + ); + sidebarListItem.style.borderBottom = "1px solid #ddd"; + sidebarListItem.id = "sb-item"; + sidebarListItem.setAttribute("data-template", template); + sidebarListItem.innerHTML = template.replace(/_/g, " "); + sidebarList.appendChild(sidebarListItem); + } + + return sidebarList; + + } + + function createTemplateInput() { + + let createTemplateDisplay = document.createElement("DIV"); + createTemplateDisplay.classList.add( + "w3-row-padding", + "w3-padding-24", + "w3-container", + "w3-flat-clouds" + ); + createTemplateDisplay.id = "createTemplateDisplayWrapper"; + + + //start building submitContainer with save and filename + + + document.getElementById("submitContainer").appendChild(userFileNameDiv()); + + let saveButton = document.createElement("input"); + saveButton.setAttribute("type", "submit"); + saveButton.setAttribute("value", "Save"); + saveButton.classList.add("w3-button"); + saveButton.classList.add("w3-grey"); + saveButton.style.margin = "20px"; + document.getElementById("submitContainer").appendChild(saveButton); + + + + let divContainer = document.createElement("DIV"); + divContainer.classList.add("w3-container", "w3-center"); + + let div = document.createElement("DIV"); + div.classList.add("w3-section"); + div.classList.add("w3-flat-silver"); + + div.setAttribute("style", "padding: 10px"); + + + + let textarea = document.createElement("textarea"); + textarea.setAttribute("name", "templateInput"); + textarea.setAttribute("id", "templateInput"); + textarea.setAttribute("cols", "100"); + textarea.setAttribute("rows", "30"); + textarea.classList.add("w3-input"); + + + div.appendChild(textarea); + divContainer.appendChild(div); + + + createTemplateDisplay.appendChild(divContainer); + return createTemplateDisplay; + + } + + + function formEvts() { + //add event listener to submitContainer + document.getElementById("submitContainer").addEventListener("click", (e) => { + if (e.target && e.target.tagName === "INPUT") { + switch (e.target.value) { + case "Save": + let fileName; + let userFileNameField = document.getElementById("userFileName"); + let userFileName = userFileNameField.value; + let userFileNamePH = userFileNameField.getAttribute("placeholder"); + if (userFileName.length != 0) { + fileName = userFileName; + //clear old data as file switches to new filename + } else if (userFileNamePH.length != 0) { + fileName = userFileNamePH; + } + let data = document.getElementById("templateInput").value; + setNewTemplate(fileName, data); + modalNotifier(fileName+" saved!", 1); + e.target.className = e.target.className.replace(" w3-grey", " w3-flat-nephritis"); + 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); + e.preventDefault; + break; + default: + e.preventDefault; + } + } + }); + document.getElementById("sidebar").addEventListener("click", (e) => { + if (e.target && e.target.matches("li.w3-bar-item")) { + let template = e.target.dataset.template; + createTemplate(template); + } + }); + } + + + + function userFileNameDiv() { + let divContainer = document.createElement("DIV"); + 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"); + 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}; \ No newline at end of file diff --git a/js/9.7/evts.js b/js/9.7/evts.js new file mode 100644 index 0000000..ad9c089 --- /dev/null +++ b/js/9.7/evts.js @@ -0,0 +1,193 @@ +import { + clearData, + createStorageObj, + createBookShelf, + importBookShelf, +} from "./storage.js"; +import { + loadTemplate, + storeFilesToServer, + setTemplatePreset, + checkForStoredDataOnServer, + delStoredDataOnServer +} from "./web.js"; +import parseFormOnSubmit from "./parseForm.js"; +import { getUsrId } from "./scripts.js"; + +function showMenu() { + var x = document.getElementById("navMob"); + if (x.className.indexOf("w3-show") == -1) { + x.className += " w3-show"; + } else { + x.className = x.className.replace(" w3-show", ""); + } + + if (screen.width < 993) { + let sidebar = document.getElementById("sidebar"); + sidebar.style.display = "none"; + } +} +function showSidebar() { + let sidebar = document.getElementById("sidebar"); + if (getComputedStyle(sidebar).display === "none") { + sidebar.style.display = "block"; + sidebar.style.marginTop = "35px"; + } else { + sidebar.style.display = "none"; + } + + if (screen.width < 993) { + let navBar = document.getElementById("navMob"); + navBar.className = navBar.className.replace(" w3-show", ""); + } +} + +function showTextBlocks() { + var x = document.getElementById("navTb"); + if (x.className.indexOf("w3-show") == -1) { + x.className += " w3-show"; + } else { + x.className = x.className.replace(" w3-show", ""); + } + + if (screen.width < 993) { + let sidebar = document.getElementById("sidebar"); + sidebar.style.display = "none"; + } +} + +function insertTextBlocks(t) { + let insert = "!" + t.innerText.split(":")[0] + " "; + let id = activeState.lastElement; + let element = document.getElementById(id); + if (element === null) { + return; + } + element.value += insert; + let tB = document.getElementById("navTb"); + tB.className.replace(" w3-show", ""); + element.focus(); +} + +function handleOnBlur(t) { + activeState.lastElement = t.id; + createStorageObj(); +} + +function clickClearForm() { + //document.activeElement.blur(); + //document.getElementById("sidebar").focus(); + clearData("userInput"); + let lT = activeState.loadedTemplate; + loadTemplate(lT); +} + +function hideMenus() { + let sidebar = document.getElementById("sidebar"); + sidebar.style.display = "none"; + let navBar = document.getElementById("navMob"); + navBar.className = navBar.className.replace(" w3-show", ""); + let tbBar = document.getElementById("navTb"); + tbBar.className = tbBar.className.replace(" w3-show", ""); +} + +function modalNotifier(msg, timeout) { + let modalElement = document.getElementById("modalNotifier"); + let msgElement = document.getElementById("modalMsg"); + + modalElement.style.display = "block"; + msgElement.innerHTML = msg; + if (timeout === undefined) { + const run = setTimeout(() => (modalElement.style.display = "none"), 5000); + } else if (timeout >= 1) { + const run = setTimeout( + () => (modalElement.style.display = "none"), + timeout * 1000 + ); + } +} + +function clickSetForm(e) { + e.preventDefault; + let dataArray = parseFormOnSubmit(true); + let lT = activeState.loadedTemplate; + setTemplatePreset(lT, JSON.stringify(dataArray)); + modalNotifier("Form Saved", 2); +} + +function clickImportFiles() { + checkForStoredDataOnServer(); + document.getElementById("modalMsg").addEventListener("click", (e) => { + if (e.target && e.target.tagName === "BUTTON") { + let modal = document.getElementById("modalNotifier"); + switch (e.target.innerHTML) { + case "Import": + modal.replaceWith(modal.cloneNode(true)); + document.getElementById("modalMsg").addEventListener("click", (e) => { + if (e.target && e.target.tagName === "BUTTON") { + let modal = document.getElementById("modalNotifier"); + + switch (e.target.innerHTML) { + case "Yes": + importBookShelf(); + modal.replaceWith(modal.cloneNode(true)); + modalNotifier("Imported!", 2); + break; + case "Cancel": + modal.replaceWith(modal.cloneNode(true)); + document.getElementById("modalNotifier").style.display = "none"; + break; + default: + e.preventDefault; + } + } + }) + modalNotifier( + "
\ + Would you like to import the backup created on: "+activeState.serverFilesTs.replace("_", " - ")+ "

\ + \ +
", + 0); + break; + case "Save": + storeFilesToServer(createBookShelf()); + modal.replaceWith(modal.cloneNode(true)); + modalNotifier( + "Files saved to server

would you like to download them?" + ); + break; + case "Delete": + delStoredDataOnServer(); + break; + + default: + e.preventDefault; + } + } + }); + modalNotifier( + "Here you can manage if your files should be saved on the server \ +
If there are stored files already on the server you can inport them \ + It will overwrite any saved documents

\ +
\ + \ + \ +
", + 0); + +} + +export { + hideMenus, + showMenu, + showSidebar, + showTextBlocks, + insertTextBlocks, + handleOnBlur, + clickClearForm, + modalNotifier, + clickSetForm, + clickImportFiles, +}; diff --git a/js/9.7/files.js b/js/9.7/files.js new file mode 100644 index 0000000..c0a7ecf --- /dev/null +++ b/js/9.7/files.js @@ -0,0 +1,313 @@ +import { + storeData, + clearData, + retrieveData, + createStorageObj, +} from "./storage.js"; +import { loadTemplate } from "./web.js"; +import parseFormOnSubmit from "./parseForm.js"; + +function buildFile() { + createStorageObj(); + + + //set current page value in activeState object + activeState.activePage = "files"; + + //check if user is authenticated and templateFilesArray is decryptable + let tF = retrieveData("templateFiles"); + if (tF != "") { + try { + tF = JSON.parse(tF); + } catch (e) { + alert("Decryption failed; are you authenticated?"); + window.location.reload(); + return; + } + } + + if (tF == null) { + //console.log("none yet"); + alert("there are no saved texts yet"); + return; + } + + if (screen.width > 992) { + document.getElementById("siteTitle").innerHTML = "Template Gen"; + } else { + document.getElementById("siteTitle").innerHTML = "TG"; + } + + //hide set Form button + document.getElementById("setFormButton").style.display = "none"; + + //reset page and event listeners + let mainFormDiv = document.getElementById("mainForm"); + let outputDiv = document.getElementById("output"); + let submitContainerDiv = document.getElementById("submitContainer"); + let sidebarDiv = document.getElementById("sidebar"); + + mainFormDiv.innerHTML = ""; + mainFormDiv.replaceWith(mainFormDiv.cloneNode(true)); + outputDiv.innerHTML = ""; + outputDiv.replaceWith(outputDiv.cloneNode(true)); + submitContainerDiv.innerHTML = ""; + submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true)); + sidebarDiv.innerHTML = ""; + sidebarDiv.replaceWith(sidebarDiv.cloneNode(true)); + + document.getElementById("mainForm").innerHTML = mainFormPlaceholder(); + + 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; + let template = e.target.dataset.template; + clickLoadFileDiv(fileName, template); + } + }); +} + +function loadFileDiv(fileName, template) { + activeState.fileName = fileName; + activeState.loadedTemplate = template; + + storeData("userInputForce", retrieveData(fileName, template)); + + loadTemplate(template, false, true); +} + +function loadFileDivCallBack() { + let tF = JSON.parse(retrieveData("templateFiles")); + document.getElementById("sidebar").appendChild(loadFileSidebar(tF)); + + let lT = activeState.loadedTemplate; + let fN = activeState.fileName; + let storageName = fN + "-" + lT; + + let fileDisplay = document.createElement("DIV"); + fileDisplay.classList.add( + "w3-row-padding", + "w3-padding-24", + "w3-container", + "w3-flat-clouds" + ); + fileDisplay.id = "fileDisplayWrapper"; + + //start building submitContainer with edit copy and delete + let editButton = document.createElement("input"); + editButton.setAttribute("type", "submit"); + editButton.setAttribute("value", "Edit"); + editButton.classList.add("w3-button"); + editButton.classList.add("w3-grey"); + document.getElementById("submitContainer").appendChild(editButton); + + document + .getElementById("submitContainer") + .appendChild(document.createTextNode(" ")); + + let copyButton = document.createElement("input"); + copyButton.setAttribute("type", "submit"); + copyButton.setAttribute("value", "Copy"); + copyButton.classList.add("w3-button"); + copyButton.classList.add("w3-grey"); + document.getElementById("submitContainer").appendChild(copyButton); + + document + .getElementById("submitContainer") + .appendChild(document.createTextNode(" ")); + + let deleteButton = document.createElement("input"); + deleteButton.setAttribute("type", "submit"); + deleteButton.setAttribute("value", "Delete"); + deleteButton.classList.add("w3-button"); + deleteButton.classList.add("w3-red"); + document.getElementById("submitContainer").appendChild(deleteButton); + + if (screen.width > 992) { + document.getElementById("siteTitle").innerHTML = lT.replace(/_/g, " "); + } else { + document.getElementById("siteTitle").innerHTML = "TG"; + } + + + let title = document.createElement("div"); + title.classList.add("w3-panel"); + let titleText = document.createElement("h2"); + titleText.innerText = fN.replace(/_/g, " "); + titleText.style.margin = "0px"; + title.appendChild(titleText); + fileDisplay.appendChild(title); + + let div = document.createElement("div"); + div.appendChild(parseFormOnSubmit(false, true)); + fileDisplay.appendChild(div); + document.getElementById("mainForm").appendChild(fileDisplay); + + //add events + formEvts(storageName); +} + +function clickLoadFileDiv(fileName, template) { + document.getElementById("mainForm").innerHTML = ""; + loadFileDiv(fileName, template); +} + +function clearFileData(storData) { + let fileName = storData.split("-")[0]; + + let tF = JSON.parse(retrieveData("templateFiles")); + let newArray = []; + for (let obj of tF) { + if (obj.fileName != fileName) { + newArray.push(obj); + } + } + storeData("templateFiles", JSON.stringify(newArray)); + + clearData(fileName); + clearData("userInput"); + + document.getElementById("mainForm").innerHTML = ""; + document.getElementById("output").innerHTML = ""; + document.getElementById("submitContainer").innerHTML = ""; + document.getElementById("sidebar").innerHTML = ""; + document.getElementById("mainForm").innerHTML = mainFormPlaceholder(); + document.getElementById("sidebar").appendChild(loadFileSidebar(newArray)); +} + +function loadFileSidebar(tF) { + let sidebarList = document.createElement("ul"); + sidebarList.classList.add("w3-ul"); + + for (let obj of tF) { + let sidebarListItem = document.createElement("li"); + sidebarListItem.classList.add( + "w3-bar-item", + "w3-padding-large", + "w3-button" + ); + sidebarListItem.style.borderBottom = "1px solid #ddd"; + sidebarListItem.id = "sb-" + obj.fileName.replace(/:/g, "_"); + sidebarListItem.innerHTML = + obj.fileName.replace(/_/g, " ") + " - " + obj.template.replace(/_/g, " "); + sidebarListItem.setAttribute("data-file", obj.fileName); + sidebarListItem.setAttribute("data-template", obj.template); + sidebarList.appendChild(sidebarListItem); + } + return sidebarList; +} + +function mainFormPlaceholder(msg = "Select a file") { + return "

" + msg + "












"; +} + +function copyFileToClipboard() { + const fileDisplay = document.getElementById("fileDisplay"); + if (fileDisplay != null) { + copyToClipBoard(fileDisplay.innerHTML); + } else { + console.log("error file not found"); + } + +} + +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 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": + loadSpecificTemplate(storageName); + break; + case "Copy": + copyFileToClipboard(); + e.target.className = e.target.className.replace(" w3-grey", " w3-flat-carrot"); + e.target.style.pointerEvents = "none"; + const timeoutCopy = setTimeout(() => { + e.target.className = e.target.className.replace(" w3-flat-carrot"," w3-grey"); + e.target.style.pointerEvents = "auto"; + }, 250); + break; + case "Delete": + let previousFile = getPreviousFile(storageName); + clearFileData(storageName); + document.getElementById("mainForm").innerHTML = ""; + if (previousFile) { + loadFileDiv(previousFile.fileName, previousFile.template); + } else { + document.getElementById("mainForm").innerHTML = mainFormPlaceholder("No file yet"); + } + + break; + default: + e.preventDefault; + } + } + }); +} + +function loadSpecificTemplate(storageName) { + storeData( + "userInputForce", + retrieveData(storageName.split("-")[0], storageName.split("-")[1]) + ); + loadTemplate(storageName.split("-")[1]); +} + +function getPreviousFile(storageName) { + + let orgFileName = storageName.split("-")[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]; + break; + } + i++; + } + + return (previousFile != undefined) ? previousFile : false; +} + +export { buildFile, loadFileDivCallBack }; diff --git a/js/9.7/form.js b/js/9.7/form.js new file mode 100644 index 0000000..6c921b6 --- /dev/null +++ b/js/9.7/form.js @@ -0,0 +1,289 @@ + +import { storeData, createStorageObj } from "./storage.js"; +import parseInput from "./parseTemplate.js"; +import transformTemplateObject from "./buildForm.js"; +import { showSidebar, handleOnBlur } from "./evts.js"; +import parseFormOnSubmit, { parseTextMarkups } from "./parseForm.js"; + +function buildForm(templateInput, loadOnly = false) { + var wordArray = []; + + //display set Form button + document.getElementById("setFormButton").style.display = "block"; + + //check for presets in "-form.txt" file; indicated by !JSON_placeholder + if (templateInput.indexOf("!JSON_placeholder:") !== -1) { + let jsonPlaceholder = templateInput.split("!JSON_placeholder:")[1]; + templateInput = templateInput.split("!JSON_placeholder:")[0]; + storeData("templatePreset", jsonPlaceholder); + } + //start building wordArray by splitting input by line win/unix and define eol char for recreating templateInput + let eol; + if (templateInput.indexOf("\r\n") !== -1) { + eol = false; + var wordArrayByLine = templateInput.split("\r\n"); + } else { + eol = true; + var wordArrayByLine = templateInput.split("\n"); + } + //finish building wordArray by Looping through lines and spliting it into one array of words + //also create temporary templateInput to exclude comments + let templateInputArr = []; + for (let wordArrayByLineLine of wordArrayByLine) { + //ignore "#" comment lines + if (wordArrayByLineLine.substring(0, 1) == "#") { + continue; + } + + //add words ob lines to wordArray + wordArray = wordArray.concat(wordArrayByLineLine.split(" ")); + //add line to temp templatearray + templateInputArr.push(wordArrayByLineLine); + } + + //create templateInput without comments + templateInput = templateInputArr.join(eol ? "\n" : "\r\n"); + + //parse text markups like !l !n in templateInput + templateInput = parseTextMarkups(templateInput); + + //set objects array for parseInput Function + var objects = []; + //loop through words, parse it individually and add it to objects array + + + for (let i = 0; i < wordArray.length; i++) { + parseInput(wordArray, objects, i); + //console.log(wordArray[i]); + } + + //set individual positionens of objects in string and add it to objects + setStringPos(objects, templateInput); + + //save objects array and template file string for web.js in session storage + window.sessionStorage.setItem("templateObjects", JSON.stringify(objects)); + window.sessionStorage.setItem("fullString", templateInput); + + //sort objects array by words prio + objects = prioritizeArray(objects); + + //remove non display objects and safe it to session storage + let objectsPurified = purifyObjects(objects); + window.sessionStorage.setItem( + "templateObjectsPurified", + JSON.stringify(objectsPurified) + ); + + //reset page and event listeners + let mainFormDiv = document.getElementById("mainForm"); + let outputDiv = document.getElementById("output"); + let submitContainerDiv = document.getElementById("submitContainer"); + let sidebarDiv = document.getElementById("sidebar"); + //sidebarDiv.replaceWith(sidebarDiv.cloneNode(true)); + + mainFormDiv.innerHTML = ""; + mainFormDiv.replaceWith(mainFormDiv.cloneNode(true)); + outputDiv.innerHTML = ""; + outputDiv.replaceWith(outputDiv.cloneNode(true)); + submitContainerDiv.innerHTML = ""; + submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true)); + sidebarDiv.innerHTML = ""; + + //finally build html code for Form and siddebar and add it to dom if needed + if (loadOnly) {return}; + + transformTemplateObject(objectsPurified); + //add events + formEvts(); +} + +function prioritizeArray(objects) { + let prioArray = []; + let objects_sorted = []; + + for (let valPreSorted of objects) { + prioArray.push(valPreSorted.prio); + } + prioArray.sort(function (a, b) { + return a - b; + }); + //console.log(prioArray); + for (let valSorted of prioArray) { + for (let obj of objects) { + if (valSorted === obj.prio) { + objects_sorted.push(obj); + if (obj.prio !== 0) { + break; + } + } + } + } + return objects_sorted; +} + +function purifyObjects(objects) { + let objectsPurified = []; + let objectsPrePurified = []; + for (let objPrePurified of objects) { + if (!objectsPrePurified.includes(objPrePurified.word)) { + objectsPurified.push(objPrePurified); + } + objectsPrePurified.push(objPrePurified.word); + } + return objectsPurified; +} + +function setStringPos(objects, fullStringMaster) { + let stringCursor = 0; + let startPos = 0; + let endPos = 0; + let fullString = ""; + for (let obj of objects) { + fullString = fullStringMaster.substring(stringCursor); + if (fullString.indexOf("%" + obj.word) !== -1) { + startPos = 0; + endPos = 0; + startPos = fullString.indexOf("%" + obj.word) + stringCursor; + let objPrioLength = 1; + if (obj.prio > 9) { + objPrioLength = 2; + } + if (obj.prio == 0) { + objPrioLength = 0; + } + + switch (obj.type) { + case "simpleInput": + endPos = startPos + 2 + obj.word.length + objPrioLength; + break; + case "genderSpecific": + let gSC = 0; + if (typeof obj.m !== "undefined") { + gSC = gSC + obj.m.length + 3; + } + if (typeof obj.w !== "undefined") { + gSC = gSC + obj.w.length + 3; + } + if (typeof obj.d !== "undefined") { + gSC = gSC + obj.d.length + 3; + } + endPos = startPos + 2 + gSC + objPrioLength + obj.word.length + 1; + break; + case "list": + let gSC1 = 0; + for ( + let objListItem = 0; + objListItem < obj.listCount + 1; + objListItem++ + ) { + if (typeof obj[objListItem] !== "undefined") { + gSC1 = gSC1 + obj[objListItem].length + 3; + } + } + endPos = startPos + 2 + gSC1 + objPrioLength + obj.word.length + 1; + break; + case "conList": + let gSC2 = 0; + for ( + let objListItem = 0; + objListItem < obj.listCount + 1; + objListItem++ + ) { + if (typeof obj[objListItem] !== "undefined") { + gSC2 = gSC2 + obj[objListItem].length + obj["clType-"+obj[objListItem]].length + 4; + if (obj["clType-"+obj[objListItem]] == "cl-simpleInput") { + gSC2 = gSC2 - obj["clType-"+obj[objListItem]].length; + } + } + } + endPos = startPos + 2 + gSC2 + objPrioLength + obj.word.length + 1; + break; + default: + endPos = + startPos + + 2 + + obj.word.length + + 1 + + obj.type.length + + objPrioLength; + break; + } + obj.spos = startPos; + obj.epos = endPos; + stringCursor = endPos; + } + } +} + +function formEvts() { + //add event for main copy button + document.getElementById("submitContainer").addEventListener("click", (e) => { + if (e.target && e.target.tagName === "INPUT") { + switch (e.target.value) { + case "Copy": + createStorageObj(); + parseFormOnSubmit(); + e.target.className = e.target.className.replace(" w3-grey", " w3-flat-carrot"); + e.target.style.pointerEvents = "none"; + const timeoutCopy = setTimeout(() => { + e.target.className = e.target.className.replace(" w3-flat-carrot"," w3-grey"); + e.target.style.pointerEvents = "auto"; + }, 250); + break; + case "Save": + createStorageObj(); + e.target.className = e.target.className.replace(" w3-grey", " w3-flat-nephritis"); + 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); + break; + default: + e.preventDefault; + } + } + }); + + //add sidebar events + document.getElementById("sidebar").addEventListener("click", (e) => { + if (e.target) { + if (e.target.id == "sb-submit") { + if (screen.width < 993) { + showSidebar(); + } + parseFormOnSubmit(); + focusOnField("output"); + } + if (e.target.id == "sb-item") { + setTimeout(() => { + focusOnField(e.target.dataset.item); + }, 100); + } + } + }); + + //add handle on blur event listener to each form object + let mainForm = document.getElementById("mainFormObj"); + for (let formElement of mainForm.children) { + let id = formElement.firstChild.lastChild.id; + document.getElementById(id).addEventListener("blur", (e) => { + e.preventDefault; + handleOnBlur(e.target); + }); + } +} + +function focusOnField(id) { + let targetElement = document.getElementById(id); + if (targetElement == null) return; + + document.activeElement.blur(); + targetElement.focus(); + setTimeout(function () { + let offset = targetElement.offsetTop - 100; + window.scrollTo(0, offset); + }, 100); +} + +export default buildForm; diff --git a/js/9.7/identify.js b/js/9.7/identify.js new file mode 100644 index 0000000..55d4687 --- /dev/null +++ b/js/9.7/identify.js @@ -0,0 +1,247 @@ +const getBrowserFingerprint = ({ hardwareOnly = false, enableWebgl = false, debug = false } = {}) => { + const devicePixelRatio = +parseInt(window.devicePixelRatio); + + const { + appName, + appCodeName, + appVersion, + cookieEnabled, + deviceMemory, + doNotTrack, + hardwareConcurrency, + language, + languages, + maxTouchPoints, + platform, + product, + productSub, + userAgent, + vendor, + vendorSub, + } = window.navigator; + + const { width, height, colorDepth, pixelDepth } = window.screen; + const timezoneOffset = new Date().getTimezoneOffset(); + const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; + const touchSupport = 'ontouchstart' in window; + + const canvas = getCanvasID(debug); + 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 data = hardwareOnly + ? JSON.stringify({ + canvas, + colorDepth, + deviceMemory, + devicePixelRatio, + hardwareConcurrency, + height, + maxTouchPoints, + pixelDepth, + platform, + touchSupport, + webgl, + webglInfo, + width, + }) + : JSON.stringify({ + appCodeName, + appName, + appVersion, + canvas, + colorDepth, + cookieEnabled, + deviceMemory, + devicePixelRatio, + doNotTrack, + hardwareConcurrency, + height, + language, + languages, + maxTouchPoints, + pixelDepth, + platform, + product, + productSub, + timezone, + timezoneOffset, + touchSupport, + userAgent, + vendor, + vendorSub, + webgl, + webglInfo, + width, + }); + + const datastring = JSON.stringify(data, null, 4); + + if (debug) console.log('fingerprint data', datastring); + + const result = murmurhash3_32_gc(datastring); + return result; +}; + +export const getCanvasID = (debug) => { + try { + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); + const text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~1!2@3#4$5%6^7&8*9(0)-_=+[{]}|;:',<.>/?"; + ctx.textBaseline = 'top'; + ctx.font = "14px 'Arial'"; + ctx.textBaseline = 'alphabetic'; + ctx.fillStyle = '#f60'; + ctx.fillRect(125, 1, 62, 20); + ctx.fillStyle = '#069'; + ctx.fillText(text, 2, 15); + ctx.fillStyle = 'rgba(102, 204, 0, 0.7)'; + ctx.fillText(text, 4, 17); + + const result = canvas.toDataURL(); + + if (debug) { + document.body.appendChild(canvas); + } else { + ctx.clearRect(0, 0, canvas.width, canvas.height); + } + + return murmurhash3_32_gc(result); + } catch { + return null; + } +}; + +export const getWebglID = (debug) => { + try { + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('webgl'); + canvas.width = 256; + canvas.height = 128; + + const f = + '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 h = ctx.createBuffer(); + + ctx.bindBuffer(ctx.ARRAY_BUFFER, h); + + 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); + + const j = ctx.createProgram(); + const k = ctx.createShader(ctx.VERTEX_SHADER); + + ctx.shaderSource(k, f); + ctx.compileShader(k); + + const l = ctx.createShader(ctx.FRAGMENT_SHADER); + + ctx.shaderSource(l, g); + ctx.compileShader(l); + ctx.attachShader(j, k); + ctx.attachShader(j, l); + ctx.linkProgram(j); + ctx.useProgram(j); + + j.vertexPosAttrib = ctx.getAttribLocation(j, 'attrVertex'); + j.offsetUniform = ctx.getUniformLocation(j, 'uniformOffset'); + + ctx.enableVertexAttribArray(j.vertexPosArray); + ctx.vertexAttribPointer(j.vertexPosAttrib, h.itemSize, ctx.FLOAT, !1, 0, 0); + ctx.uniform2f(j.offsetUniform, 1, 1); + ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, h.numItems); + + const n = new Uint8Array(canvas.width * canvas.height * 4); + ctx.readPixels(0, 0, canvas.width, canvas.height, ctx.RGBA, ctx.UNSIGNED_BYTE, n); + + const result = JSON.stringify(n).replace(/,?"[0-9]+":/g, ''); + + if (debug) { + document.body.appendChild(canvas); + } else { + ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT | ctx.STENCIL_BUFFER_BIT); + } + + return murmurhash3_32_gc(result); + } catch { + return null; + } +}; + +export const getWebglInfo = () => { + try { + const ctx = document.createElement('canvas').getContext('webgl'); + + const result = { + VERSION: ctx.getParameter(ctx.VERSION), + SHADING_LANGUAGE_VERSION: ctx.getParameter(ctx.SHADING_LANGUAGE_VERSION), + VENDOR: ctx.getParameter(ctx.VENDOR), + SUPORTED_EXTENSIONS: ctx.getSupportedExtensions(), + }; + + return result; + } catch { + return null; + } +}; + +export const murmurhash3_32_gc = (key) => { + const remainder = key.length & 3; // key.length % 4 + const bytes = key.length - remainder; + const c1 = 0xcc9e2d51; + const c2 = 0x1b873593; + + let h1, h1b, k1; + + 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); + ++i; + + k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1b = ((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) & 0xffffffff; + h1 = (h1b & 0xffff) + 0x6b64 + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16); + } + + const i = bytes - 1; + + k1 = 0; + + switch (remainder) { + case 3: { + k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; + break; + } + case 2: { + k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; + break; + } + case 1: { + k1 ^= key.charCodeAt(i) & 0xff; + break; + } + } + + k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; + h1 ^= k1; + + h1 ^= key.length; + + h1 ^= h1 >>> 16; + h1 = ((h1 & 0xffff) * 0x85ebca6b + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = ((h1 & 0xffff) * 0xc2b2ae35 + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; +}; + +export default getBrowserFingerprint; diff --git a/js/9.7/init.js b/js/9.7/init.js new file mode 100644 index 0000000..a4d8aa1 --- /dev/null +++ b/js/9.7/init.js @@ -0,0 +1,151 @@ +import { hideMenus, showMenu, showSidebar, showTextBlocks, clickSetForm, clickImportFiles } from "./evts.js"; +import { buildFile } from "./files.js"; +import setPassword, { passwordHash } from "./scripts.js"; +import { getUsrId } from "./scripts.js"; +import parseFormOnSubmit from "./parseForm.js"; +import { createStorageObj } from "./storage.js"; +import XORCipher from "./xorc.js"; +import sha256 from "./sha256.min.js"; +import { loadNavBar, initTextBlocks } from "./web.js"; + + +window.activeState = { + userId: getUsrId(), + activePage: "landing", + loadedTemplate: "", + fileName: "", + lastElement: "", + serverFilesTs: "", + templates: [], + templateFieldTypes: [ + "simpleInput", + "longText", + "hiddenField", + "current_time", + "current_date", + "markup", + ], + markups: [ + "title", + "link", + "italic", + "green_highlighted", + "highlighted", + ] +}; + + +function init() { + + //check if user is logged in + let verfiedStatus = window.sessionStorage.getItem(sha256("verified")); + if (verfiedStatus != null) { + //user logged in + + //write verifiedStatus content into passwordHash for decode check later + passwordHash.set(XORCipher.decode(sha256("passwordHash"), verfiedStatus)); + document.getElementById("login").style.display = "none"; + + } else { + document.getElementById("login").style.display = "block"; + } + + //load NavigationBar with templates according to server + loadNavBar(); + + //init Textblocks field with entries according to server + initTextBlocks(); + + //add event listeners to document and window + eventListeners(); + + //print current version to footer + printVersion(); + + //adjust title for mobile use + if (screen.width < 993) { + document.getElementById("siteTitle").innerHTML = "TG"; + } + + + +} + +function eventListeners() { + + //add hideMenu to Body + document + .getElementsByClassName("w3-main")[0] + .addEventListener("click", hideMenus); + +//add set Password to loginForm +document + .getElementById("submitPassword") + .addEventListener("click", setPassword); +//add toggle Navigation Menu +document + .getElementById("toggleNavigationMenu") + .addEventListener("click", showMenu); +//add loadTemplateBtn event showMenu +document + .getElementById("loadTemplateBtn") + .addEventListener("click", showMenu); +//add toggle sideBar Menu +document + .getElementById("toggleSidebarMenu") + .addEventListener("click", showSidebar); +//add toggle files Menu and sidebar button +document + .getElementById("toggleFilesMenuSB") + .addEventListener("click", buildFile); +document + .getElementById("toggleFilesMenu") + .addEventListener("click", buildFile); +//add load template sidebar entry +document + .getElementById("loadTemplateBtn") + .addEventListener("click", showMenu); +//add toggle textBLocks Menu +document + .getElementById("toggleTestBlocksMenu") + .addEventListener("click", showTextBlocks); + +//add setFormBtn for use in form +document + .getElementById("setFormBtn") + .addEventListener("click", (e) => clickSetForm(e)); + +//add saveFiles to server listener on launch page +document + .getElementById("importFilesSB") + .addEventListener("click", () => clickImportFiles()); + +//add key listener for ctrl s in form mode +window.addEventListener("keydown", (e) => { + + if (e.ctrlKey && e.key == "s") { + if (activeState.activePage == "form"); + createStorageObj(); + parseFormOnSubmit(); + e.preventDefault(); + } +}) +} + +function printVersion() { + const scripts = document.getElementsByTagName("script"); + const versionSpan = document.getElementById("currentVersion").lastChild; + + for (var i=0;i init()); + + + diff --git a/js/9.7/parseForm.js b/js/9.7/parseForm.js new file mode 100644 index 0000000..aaacf94 --- /dev/null +++ b/js/9.7/parseForm.js @@ -0,0 +1,366 @@ +import { storeData, clearData, retrieveData } from "./storage.js"; + +function parseFormOnSubmit(returnJSON = false, parseOnly = false) { + //event.preventDefault; + + let dataArray = []; + + if (parseOnly) { + let lT = activeState.loadedTemplate; + dataArray = retrieveData("userInputForce", lT); + if (dataArray != "") { + try { + dataArray = JSON.parse(dataArray); + } catch (e) { + alert("Decryption failed; are you authenticated?"); + window.location.reload(); + return; + } + } + if (dataArray == null) { + let wrapper = document.createElement("div"); + wrapper.innerHTML = mainFormPlaceholder(); + let div = wrapper.firstChild; + return div; + } + + if (dataArray.length <= 0) { + let wrapper = document.createElement("div"); + wrapper.innerHTML = mainFormPlaceholder(); + let div = wrapper.firstChild; + return div; + } + + } else { + let x = document.getElementById("mainFormObj"); + + if (x != null) { + for (let i = 0; i < x.length; i++) { + dataArray.push({ + 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"); + let userFileName = userFileNameField.value; + let userFileNamePH = userFileNameField.getAttribute("placeholder"); + if (userFileName.length != 0) { + activeState.fileName = userFileName; + } else if (userFileNamePH != null) { + activeState.fileName = userFileNamePH; + } + } + + + //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"); + + let b = ""; + + if (objects == null) { + return; + } + + + //iterate through templateObjects and look for according formdata + for (let obj of objects) { + 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; + if (data.name.split("-")[0] == "clM") { + if (data.name.substring(4) === obj.word.replace(/ /g, "_") ) { + conListFlag = true; + data.name = data.name.substring(4); + if (data.value == "!none") { + obj.result = ""; + continue; + } + if (data.value == "!selected") { + data.value = obj[0]; + obj.result = ""; + } + } + } + if (obj.word.replace(/ /g, "_") === data.name) { + let value = parseDataForResult(obj, data.value); + obj.result = value; + + } + if (conListFlag) { + if (obj.type == "conList") { + + //check for button if only one item exists and search conlist item + if (obj.listCount == 0) { + for (let d of dataArray) { + 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)) { + if (d.hasOwnProperty("placeholder")) d.value = d.placeholder + "\n" + d.value; + let value = parseDataForResult(obj, d.value); + obj.result = obj.result + "\n" + value; + } + } + } + } else { + //loop through dataArray and look for coresponding conlist items + for (let i = 0; i <= obj.listCount; i++) { + for (let d of dataArray) { + if (d.name.split(":!")[1] !== undefined) d.placeholder = "!"+d.name.split(":!")[1]; + d.name = d.name.split(":!")[0]; + if ("cl-"+obj[i].replace(/ /g, "_") == d.name && d.value != "") { + if (data.value.replace(/ /g, "_") == d.name.substring(3)) { + if (d.hasOwnProperty("placeholder")) d.value = d.placeholder + "\n" + d.value; + let value = parseDataForResult(obj, d.value); + obj.result = obj.result + "\n" + value; + } + } + } + } + } + } + } + } + } + + //console.log(this, dataArray); + + b = fullString.substring(0, objects[0].spos); + for (let i = 0; i < objects.length; i++) { + let j = i + 1; + if (objects[j] === undefined) { + b += + objects[i].result + + fullString.substring(objects[i].epos, fullString.length); + } else { + b += + objects[i].result + + fullString.substring(objects[i].epos, objects[j].spos); + } + } + + let bHtml = b.replace(/(?:\r\n|\r|\n)/g, "
"); + bHtml = bHtml.replace(/!l /g, " • "); + bHtml = bHtml.replace(/!ls /g, " ○ "); + bHtml = bHtml.replace(/ /g, " "); + + bHtml = + "
" + + bHtml + + "
"; + + let div = document.createElement("div"); + div.classList.add("w3-code", "notranslate", "w3-border-white"); + div.id = "fileDisplay"; + div.innerHTML = bHtml; + + if (parseOnly) { + return div; + } + + let p = document.createElement("p"); + p.innerHTML = "Copied to Clipboard:"; + document.getElementById("output").innerHTML = ""; + document.getElementById("output").appendChild(p); + document.getElementById("output").appendChild(div); + + storeData("userInput", JSON.stringify(dataArray)); + clearData("userInput"); + + if (returnJSON) { + return dataArray; + } else { + copyToClipBoard(bHtml); + } + } + + function parseDataForResult(obj, value) { + //handle placeholders like title, link, italic + if (obj.hasOwnProperty("placeholder") && value !== "") { + //console.log(obj.placeholder); + //check for markups + if (activeState.markups.includes(obj.placeholder)) { + value = parseMarkupmarkups(value, obj.placeholder); + } else { + value = obj.placeholder + "\n" + value; + } + } + + + //Plugin TextBlock Insertion according to file _textblocks.txt + value = parseTextBlocks(value); + + + //handle placeholders like !l or !n and set it to final interpreted string for object + value = parseTextMarkups(value); + + return value; + } + + export function parseTextMarkups(data) { + let dataArray = data.split("\n"); + let listFlag = false; + let listSubFlag = false; + let boldFlag = false; + let listNumberFlag = false; + let listNumberFlagNum = 1; + for (let i = 0; i < dataArray.length; i++) { + if (dataArray[i] == "") continue; + switch (dataArray[i]) { + case "!l": + listFlag = true; + dataArray.splice(i, 1); + i = i - 1; + break; + case "!ls": + listSubFlag = true; + dataArray.splice(i, 1); + i = i - 1; + break; + case "!n": + listNumberFlag = true; + dataArray.splice(i, 1); + i = i - 1; + break; + case "!b": + boldFlag = true; + dataArray.splice(i, 1); + i = i - 1; + break; + case "!e": + listFlag = false; + listNumberFlag = false; + dataArray.splice(i, 1); + i = i - 1; + break; + case "!es": + listSubFlag = false; + dataArray.splice(i, 1); + i = i - 1; + break; + default: + if (boldFlag) { + dataArray[i] = "" + dataArray[i] + ""; + boldFlag = false; + continue; + } + if (listNumberFlag) { + dataArray[i] = " " + listNumberFlagNum + ". " + dataArray[i]; + listNumberFlagNum++; + continue; + } + if (listSubFlag) { + dataArray[i] = " ○ " + dataArray[i]; + continue; + } + if (listFlag) { + dataArray[i] = " • " + dataArray[i]; + continue; + } + } + } + return dataArray.join("\n"); + } + + function parseMarkupmarkups(value, markup) { + switch (markup) { + case "title": + return "" + value + ""; + break; + case "italic": + return "" + value + ""; + break; + } + } + + function parseTextBlocks(data) { + let textBlocks = loadTextBlocks(); + let textBlockIds = Object.keys(textBlocks); + for (let i = 0; i < textBlockIds.length; i++) { + let id = textBlockIds[i]; + if (data.indexOf("!" + id) !== -1) { + //console.log("found: "+id); + let sPos = data.indexOf("!" + id); + let ePos = sPos + id.length + 1; + data = + data.substring(0, sPos) + + textBlocks[id] + + data.substring(ePos, data.length); + } + } + return data; + } + + +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 "

Select a file












"; + } + + export default parseFormOnSubmit; \ No newline at end of file diff --git a/js/9.7/parseTemplate.js b/js/9.7/parseTemplate.js new file mode 100644 index 0000000..f639c2a --- /dev/null +++ b/js/9.7/parseTemplate.js @@ -0,0 +1,374 @@ +function parseInput(wordArray, objects, i) { + let word = wordArray[i]; + + if (word.substring(0, 1) == "%") { + //check if regular use of % in text 20% an ignoreCase + if (word.substring(0, 2) !== "% ") { + //found simple input %word / excluding %m: + if (word.substring(2, 3) !== ":") { + //init Word Object + var wordObj = {}; + + let w = word.substring(1); + //for loop to escape spaces in simple input + for (let j = i + 1; j < wordArray.length; j++) { + w = w + " " + wordArray[j]; + //invoke look for gender specific template + i = findGenderSpecificInput(wordArray, wordObj, j); + //invoke look for list template + 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 (w.indexOf("%") !== -1) { + //found % sign + if (w.indexOf("%") !== w.length - 1) { + //% is not last char of string + word = "%" + w; + } else { + //% is last + //no prio has been set + word = w.slice(0, -1); + } + break; + } + } + + if (word.indexOf("\n") !== -1) { + if (word.substring(word.indexOf("\n"), 2).indexOf("%") !== -1) { + //alert("attention newlineChar in: "+ word.substring(word.indexOf("\n"),2)); + } + } + //parse priority + if (word.substring(1).indexOf("%") === -1) { + //object if no prio was set + wordObj.word = word; + wordObj.arrayPos = objects.length; + wordObj.prio = 0; + } else { + //handle edgecase if punctuation mark is directly after prio + let postMarker = word.substring(1).indexOf("%") + 2; + let postMarkerEnd = word.length; + let isPriority = true; + let i = 0; + //console.log(word + " * " + word.substring(postMarkerEnd-2, postMarkerEnd) + " - " + postMarker + ":" + postMarkerEnd + " - " + word.length); + while ( + !isCharNumber(word.substring(postMarkerEnd - 1, postMarkerEnd)) + ) { + postMarkerEnd = postMarkerEnd - 1; + //if no priority has been set; set flag + //console.log(word.substring(postMarkerEnd-1, postMarkerEnd)); + + if (postMarkerEnd < 1) { + isPriority = false; + break; + } + + i++; + } + + if (isPriority) { + //console.log(word + " prio: "+isPriority); + //object if prio has been defined + wordObj.word = word.substring(1, postMarker - 1); + wordObj.arrayPos = objects.length; + wordObj.prio = parseInt( + word.substring(postMarker, postMarkerEnd), + 10 + ); + if (isNaN(wordObj.prio)) { + alert( + "error in template: %" + + wordObj.word + + "% there must always a space after the priority number" + ); + wordObj.prio = 0; + } + } else { + //object if no prio has been defined + wordObj.word = word.substring(1, postMarker - 1); + wordObj.arrayPos = objects.length; + wordObj.prio = 0; + } + } + //check if genderSpecific or list has been found and if so reformat word + //console.log(wordObj); + switch (wordObj.type) { + case "genderSpecific": + if (word.substring(0, 1) === "%") { + wordObj.word = word.split("=")[0].substring(1); + } else { + wordObj.word = word.split("=")[0]; + } + break; + case "list": + if (word.substring(0, 1) === "%") { + wordObj.word = word.split("=")[0].substring(1); + } else { + wordObj.word = word.split("=")[0]; + } + break; + case "conList": + if (word.substring(0, 1) === "%") { + wordObj.word = word.split("=")[0].substring(1); + } else { + wordObj.word = word.split("=")[0]; + } + //check if format has been given or markup + for (let i = 0; i <= wordObj.listCount; i++) { + let params = wordObj[i].split(":"); + if (params[1] !== undefined) { + wordObj[i] = params[0]; + wordObj["clType-"+wordObj[i]] = (params[2] !== undefined) ? params[1]+":"+params[2]: params[1]; + } else { + wordObj["clType-"+wordObj[i]] = "cl-simpleInput"; + } + } + break; + default: + wordObj.type = "simpleInput"; + //check if customTemplate was used set type and format word + if (word.indexOf("=") !== -1) { + parseCustomTemplates(wordObj); + } + break; + } + + objects.push(wordObj); + } + } + } +} + +function findGenderSpecificInput(wordArray, wordObj, i) { + let word = wordArray[i]; + if (word.indexOf("=m:") !== -1) { + wordObj.type = "genderSpecific"; + let mw = word.substring(word.indexOf("=m:") + 3); + for (let j = i + 1; j < wordArray.length; j++) { + mw = mw + " " + wordArray[j]; + i = j; + if (mw.indexOf(";") !== -1) { + wordObj.m = mw.slice(0, mw.indexOf(";")); + //adding length word + 3 = m: ; + i = parseGenderTemplate(wordArray, wordObj, i); + break; + } + } + } + + if (word.indexOf("=w:") !== -1) { + let ww = word.substring(word.indexOf("=w:") + 3); + for (let j = i + 1; j < wordArray.length; j++) { + ww = ww + " " + wordArray[j]; + i = j; + if (ww.indexOf(";") !== -1) { + wordObj.w = ww.slice(0, ww.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++) { + dw = dw + " " + wordArray[j]; + i = j; + if (dw.indexOf(";") !== -1) { + wordObj.d = dw.slice(0, dw.indexOf(";")); + i = parseGenderTemplate(wordArray, wordObj, i); + break; + } + } + } + return i; +} + +function parseGenderTemplate(wordArray, wordObj, i) { + let word = wordArray[i]; + if (word.indexOf(";m:") !== -1) { + let mw = word.substring(word.indexOf(";m:") + 3); + for (let j = i + 1; j < wordArray.length; j++) { + mw = mw + " " + wordArray[j]; + i = j; + if (mw.indexOf(";") !== -1) { + wordObj.m = mw.slice(0, mw.indexOf(";")); + i = parseGenderTemplate(wordArray, wordObj, i); + break; + } + } + } + if (word.indexOf(";w:") !== -1) { + let ww = word.substring(word.indexOf(";w:") + 3); + for (let j = i + 1; j < wordArray.length; j++) { + ww = ww + " " + wordArray[j]; + i = j; + if (ww.indexOf(";") !== -1) { + wordObj.w = ww.slice(0, ww.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++) { + dw = dw + " " + wordArray[j]; + i = j; + if (dw.indexOf(";") !== -1) { + wordObj.d = dw.slice(0, dw.indexOf(";")); + i = parseGenderTemplate(wordArray, wordObj, i); + break; + } + } + } + return i; +} + +function findListInput(wordArray, wordObj, i) { + let word = wordArray[i]; + if (word.indexOf("=l:") !== -1) { + wordObj.type = "list"; + wordObj.listCount = 0; + let lw = word.substring(word.indexOf("=l:") + 3); + //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: ; + i = parseListTemplate(wordArray, wordObj, i); + return i; + } + for (let j = i + 1; j < wordArray.length; j++) { + lw = lw + " " + wordArray[j]; + i = j; + if (lw.indexOf(";") !== -1) { + wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); + //adding length word + 3 = m: ; + i = parseListTemplate(wordArray, wordObj, i); + break; + } + } + } + return i; +} + +function parseListTemplate(wordArray, wordObj, i) { + let word = wordArray[i]; + if (word.indexOf(";l:") !== -1) { + let lw = word.substring(word.indexOf(";l:") + 3); + //escape if there is no space in listitem + if (lw.indexOf(";") !== -1) { + wordObj.listCount++; + 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) + .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++; + } + //console.log(wordArray[i].substring(1)); + i = parseListTemplate(wordArray, wordObj, i); + return i; + } + for (let j = i + 1; j < wordArray.length; j++) { + lw = lw + " " + wordArray[j]; + i = j; + if (lw.indexOf(";") !== -1) { + wordObj.listCount++; + wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); + i = parseListTemplate(wordArray, wordObj, i); + break; + } + } + } + return i; +} + +function findConnectedListInput(wordArray, wordObj, i) { + let word = wordArray[i]; + if (word.indexOf("=h:") !== -1) { + wordObj.type = "conList"; + wordObj.listCount = 0; + let lw = word.substring(word.indexOf("=h:") + 3); + //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: ; + i = parseConnectedListTemplate(wordArray, wordObj, i); + return i; + } + for (let j = i + 1; j < wordArray.length; j++) { + lw = lw + " " + wordArray[j]; + i = j; + if (lw.indexOf(";") !== -1) { + wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); + //adding length word + 3 = m: ; + i = parseConnectedListTemplate(wordArray, wordObj, i); + break; + } + } + } + return i; +} + + +function parseConnectedListTemplate(wordArray, wordObj, i) { + let word = wordArray[i]; + if (word.indexOf(";h:") !== -1) { + let lw = word.substring(word.indexOf(";h:") + 3); + //escape if there is no space in listitem + if (lw.indexOf(";") !== -1) { + wordObj.listCount++; + 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) + .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++; + } + //console.log(wordArray[i].substring(1)); + i = parseConnectedListTemplate(wordArray, wordObj, i); + return i; + } + for (let j = i + 1; j < wordArray.length; j++) { + lw = lw + " " + wordArray[j]; + i = j; + if (lw.indexOf(";") !== -1) { + wordObj.listCount++; + wordObj[wordObj.listCount] = lw.slice(0, lw.indexOf(";")); + i = parseConnectedListTemplate(wordArray, wordObj, i); + break; + } + } + } + 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) { + wordObj.word = word.split("=")[0]; + wordObj.type = word.split("=")[1]; + + if (wordObj.type.indexOf(":") !== -1) { + 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; diff --git a/js/9.7/scripts.js b/js/9.7/scripts.js new file mode 100644 index 0000000..c5f2e52 --- /dev/null +++ b/js/9.7/scripts.js @@ -0,0 +1,96 @@ +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)); + } +} + +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; diff --git a/js/9.7/sha256.min.js b/js/9.7/sha256.min.js new file mode 100644 index 0000000..4aa510b --- /dev/null +++ b/js/9.7/sha256.min.js @@ -0,0 +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>8)return;j[d>>2]|=e<<(3-d)%4*8}for(j[j[h]]=k/g|0,j[j[h]]=k,e=0;ed;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; \ No newline at end of file diff --git a/js/9.7/storage.js b/js/9.7/storage.js new file mode 100644 index 0000000..5dbf6d4 --- /dev/null +++ b/js/9.7/storage.js @@ -0,0 +1,223 @@ +import XORCipher from "./xorc.js"; +import sha256 from "./sha256.min.js"; +import { getUsrId, passwordHash } from "./scripts.js"; + + +function createStorageObj() { + let x = document.getElementById("mainFormObj"); + let dataArray = []; + if (x == null) { + return; + } + for (let i = 0; i < x.length; i++) { + dataArray.push({ + value: x.elements[i].value, + name: x.elements[i].name, + }); + } + + //console.log(this, dataArray); + + let userFileNameField = document.getElementById("userFileName"); + let userFileName = userFileNameField.value; + let userFileNamePH = userFileNameField.getAttribute("placeholder"); + if (userFileName.length != 0) { + activeState.fileName = userFileName; + //clear old data as file switches to new filename + if (userFileNamePH.length != 0) { + clearData(userFileNamePH); + popFromTemplateFiles(userFileNamePH); + } + } else if (userFileNamePH.length != 0) { + activeState.fileName = userFileNamePH; + } + + storeData("userInput", JSON.stringify(dataArray)); + +} + +function storeData(name, data) { + //setCookie(name, btoa(data), 7); + if (name == "userInput") { + name = getFileName(); + } + if (name == "userInputForce") { + name = "userInput"; + } + let lT = activeState.loadedTemplate; + let key = sha256(name + "-" + lT); + if (name == "templateFiles") { + key = sha256(name + "-"); + } + window.localStorage.setItem(key, obfuscate(data)); +} + +function retrieveData(type, template = "none") { + if (type == "userInput") { + let tF = JSON.parse(retrieveData("templateFiles")); + if (tF == null) { + return ""; + } else { + type = tF[tF.length - 1].fileName; + } + } + if (type == "userInputForce") { + type = "userInput"; + } + let cdata; + if (template == "none") { + let lT = activeState.loadedTemplate; + let key = sha256(type + "-" + lT); + if (type == "templateFiles") { + key = sha256(type + "-"); + } + cdata = window.localStorage.getItem(key); + } else { + let key = sha256(type + "-" + template); + cdata = window.localStorage.getItem(key); + } + if (cdata != null) { + return obfuscate(cdata, false); + } else { + return "[]"; + } +} + +function clearData(type, template = "none") { + let lT; + let key; + if (template == "none") { + lT = activeState.loadedTemplate; + key = sha256(type + "-" + lT); + if (type == "templateFiles") { + key = sha256(type + "-"); + } + } else { + lT = template; + key = sha256(type + "-" + template); + } + window.localStorage.removeItem(key); +} + +function getFileName() { + let currentFileName = activeState.fileName; + if (currentFileName == "none" || currentFileName == "") { + let date = new Date(); + let current_hour = date.getHours(); + current_hour = current_hour <= 9 ? "0" + current_hour : current_hour; + let current_minute = date.getMinutes(); + current_minute = + current_minute <= 9 ? "0" + current_minute : current_minute; + let current_month = date.getMonth() + 1; + current_month = current_month <= 9 ? "0" + current_month : current_month; + 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; + currentFileName = current_time + "_" + current_date; + //console.log(currentFileName); + } + + let lT = activeState.loadedTemplate; + let tF = retrieveData("templateFiles"); + if (tF != "") { + try { + tF = JSON.parse(tF); + } catch (e) { + alert("Decryption failed; are you authenticated?"); + window.location.reload(); + return; + } + } + if (tF != null) { + for (let tFi of tF) { + if (tFi.fileName == currentFileName) {return currentFileName}; + } + tF.push({ fileName: currentFileName, template: lT }); + } else { + tF = [{ fileName: currentFileName, template: lT }]; + } + storeData("templateFiles", JSON.stringify(tF)); + activeState.fileName = currentFileName; + return currentFileName; +} + +function obfuscate(data, mode = true) { + if (mode) { + return XORCipher.encode(sha256(passwordHash), data); + } else { + return XORCipher.decode(sha256(passwordHash), data); + } +} + +function popFromTemplateFiles(fileName) { + let tF = JSON.parse(retrieveData("templateFiles")); + let newArray = []; + for (let obj of tF) { + if (obj.fileName != fileName) { + newArray.push(obj); + } + } + storeData("templateFiles", JSON.stringify(newArray)); +} + +function createBookShelf() { + let tF = JSON.parse(retrieveData("templateFiles")); + let bookShelf = {}; + let date = new Date(); + let current_hour = date.getHours(); + current_hour = current_hour <= 9 ? "0" + current_hour : current_hour; + let current_minute = date.getMinutes(); + current_minute = + current_minute <= 9 ? "0" + current_minute : current_minute; + let current_month = date.getMonth() + 1; + current_month = current_month <= 9 ? "0" + current_month : current_month; + 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 saveFileName = current_time + "_" + current_date; + + if (tF != null) { + bookShelf[0] = {name: "hash", data: getUsrId(), ts: saveFileName}; + let i = 1; + for (let tFi of tF) { + let data = retrieveData(tFi.fileName, tFi.template); + bookShelf[i] = {}; + bookShelf[i].name = tFi.fileName + "-" + tFi.template; + bookShelf[i].data = obfuscate(data); + i++; + } + } + return bookShelf; +} + +function importBookShelf() { + + localStorage.clear() + var xhttp = new XMLHttpRequest(); + xhttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + if (this.responseText == "none") { + console.log("no files saved on server"); + } else { + let respText = decodeURIComponent(this.responseText); + let mainArray = JSON.parse(respText); + let templateFilesArray = []; + for (let file of mainArray) { + if (file.name == "hash") continue; + window.localStorage.setItem(sha256(file.name), file.data); + templateFilesArray.push({ fileName: file.name.split("-")[0], template: file.name.split("-")[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(); +} + +export { createStorageObj, storeData, retrieveData, clearData, getFileName, createBookShelf, importBookShelf}; diff --git a/js/9.7/web.js b/js/9.7/web.js new file mode 100644 index 0000000..44da8f5 --- /dev/null +++ b/js/9.7/web.js @@ -0,0 +1,301 @@ +import buildForm from "./form.js"; +import { loadFileDivCallBack } from "./files.js"; +import { retrieveData, clearData, getFileName, importBookShelf } from "./storage.js"; +import { insertTextBlocks } from "./evts.js"; +import { createTemplate, createTemplateCallBack} from "./createTemplate.js"; +import { getUsrId } from "./scripts.js"; + +function loadTemplate(template, newFlag = false, loadOnly = false) { + document.getElementById("siteTitle").innerHTML = template.replace(/_/g, " "); + activeState.loadedTemplate = template; + + if (newFlag) { + activeState.fileName = "none"; + } else { + activeState.fileName = getFileName(); + } + + document.getElementById("navMob").className = document + .getElementById("navMob") + .className.replace(" w3-show", ""); + if (screen.width < 993) { + let sidebar = document.getElementById("sidebar"); + sidebar.style.display = "none"; + document.getElementById("siteTitle").innerHTML = "TG"; + } + var xhttp = new XMLHttpRequest(); + xhttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + let respText = decodeURIComponent(this.responseText); + if (loadOnly == "createTemplate") { + createTemplateCallBack(template, respText.split("!JSON_placeholder:")[0]); + return; + } + buildForm(respText, loadOnly); + if (loadOnly) { + loadFileDivCallBack(); + return; + } + + //retrieve previos userData / or preset data if newFile is called + let cdata; + if (newFlag) { + cdata = retrieveData("templatePreset", template); + } else { + cdata = retrieveData("userInputForce"); + } + if (cdata != "") { + let res = ""; + try { + res = JSON.parse(cdata); + } catch (e) { + console.log("error", cdata); + return; + } + retrieveForm(res); + } + + //select first object and focus on it + let obj = JSON.parse( + window.sessionStorage.getItem("templateObjectsPurified") + ); + let firstElement = document.getElementById(obj[0].word.replace(/ /g, "_")); + if (firstElement != null) firstElement.focus(); + + } + }; + xhttp.open("GET", "php/?template=" + template, true); + xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8'); + xhttp.send(); +} + +function loadNewTemplate(template) { + //set current page value in activeState object + activeState.activePage = "template"; + + let sidebarDiv = document.getElementById("sidebar"); + sidebarDiv.replaceWith(sidebarDiv.cloneNode(true)); + + clearData("userInput", template); + loadTemplate(template, true); +} + +function loadNavBar() { + var xhttp = new XMLHttpRequest(); + xhttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + let res = ""; + try { + res = JSON.parse(this.responseText); + } catch (e) { + console.log("error", this.responseText); + return; + } + + let divMob = document.getElementById("navMob"); + for (let x in res) { + let aMob = document.createElement("a"); + + aMob.setAttribute("href", "#"); + aMob.setAttribute("data-template", res[x][1]); + aMob.classList.add("w3-bar-item", "w3-button", "w3-padding-large"); + aMob.innerHTML = res[x][0]; + + divMob.appendChild(aMob); + + activeState.templates.push(res[x][1]); + } + let createEntry = document.createElement("a"); + createEntry.setAttribute("href", "#"); + createEntry.setAttribute("data-template", "createNew"); + createEntry.classList.add("w3-bar-item", "w3-button", "w3-padding-large"); + createEntry.innerHTML = "Manage templates"; + + divMob.appendChild(createEntry); + divMob.addEventListener("click", (e) => { + if (e.target && e.target.matches("a.w3-bar-item")) { + let template = e.target.dataset.template; + if (template == "createNew") { + createTemplate(); + return; + } + loadNewTemplate(template); + } + }); + } + }; + xhttp.open("GET", "php/?templates", true); + xhttp.send(); +} +function initTextBlocks() { + var xhttp = new XMLHttpRequest(); + xhttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + let res = ""; + try { + res = JSON.parse(this.responseText); + } catch (e) { + console.log("error", this.responseText) + return; + } + const textBlocksHolder = document.getElementById("textBlocks"); + const divReg = document.getElementById("navTb"); + for (let x in res) { + if (res[x][1].length < 1) continue; + + let aReg = document.createElement("a"); + aReg.setAttribute("href", "#"); + aReg.classList.add("w3-bar-item", "w3-hide-small", "w3-padding-small"); + let textBlockText = res[x][1]; + if (res[x][1].length > 80) { + textBlockText = res[x][1].substr(0, 80) + "..."; + } + aReg.innerHTML = "" + res[x][0] + ": " + textBlockText; + divReg.appendChild(aReg); + + const text = document.createTextNode( + res[x][0] + ": " + res[x][1] + "\n" + ); + textBlocksHolder.appendChild(text); + } + divReg.addEventListener("click", (e) => { + if (e.target && e.target.matches("a.w3-bar-item")) { + insertTextBlocks(e.target); + } + }); + } + }; + xhttp.open("GET", "php/?textBlocks", true); + xhttp.send(); +} + +function setTemplatePreset(template, formData) { + //console.log(template +" : "+ formData); + var xhttp = new XMLHttpRequest(); + xhttp.open("POST", "php/?setForm"); + xhttp.setRequestHeader("Accept", "application/json"); + xhttp.setRequestHeader("Content-Type", "application/json"); + xhttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + //console.log(this.responseText); + } + }; + let data = { + template: template, + data: formData, + }; + + xhttp.send(JSON.stringify(data)); +} + +function setNewTemplate(fileName, data) { + let obj = { + fileName: fileName, + data: data, + }; + //console.log(template +" : "+ formData); + var xhttp = new XMLHttpRequest(); + xhttp.open("POST", "php/?setTemplate"); + xhttp.setRequestHeader("Accept", "application/json"); + xhttp.setRequestHeader("Content-Type", "application/json"); + xhttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + //console.log(this.responseText); + } + }; + + xhttp.send(JSON.stringify(obj)); +} + +function storeFilesToServer(data) { + //console.log(template +" : "+ formData); + var xhttp = new XMLHttpRequest(); + xhttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + if (this.responseText == "success") { + console.log("files saved"); + } + } + }; + xhttp.open("POST", "php/?storeFiles", true); + xhttp.setRequestHeader("Accept", "application/json"); + xhttp.setRequestHeader("Content-Type", "application/json"); + xhttp.send(JSON.stringify(data)); +} + +function checkForStoredDataOnServer() { + var xhttp = new XMLHttpRequest(); + xhttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + if (this.responseText == "none") { + } else { + activeState.serverFilesTs = this.responseText; + let btn = document.getElementById("importModalBtn"); + btn.style.display = ""; + } + } + }; + xhttp.open("GET", "php/?storedFiles="+getUsrId(), true); + xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8'); + xhttp.send(); +} + +function delStoredDataOnServer() { + var xhttp = new XMLHttpRequest(); + xhttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + if (this.responseText == "none") { + let btn = document.getElementById("importModalBtn"); + btn.style.display = "none"; + } + } + }; + xhttp.open("GET", "php/?storedFiles="+getUsrId()+"&del", true); + xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8'); + xhttp.send(); +} + + +function retrieveForm(arr) { + for (let i = 0; i < arr.length; i++) { + let e = document.getElementById(arr[i].name); + if (e === null) { + e = document.getElementById(arr[i].name.split("cl-")[1]); + if (e === null) continue; + } + + if (e.name.substr(0, 4) == "clM-") continue; + + switch (e.nodeName) { + case "TEXTAREA": + e.innerHTML = arr[i].value; + 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 +}; diff --git a/js/9.7/xorc.js b/js/9.7/xorc.js new file mode 100644 index 0000000..5e17850 --- /dev/null +++ b/js/9.7/xorc.js @@ -0,0 +1,187 @@ + +var XORCipher = { + encode: function (key, data, seed) { + data = xor_encrypt(key, data, seed); + return b64_encode(data); + }, + decode: function (key, data) { + data = b64_decode(data); + return xor_decrypt(key, data); + }, + seed: function (n) { + return randString(n); + }, +}; + +function stringToUtf8ByteArray(str) { + var out = [], + p = 0; + for (var i = 0; i < str.length; i++) { + var c = str.charCodeAt(i); + if (c < 128) { + out[p++] = c; + } else if (c < 2048) { + out[p++] = (c >> 6) | 192; + out[p++] = (c & 63) | 128; + } else if ( + (c & 0xfc00) == 0xd800 && + i + 1 < str.length && + (str.charCodeAt(i + 1) & 0xfc00) == 0xdc00 + ) { + // Surrogate Pair + c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); + out[p++] = (c >> 18) | 240; + out[p++] = ((c >> 12) & 63) | 128; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } else { + out[p++] = (c >> 12) | 224; + out[p++] = ((c >> 6) & 63) | 128; + out[p++] = (c & 63) | 128; + } + } + return out; +} + +function utf8ByteArrayToString(bytes) { + // array of bytes + var out = [], + pos = 0, + c = 0; + while (pos < bytes.length) { + var c1 = bytes[pos++]; + if (c1 < 128) { + out[c++] = String.fromCharCode(c1); + } else if (c1 > 191 && c1 < 224) { + var c2 = bytes[pos++]; + out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); + } else if (c1 > 239 && c1 < 365) { + // Surrogate Pair + var c2 = bytes[pos++]; + var c3 = bytes[pos++]; + var c4 = bytes[pos++]; + var u = + (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) - + 0x10000; + out[c++] = String.fromCharCode(0xd800 + (u >> 10)); + out[c++] = String.fromCharCode(0xdc00 + (u & 1023)); + } else { + var c2 = bytes[pos++]; + var c3 = bytes[pos++]; + out[c++] = String.fromCharCode( + ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63) + ); + } + } + return out.join(""); +} + +var b64_table = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +function b64_encode(data) { + var o1, + o2, + o3, + h1, + h2, + h3, + h4, + bits, + r, + i = 0, + enc = ""; + if (!data) { + return data; + } + do { + o1 = data[i++]; + o2 = data[i++]; + o3 = data[i++]; + bits = (o1 << 16) | (o2 << 8) | o3; + h1 = (bits >> 18) & 0x3f; + h2 = (bits >> 12) & 0x3f; + h3 = (bits >> 6) & 0x3f; + h4 = bits & 0x3f; + enc += + b64_table.charAt(h1) + + b64_table.charAt(h2) + + b64_table.charAt(h3) + + b64_table.charAt(h4); + } while (i < data.length); + r = data.length % 3; + return (r ? enc.slice(0, r - 3) : enc) + "===".slice(r || 3); +} + +function b64_decode(data) { + var o1, + o2, + o3, + h1, + h2, + h3, + h4, + bits, + i = 0, + result = []; + if (!data) { + return data; + } + data += ""; + do { + h1 = b64_table.indexOf(data.charAt(i++)); + h2 = b64_table.indexOf(data.charAt(i++)); + h3 = b64_table.indexOf(data.charAt(i++)); + h4 = b64_table.indexOf(data.charAt(i++)); + bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4; + o1 = (bits >> 16) & 0xff; + o2 = (bits >> 8) & 0xff; + o3 = bits & 0xff; + result.push(o1); + if (h3 !== 64) { + result.push(o2); + if (h4 !== 64) { + result.push(o3); + } + } + } while (i < data.length); + return result; +} + +function rand(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; +} + +function randString(n) { + var r = ""; + for (var i = 0; i < n; i++) r += String.fromCharCode(rand(1, 65535)); + + return r; +} + +function xor_encrypt(key, data, seed) { + if (typeof seed == "undefined") seed = randString(32); + + var d = stringToUtf8ByteArray(seed + String.fromCharCode(0) + data), + k = stringToUtf8ByteArray(key), + r = []; + + for (var i = 0; i < d.length; i++) + r[i] = r[i - 1] ^ d[i] ^ k[Math.floor(i % k.length)]; + + return r; +} + +function xor_decrypt(key, data) { + var d = data, + k = stringToUtf8ByteArray(key), + r = []; + + for (var i = 0; i < d.length; i++) + r[i] = d[i - 1] ^ d[i] ^ k[Math.floor(i % k.length)]; + + r.splice(0, r.indexOf(0) + 1); + return utf8ByteArrayToString(r); +} + + export default XORCipher; \ No newline at end of file