Commit 2229feb0 by Jorem Magcawas

recommit build

parent 9422f066
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre1.8.0_231">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v9.0">
<attributes>
<attribute name="owner.project.facets" value="jst.web"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="output" path="build/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>WebGde</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="**/bower_components/*|**/node_modules/*|**/*.min.js" kind="src" path="WebContent"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="WebGde">
<wb-resource deploy-path="/" source-path="/WebContent" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src"/>
<property name="context-root" value="WebGde"/>
<property name="java-output-path" value="/WebGde/build/classes"/>
</wb-module>
</project-modules>
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="Apache Tomcat v9.0"/>
<fixed facet="jst.web"/>
<fixed facet="java"/>
<fixed facet="wst.jsdt.web"/>
<installed facet="java" version="1.8"/>
<installed facet="jst.web" version="3.1"/>
<installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>
org.eclipse.wst.jsdt.launching.baseBrowserLibrary
\ No newline at end of file
Manifest-Version: 1.0
Class-Path:
# Web-GDE
A prototype Web General Data Entry Tool.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>WebGde</display-name>
<welcome-file-list>
<welcome-file>App/index.html</welcome-file>
</welcome-file-list>
</web-app>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ending session...</title>
</head>
<body>
<div class="dv_body">
<div class="content">
<div class="panel-widget" style="display: flex;justify-content: center;padding: 100px 0;">
<div class="panel-body">
<div class="logout-icon">
<img src="https://static.vecteezy.com/system/resources/thumbnails/000/593/212/small/40_350.jpg" width="200px" height="200px" alt="logout icon" style="display: block;margin-left: auto;margin-right: auto;width: 50%;">
</div>
<h1 style="text-align: center;font-family: sans-serif; font-size: 36px;color: rgb(54,54,54); max-width: 500px; min-width: 100px;">Session has been successfully ended</h1>
<h3 style="text-align: center;font-family: sans-serif;color: rgb(54,54,54); max-width: 500px; min-width: 100px;">Thank you for using GDE Tool</h3>
<h5 style="text-align: center;font-family: sans-serif;color: rgb(54,54,54); max-width: 500px; min-width: 100px;">Please click <a href="./login.html">here</a> to return to the GDE Login</h5>
</div>
</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
/**
* for testing purposes, below are different files to be used showing
* some possible configurations of the file
*/
// schema with no "SECTION" key
// const SCHEMA_FILE = "./src/sample_schema/no_section.json"
// schema with missing fields (fieldLabel, validation)
// const SCHEMA_FILE = "./src/sample_schema/missing_fields.json"
// schema with 20 fields
// const SCHEMA_FILE = "./src/sample_schema/20_field_schema.json"
// schema with 15 fields
// const SCHEMA_FILE = "./src/sample_schema/15_field_schema.json"
// schema with 10 fields
// const SCHEMA_FILE = "./src/sample_schema/10_field_schema.json"
// schema with 5 fields and all possible collections
//const SCHEMA_FILE = "./src/sample_schema/5_field_schema.json"
var SCHEMA_FILE = "./src/sample_schema/HR Speed Test schema.json"
// const SCHEMA_FILE = "./src/sample_schema/Sample_Schema.json"
//const INPUT_FILES = ["./input/Ong, Mae Janica - Application Form.TIFF","./input/Magalona, Rowell James - Application Form.TIFF","./input/Felizardo, Brylle Theodure - Application Form.TIFF","./input/Laxamana, Conrad John - Application Form.TIFF"] // list of URLs
var INPUT_FOLDER = "./input/"
var OUTPUT_FILES = "../../output/"
var METRIC_FILES = "../../metrics/"
var HIGH_LIGHT_SCHEMA = "./src/highlight/dbSchema_anno.xlsx"
//this determines if the images will be retrieved from the gfs
var DOMAIN = "http://35.169.23.0:8080"
var CONTEXTROOT = "gfs-explorer-ws"
var FOLDER_URL = DOMAIN + "/" + CONTEXTROOT + "/svc/gfs-rest/get-folder?parentPath=/Users/"
var DOWNLOAD_URL = DOMAIN + "/" + CONTEXTROOT + "/svc/gfs-rest/get-download-link"
var IS_RETRIEVE_FROM_GFS = "Y"
var INVALID_KEYS = "F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,PrintScreen,ScrollLock,Pause,PageUp,PageDown,Insert,Delete,Control"
var credObj =
[
{
"username": "sample1",
"password": "passw0rd"
},
{
"username": "sample2",
"password": "passw0rd"
},
{
"username": "sample3",
"password": "passw0rd"
},
{
"username": "demo",
"password": "passw0rd"
}
];
\ No newline at end of file
var Dirfiles = <?php $arrFiles = array();
$path = './input';
$iterator = new FilesystemIterator($path);
foreach($iterator as $entry) {
$arrFiles[] = './input/' . $entry-> getFilename();
}
echo json_encode($arrFiles);
?>
const disableTiffButtons = () => {
var element = document.getElementById("TiffViewer_ButtonContainer");
element.style.visibility = 'hidden';
}
const enableTiffButtons = () => {
var element = document.getElementById("TiffViewer_ButtonContainer");
element.style.visibility = 'visible';
}
\ No newline at end of file
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link rel="stylesheet" type="text/css" href="gde.css"> -->
<!-- CSS for the fields -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@300&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="./config.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.rawgit.com/seikichi/tiff.js/master/tiff.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<script src="./src/accessFile/accessFile.js"></script>
<script src="./src/XMLWriter/Global.js" language="javascript"></script>
<script src="./src/XMLWriter/XMLWriter.js" language="javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script src="./src/XMLWriter/XML_Saver.js" language="javascript"></script>
<script src="./src/submit/submit.js" language="javascript"></script>
<script src="./src/fetchConfig/fetchConfig.js"></script>
<script src="./src/init/init.js"></script>
<script src="https://requirejs.org/docs/release/2.3.5/minified/require.js"></script>
<script src="https://auth.svi.cloud/auth/js/keycloak.js"></script>
<script type="text/javascript" src="./keycloak-login.js"></script>
<script type="text/javascript" src="./project_config.js"></script>
<link rel="stylesheet" href="./src/tiffViewer/tiffViewer.css">
</head>
<!-- <script>
if (sessionStorage.getItem('user_id') === null) {
window.location.href = "./login.html";
} else {
fetchConfig();
}
</script> -->
<body>
<div id="no-config" style="display:none"> There is no config file found</div>
<div id="with-config" style="display:grid">
<!-- Creates the right pane of the window -->
<aside class="sidebar" id="sidebar">
<!-- Holds the login credentials -->
<!-- <div class="sidebar" id="username">
<button class="sidebar" id="user-settings">...</button>
<span class="sidebar" id="username-text">username@svi ()</span>
</div> -->
<!-- Holds the project description -->
<!-- <aside class="sidebar" id="project-description">
<p class="sidebar" id="column"><br />
</p>
<p class="sidebar" id="column">
</p>
</aside> -->
<!-- Space for the fields -->
<!-- <div class="sidebar" id="fields"> </div> -->
<div id='pauseBtn'>
<button id='pause'>Pause</button>
</div>
<form id='fields' autocomplete="off" style="display: flex; flex-direction:column;"
onsubmit="submitForm(event);return false"></form>
<div id="counter"></div>
</aside>
<!-- Embed viewer -->
<main id="viewer">
<!-- CHANGED: commented out button that triggers the modal -->
<!-- <div> -->
<!-- CHANGED: keep img since id is used for displaying image on modal -->
<img id="TestTIFFDisplay">
<!-- <br><br> -->
<!-- Trigger/Open The Modal -->
<!-- <button id="TestBtn">Open TIFF Image</button>
</div> -->
<div id="TiffViewerModal">
<!-- Modal content -->
<div class="TiffModalContent">
<div class="bar">
<progress id="progressBar" value="0" max="100" style="width:150px;"></progress>
<div id="status">&nbsp;</div>
<h3 id="progress">&nbsp;</h3>
</div>
<div id="TiffModalHeader">
<!-- CHANGED: commented out close button, to avoid closing the modal -->
<!-- <span class="TiffModalClose">&times;</span> -->
</div>
<div id="TiffModalBody">
</div>
<div id="TiffModalFooter">
</div>
</div>
</div>
<img src="" id="tableBanner" />
<img id="myImage" crossorigin="anonymous" src="">
<img id="ImgPrev" crossorigin="anonymous" src="">
<img id="my-img" />
<img id="img" />
</main>
</div>
</body>
<!--body onload-->
<script src='dir.php'></script>
<script src="./disable.js"></script>
<script src="./src/captureMetrics/captureMetrics.js"></script>
<!-- fetch the schema -->
<script src="./src/fetchSchema/fetchSchema.js"></script>
<script src="./src/validateSchema/validateSchema.js"></script> <!-- validate the schema -->
<script src="./src/validateInput/validateInput.js"></script> <!-- functions for validating inputs -->
<script src="./src/getFields/getFields.js"></script> <!-- display the input fields -->
<script src="./src/accessFile/accessFile.js"></script>
<script>
if (!found) { //if config file is not found, change the screen
let withConfig = document.getElementById("with-config");
let noConfig = document.getElementById("no-config");
if (withConfig.style.display === "grid") {
withConfig.style.display = "none";
noConfig.style.display = "block";
}
} else {
if (performance.navigation.type == 1) {
refresh();
} else {
init();
}
}
</script>
<script src="./src/endSession/endSession.js"></script>
<script src="./src/tiffViewer/tiffViewer.js"></script>
<script src="./src/tiffViewer/tiffViewer-new.js"></script>
<script src="./src/highlight/highlight.js"></script>
</html>
\ No newline at end of file
/**
* keycloak-login.js
* author: mel galecio
* date: 2021/06/23
* ticket-number:SLF-4
*
* IMPORTANT: When adding this to your HTML file's <HEAD> tag, list this first before sso-plugin.js
*
*
*
* changes
* date description jira id author
* 2021/06/23 initial version #SLF-5 mel galecio
*/
var isAuth;
var login_userData = {
access_token: '',
id_token: '',
roles: [],
apps: [],
username: '',
fname: '',
name: '',
roleId: '',
jti: '',
wid: ''
}
var username;
var name;
var appID;
var app;
// #NODES
const CURRENT_NODE = 'BPI_PNID';
const NEXT_NODE = '';
const REJECT_NODE = '';
const CURRENT_WORKERS_URL = "http://atropos:8080/BPO_v5.2.9.5/req/nodes/" + CURRENT_NODE + "/workers";
const REDIRECT_URL = 'http://auth-server/auth/realms/DevRealm/protocol/openid-connect/logout?redirect_uri=encodedRedirectUri';
const kc = Keycloak();
var updateProfile = function () {
console.log(kc.token);
login_userData.access_token = kc.tokenParsed;
login_userData.id_token = kc.idTokenParsed;
setUser();
setRoles();
setApps();
}
kc.onAuthRefreshSuccess = function () {
};
function clearAll() {
localStorage.clear();
sessionStorage.clear();
var DBdeleteRequest = window.indexedDB.deleteDatabase("ImageDatabase");
DBdeleteRequest.addEventListener('blocked', function (e) {
console.log("Database cleared.");
// closerWindow = window.open("closer.html", '_self');
});
DBdeleteRequest.addEventListener('upgradeneeded', function (e) {
console.log("Upgrade needed in deleting database");
});
DBdeleteRequest.addEventListener('error', function (e) {
console.log("Error in deleting database");
});
DBdeleteRequest.addEventListener('success', function (e) {
console.log("Database cleared.");
//closerWindow = window.open("closer.html", '_self');
});
}
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
// Flow can be changed to 'implicit' or 'hybrid', but then client must enable implicit flow in admin console too
var initOptions = {
onLoad: 'login-required',
checkLoginIframeInterval: false
};
kc.init(initOptions).then(function (authenticated) {
isAuth = authenticated;
if (!authenticated) {
console.warn('Not authenticated');
} else {
// updateProfile();
refreshImage();
//set email
}
}).catch(function () {
console.info('Init Error');
});
kc.onAuthSuccess = function () {
console.log("SuccessFul login");
fetch(CURRENT_WORKERS_URL)
.then(function (response) {
return response.json();
})
.then(function (data) {
// console.log(data);
// console.log(kc.tokenParsed['preferred_username']);
sessionStorage.setItem("user_id", kc.tokenParsed['email']);
sessionStorage.setItem("token", kc.token);
processLogin(data['workers'],kc.tokenParsed['preferred_username']);
})
.catch(function (err) {
alert('error: ' + err);
alert('Logging out User');
logoutKeycloak();
});
}
//fetch workers
function processLogin(data,user){
let isPresent = data.find((worker) => worker.workerId === user);
if(isPresent){
console.log("Worker is present");
}else{
alert("User not included in the worker List for the Node");
logoutKeycloak();
}
}
const logoutKeycloak = () => {
var logoutOptions = { redirectUri: REDIRECT_URL };
kc.logout(logoutOptions).then((success) => {
console.log("--> log: logout success ", success);
}).catch((error) => {
console.log("--> log: logout error ", error);
});
}
function getkcToken() {
return kc.token;
}
function setUser() {
console.log('setting up user');
login_userData.username = kc.tokenParsed['preferred_username'];
login_userData.fname = kc.tokenParsed['given_name'];
login_userData.name = kc.tokenParsed['name'];
login_userData.wid = kc.tokenParsed['wid'];
login_userData.jti = kc.tokenParsed['jti']
}
function setRoles() {
console.log('setting up roles');
var myobj = kc.tokenParsed['resource_access'];
console.log(myobj);
$.each(myobj, function (index, object) {
console.log('i: ' + index);
if (appID.length > 0 && appID == index) {
console.log(appID);
for (var property in object) {
if (property == "roles") {
var approles = object[property];
for (var item in approles) {
var roleId = approles[item];
var role = {
'roleId': roleId,
'roleName': roleId
}
login_userData.roles.push(role);
}
}
}
}
});
}
function setApps() {
var clientAttributes = [];
var myobj = kc.tokenParsed['resource_access'];
var realmObj = kc.tokenParsed['realm_access'];
var realmRoles = realmObj['roles'];
//get the apps
$.each(myobj, function (index, object) {
console.log('app: ' + index);
var appIcon = '';
var appUrl = '';
//filter out application 'account' as this is a keycloak application
if (index !== "account") {
//we use keycloak realm roles to store the url and icons of the apps in the apprdrawer
//as keycloak doesnt have attributes for clients/applications to hold these two
$.each(realmRoles, function (i, o) {
if (o.includes(index) && o.includes("url")) {
appUrl = o.split("url-")[1];
}
if (o.includes(index) && o.includes("icon")) {
appIcon = o.split("icon-")[1];
}
})
app = {
'id': index,
'name': index,
'icon': appIcon,
'url': appUrl
}
if (appUrl.length > 0) {
login_userData.apps.push(app);
}
}
});
}
function setUserRoleAndApps(appid) {
appID = appid;
setRoles();
setApps();
}
function createjwt(role) {
const header = {
"alg": ALG
}
var stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header));
var encodedHeader = base64url(stringifiedHeader);
const data = {
"jti": login_userData.jti,
"iss": "sso",
"sub": "authorized",
"usr": login_userData.username.toUpperCase(),
"wid": login_userData.wid,
"rol": [
role
],
"app": [
app.id
],
"iat": timestampIssued(getDate()),
"exp": timestampExpired(getDate(), TIMEOUT)
}
var stringifiedData = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
var encodedData = base64url(stringifiedData);
var token = encodedHeader + "." + encodedData;
var secret = CryptoJS.enc.Base64.parse(SECRET)
var signature = CryptoJS.HmacSHA256(token, secret);
var base64sign = base64url(signature);
var signedToken = token + "." + base64sign;
return signedToken;
}
function base64url(source) {
// Encode in classical base64
encodedSource = CryptoJS.enc.Base64.stringify(source);
// Remove padding equal characters
encodedSource = encodedSource.replace(/=+$/, '');
// Replace characters according to base64url specifications
encodedSource = encodedSource.replace(/\+/g, '-');
encodedSource = encodedSource.replace(/\//g, '_');
return encodedSource;
}
function setCookie(token) {
var cookie = 'access_token=' + token + ';' + 'Path=/;Secure;HttpOnly';
document.cookie = cookie;
}
function encryptedjson(role) {
var jwt = createjwt(role);
return jwt;
}
function getDate() {
const date = new Date();
return date;
}
function timestampIssued(dt) {
const unix = Math.round(+dt / 1000);
return unix;
}
function timestampExpired(dt, seconds) {
dt.setSeconds(dt.getSeconds() + seconds);
const unix = Math.round(+dt / 1000);
return unix;
}
{
"realm": "GFS",
"auth-server-url": "https://auth.svi.cloud/auth/",
"ssl-required": "external",
"resource": "webgde",
"public-client": true,
"confidential-port": 0
}
\ No newline at end of file
Body {
font-family: Calibri, Helvetica, sans-serif;
background-color: rgb(255, 255, 255);
}
.main-div{
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
button{
background-color: #EB9B3E;
width: 100%;
color: rgb(0, 0, 0);
padding: 15px;
margin: 10px 0px;
border: none;
cursor: pointer;
}
input[type=text], input[type=password] {
width: 100%;
margin: 8px 0;
padding: 12px 20px;
display: inline-block;
border: 2px solid #ff8800;
box-sizing: border-box;
}
button:hover {
background-color: #ff8800;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
margin: 10px 5px;
}
.container {
padding: 25px;
background-color: #0F2853;
max-width: 600px;
border: 3px solid #0F2853;
color:white;
}
.popup{
display:none;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
width: 700px;
background-color: white;
padding: 20px;
border: 1px solid rgb(179, 176, 176);
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Login Page </title>
<link rel="stylesheet" href="./login.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="./src/fetchConfig/fetchConfig.js"></script>
<script>
if(sessionStorage.getItem('user_id') !== null ) {
window.location.href = "./index.html";
} else {
fetchConfig();
}
</script>
</head>
<body>
<div class="main-div">
<form name="loginForm">
<div class="container">
<h2><center>Sign in to your account</center></h2>
<label>Username : </label>
<input type="text" placeholder="Enter Username" name="username" id="username" required>
<label>Password : </label>
<input type="password" placeholder="Enter Password" name="password" id="password" required>
<button type="button" onclick="validateForm(); return false; ">Sign in</button>
<input type="checkbox" checked="checked"> Remember me
</div>
</form>
</div>
<div class="popup" id="popup">
<div>
<p>Minimum display must be 1366x768</p>
<p>Use "Chrome" Browser for this app</p>
<p>Additional Req: Use Keyboard with Num Pad</p>
</div>
<div>
<button type="button" onclick="hideNotice(); return false; ">Ok</button>
</div>
</div>
</body>
<script src="./config.js"></script>
<script src="./creds.js"></script>
<script src="./script.js"></script>
</html>
\ No newline at end of file
filename,speed,avg_speed
"Felizardo, Brylle Theodure - Application Form.TIFF",228.62614252006588,228.62614252006588
"Felizardo, Theodure Brylle - Application Form.TIFF",8528.560147407214,4378.59314496364
"Laxamana, Conrad John - Application Form.TIFF",11748.708186021213,6835.298158649498
"Laxamana, John Conrad - Application Form.TIFF",7340.2809243316715,6961.543850070042
"Magalona, James Rowell - Application Form.TIFF",8792.401628222524,7327.715405700539
"Magalona, Rowell James - Application Form.TIFF",7034.684904738641,7278.876988873556
"Ong, Janica Mae - Application Form.TIFF",6632.2770817980845,7186.50557357706
"Ong, Mae Janica - Application Form.TIFF",6885.010757829309,7148.818721608592
\ No newline at end of file
filename,speed,avg_speed
"Felizardo, Brylle Theodure - Application Form.TIFF",2019.4465220643233,2019.4465220643233
"Felizardo, Theodure Brylle - Application Form.TIFF",1667.6961087090797,1843.5713153867014
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,"Felizardo, Brylle Theodure - Application Form.TIFF",69.17903277463435,9/22/2022 2:48:09 PM,69.17903277463435
2,"Felizardo, Theodure Brylle - Application Form.TIFF",6445.837063563115,9/22/2022 2:48:15 PM,3257.5080481688747
3,"Laxamana, Conrad John - Application Form.TIFF",8766.88067301306,9/22/2022 2:48:20 PM,5093.965589783603
4,"Laxamana, John Conrad - Application Form.TIFF",9209.123854188872,9/22/2022 2:48:27 PM,6122.755155884921
5,"Magalona, James Rowell - Application Form.TIFF",8878.923766816144,9/22/2022 2:48:33 PM,6673.988878071165
6,"Magalona, Rowell James - Application Form.TIFF",3806.6465256797587,9/22/2022 2:48:42 PM,6196.098486005932
7,"Ong, Janica Mae - Application Form.TIFF",11316.010058675607,9/22/2022 2:48:49 PM,6927.514424958742
8,"Ong, Mae Janica - Application Form.TIFF",7704.280155642024,9/22/2022 2:48:57 PM,7024.6101412941525
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,"Felizardo, Brylle Theodure - Application Form.TIFF",4122.362178962865,9/23/2022 10:26:52 AM,4122.362178962865
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0016_accounting.tif,8209.854661467565,9/29/2022 3:18:05 PM,8209.854661467565
2,0001SVI_0006_accounting.tif,8773.925194163714,9/29/2022 3:19:45 PM,8491.889927815639
3,SPEED TEST_031_accounting.tif,7092.418372993913,9/29/2022 3:20:34 PM,8025.39940954173
4,SPEED TEST_032_accounting.tif,5130.180249576337,9/29/2022 3:21:32 PM,7301.594619550382
5,SPEED TEST_035_accounting.tif,6683.48645689532,9/29/2022 3:22:16 PM,7177.97298701937
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0005.tif,11989.100817438692,10/4/2022 3:08:20 PM,11989.100817438692
2,0001SVI_0004.tif,11195.928753180662,10/4/2022 3:48:58 PM,11592.514785309677
3,0001SVI_0006.tif,2265.39762447888,10/4/2022 3:49:41 PM,8483.475731699411
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0004.tif,993.2382007734232,10/5/2022 3:07:22 PM,993.2382007734232
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0004.tif,11919.068056407114,10/7/2022 9:20:38 AM,11919.068056407114
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0004.tif,9066.844851070391,10/11/2022 1:59:10 PM,9066.844851070391
2,0001SVI_0005.tif,5000.277793210735,10/11/2022 1:59:47 PM,7033.561322140563
3,0001SVI_0006.tif,6793.577222314187,10/11/2022 2:00:19 PM,6953.566622198438
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0004.tif,12507.664009809932,10/3/2022 3:40:56 PM,12507.664009809932
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0004.tif,14262.13271706834,10/5/2022 12:53:03 PM,14262.13271706834
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0004.tif,11716.2074202647,10/7/2022 8:57:02 AM,11716.2074202647
2,0001SVI_0005.tif,14438.502673796791,10/7/2022 8:57:07 AM,13077.355047030745
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0004.tif,11758.301578660861,11/15/2022 2:53:32 PM,11758.301578660861
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0004.tif,8424.99414930962,11/17/2022 1:33:46 PM,8424.99414930962
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0004.tif,1479.7223237120934,11/23/2022 10:47:55 AM,1479.7223237120934
\ No newline at end of file
filename,speed,avg_speed
"Felizardo, Brylle Theodure - Application Form.TIFF",4493.950451315536,4493.950451315536
\ No newline at end of file
record_no,filename,speed,eoe_timestamp,avg_speed
1,0001SVI_0025.tif,4672.2907203114855,11/24/2022 12:38:07 PM,4672.2907203114855
\ No newline at end of file
const ALLOWED_KPH = 8000;
const ALLOWED_DIMENSION_WIDTH = 1366;
const ALLOWED_DIMENSION_HEIGHT = 728;
const ALLOWED_BROWSERS = "Chrome";
function getWindowWidth(){
return window.outerWidth;
}
function getWindowHeight(){
return window.outerHeight;
}
console.log(getWindowWidth() + "x" + getWindowHeight());
console.log(getBrowserName());
function validateForm() {
const reqWindowWidth = ALLOWED_DIMENSION_WIDTH;
const reqWindowHeight = ALLOWED_DIMENSION_HEIGHT;
const reqBrowser = ALLOWED_BROWSERS;
var windowWidth = getWindowWidth();
var windowHeight = getWindowHeight();
var browser = getBrowserName();
var un = document.forms['loginForm'].elements['username'].value
var pw = document.forms['loginForm'].elements['password'].value
var isGranted = true;
if(windowWidth >= reqWindowWidth && windowHeight >= reqWindowHeight && browser == reqBrowser){
for (let i = 0; i < credObj.length; i++) {
// console.log(credObj[i].username + " " + credObj[i].password);
if ((un == credObj[i].username) && (pw == credObj[i].password)) {
sessionStorage.setItem('user_id', un);
window.location = "index.html";
return false;
}
else {
isGranted = false;
}
}
console.log(isGranted);
if(isGranted == false){
alert ("Login denied, please check your username and password");
}
}
else{
showNotice();
}
}
function showNotice(){
var popup = document.getElementById('popup');
popup.style.display = 'block';
}
function hideNotice(){
var popup = document.getElementById('popup');
popup.style.display = 'none';
}
function getBrowserName(){
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
let ieCheck = /Edg/.test(navigator.userAgent);
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
}
if ((verOffset=nAgt.indexOf("Version"))!=-1){
}
//In Edge, the true version is after "Edge"
if (ieCheck) {
browserName = "Edge";
}
//If Opera
var isChromium = window.chrome,
isOpera = window.navigator.userAgent.indexOf("OPR") > -1 || window.navigator.userAgent.indexOf("Opera") > -1;
if(isChromium !== null && isOpera == true) {
browserName = "Opera";
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) {
browserName = nAgt.substring(nameOffset,verOffset);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
return browserName;
}
\ No newline at end of file
function JSettings()
{
this.IE=document.all?true:false;
this.MouseX=_JSettings_MouseX;
this.MouseY=_JSettings_MouseY;
this.SrcElement=_JSettings_SrcElement;
this.Parent=_JSettings_Parent;
this.RunOnLoad=_JSettings_RunOnLoad;
this.FindParent=_JSettings_FindParent;
this.FindChild=_JSettings_FindChild;
this.FindSibling=_JSettings_FindSibling;
this.FindParentTag=_JSettings_FindParentTag;
}
function _JSettings_MouseX(e)
{return this.IE?event.clientX:e.clientX;}
function _JSettings_MouseY(e)
{return this.IE?event.clientY:e.clientY;}
function _JSettings_SrcElement(e)
{return this.IE?event.srcElement:e.target;}
function _JSettings_Parent(Node)
{return this.IE?Node.parentNode:Node.parentElement;}
function _JSettings_RunOnLoad(Meth){var Prev=(window.onload)?window.onload:function(){};window.onload=function(){Prev();Meth();};}
function _JSettings_FindParent(Node, Attrib, Value)
{var Root = document.getElementsByTagName("BODY")[0];
Node = Node.parentNode; while (Node != Root && Node.getAttribute(Attrib) != Value){Node=Node.parentNode;}
if (Node.getAttribute(Attrib) == Value) {return Node;} else {return null;}}
function _JSettings_FindParentTag(Node, TagName)
{var Root = document.getElementsByTagName("BODY")[0];
TagName=TagName.toLowerCase();
Node = Node.parentNode; while (Node != Root && Node.tagName.toLowerCase() != TagName){Node=Node.parentNode;}
if (Node.tagName.toLowerCase() == TagName) {return Node;} else {return null;}}
function _JSettings_FindChild(Node, Attrib, Value)
{
if (Node.getAttribute)
if (Node.getAttribute(Attrib) == Value) return Node;
var I=0;
var Ret = null;
for (I=0;I<Node.childNodes.length;I++)
{
Ret = FindChildByAttrib(Node.childNodes[I]);
if (Ret) return Ret;
}
return null;
}
function _JSettings_FindSibling(Node, Attrib, Value)
{
var Nodes=Node.parentNode.childNodes;
var I=0;
for (I=0;I<Nodes.length;I++)
{
if (Nodes[I].getAttribute)
{
if (Nodes[I].getAttribute(Attrib) == Value)
{return Nodes[I];}
}
}
return null;
}
var Settings = new JSettings();
\ No newline at end of file
function XMLWriter()
{
this.XML=[];
this.Nodes=[];
this.State="";
this.FormatXML = function(Str)
{
if (Str)
return Str.replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
return ""
}
this.BeginNode = function(Name)
{
if (!Name) return;
if (this.State=="beg") this.XML.push(">");
this.State="beg";
this.Nodes.push(Name);
this.XML.push("<"+Name);
}
this.EndNode = function()
{
if (this.State=="beg")
{
this.XML.push("/>");
this.Nodes.pop();
}
else if (this.Nodes.length>0)
this.XML.push("</"+this.Nodes.pop()+">");
this.State="";
}
this.Attrib = function(Name, Value)
{
if (this.State!="beg" || !Name) return;
this.XML.push(" "+Name+"=\""+this.FormatXML(Value)+"\"");
}
this.WriteString = function(Value)
{
if (this.State=="beg") this.XML.push(">");
this.XML.push(this.FormatXML(Value));
this.State="";
}
this.Node = function(Name, Value)
{
if (!Name) return;
if (this.State=="beg") this.XML.push(">");
this.XML.push((Value=="" || !Value)?"<"+Name+"/>":"<"+Name+">"+this.FormatXML(Value)+"</"+Name+">");
this.State="";
}
this.Close = function()
{
while (this.Nodes.length>0)
this.EndNode();
this.State="closed";
}
this.ToString = function(){return this.XML.join("");}
}
\ No newline at end of file
function WriteForm(e,metrics,doctype,section)
{
try
{
const lookup = schema[doctype][section]
const myArray = Object.values(metrics);
localStorage.setItem("submit", "1");
var Frm=Settings.SrcElement(e);
var XML=new XMLWriter();
XML.WriteString('<?xml version="1.0" encoding="UTF-8" standalone="no"?>');
XML.BeginNode(Frm.name);
var Nodes=Frm.elements;
XML.Node("Image_Source_Path",File_Path);
XML.Node("No_of_Keystrokes",JSON.stringify(myArray[0]));
XML.Node("Processing_Time_Seconds",JSON.stringify(myArray[1]));
for (var i=0;i<Nodes.length;i++){
if (Nodes[i].style.display === 'none') continue
let fid = Nodes[i].id;
if (fid == 'DocType' || fid == 'Section' || fid == '') continue
XML.Node(Object.keys(lookup[fid]).includes('aka') ? lookup[fid].aka : fid,
Nodes[i].value);
// console.log(Nodes[i]);
}
XML.EndNode();
XML.Close();
var final_xml=XML.ToString().replace(/</g,"\n<").replace(/&lt;/g,"\<").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/\n<\//g,"</").replace(/<\/xml>/g,"\n</xml>");
var myFile = new File([final_xml], sessionStorage.getItem('user_id') + "_" + File_Name + ".xml", {type: "text/plain;charset=utf-8"});
// saveAs(myFile);
let formData = new FormData();
formData.append("file", myFile);
fetch('./src/XMLWriter/upload.php', {
method: "POST",
body: formData
});
}
catch(Err)
{
alert("Error: " + Err.description);
}
return false;
}
<?php
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "../../output/".$filename;
/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo 'Failure';
}
?>
\ No newline at end of file
var File_Name;
var File_Path;
async function accessFile() {
var button = 0;
var size = 0;
let file_url = [];
const elStatus = document.getElementById('status');
function status(text) {
elStatus.innerHTML = text;
}
const progressBar = document.getElementById('progressBar');
const elProgress = document.getElementById('progress');
function progress({ loaded, total }) {
// elProgress.innerHTML = Math.round(loaded * .000001) + " mb of " + Math.round(total * .000001);
progressBar.value = Math.round(loaded / total * 100);
}
const indexedDB =
window.indexedDB ||
window.mozIndexedDB ||
window.webkitIndexedDB ||
window.msIndexedDB ||
window.shimIndexedDB;
if (!indexedDB) {
console.log("IndexedDB could not be found in this browser.");
}
const request = indexedDB.open("ImageDatabase", 1);
request.onerror = function (event) {
console.error("An error occurred with IndexedDB");
console.error(event);
};
request.onupgradeneeded = function () {
const db = request.result;
const store = db.createObjectStore("image", { keyPath: "id" });
store.createIndex("image_address", ["address"], { unique: false });
};
async function main(img) { status('downloading ...');
var image_info=[];
const response = await fetch(img);
const contentLength = response.headers.get('content-length');
// console.log(contentLength);
const total = (parseInt(contentLength, 10));
let loaded = 0;
const res = new Response(new ReadableStream({
async start(controller) {
const reader = response.body.getReader();
for (;;) {
const {done, value} = await reader.read();
if (done) break;
loaded += (value.byteLength);
// console.log(loaded);
progress({loaded, total});
controller.enqueue(value);
}
controller.close();
},
}));
const blob = await res.blob();
status('download completed');
[...document.getElementsByClassName("bar")].forEach(el => {
el.style.display = "none";
});
const request = indexedDB.open("ImageDatabase", 1);
request.onsuccess = async function () {
// console.log("Database opened successfully " + val );
const db = request.result;
const transaction = db.transaction("image", "readwrite");
const store = transaction.objectStore("image");
const imageIndex = store.index("image_address");
if(img!=null){
var filename = get_file_name(img);
}
var count = store.count();
count.onsuccess = function() {
if (count.result == 0) {
store.put({ id: count.result + 1, address: blob , name:filename, path:img});
url = URL.createObjectURL(blob);
window.addEventListener("load", loadDoc(url, TIFFViewer,filename), false);
localStorage.setItem("display_counter", 1);
size = size + total;
File_Name = filename;
File_Path = img;
var file = new File([blob], filename + ".TIFF", {type: "img"}); //uplaod to uploadimgfolder //scanned images
uploadFile(file);
} else if (count.result == 1) {
store.put({ id: count.result + 1, address: blob , name:filename, path:img});
localStorage.setItem("submit", "0");
localStorage.setItem("display_counter", 2);
size = size + total;
var file = new File([blob], filename + ".TIFF", {type: "img"}); //uplaod to uploadimgfolder //scanned images
uploadFile(file);
} else if(img == null && count.result == 2 && (localStorage.length) == 2 && localStorage.getItem("submit") == 1){ //if only one file left
const idQuery = store.get(parseInt(localStorage.getItem("display_counter")));
idQuery.onsuccess = function () {
url = URL.createObjectURL(idQuery.result.address);
window.addEventListener("load", loadDoc(url, TIFFViewer,idQuery.result.name), false);
File_Name = idQuery.result.name;
File_Path = idQuery.result.path;
store.delete(parseInt(localStorage.getItem("display_counter")) - 1);
localStorage.setItem("submit", "0");
};
} else if(img == null && count.result == 1 && (localStorage.length) == 2 && localStorage.getItem("submit") == 1){//no files left
// alert("No Files Left");
if(IS_RETRIEVE_FROM_GFS != 'Y'){
store.clear();
disableForm();
promptNoFilesLeft();
}
}else if (count.result == 2 && (localStorage.length) == 2 && localStorage.getItem("submit") == 1) {
const idQuery = store.get(parseInt(localStorage.getItem("display_counter")));
idQuery.onsuccess = function () {
url = URL.createObjectURL(idQuery.result.address);
window.addEventListener("load", loadDoc(url, TIFFViewer,idQuery.result.name), false);
File_Name = idQuery.result.name;
File_Path = idQuery.result.path;
store.delete(parseInt(localStorage.getItem("display_counter")) - 1);
store.put({ id: parseInt(localStorage.getItem("display_counter")) + 1, address: blob , name:filename, path:img});
localStorage.setItem("submit", "0");
localStorage.setItem("display_counter", parseInt(localStorage.getItem("display_counter")) + 1); //update how many have been fetched
var file = new File([blob], filename + ".TIFF", {type: "img"}); //uplaod to uploadimgfolder //scanned images
uploadFile(file);
};
size = size + total;
}
else {
// console.log(count.result);
// console.log(localStorage.length);
}
}
transaction.oncomplete = function () {
db.close();
status('downloaded '+Math.trunc(size/1000)+" kb");
};
};
}
var updated_input_files = await Input_files();
if(IS_RETRIEVE_FROM_GFS == "Y"){
const modal = document.getElementById("TiffViewerModal");
modal.style.display = 'none';//hide local modal
getFolder(FOLDER_URL+sessionStorage.getItem('user_id'));
}else{
if((localStorage.length)==0){
if(updated_input_files.length==0){
alert("No Inputs");
} else if (updated_input_files.length==1){
main(updated_input_files[0]);
} else {
await main(updated_input_files[0]);
main(updated_input_files[1]);
}
}else{
main(updated_input_files[0]);
}
}
function get_file_name(filepath){
var filename = filepath.substring(8);
var flag=0;
for (var i = 0; i < filename.length; i++) {
if(filename.charAt(filename.length-i) != "."){
flag++;
}else{
break;
}
}
filename = filename.substring(0,filename.length-flag);
return filename;
}
function Input_files() {
//Dirfiles from dir.php
var urls = Object.assign(new Array(), Dirfiles);
var count;
if((localStorage.length) == 0){
count = 0;
}else{
count = parseInt(localStorage.getItem("display_counter"));
}
for (var i = 0; i < count; i++) {
urls.shift();
}
// console.log(urls);
return urls;
}
function uploadFile(file) {
let formData = new FormData();
formData.append("file", file);
fetch('http://localhost/Web-GDE/src/accessFile/uploadimg.php',{
method: "POST",
body: formData
});
}
function getFolder(url){
const promise = fetch(url, {
method: 'GET',
headers: {
'Authorization': sessionStorage.getItem('token')
// 'Content-Type': 'application/x-www-form-urlencoded',
}
//body: JSON.stringify(myObject)
})
.then(function (response) {
if(response.status === 200){
response.json().then(function(data) {
let temp = data.folderContent;
// temp.forEach(function(obj){
// //getFiles(DOWNLOAD_URL,obj.fileId);
// getFiles(DOWNLOAD_URL,obj.fileId);
// })
var container = document.getElementById("viewer");
var overlay;
for (let i = 0; i < temp.length; i++) {
overlay = document.createElement('div');
overlay.id = "containerModal" + i;
overlay.style.display = 'none';
container.append(overlay);
getFiles(DOWNLOAD_URL,temp[i].fileId,overlay,temp[i].name);
}
let counter = 0;
sessionStorage.setItem("gfsCounter", counter);
var currDislplay = document.getElementById("containerModal" + sessionStorage.getItem('gfsCounter'));
currDislplay.style.display = 'block';
});
}else{
console.log("Error");
}
})
.catch(function (error) {
console.log('Request failed', error);
});
return promise;
}
async function getFiles(url,id,overlay,filename){
var myObject = {fileId : id};
fetch(url, {
method: 'POST',
headers: {
'Authorization': sessionStorage.getItem('token'),
'Content-Type':'application/json'
},
body: JSON.stringify(myObject)
})
.then(async function(response) {
await response.text().then(async function(imgData) {
console.log(imgData);
getBlobService(imgData, function(data) {
var fileReader = new FileReader();
fileReader.onload = function() {
console.log(this.result);
var fileReader = new FileReader();
fileReader.onload = function () {
// File_Name = filename;
tiffViewerTest(this.result, overlay, filename);
};
fileReader.readAsArrayBuffer(data);
};
fileReader.readAsArrayBuffer(data);
});
});
})
.catch(function (error) {
console.log('Request failed', error);
});
// .then(response => {
// response.blob().then(blob => {
// console.log(blob);
// // const link = document.createElement('a');
// const url = URL.createObjectURL(blob);
// file_url.push(url);
// console.log(file_url);
// // link.href = url;
// // link.download = '111.txt';
// // link.click();
// })
// })
}
function getBlobService(url, func) {
const promise = fetch(url, {
method: 'get',
headers: {
'Authorization': sessionStorage.getItem('token')
}
})
.then(function(response) {
switch (response.status) {
case 200: response.blob().then(function(data) { func(data); }); break;
case 460: createInfoPopup("Error 460", "User does not exist."); break;
case 403: removeOverlay(); createInfoPopup("We are so sorry...", "Permission Denied: You don't have access here."); break;
case 464: createInfoPopup("Error 464", "No folder was retrieved."); break;
case 463: createInfoPopup("Error 463", "The folder name you entered already exists."); break;
case 462: createInfoPopup("Error 462", "No file was retrieved."); break;
case 461: createInfoPopup("Error 461", "File already exists."); break;
case 465: createInfoPopup("Error 465", "Source not found"); break;
case 500: removeOverlay(); createInfoPopup("It's not you. It's us... So sorry.", "Error 500: Please contact the support team so we can fix this immediately."); break;
default: break;
}
})
.catch(function(error) {
removeOverlay();
createInfoPopup("Whoops!", "We encountered some problems with your request. Rest assured we're working on this and it'll be okay soon.");
});
return promise;
}
}
function postServiceText(url, myObject, funcSuccess, funcFail){
const promise = fetch(url, {
method: 'post',
body: JSON.stringify(myObject),
headers: {
'Content-Type': 'application/json',
'Authorization': kc.token
// 'Content-Type': 'application/x-www-form-urlencoded',
}
})
.then(function (response) {
if(response.status === 200){
response.text().then(function(data) {
//var parseData = JSON.parse(data);
// funcSuccess(data);
console.log(data);
//alert(data);
//displayData(parseData);
});
}else{
console.log("Error");
funcFail();
}
})
.catch(function (error) {
console.log('Request failed', error);
});
return promise;
}
function refreshImage() {
var size = 0;
const elStatus = document.getElementById('status');
function status(text) {
elStatus.innerHTML = text;
}
const progressBar = document.getElementById('progressBar');
const elProgress = document.getElementById('progress');
function progress() {
// elProgress.innerHTML = Math.round(loaded * .000001) + " mb of " + Math.round(total * .000001);
progressBar.value = Math.round(100 / 100 * 100);
}
const request = indexedDB.open("ImageDatabase", 1);
request.onsuccess = async function () {
// console.log("Database opened successfully " + val );
const db = request.result;
const transaction = db.transaction("image", "readwrite");
const store = transaction.objectStore("image");
const imageIndex = store.index("image_address");
var count = store.count();
count.onsuccess = function() {
if (count.result == 0 && IS_RETRIEVE_FROM_GFS != 'Y') {
disableForm();
promptNoFilesLeft();
} else {
const idQuery = count.result == 2 ? store.get(parseInt(localStorage.getItem("display_counter")) - 1) : store.get(parseInt(localStorage.getItem("display_counter")));
idQuery.onsuccess = function () {
url = URL.createObjectURL(idQuery.result.address);
window.addEventListener("load", loadDoc(url, TIFFViewer,idQuery.result.name), false);
File_Name = idQuery.result.name;
File_Path = idQuery.result.path;
};
}
}
transaction.oncomplete = function () {
db.close();
status('downloaded '+Math.trunc(size/1000)+" kb");
progress();
[...document.getElementsByClassName("bar")].forEach(el => {
el.style.display = "none";
});
};
};
}
function promptNoFilesLeft(){
var viewer = document.getElementById('viewer');
var promptMain = document.createElement('div');
promptMain.setAttribute("id", "prompt");
var message = document.createElement('p');
message.innerHTML = 'No images left to be fetched, Proceed to end session';
var okButton = document.createElement('button');
okButton.innerHTML = 'ok';
okButton.onclick = function() {
promptMain.style.display = 'none';
};
promptMain.appendChild(message);
promptMain.appendChild(okButton);
viewer.appendChild(promptMain);
}
<?php
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "./uploadimg/".$filename;
/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo 'Failure';
}
?>
\ No newline at end of file
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache/2.4.53 (Win64) OpenSSL/1.1.1n PHP/8.1.6 Server at localhost Port 80</address>
</body></html>
let key_strokes = 0
let time_spent = 0
let time_start = 0
let time_pause = 0
let time_pause_spent = 0
const conflicts = ['F', 'f', 'alphabet', 'alphanumeric']
const shift_shortcuts = ['f', 'F']
const ctrl_shortcuts = ['PageUp', 'PageDown', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', '-', '=']
const ctrl_shift_shortcuts = ['v', 'h', 'V', 'H']
const shortcut_triggers = ['Shift', 'Control']
let shortcut_flag = false
const csv_header = ['record_no', 'filename', 'speed', 'eoe_timestamp', 'avg_speed'];
let temp;
const keyArray = INVALID_KEYS.split(",");
const startMetricCapture = () => {
// reset key strokes
key_strokes = 0
time_start = Date.now()
time_pause_spent = 0
console.log(`Metric Capture Started
Key strokes: ${key_strokes}
Start of encoding time: ${time_start}
Total time spent encoding: ${time_spent}`) // for demonstration purposes
window.onkeyup = (key) => {
const onfocus = document.activeElement
if (shortcut_flag && shortcut_triggers.includes(key.key)) {
if (!key.ctrlKey && !key.shiftKey) { // will disregard key up event on shift or ctrl right after a short cut key combination
console.log('Shortcut trigger lifted') // for demonstration purposes
shortcut_flag = false
}
return
}
if ((key.shiftKey && shift_shortcuts.includes(key.key)) || // shift shortcut
(key.ctrlKey && ctrl_shortcuts.includes(key.key))) { // ctrl shortcut
if (onfocus.nodeName !== 'INPUT' ||
!conflicts.includes(key.key)) { // ignore shortcuts with conflict if triggered inside input field
console.log('Shortcut Triggered') // for demonstration purposes
shortcut_flag = true
return
}
}
if (key.shiftKey && key.ctrlKey && ctrl_shift_shortcuts.includes(key.key)) {
console.log('Shortcut Triggered') // for demonstration purposes
shortcut_flag = true
return
}
if (searchStringInArray(`${key.key}`, keyArray) == true || key.ctrlKey && key.key) {
console.log('key invalid');
} else {
key_strokes++
}
console.log(`key: ${key.key}; key_strokes: ${key_strokes}; time_spent: ${((Date.now() - time_start) / 1000) - time_pause_spent}`) // for demonstration purposes
}
window.onclick = (event) => {
if (event.path[0].id == 'pause') {
pauseMetricCapture();
disableTiffButtons();
}
}
showMetricCapture();
}
function searchStringInArray(str, strArray) {
for (var j = 0; j < strArray.length; j++) {
if (strArray[j] == str) return true;
}
return false;
}
const stopMetricCapture = () => {
const time_end = Date.now()
time_spent = (time_end - time_start) / 1000 // time spend in seconds
const rate = (key_strokes / time_spent) * 3600 // key strokes made per hour
return {
key_strokes,
time_spent,
rate
}
}
let interval = null;
const showMetricCapture = () => {
const obj = document.getElementById("counter");
if (key_strokes != 0) {
let time_spent = ((Date.now() - time_start) / 1000) - time_pause_spent;
let rate = ((key_strokes / time_spent) * 3600).toFixed(0);
rate >= ALLOWED_KPH ? obj.className = "green" : obj.className = "red";
obj.innerHTML = (rate < 0 ? 0 : rate) + " kph"; // immediately apply start value
}
interval = setTimeout(showMetricCapture, 1000);
}
const saveMetrics = (metrics, eoe_ts) => {
try {
eoe_ts = formatDate(eoe_ts);
let rows = new Array();
if (sessionStorage.getItem('csv') === null) {
rows.push(csv_header);
rows.push([1, escapeCSV(File_Path.replace(/^.*[\\\/]/, '')), metrics.rate, eoe_ts, metrics.rate]);
} else {
rows = JSON.parse(sessionStorage.getItem('csv'));
let size = rows.length - 1;
let last = rows[size];
let avg = last[last.length - 1];
let newAvg = ((avg * size) + metrics.rate) / (size + 1);
rows.push([(size + 1), escapeCSV(File_Path.replace(/^.*[\\\/]/, '')), metrics.rate, eoe_ts, newAvg]);
}
var myFile = new File(
[(rows.map(e => e.join(",")).join("\n"))],
sessionStorage.getItem('user_id') + '_Metrics_' + (new Date()).toISOString().slice(0, 10).replace(/-/g, "") + ".csv",
{ type: "text/plain;charset=utf-8" }
);
let formData = new FormData();
formData.append("file", myFile);
formData.append("data", JSON.stringify({ "metrics_dir": METRIC_FILES }));
fetch('./src/captureMetrics/saveMetrics.php', {
method: "POST",
body: formData
});
sessionStorage.setItem('csv', JSON.stringify(rows));
} catch (Err) {
console.log("Error: " + Err.description);
}
}
const escapeCSV = (filename) => {
return filename.includes(",") ? '"' + filename + '"' : filename;
}
const pauseMetricCapture = () => {
time_pause = Date.now();
hideImage();
disableForm();
promptPaused();
clearTimeout(interval);
temp = key_strokes;
// unpauseMetricCapture();
// alert("PAUSED");
}
const unpauseMetricCapture = () => {
time_pause_spent += (Date.now() - time_pause) / 1000;
time_pause = 0;
unhideImage();
enableForm();
key_strokes = temp;
showMetricCapture();
}
const hideImage = () => {
var tiffbody = document.getElementById("TiffModalBody");
tiffbody.style.opacity = 0;
}
const unhideImage = () => {
var tiffbody = document.getElementById("TiffModalBody");
tiffbody.style.opacity = 1;
}
function promptPaused() {
var viewer = document.getElementById('viewer');
var promptMain = document.createElement('div');
promptMain.setAttribute("id", "prompt");
promptMain.style.zIndex = 999;
promptMain.style.textAlign = 'center';
promptMain.style.margin = 0 + ' auto';
promptMain.style.position = 'absolute';
promptMain.style.top = '50%';
promptMain.style.left = '50%';
promptMain.style.border = '1px solid gray';
promptMain.style.transform = 'translate(-50%, -50%)';
promptMain.style.backgroundColor = 'gray';
promptMain.style.padding = '10px';
promptMain.style.display = 'block';
var message = document.createElement('p');
message.innerHTML = 'Session Paused';
var okButton = document.createElement('button');
okButton.setAttribute("id", "continue");
okButton.innerHTML = 'continue';
okButton.onclick = function () {
promptMain.style.display = 'none';
unpauseMetricCapture();
enableTiffButtons();
};
promptMain.appendChild(message);
promptMain.appendChild(okButton);
viewer.appendChild(promptMain);
}
function disableForm() {
var pbutton = document.getElementById("pause");
pbutton.disabled = true;
var form = document.getElementById("fields");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].disabled = true;
// elements[i].style.backgroundColor = "gray";
}
}
function enableForm() {
var pbutton = document.getElementById("pause");
pbutton.disabled = false;
var form = document.getElementById("fields");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].disabled = false;
// elements[i].style.backgroundColor = "white";
}
}
const formatDate = (date) => {
return date.replace(",", "");
}
\ No newline at end of file
<?php
$dir = json_decode($_POST['data'], true)['metrics_dir'];
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = $dir.$filename;
/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo 'Failure';
}
?>
\ No newline at end of file
// var submitted = false;
const form = document.getElementById("fields");
const sidebar = document.getElementById("sidebar");
let closerWindow;
// form.addEventListener('submit', (e)=>{
// submitted = true;
// })
endButton = document.createElement("button");
endButton.id = "endBtn";
endButton.innerHTML = "End Session";
var endDiv = document.createElement("div");
endDiv.id = "endDiv";
endDiv.append(endButton);
sidebar.append(endDiv);
//checks if form is empty
function checkForm(form){
var inputs = form.getElementsByTagName("input");
var selects = form.getElementsByTagName("select");
inputsBlankCount = inputs.length;
selectsBlankCount = selects.length - 2;
for(var i=0; i<inputs.length; i++){
if(inputs[i].value == "") inputsBlankCount--;
}
for(var i=0; i<selects.length; i++){
if(selects[i].options[selects[i].selectedIndex].value === "null") selectsBlankCount--;
}
if(inputsBlankCount==0 && selectsBlankCount==0) return true;
}
//deletes the indexedDB if form is submitted or form is empty
endButton.addEventListener("click", function(){
//clear localStorage
localStorage.clear();
sessionStorage.clear();
//if form is submitted or fields are blank, delete database
if(checkForm(form)){
var DBdeleteRequest = window.indexedDB.deleteDatabase("ImageDatabase");
DBdeleteRequest.addEventListener('blocked', function(e){
console.log("Database cleared.");
//closerWindow = window.open("closer.html", '_self');
});
DBdeleteRequest.addEventListener('upgradeneeded', function(e){
console.log("Upgrade needed in deleting database");
});
DBdeleteRequest.addEventListener('error', function(e){
console.log("Error in deleting database");
});
DBdeleteRequest.addEventListener('success', function(e){
console.log("Database cleared.");
//closerWindow = window.open("closer.html", '_self');
});
logoutKeycloak();
//resets the the boolean checker if data is submitted
submitted = false;
}
//if form is not empty but "End Session" button is pressed without submitting the form
else{
alert("Fields are not empty. Submit or clear fields first.");
}
});
\ No newline at end of file
var found = true; //variable to return
var embed = 0; //checker if which file is using the function
const fetchConfig = () => {
$.ajax({ //locates the config file
url: './config.js',
async: false,
success: function (data) { },
error: function (data) {
handleError("application config");
},
})
$.ajax({ //locates the project config file
url: './project_config.js',
async: false,
success: function (data) { },
error: function (data) {
handleError("project config");
},
})
}
const handleError = (file) => {
if (embed == 0) {//to ensure the prompt appears only once
if (confirm(`${file} not found, application will not commence`)) { }
}
found = false;
}
/**
* will fetch the json file containing the schema.
* update the value of the variable file to the path/url of the json file
*/
// const file = "./fetchSchema/5_field_schema.json"
let schema = {}
const fetchSchema = async () => {
await fetch(SCHEMA_FILE)
.then(res => res.json())
.then(data => {
schema = data;
})
.catch(schema = {})
}
\ No newline at end of file
/**
* AUTHOR: btsfelizardo
* DATE: 20 July 2022
* DESCRIPTION: User: Encode specific document based on fixed schema. The main function
* will loop through all the keys in schema then create a div containing a label
* and an input field, which will depend on the type of collection specified in
* the validation. Text input field for alphanumeric, alphabet, and numeric. Date
* input field for date and datepicker type. Additional validation are also included
* if found in the schema like maximum length of input and required fields.
*/
/**
*
* @param {*} parentID
* ID of the element that will contain the input fields
* @returns
*/
let getDocType;
const displayFields = async (parentID) => {
try {
let div = document.getElementById(parentID)
if(!div) return { valid: false, error: `Element with ID '${parentID}' not found` }
clearFields(parentID) // make sure input fields are clear
await fetchSchema()
createDocTypeDropdown('DocType', div, schema)
createSection('Section', div)
const { ACCOUNTING_DOCUMENTS } = schema
//getDocType = DOC_TYPE1 ;
const { SECTION1 } = ACCOUNTING_DOCUMENTS
div = deconstruct(SECTION1, div, 'SECTION1')
const { valid, error } = validateSchema()
const { BANK_APPLICATION_FORM } = schema
const { SECTION2 } = BANK_APPLICATION_FORM
div = deconstruct(SECTION2, div, 'SECTION2')
const { HR_FILES } = schema
const { SECTION3 } = HR_FILES
div = deconstruct(SECTION3, div, 'SECTION3')
if(!valid){
div.textContent = error
div.style.color = '#ff3333'
}
const submit = document.createElement('input')
submit.type = 'submit'
div.appendChild(submit)
// add handler event handler for dropdown
// separate handler is used to fit with the library used 'select2'
$(document).ready(function() {
let dropdowns = $('.dropdown-input').select2();
dropdowns.splice(0,2);
dropdowns.on('select2:open', () => {
document.querySelector('.select2-search__field').focus();
});
dropdowns.on('select2:close', handleDropdown)
// dropdowns.splice(0,2);
// console.log(dropdowns);
});
//
$(document).ready(function() {
var dropdown1 = {
1 : ['SECTION1'],
2 : ['SECTION2'],
3 : ['SECTION3']
}
$(".SECTION2").hide();
$(".SECTION3").hide();
[...document.querySelectorAll('.SECTION2 input, .SECTION2 textarea, .SECTION3 input, .SECTION3 textarea')].forEach(el => el.removeAttribute("required"));
$('#Section').html(
'<option>'+dropdown1[1].join('</option><option>')+'</option>'
);
$('#Section').on('change',function() {
if($(this).val() == "SECTION1") {
$(".SECTION1").show();
$(".SECTION2").hide();
$(".SECTION3").hide();
} else if($(this).val() == "SECTION2") {
$(".SECTION2").show();
$(".SECTION1").hide();
$(".SECTION3").hide();
} else if($(this).val() == "SECTION3") {
$(".SECTION3").show();
$(".SECTION1").hide();
$(".SECTION2").hide();
}
});
$('#DocType').on('change',function() {
if($(this).val() == "1") {
$(".SECTION1").show();
$(".SECTION2").hide();
$(".SECTION3").hide();
[...document.querySelectorAll('.SECTION2 input, .SECTION2 textarea, .SECTION3 input, .SECTION3 textarea')].forEach(el => el.removeAttribute("required"));
} else if($(this).val() == "2") {
$(".SECTION2").show();
$(".SECTION1").hide();
$(".SECTION3").hide();
[...document.querySelectorAll('.SECTION1 input, .SECTION1 textarea, .SECTION3 input, .SECTION3 textarea')].forEach(el => el.removeAttribute("required"));
} else if($(this).val() == "3") {
$(".SECTION3").show();
$(".SECTION1").hide();
$(".SECTION2").hide();
[...document.querySelectorAll('.SECTION1 input, .SECTION1 textarea, .SECTION2 input, .SECTION2 textarea')].forEach(el => el.removeAttribute("required"));
}
$('#Section').html(
'<option>'+dropdown1[$(this).val()].join('</option><option>')+'</option>'
);
});
});
$(document).ready(function () {
$('form:first *:input[type!=hidden]:first').focus(); // Run code
});
} catch(err) {
console.log(err)
return { valid: false, error: err }
}
}
/**
*
* @param {*} key
* will serve as id of input field
* @returns
* created input field element
*/
const noValidation = (key) => {
try {
const input = document.createElement('input')
input.setAttribute('id', `${key}`)
input.setAttribute('placeholder', 'Invalid field!')
input.setAttribute('disabled', 'true')
return input
} catch(err) {
throw err
}
}
/**
*
* @param {*} key
* will serve as id of input field
* @param {*} validation
* validation of field from schema
* @returns
* created input field element
*/
const inputString = (key, validation) => {
try {
const { mandatory, fieldLength } = validation
let input = document.createElement('input')
input.setAttribute('id', `${key}`)
input.setAttribute('type', 'text')
input.setAttribute('autocomplete', 'off')
input.addEventListener('focusout', handleInput)
if(fieldLength >= 31 && fieldLength <= 60){
input = document.createElement('TEXTAREA')
input.setAttribute('rows', 2)
input.setAttribute('id', `${key}`)
input.setAttribute('name', `${key}`)
input.setAttribute('cols', 30)
input.addEventListener('focusout', handleInput)
}
else if(fieldLength >= 61 && fieldLength <= 90){
input = document.createElement('TEXTAREA')
input.setAttribute('rows', 3)
input.setAttribute('id', `${key}`)
input.setAttribute('name', `${key}`)
input.setAttribute('cols', 30)
input.addEventListener('focusout', handleInput)
}
else if(fieldLength >= 91 && fieldLength <= 120){
input = document.createElement('TEXTAREA')
input.setAttribute('rows', 4)
input.setAttribute('id', `${key}`)
input.setAttribute('name', `${key}`)
input.setAttribute('cols', 30)
input.addEventListener('focusout', handleInput)
}
else if (fieldLength >= 120) {
input = document.createElement('TEXTAREA')
input.setAttribute('rows', 5)
input.setAttribute('id', `${key}`)
input.setAttribute('name', `${key}`)
input.setAttribute('cols', 30)
input.addEventListener('focusout', handleInput)
}
fieldLength ? input.setAttribute('maxLength', `${fieldLength}`) : null
mandatory ? input.setAttribute('required', 'true') : null
return input
} catch(err) {
throw err
}
}
/**
*
* @param {*} key
* will serve as id of input field
* @param {*} validation
* validation of field from schema
* @returns
* created input field element
*/
const inputNumeric = (key, validation) => {
try {
const { mandatory, fieldLength } = validation
const input = document.createElement('input')
input.setAttribute('id', `${key}`)
input.setAttribute('type', 'text')
input.setAttribute('autocomplete', 'off')
input.setAttribute('pattern', '[0-9/-]+')
input.addEventListener('focusout', handleInput)
fieldLength ? input.setAttribute('maxLength', `${fieldLength}`) : null
mandatory ? input.setAttribute('required', 'true') : null
return input
} catch(err) {
throw err
}
}
/**
*
* @param {*} key
* will serve as id of input field
* @param {*} validation
* validation of field from schema
* @returns
* created input field element
*/
const inputDate = (key, validation) => {
try {
const { mandatory, fieldLength } = validation
const input = document.createElement('input')
input.setAttribute('id', `${key}`)
input.setAttribute('type', 'date')
input.addEventListener('focusout', handleInput)
mandatory ? input.setAttribute('required', 'true') : null
return input
} catch(err) {
throw err
}
}
/**
*
* @param {*} key
* will serve as id of input field
* @param {*} validation
* validation of field from schema
* @returns
* created input field element
*/
const inputDropdown = (key, validation) => {
try {
const { mandatory, options } = validation
const input = document.createElement('select')
input.setAttribute('id', `${key}`)
input.classList.add('dropdown-input')
input.addEventListener('focusout', handleInput)
input.addEventListener('keydown', function(event) {
if (event.keyCode == 9) {
event.preventDefault();
var elem = document.getElementsByClassName('select2-search__field');
elem.focus();
}
});
if(options && options.length>0) {
newOption = document.createElement("option")
newOption.text = 'Choose an option'
newOption.value = null
input.add(newOption)
for(const option of options) {
newOption = document.createElement("option")
newOption.text = option
newOption.value = option
input.add(newOption)
}
}
else {
newOption = document.createElement("option")
newOption.text = 'No option available'
newOption.value = null
input.add(newOption)
input.setAttribute('disabled', 'false')
}
return input
} catch(err) {
throw err
}
}
/**
*
* @param {*} event
*/
const handleInput = (event) => {
const { id, value, style} = event.target
try {
const validation = validateInput(id, value)
if(!validation.valid) {
event.target.classList.remove('input-valid')
event.target.classList.add('input-invalid')
} else {
event.target.classList.remove('input-ivalid')
event.target.classList.add('input-valid')
}
} catch(err) {
throw err
}
}
const handleOpen = (event) => {
const [id, value, style] = [
event.currentTarget.id,
$(event.currentTarget).val(),
event.currentTarget.style
]
console.log(id);
event.find("input").focus();
// const dropdowns = $('.dropdown-input').search();
// dropdowns.focus();
}
const handleDropdown = (event) => {
const [id, value, style] = [
event.currentTarget.id,
$(event.currentTarget).val(),
event.currentTarget.style
]
try {
const validation = validateInput(id, value)
if(!validation.valid) {
$(`#${id}`).select2({
selectionCssClass: 'input-invalid'
})
} else {
$(`#${id}`).select2({
selectionCssClass: 'input-valid'
})
}
} catch(err) {
throw err
}
}
/**
*
* @param {*} elementID
* id of element containing the input fields
*/
const clearFields = (elementID) => {
try{
const element = document.getElementById(elementID)
element.innerHTML = ''
} catch(err) {
throw err
}
}
/**
*
* @param {*} section
* section in schema.
* @returns
* div with the deconsctructed section
*/
const deconstruct = (section, div, classAttribute) => {
try {
for(const key in section) {
const { fieldLabel } = section[key]
const validation = getValidation(key)
const newField = document.createElement('div') // will contain input field and label
newField.setAttribute('class', 'fieldContainer ' + classAttribute)
div.appendChild(newField)
const labelContainer = document.createElement('div') // name beside input field
labelContainer.setAttribute('class', 'labelContainer ' + classAttribute)
newField.appendChild(labelContainer)
const label = document.createElement('label')
label.textContent = fieldLabel ? fieldLabel : `Missing label`
label.style.color = fieldLabel ? '#000000' : '#ff3333'
labelContainer.appendChild(label)
const inputContainer = document.createElement('div') // input field
inputContainer.setAttribute('class', 'inputContainer ' + classAttribute)
newField.appendChild(inputContainer)
let input
switch(fieldLabel && validation && validation.collection) {
case 'alphanumeric':
case 'alphabet':
input = inputString(key, validation)
break
case 'specific':
case 'dropdown':
input = inputDropdown(key, validation)
break
case 'numeric':
input = inputNumeric(key, validation)
break
case 'date':
case 'datepicker':
input = inputDate(key, validation)
break
default:
input = noValidation()
break
}
input.setAttribute('class', classAttribute)
input.classList.add('inputField')
inputContainer.appendChild(input)
}
return div
} catch(err) {
throw err
}
}
/**
*
* @param {*} fieldLabel
* to be written as field label of the dropdown
* @returns
* div with the deconsctructed section
*/
const createDocTypeDropdown = (fieldLabel, div, options) => {
try {
const newField = document.createElement('div') // will contain input field and label
newField.setAttribute('class', 'fieldContainer')
div.appendChild(newField)
const labelContainer = document.createElement('div') // name beside input field
labelContainer.setAttribute('class', 'labelContainer')
newField.appendChild(labelContainer)
const label = document.createElement('label')
label.textContent = fieldLabel ? fieldLabel : `Missing label`
label.style.color = fieldLabel ? '#000000' : '#ff3333'
labelContainer.appendChild(label)
const inputContainer = document.createElement('div') // input field
inputContainer.setAttribute('class', 'inputContainer')
newField.appendChild(inputContainer)
const docTypeDropDown = document.createElement('select')
docTypeDropDown.setAttribute('id', fieldLabel)
docTypeDropDown.classList.add('dropdown-input')
let ctr = 0;
for(const option in options) {
newOption = document.createElement("option")
newOption.text = option
ctr++
newOption.value = ctr
docTypeDropDown.add(newOption)
}
docTypeDropDown.classList.add('inputField')
inputContainer.appendChild(docTypeDropDown)
return div
} catch(err) {
throw err
}
}
/**
*
* @param {*} fieldLabel
* to be written as field label of the dropdown
* @returns
* div with the deconsctructed section
*/
const createSection = (fieldLabel, div) => {
try {
const newField = document.createElement('div') // will contain input field and label
newField.setAttribute('class', 'fieldContainer')
div.appendChild(newField)
const labelContainer = document.createElement('div') // name beside input field
labelContainer.setAttribute('class', 'labelContainer')
newField.appendChild(labelContainer)
const label = document.createElement('label')
label.textContent = fieldLabel ? fieldLabel : `Missing label`
label.style.color = fieldLabel ? '#000000' : '#ff3333'
labelContainer.appendChild(label)
const inputContainer = document.createElement('div') // input field
inputContainer.setAttribute('class', 'inputContainer')
newField.appendChild(inputContainer)
const docTypeDropDown = document.createElement('select')
docTypeDropDown.setAttribute('id', fieldLabel)
docTypeDropDown.classList.add('dropdown-input')
docTypeDropDown.classList.add('inputField')
inputContainer.appendChild(docTypeDropDown)
return div
} catch(err) {
throw err
}
}
\ No newline at end of file
var coordinatesData;
var highlightCanvas;
var ctx;
var isCanvasNotCreated = true;
var isInitialPositioning = true;
var resizeWidthVal;
var resizeHeightVal;
var currIdVal;
var rect;
//creates the canvas for highlight rectangles
function createHighlight(width, height){
highlightCanvas = document.createElement('canvas');
highlightCanvas.id = "highlightCanvas";
ctx = highlightCanvas.getContext("2d");
highlightCanvas.classList.add("TiffViewer_imgclass");
// document.getElementById('TiffViewer_ImageContainer').append(highlightCanvas);
//inserts canvas before the TIFF image to fix its position at the top/first page
var imgContainer = document.getElementById('TiffViewer_ImageContainer');
imgContainer.insertBefore(highlightCanvas, imgContainer.firstChild);
//set style for highlight canvas
//z-index is increased to put it above the TIFF image
highlightCanvas.style.position = "absolute";
// highlightCanvas.style.width = width;
// highlightCanvas.style.height = height;
highlightCanvas.setAttribute("width", width);
highlightCanvas.setAttribute("height", height);
highlightCanvas.style.zIndex = "20";
}
//function for drawing translucent rectangle
function highlight(nameVal){
for(var i=0; i<coordinatesData.length; i++){
if(nameVal.toUpperCase().localeCompare(coordinatesData[i].FieldName.toUpperCase())==0){
//clears the canvas
ctx.clearRect(0, 0, highlightCanvas.width, highlightCanvas.height);
//resize factor for image
resizeWidthVal = highlightCanvas.width/2550;
resizeHeightVal = highlightCanvas.height/4200;
//split by '~', and create an array of the splitted chars
//format: rotation~zoom~scrollx~scrolly~left~top~width~height~pageno~imagename~annotationtype~highlightcolor
const fieldHighlightData = coordinatesData[i].Default_Annotation.split(/~+/);
//indicates color and opacity of shape
//fieldHighlightData[10] is the string already in RGB format (e.g. 255,255,0)
//uses coordinates given in coordinates text file
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = `rgba(${fieldHighlightData[10]})`;
ctx.rect(Math.round(fieldHighlightData[4]*resizeWidthVal),Math.round(fieldHighlightData[5]*resizeHeightVal),Math.round(fieldHighlightData[6]*resizeWidthVal),Math.round(fieldHighlightData[7]*resizeHeightVal));
ctx.stroke();
break;
}
}
}
function resizeHighlightCanvas(width, height, left){
resizeWidthVal = highlightCanvas.width*(width/highlightCanvas.width);
resizeHeightVal = highlightCanvas.height*(height/highlightCanvas.height);
highlightCanvas.style.width = resizeWidthVal;
highlightCanvas.style.height = resizeHeightVal;
// highlightCanvas.style.left = `${left}px`;
}
//flips the canvas horizontally by scaling it (ctx.scale) to its reverse x position
function flipXHighlightCanvas(idVal){
ctx.translate(highlightCanvas.width, 0);
ctx.scale(-1, 1);
highlight(idVal);
}
//flips the canvas vertically by scaling it (ctx.scale) to its reverse y position
function flipYHighlightCanvas(idVal){
ctx.translate(0, highlightCanvas.height);
ctx.scale(1, -1);
highlight(idVal);
}
function initHighlight() {
//tab traversal event listener
$(document).on('keyup', '.select2.select2-container', function (e) {
if (e.which == 9) {
//gets the id of the focused select element by using Tab key
const idArr = e.target.childNodes[0].id.split(/-container|select2-/);
//array created ALWAYS has empty characters on its first and last chars ["", "Civil Status", ""],
//so index 1 is used to get select element ID
highlight(idArr[1]);
currIdVal = idArr[1];
}
});
window.addEventListener("keydown", (e) => {
if (e.ctrlKey && e.shiftKey && e.key === "H") {
flipXHighlightCanvas(currIdVal);
isInitialPositioning = false;
}
})
window.addEventListener("keydown", (e) => {
if (e.ctrlKey && e.shiftKey && e.key === "V") {
flipYHighlightCanvas(currIdVal);
}
})
//waits for flip buttons to be created before adding event listeners for adjusting highlights
const flipBtnObserver = new MutationObserver(function (mutations, mutationInstance){
const flipBtnX = document.getElementById("TiffViewer_FlipX");
const flipBtnY = document.getElementById("TiffViewer_FlipY");
if(flipBtnX){
flipBtnX.addEventListener("click", function(){
flipXHighlightCanvas(currIdVal);
});
flipBtnY.addEventListener("click", function(){
flipYHighlightCanvas(currIdVal);
});
mutationInstance.disconnect();
}
});
flipBtnObserver.observe(document, {
childList: true,
subtree: true
});
//waits for fields to be created before adding event listeners
const fieldObserver = new MutationObserver(function (mutations, mutationInstance) {
//find input elements inside div element with id='fields'
const fields = document.getElementById('fields').querySelectorAll('input, textarea');
if (fields.length>0) {
fields.forEach((field) => {
//event listener when a field is focused
field.addEventListener('focus', (e) =>{
// flippedH = false;
highlight(e.target.id);
currIdVal = e.target.id;
})
});
//open dropdown list event listener
//find select elements in div with id='fields'
$('#fields').find('select').each(function() {
$(this).on('select2:open', function (e) {
highlight($(this)[0].id);
currIdVal = $(this)[0].id;
});
});
mutationInstance.disconnect();
}
});
fieldObserver.observe(document, {
childList: true,
subtree: true
});
//waits until TIFF image is loaded, since its size is based on the displayed TIFF image
const observer = new MutationObserver(function (mutations, mutationInstance) {
const TIFFimg = document.getElementById('IMG1');
if (TIFFimg) {
//waits until width and height has been assigned
var sizeObserver = new window.ResizeObserver(entries => {
if(isCanvasNotCreated){
rect = document.getElementById("IMG1").getBoundingClientRect();
// createHighlight(entries[0].contentRect.width, entries[0].contentRect.height);
createHighlight(entries[0].contentRect.width, entries[0].contentRect.height);
isCanvasNotCreated = false;
ctx.clearRect(0, 0, highlightCanvas.width, highlightCanvas.height);
}
else{
rect = document.getElementById("IMG1").getBoundingClientRect();
if(isInitialPositioning){
resizeHighlightCanvas(entries[0].contentRect.width, entries[0].contentRect.height, (rect.left-263));
}
else{
resizeHighlightCanvas(entries[0].contentRect.width, entries[0].contentRect.height, (rect.left));
isInitialPositioning = true;
}
}
$(document).ready(function () {
$('form:first *:input[type!=hidden]:first').focus(); // Run code
});
});
sizeObserver.observe(TIFFimg);
mutationInstance.disconnect();
}
});
observer.observe(document, {
childList: true,
subtree: true
});
};
fetch(HIGH_LIGHT_SCHEMA)
.then(res => {
return res.arrayBuffer();
}).then(res => {
var workbook = XLSX.read(new Uint8Array(res), {
type: "array"
});
data = workbook.Sheets["Sheet5"]
const importRange = "B3:C109";
const headers = ["FieldName", "Default_Annotation"];
coordinatesData = XLSX.utils.sheet_to_json(data, {range: importRange, header: headers});
});
\ No newline at end of file
const init = () => {
let started_flag = false;
displayFields("fields");
accessFile();
window.onkeydown = (key) => {
if (!started_flag) {
if (searchStringInArray(`${key.key}`, keyArray) == true || key.ctrlKey && key.key) {
console.log('Invalid key cannot Start');
} else {
started_flag = true;
startMetricCapture();
}
}
}
}
const refresh = () => {
let started_flag = false;
displayFields("fields");
refreshImage();
window.onkeydown = (key) => {
if (!started_flag) {
if (searchStringInArray(`${key.key}`, keyArray) == true || key.ctrlKey && key.key) {
console.log('Invalid key cannot Start');
} else {
started_flag = true;
startMetricCapture();
}
}
}
}
function searchStringInArray(str, strArray) {
for (var j = 0; j < strArray.length; j++) {
if (strArray[j] == str) return true;
}
return false;
}
{
"SECTION":
{
"Surname":
{
"fieldLabel": "Surname",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Religion":
{
"fieldLabel": "Religion",
"validation":
{
"fieldLength": 30,
"collection": "alphabet"
}
},
"Place_of_Birth":
{
"fieldLabel": "Place of Birth",
"validation":
{
"fieldLength": 50,
"collection": "alphanumeric",
"mandatory": true,
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Birthdate":
{
"fieldLabel": "Birthdate",
"validation":
{
"fieldLength": 10,
"collection": "datepicker",
"regexformat": "(^0[0-9]|^1[012])[-](0[0-9]|[12][0-9]|3[01])[-]((19\\d\\d)|(200[0-9])|(201[0-9])|(202[0])|0000)",
"mandatory": true
}
},
"Age":
{
"fieldLabel": "Age",
"validation":
{
"fieldLength": 2,
"collection": "numeric",
"mandatory": true
}
},
"Gender":
{
"fieldLabel": "Gender",
"validation":
{
"fieldLength": 1,
"collection": "dropdown",
"options": ["M", "F"],
"mandatory": true
}
},
"Civil_Status":
{
"fieldLabel": "Civil Status",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Single", "Married", "Widowed"],
"mandatory": true
}
},
"Nationality":
{
"fieldLabel": "Nationality",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Filipino", "Foreigner"],
"mandatory": true
}
},
"Height_in_Cm":
{
"fieldLabel": "Height (in cm)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
},
"Weight_in_Kg":
{
"fieldLabel": "Weight (in kg)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
}
}
}
\ No newline at end of file
{
"SECTION":
{
"Surname":
{
"fieldLabel": "Surname",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"House_Number":
{
"fieldLabel": "House Number",
"validation":
{
"fieldLength": 15,
"collection": "alphanumeric",
"invalidchar": "`~!@&$%^*_={}[]:;\"|\\<>"
}
},
"Street":
{
"fieldLabel": "Street",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Village_Subdivision":
{
"fieldLabel": "Village/Subdivision",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Municipality_City_Province":
{
"fieldLabel": "Municipality/City/Province",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"mandatory": true,
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Years_of_Stay":
{
"fieldLabel": "Years of Stay",
"validation":
{
"fieldLength": 2,
"collection": "numeric"
}
},
"Religion":
{
"fieldLabel": "Religion",
"validation":
{
"fieldLength": 30,
"collection": "alphabet"
}
},
"Place_of_Birth":
{
"fieldLabel": "Place of Birth",
"validation":
{
"fieldLength": 50,
"collection": "alphanumeric",
"mandatory": true,
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Birthdate":
{
"fieldLabel": "Birthdate",
"validation":
{
"fieldLength": 10,
"collection": "datepicker",
"regexformat": "(^0[0-9]|^1[012])[-](0[0-9]|[12][0-9]|3[01])[-]((19\\d\\d)|(200[0-9])|(201[0-9])|(202[0])|0000)",
"mandatory": true
}
},
"Age":
{
"fieldLabel": "Age",
"validation":
{
"fieldLength": 2,
"collection": "numeric",
"mandatory": true
}
},
"Gender":
{
"fieldLabel": "Gender",
"validation":
{
"fieldLength": 1,
"collection": "dropdown",
"options": ["M", "F"],
"mandatory": true
}
},
"Civil_Status":
{
"fieldLabel": "Civil Status",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Single", "Married", "Widowed"],
"mandatory": true
}
},
"Nationality":
{
"fieldLabel": "Nationality",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Filipino", "Foreigner"],
"mandatory": true
}
},
"Height_in_Cm":
{
"fieldLabel": "Height (in cm)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
},
"Weight_in_Kg":
{
"fieldLabel": "Weight (in kg)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
}
}
}
\ No newline at end of file
{
"SECTION":
{
"Surname":
{
"fieldLabel": "Surname",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Middle_Name":
{
"fieldLabel": "Middle Name",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Nickname":
{
"fieldLabel": "Nickname",
"validation":
{
"fieldLength": 15,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Email_Address":
{
"fieldLabel": "Email Address",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric"
}
},
"Mobile_Number":
{
"fieldLabel": "Mobile Number",
"validation":
{
"fieldLength": 15,
"collection": "numeric"
}
},
"Telephone_Number":
{
"fieldLabel": "Telephone Number",
"validation":
{
"fieldLength": 15,
"collection": "numeric"
}
},
"House_Number":
{
"fieldLabel": "House Number",
"validation":
{
"fieldLength": 15,
"collection": "alphanumeric",
"invalidchar": "`~!@&$%^*_={}[]:;\"|\\<>"
}
},
"Street":
{
"fieldLabel": "Street",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Village_Subdivision":
{
"fieldLabel": "Village/Subdivision",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Municipality_City_Province":
{
"fieldLabel": "Municipality/City/Province",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"mandatory": true,
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Years_of_Stay":
{
"fieldLabel": "Years of Stay",
"validation":
{
"fieldLength": 2,
"collection": "numeric"
}
},
"Religion":
{
"fieldLabel": "Religion",
"validation":
{
"fieldLength": 30,
"collection": "alphabet"
}
},
"Place_of_Birth":
{
"fieldLabel": "Place of Birth",
"validation":
{
"fieldLength": 50,
"collection": "alphanumeric",
"mandatory": true,
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Birthdate":
{
"fieldLabel": "Birthdate",
"validation":
{
"fieldLength": 10,
"collection": "datepicker",
"regexformat": "(^0[0-9]|^1[012])[-](0[0-9]|[12][0-9]|3[01])[-]((19\\d\\d)|(200[0-9])|(201[0-9])|(202[0])|0000)",
"mandatory": true
}
},
"Age":
{
"fieldLabel": "Age",
"validation":
{
"fieldLength": 2,
"collection": "numeric",
"mandatory": true
}
},
"Gender":
{
"fieldLabel": "Gender",
"validation":
{
"fieldLength": 1,
"collection": "dropdown",
"options": ["M","F"],
"mandatory": true
}
},
"Civil_Status":
{
"fieldLabel": "Civil Status",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Single", "Married", "Widowed"]
}
},
"Nationality":
{
"fieldLabel": "Nationality",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Filipino", "Foreigner"],
"mandatory": true
}
},
"Height_in_Cm":
{
"fieldLabel": "Height (in cm)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
},
"Weight_in_Kg":
{
"fieldLabel": "Weight (in kg)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
}
}
}
\ No newline at end of file
{
"SECTION":
{
"Surname":
{
"fieldLabel": "Surname",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Religion":
{
"fieldLabel": "Religion",
"validation":
{
"fieldLength": 30,
"collection": "alphabet"
}
},
"Birthdate":
{
"fieldLabel": "Birthdate",
"validation":
{
"fieldLength": 10,
"collection": "datepicker",
"mandatory": true
}
},
"Age":
{
"fieldLabel": "Age",
"validation":
{
"fieldLength": 2,
"collection": "numeric",
"mandatory": true
}
},
"Civil_Status":
{
"fieldLabel": "Civil Status",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Single", "Married", "Widowed"],
"mandatory": true
}
}
}
}
\ No newline at end of file
{
"SECTION":
{
"Payee":
{
"fieldLabel": "Payee",
"page": 1,
"validation":
{
"fieldLength": 50,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Particulars":
{
"fieldLabel": "Particulars",
"validation":
{
"fieldLength": 200,
"collection": "alphanumeric",
"mandatory": true
}
},
"Account_No":
{
"fieldLabel": "Account No",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Transaction_Date":
{
"fieldLabel": "Transaction Date",
"validation":
{
"fieldLength": 10,
"collection": "datepicker",
"mandatory": true
}
}
}
}
{
"ACCOUNTING_DOCUMENTS":
{
"SECTION1":
{
"Name":
{
"fieldLabel": "Name",
"aka": "field7",
"validation":
{
"fieldLength": 100,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Subject":
{
"fieldLabel": "Subject",
"aka": "field8",
"validation":
{
"fieldLength": 200,
"collection": "alphanumeric",
"mandatory": true
}
},
"Document_No":
{
"fieldLabel": "Document Number",
"aka": "field6",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Date":
{
"fieldLabel": "Date",
"aka": "field5",
"validation":
{
"fieldLength": 20,
"collection": "datepicker",
"mandatory": true
}
}
}
},
"BANK_APPLICATION_FORM":
{
"SECTION2":
{
"Name":
{
"fieldLabel": "Name",
"aka": "field3",
"validation":
{
"fieldLength": 100,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Account_No":
{
"fieldLabel": "Account Number",
"aka": "field4",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Date":
{
"fieldLabel": "Date",
"aka": "field2",
"validation":
{
"fieldLength": 20,
"collection": "datepicker",
"mandatory": true
}
}
}
},
"HR_FILES":
{
"SECTION3":
{
"Name":
{
"fieldLabel": "Name",
"aka": "field10",
"validation":
{
"fieldLength": 100,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Subject":
{
"fieldLabel": "Subject",
"aka": "field12",
"validation":
{
"fieldLength": 200,
"collection": "alphanumeric",
"mandatory": true
}
},
"Employee_No":
{
"fieldLabel": "Employee_No",
"aka": "field11",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Date":
{
"fieldLabel": "Date",
"aka": "field9",
"validation":
{
"fieldLength": 20,
"collection": "datepicker",
"mandatory": true
}
}
}
}
}
{
"SECTION":
{
"Surname":
{
"fieldLabel": "Surname",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"First_Name":
{
"fieldLabel": "First Name",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Middle_Name":
{
"fieldLabel": "Middle Name",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Nickname":
{
"fieldLabel": "Nickname",
"validation":
{
"fieldLength": 15,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Email_Address":
{
"fieldLabel": "Email Address",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric"
}
},
"Mobile_Number":
{
"fieldLabel": "Mobile Number",
"validation":
{
"fieldLength": 15,
"collection": "numeric"
}
},
"Telephone_Number":
{
"fieldLabel": "Telephone Number",
"validation":
{
"fieldLength": 15,
"collection": "numeric"
}
},
"House_Number":
{
"fieldLabel": "House Number",
"validation":
{
"fieldLength": 15,
"collection": "alphanumeric",
"invalidchar": "`~!@&$%^*_={}[]:;\"|\\<>"
}
},
"Street":
{
"fieldLabel": "Street",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Village_Subdivision":
{
"fieldLabel": "Village/Subdivision",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Municipality_City_Province":
{
"fieldLabel": "Municipality/City/Province",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"mandatory": true,
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Years_of_Stay":
{
"fieldLabel": "Years of Stay",
"validation":
{
"fieldLength": 2,
"collection": "numeric"
}
},
"Religion":
{
"fieldLabel": "Religion",
"validation":
{
"fieldLength": 30,
"collection": "alphabet"
}
},
"Place_of_Birth":
{
"fieldLabel": "Place of Birth",
"validation":
{
"fieldLength": 50,
"collection": "alphanumeric",
"mandatory": true,
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Birthdate":
{
"fieldLabel": "Birthdate",
"validation":
{
"fieldLength": 10,
"collection": "datepicker",
"regexformat": "(^0[0-9]|^1[012])[-](0[0-9]|[12][0-9]|3[01])[-]((19\\d\\d)|(200[0-9])|(201[0-9])|(202[0])|0000)",
"mandatory": true
}
},
"Age":
{
"fieldLabel": "Age",
"validation":
{
"fieldLength": 2,
"collection": "numeric",
"mandatory": true
}
},
"Gender":
{
"fieldLabel": "Gender",
"validation":
{
"fieldLength": 1,
"collection": "dropdown",
"options": ["M", "F"],
"mandatory": true
}
},
"Civil_Status":
{
"fieldLabel": "Civil Status",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Single", "Married", "Widowed"],
"mandatory": true
}
},
"Nationality":
{
"fieldLabel": "Nationality",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Filipino", "Foreigner"],
"mandatory": true
}
},
"Height_in_Cm":
{
"fieldLabel": "Height (in cm)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
},
"Weight_in_Kg":
{
"fieldLabel": "Weight (in kg)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
}
}
}
\ No newline at end of file
{
"SECTION":
{
"Surname":
{
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Gender":
{
"fieldLabel": "Gender",
"validation":
{
"fieldLength": 1,
"collection": "dropdown",
"options": [],
"mandatory": true
}
},
"Middle_Name":
{
"fieldLabel": "Middle Name"
},
"fieldLabel": "Nickname",
"validation":
{
"fieldLength": 15,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
},
"Email_Address":
{
"fieldLabel": "Email Address",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric"
}
}
}
}
\ No newline at end of file
{
"Surname":
{
"fieldLabel": "Surname",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*._={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Middle_Name":
{
"fieldLabel": "Middle Name",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>",
"mandatory": true
}
},
"Nickname":
{
"fieldLabel": "Nickname",
"validation":
{
"fieldLength": 15,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Email_Address":
{
"fieldLabel": "Email Address",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric"
}
},
"Mobile_Number":
{
"fieldLabel": "Mobile Number",
"validation":
{
"fieldLength": 15,
"collection": "numeric"
}
},
"Telephone_Number":
{
"fieldLabel": "Telephone Number",
"validation":
{
"fieldLength": 15,
"collection": "numeric"
}
},
"House_Number":
{
"fieldLabel": "House Number",
"validation":
{
"fieldLength": 15,
"collection": "alphanumeric",
"invalidchar": "`~!@&$%^*_={}[]:;\"|\\<>"
}
},
"Street":
{
"fieldLabel": "Street",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Village_Subdivision":
{
"fieldLabel": "Village/Subdivision",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Municipality_City_Province":
{
"fieldLabel": "Municipality/City/Province",
"validation":
{
"fieldLength": 30,
"collection": "alphanumeric",
"mandatory": true,
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Years_of_Stay":
{
"fieldLabel": "Years of Stay",
"validation":
{
"fieldLength": 2,
"collection": "numeric"
}
},
"Religion":
{
"fieldLabel": "Religion",
"validation":
{
"fieldLength": 30,
"collection": "alphabet"
}
},
"Place_of_Birth":
{
"fieldLabel": "Place of Birth",
"validation":
{
"fieldLength": 50,
"collection": "alphanumeric",
"mandatory": true,
"invalidchar": "`~!@#&$%^*_={}[]:;/\"|\\<>"
}
},
"Birthdate":
{
"fieldLabel": "Birthdate",
"validation":
{
"fieldLength": 10,
"collection": "datepicker",
"regexformat": "(^0[0-9]|^1[012])[-](0[0-9]|[12][0-9]|3[01])[-]((19\\d\\d)|(200[0-9])|(201[0-9])|(202[0])|0000)",
"mandatory": true
}
},
"Age":
{
"fieldLabel": "Age",
"validation":
{
"fieldLength": 2,
"collection": "numeric",
"mandatory": true
}
},
"Gender":
{
"fieldLabel": "Gender",
"validation":
{
"fieldLength": 1,
"collection": "dropdown",
"options": [],
"mandatory": true
}
},
"Civil_Status":
{
"fieldLabel": "Civil Status",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Single", "Married", "Widowed"],
"mandatory": true
}
},
"Nationality":
{
"fieldLabel": "Nationality",
"validation":
{
"fieldLength": 15,
"collection": "dropdown",
"options": ["Filipino", "Foreigner"],
"mandatory": true
}
},
"Height_in_Cm":
{
"fieldLabel": "Height (in cm)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
},
"Weight_in_Kg":
{
"fieldLabel": "Weight (in kg)",
"validation":
{
"fieldLength": 3,
"collection": "numeric"
}
}
}
\ No newline at end of file
const submitForm = (e) => {
try {
let eoe_ts = new Date().toLocaleString();
const Form = Settings.SrcElement(e);
const { elements } = Form
let error = false
let doctype;
let section;
// Validate all elements again
for(let element of elements) {
if (element.style.display === 'none') continue
const { id, value,type } = element
const { valid } = validateInput(id, value)
// Skip submit button
if(type==='submit') continue
if(id==='DocType') {
doctype = element.options[element.selectedIndex].text;
continue;
}
if(id==='Section') {
section = element.options[element.selectedIndex].text;
continue;
}
// Update display of input field if input is not valid
if(!valid) {
error = true
if(type==='select-one') {
continue
}
const field = document.getElementById(id)
const newEvent = new Event('focusout')
field.dispatchEvent(newEvent)
}
}
// Update display of dropdown field if input is not valid
const dropdowns = $('.dropdown-input').select2();
for(let dropdown of dropdowns) {
const newEvent = new Event('select2:close')
dropdown.dispatchEvent(newEvent)
}
if(error) {
alert('Invalid or Missing data on highlighted fields!')
return false
}
else {
if(IS_RETRIEVE_FROM_GFS == "Y"){
const container = document.querySelector('#containerModal' + sessionStorage.getItem('gfsCounter'));
const label = container.querySelector("div.tiffViewerHeader .tiffViewerPageInfo label");
File_Name = label.innerText;
File_Path = label.innerText;
}
const metrics = stopMetricCapture();
WriteForm(e, metrics, doctype, section);
saveMetrics(metrics, eoe_ts);
[...document.getElementsByClassName("TiffModalContent")].forEach(el => {
while (el.children[1].hasChildNodes()) {
el.children[1].removeChild(el.children[1].firstChild);
}
while (el.children[2].hasChildNodes()) {
el.children[2].removeChild(el.children[2].firstChild);
}
while (el.children[3].hasChildNodes()) {
el.children[3].removeChild(el.children[3].firstChild);
}
});
[...document.getElementsByClassName("bar")].forEach(el => {
el.style.removeProperty('display');
});
document.getElementById("counter").innerHTML = "";
clearTimeout(interval);
isCanvasNotCreated = true;
if(IS_RETRIEVE_FROM_GFS != "Y"){
init();
}else{
var current = document.getElementById('containerModal' + sessionStorage.getItem('gfsCounter'));
current.style.display = 'none';
var next = document.getElementById('containerModal' + (parseInt(sessionStorage.getItem('gfsCounter')) + 1));
if(next){
next.style.display = 'block';
}else{
promptNoFilesLeft();
//disableForm();
}
var counter = parseInt(sessionStorage.getItem('gfsCounter'));
sessionStorage.setItem('gfsCounter', counter + 1);
refresh();
}
return true
}
} catch(err) {
console.log(err)
return false
}
}
\ No newline at end of file
function tiffViewerTest(xhr, overlay, name){
let images = [];
let imagesTranformVal = [];
let tiff = new Tiff({ buffer: xhr });
let pageFlag = 0;
let pages = tiff.countDirectory();
console.log(pages);
let header = document.createElement("div");
header.classList.add("tiffViewerHeader");
let container = document.createElement("div");
container.classList.add("tiffViewerContainer");
let footer = document.createElement("div");
footer.classList.add("tiffViewerFooter");
for (var i = 0; i <= pages; i++) {
let img = document.createElement('img');
img.classList.add("tiffViewerImg");
tiff.setDirectory(i);
var canvas = tiff.toCanvas().toDataURL();
img.src = canvas;
if(i != 0){
img.style.display = "none";
}
images.push(img);
imagesTranformVal.push({scaleX:1,scaleY:1,rotate:0});
container.append(img);
}
overlay.append(header);
overlay.append(container);
overlay.append(footer);
//create Header
let tiffInfoContainer = document.createElement("div");
tiffInfoContainer.classList.add("tiffViewerPageInfo");
let infoLabel = document.createElement("label");
infoLabel.textContent = name;
let pagerContainer = document.createElement("div");
pagerContainer.classList.add("tiffViewerPagePagerContainer");
let prevPage = document.createElement("div");
prevPage.textContent = "<";
let pageLabel = document.createElement("label");
pageLabel.textContent = (pageFlag + 1) + "/" + (images.length - 1);
let nextPage = document.createElement("div");
nextPage.textContent = ">";
tiffInfoContainer.append(infoLabel);
pagerContainer.append(prevPage);
pagerContainer.append(pageLabel);
pagerContainer.append(nextPage);
header.append(tiffInfoContainer);
header.append(pagerContainer);
//create Footer
let fullscreen = document.createElement("button");
fullscreen.textContent = "Fullscreen";
let rotateLeft = document.createElement("button");
rotateLeft.textContent = "Rotate left";
let rotateRight = document.createElement("button");
rotateRight.textContent = "Rotate right";
let flipH = document.createElement("button");
flipH.textContent = "Flip Horizontal";
let flipV = document.createElement("button");
flipV.textContent = "Flip Vertical";
let fitContentButton = document.createElement("button");
fitContentButton.textContent = "Fit Content";
let zoomInButton = document.createElement("button");
zoomInButton.textContent = "Zoom in";
let zoomOutButton = document.createElement("button");
zoomOutButton.textContent = "Zoom out";
footer.append(fullscreen);
footer.append(rotateLeft);
footer.append(rotateRight);
footer.append(flipH);
footer.append(flipV);
footer.append(fitContentButton);
footer.append(zoomInButton);
footer.append(zoomOutButton);
//events
nextPage.addEventListener("click", function(){
if(pageFlag < (images.length - 2) ){
pageFlag++;
}else{
pageFlag = 0;
}
for(let image of images){
image.style.display = "none";
}
console.log(pageFlag);
images[pageFlag].style.display = "block";
pageLabel.textContent = (pageFlag + 1) + "/" + (images.length - 1);
});
prevPage.addEventListener("click", function(){
if(pageFlag != 0 ){
pageFlag--;
}else{
pageFlag = images.length - 2;
}
for(let image of images){
image.style.display = "none";
}
console.log(pageFlag);
images[pageFlag].style.display = "block";
pageLabel.textContent = (pageFlag + 1) + "/" + (images.length - 1);
});
zoomInButton.addEventListener("click", function(){
console.log(images[pageFlag].style.width);
let newWidth = images[pageFlag].width + (images[pageFlag].width * .10);
images[pageFlag].style.width = newWidth + "px";
});
zoomOutButton.addEventListener("click", function(){
console.log(images[pageFlag].style.width);
let newWidth = images[pageFlag].width - (images[pageFlag].width * .10);
if(newWidth< 0){
newWidth = 100;
}
images[pageFlag].style.width = newWidth + "px";
});
fitContentButton.addEventListener("click", function(){
images[pageFlag].style.width = "100%";
});
flipH.addEventListener("click", function(){
let transformVal = imagesTranformVal[pageFlag];
console.log(transformVal);
let scaleX = transformVal.scaleX;
let scaleY = transformVal.scaleY;
let rotate = transformVal.rotate;
if(scaleX === 1){
transformVal.scaleX = -1;
}else{
transformVal.scaleX = 1;
}
images[pageFlag].style.msTransform = "rotate(" + rotate + "deg) scale("+ transformVal.scaleX + ","+ scaleY +")";
images[pageFlag].style.transform = "rotate(" + rotate + "deg) scale("+ transformVal.scaleX + ","+ scaleY +")";
});
flipV.addEventListener("click", function(){
let transformVal = imagesTranformVal[pageFlag];
console.log(transformVal);
let scaleX = transformVal.scaleX;
let scaleY = transformVal.scaleY;
let rotate = transformVal.rotate;
if(scaleY === 1){
transformVal.scaleY = -1;
}else{
transformVal.scaleY = 1;
}
images[pageFlag].style.msTransform = "rotate(" + rotate + "deg) scale("+ scaleX + ","+ transformVal.scaleY +")";
images[pageFlag].style.transform = "rotate(" + rotate + "deg) scale("+ scaleX + ","+ transformVal.scaleY +")";
});
rotateLeft.addEventListener("click", function(){
let transformVal = imagesTranformVal[pageFlag];
console.log(transformVal);
let scaleX = transformVal.scaleX;
let scaleY = transformVal.scaleY;
let rotate = transformVal.rotate;
if(rotate == -270){
transformVal.rotate = 0;
}else{
transformVal.rotate = rotate - 90;
}
images[pageFlag].style.msTransform = "rotate(" + transformVal.rotate + "deg) scale("+ scaleX + ","+ scaleY +")";
images[pageFlag].style.transform = "rotate(" + transformVal.rotate + "deg) scale("+ scaleX + ","+ scaleY +")";
});
rotateRight.addEventListener("click", function(){
let transformVal = imagesTranformVal[pageFlag];
console.log(transformVal);
let scaleX = transformVal.scaleX;
let scaleY = transformVal.scaleY;
let rotate = transformVal.rotate;
if(rotate == 270){
transformVal.rotate = 0;
}else{
transformVal.rotate = rotate + 90;
}
images[pageFlag].style.msTransform = "rotate(" + transformVal.rotate + "deg) scale("+ scaleX + ","+ scaleY +")";
images[pageFlag].style.transform = "rotate(" + transformVal.rotate + "deg) scale("+ scaleX + ","+ scaleY +")";
});
fullscreen.addEventListener("click", function(){
if (overlay.requestFullscreen) {
overlay.requestFullscreen();
} else if (overlay.webkitRequestFullscreen) { /* Safari */
overlay.webkitRequestFullscreen();
} else if (overlay.msRequestFullscreen) { /* IE11 */
overlay.msRequestFullscreen();
}
});
}
\ No newline at end of file
.tiffViewerContainer {
margin: auto;
height: calc(100% - 60px);
width: 70%;
position: relative;
display: block;
overflow: auto;
}
.tiffViewerHeader {
margin: auto;
height: 30px;
width: 70%;
display: block;
background-color: #686868;
}
.tiffViewerFooter{
margin: auto;
height: 30px;
width: 70%;
display: block;
background-color: #ffffff;
}
.tiffViewerImg{
display: block;
width: 100%;
margin-bottom: 4px;
margin: auto;
}
.tiffViewerPageInfo{
height: calc(100% - 4px);
text-align: left;
text-indent: 7px;
padding-top: 4px;
display: inline-block;
width: calc(100% - 200px);
position: relative;
vertical-align: top;
}
.tiffViewerPageInfo label{
color: white;
font-size: 18px;
}
.tiffViewerPagePagerContainer{
width: 200px;
display: inline-block;
height: 100%;
}
.tiffViewerPagePagerContainer div{
width: 30px;
height: calc(100% - 3px);
font-size: 20px;
font-weight: bolder;
color: white;
padding-top: 3px;
display: inline-block;
background-color: #353535;
cursor: pointer;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Old versions of Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome, Edge, Opera and Firefox */
}
.tiffViewerPagePagerContainer div:hover{
-webkit-transform: scale(1.1);
transform: scale(1.1);
}
.tiffViewerPagePagerContainer div:active{
-webkit-transform: scale(1.0);
transform: scale(1.0);
}
.tiffViewerPagePagerContainer label{
font-size: 17px;
font-weight: bolder;
color: white;
padding-top: 3px;
display: inline-block;
cursor: pointer;
margin-left: 10px;
margin-right: 10px;
}
.tiffViewerFooter button{
border: 1px solid gray;
width: fit-content;
height: 26px;
font-size: 15px;
margin-top: 2px;
cursor:pointer;
}
.tiffViewerFooter button:hover{
-webkit-transform: scale(1.1);
transform: scale(1.1);
}
.tiffViewerFooter button:active{
-webkit-transform: scale(1.0);
transform: scale(1.0);
}
//Run TIFF Viewer Widget
// (async () => {
// console.log("waiting for variable");
// while (url == undefined) // define the condition as you like
// await new Promise(resolve => setTimeout(resolve, 1000));
// window.addEventListener("load", loadDoc("input/SVI Internship Application Form - FELIZARDO, BRYLLE.TIFF", TIFFViewer), false);
// console.log("variable is defined");
// })();
//Get Modal as Variables
const TiffViewer_Header = document.getElementById("TiffModalHeader");
const TiffViewer_Body = document.getElementById("TiffModalBody");
const TiffViewer_Footer = document.getElementById("TiffModalFooter");
// Get the modal
var modal = document.getElementById("TiffViewerModal");
// Get the button that opens the modal
var btn = document.getElementById("TestBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("TiffModalClose")[0];
// CHANGED: commented out onClick function to display modal upon page load
// When the user clicks the button, open the modal
// btn.onclick = function() {
// modal.style.display = "block";
// }
// When the user clicks on <span> (x), close the modal
// span.onclick = function() {
// modal.style.display = "none";
// }
// // When the user clicks anywhere outside of the modal, close it
// window.onclick = function(event) {
// if (event.target == modal) {
// modal.style.display = "none";
// }
// }
// // When the user presses down the ESC key on the keyboard, close the modal
// document.addEventListener("keydown", function(event) {
// const key = event.key; // Or const {key} = event; in ES6+
// if (key === "Escape") {
// modal.style.display = "none";
// }
// });
//XHR to Load Test TIFF Image
function loadDoc(url, cFunction,filename) {
Tiff.initialize({ TOTAL_MEMORY: 16777216 * 10 });
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var startIndex = (xhr.responseURL.indexOf('\\') >= 0 ? xhr.responseURL.lastIndexOf('\\') : xhr.responseURL.lastIndexOf('/'));
var TiffViewerImageName = xhr.responseURL.substring(startIndex);
if (TiffViewerImageName.indexOf('\\') === 0 || TiffViewerImageName.indexOf('/') === 0) {
if (TiffViewerImageName.length > 40) {
TiffViewerImageName = decodeURI(TiffViewerImageName); /* ADDED: replaces the %20 that replaces the spaces when file name is displayed */
TiffViewerImageName = TiffViewerImageName.substring(1, 40);
TiffViewerImageName = TiffViewerImageName.concat("...");
} else {
TiffViewerImageName = TiffViewerImageName.substring(1);
}
}
cFunction(xhr.response, filename);
}
};
xhr.open('GET', url, true);
xhr.send();
}
//Main Widget
function TIFFViewer(xhr, TiffViewerImageName) {
var buffer = xhr;
var TiffViewerImageName = TiffViewerImageName;
var flippedX = new Array(), flippedY = new Array(), rot = new Array(), checker = new Array();
var width = 0, height = 0; //changing variable for width and height
var origwidth = 0, origheight = 0, changedwidth = 0; changedheight = 0;
var setwidth = 0, setheight = 0; //constant variable for width and height
var editedwidth = 0, editedheight = 0; //checker of width and height change
var hpercent = 0, wpercent = 0; //set of percent increase or decrease per zoom
var hzoom = new Array(), wzoom = new Array(); //zoom data per page
let changed = false;
let TiffViewer_pages = 0; //page count
let TiffViewer_current = 1; // TiffViewer_current page number
//declaration of HTML Contents
const TiffViewer_detailcont = document.createElement("div");
TiffViewer_detailcont.id = "TiffViewerDetailscontainer";
TiffViewer_detailcont.classList.add("TiffViewercontainer");
const TiffViewer_filedetail = document.createElement('p');
TiffViewer_filedetail.id = "TiffViewerImageName";
TiffViewer_filedetail.style.display = "none";
TiffViewer_filedetail.innerHTML = "Filename: ";
const TiffViewer_pagedetail = document.createElement('p');
TiffViewer_pagedetail.id = "TiffViewer_PageCount";
TiffViewer_pagedetail.style.display = "none";
TiffViewer_pagedetail.innerHTML = "Page: ";
const TiffViewer_filecont = document.createElement("div");
TiffViewer_filecont.id = "TiffViewer_FileContainer";
TiffViewer_filecont.classList.add("TiffViewercontainer");
const TiffViewer_scrncont = document.createElement("div");
TiffViewer_scrncont.id = "TiffViewer_Screen";
const TiffViewer_imgcont = document.createElement("div");
TiffViewer_imgcont.id = "TiffViewer_ImageContainer"
const TiffViewer_btncont = document.createElement("div");
TiffViewer_btncont.id = "TiffViewer_ButtonContainer";
TiffViewer_btncont.classList.add("TiffViewercontainer");
const TiffViewer_hflip = document.createElement("button");
TiffViewer_hflip.id = "TiffViewer_FlipX";
TiffViewer_hflip.classList.add("TiffViewer_ButtonClass");
TiffViewer_hflip.innerHTML = "Flip Horizontally";
const TiffViewer_vflip = document.createElement("button");
TiffViewer_vflip.id = "TiffViewer_FlipY";
TiffViewer_vflip.classList.add("TiffViewer_ButtonClass");
TiffViewer_vflip.innerHTML = "Flip Vertically";
const TiffViewer_Rrotate = document.createElement("button");
TiffViewer_Rrotate.id = "TiffViewer_RotateR";
TiffViewer_Rrotate.classList.add("TiffViewer_ButtonClass");
TiffViewer_Rrotate.innerHTML = "Rotate to right";
const TiffViewer_Lrotate = document.createElement("button");
TiffViewer_Lrotate.id = "TiffViewer_RotateL";
TiffViewer_Lrotate.classList.add("TiffViewer_ButtonClass");
TiffViewer_Lrotate.innerHTML = "Rotate to left";
const TiffViewer_Pzoom = document.createElement("button");
TiffViewer_Pzoom.id = "TiffViewer_ZoomP";
TiffViewer_Pzoom.classList.add("TiffViewer_ButtonClass");
TiffViewer_Pzoom.innerHTML = "Zoom in";
const TiffViewer_Mzoom = document.createElement("button");
TiffViewer_Mzoom.id = "TiffViewer_ZoomM";
TiffViewer_Mzoom.classList.add("TiffViewer_ButtonClass");
TiffViewer_Mzoom.innerHTML = "Zoom out";
const TiffViewer_Pbtn = document.createElement("button");
TiffViewer_Pbtn.id = "TiffViewer_PrevButton";
TiffViewer_Pbtn.classList.add("TiffViewer_ButtonClass");
TiffViewer_Pbtn.innerHTML = "Previous";
TiffViewer_Pbtn.style.display = "none";
const TiffViewer_Nbtn = document.createElement("button");
TiffViewer_Nbtn.id = "TiffViewer_NextButton";
TiffViewer_Nbtn.classList.add("TiffViewer_ButtonClass");
TiffViewer_Nbtn.innerHTML = "Next";
TiffViewer_Nbtn.style.display = "none";
const TiffViewer_Fscrn = document.createElement("button");
TiffViewer_Fscrn.id = "TiffViewer_FullscreenButton";
TiffViewer_Fscrn.classList.add("TiffViewer_ButtonClass");
TiffViewer_Fscrn.innerHTML = "Fullscreen";
const TiffViewer_Fit = document.createElement("button");
TiffViewer_Fit.id = "TiffViewer_FitButton";
TiffViewer_Fit.classList.add("TiffViewer_ButtonClass");
TiffViewer_Fit.innerHTML = "Fit Content";
TiffViewer_Fit.style.display = "none";
//append all content declarations to modal
TiffViewer_Header.append(TiffViewer_detailcont);
TiffViewer_Body.append(TiffViewer_filecont);
TiffViewer_Footer.append(TiffViewer_btncont);
//append Contents to containers
TiffViewer_detailcont.append(TiffViewer_filedetail, TiffViewer_pagedetail);
TiffViewer_filecont.appendChild(TiffViewer_scrncont);
TiffViewer_scrncont.appendChild(TiffViewer_imgcont);
TiffViewer_btncont.append(TiffViewer_Fscrn, TiffViewer_Fit, TiffViewer_hflip, TiffViewer_vflip, TiffViewer_Rrotate, TiffViewer_Lrotate, TiffViewer_Pzoom, TiffViewer_Mzoom, TiffViewer_Pbtn, TiffViewer_Nbtn);
//get Content placeholders
const wrapper = document.querySelector("#TiffViewer_Screen"), header = wrapper.querySelector("#TiffViewer_ImageContainer");
var TiffViewer_scrn = document.getElementById('TiffViewer_Screen');
var TiffViewer_file = document.getElementById("TiffViewerImageName");
TiffViewer_file.append(TiffViewerImageName); //Append Filename to div placeholder
TiffViewer_file.style.display = "block"; //Show Filename
var tiff = new Tiff({ buffer: buffer }); //get TIFF data via buffer
TiffViewer_pages = tiff.countDirectory(); //count TIFF image TiffViewer_pages
//if TIFF page is greater than one, display Previous and TiffViewer_NextButton buttons
if (TiffViewer_pages > 1) {
document.getElementById("TiffViewer_PrevButton").style.display = "block";
document.getElementById("TiffViewer_NextButton").style.display = "block";
var TiffViewer_PageCount = document.getElementById("TiffViewer_PageCount");
var pageappend = TiffViewer_current + " / " + TiffViewer_pages;
TiffViewer_PageCount.append(pageappend); //display of page number
TiffViewer_PageCount.style.display = "block";
}
document.getElementById('TestTIFFDisplay').src = tiff.toCanvas().toDataURL();
//creating blank image containers for each page and setting TIFF data as image source
for (var i = 0; i < TiffViewer_pages; ++i) {
var img = document.createElement('img');
img.id = `IMG${i + 1}`;
if (i != 0) {
img.style.display = "none";
wzoom[TiffViewer_current - 1] = changedwidth; /*ADDED: to fit large TIFF files*/
hzoom[TiffViewer_current - 1] = changedheight;
Edited();
}
img.classList.add("TiffViewer_imgclass");
document.getElementById('TiffViewer_ImageContainer').append(img);
tiff.setDirectory(i);
var canvas = tiff.toCanvas().toDataURL();
document.getElementById(`IMG${i + 1}`).src = canvas;
}
//setting the style per page
for (var j = 1; j <= TiffViewer_pages; ++j) {
var img = document.getElementById("IMG" + j);
getMeta(canvas, function (width, height) {
wzoom[TiffViewer_current - 1] = changedwidth; /*ADDED: to fit large TIFF files*/
hzoom[TiffViewer_current - 1] = changedheight;
Edited(); origheight = height;
origwidth = width;
setwidth = width;
setheight = height;
//to only display single page
if (setheight > 800 && setwidth > 1000) {
if (setheight > setwidth) {
// img.style = "width: 870px; height: 1160px";
img.style = "width: 600; height: 800";
} else {
// img.style = "width: 800; height: 600";
//img.style = "width: 600; height: 800";
img.style = "width: 800; height: 600";
}
changed = true;
} else if (setwidth > 1000 && setheight <= 800) {
img.style = "width: 1000;";
changed = true;
} else if (setheight > 800 && setwidth <= 1000) {
img.style = "width: 800;";
changed = true;
}
if (changed) {
setwidth = parseInt(img.style.width, 10);
setheight = parseInt(img.style.height, 10);
document.getElementById("TiffViewer_FitButton").style.display = "block";
}
changedheight = setheight;
changedwidth = setwidth;
hpercent = (parseInt(setheight, 10) * (15 / 100));
wpercent = (parseInt(setwidth, 10) * (15 / 100));
hzoom.push(parseInt(setheight, 10));
wzoom.push(parseInt(setwidth, 10));
TiffViewer_scrn.style = `width: ${setwidth}; height: ${setheight};`;
document.getElementById("TiffViewer_FileContainer").style = `width: ${setwidth}; height: ${setheight};`;
TiffViewer_ImageContainer.style = `width: ${setwidth}; height: ${setheight};`;
});
checker.push(0);
flippedX.push(1);
flippedY.push(1);
rot.push(0);
if (j === 1) {
img.style.display = "flex";
}
}
//getting the metadata of each TIFF page
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function () { callback(this.width, this.height); }
}
//display image in fullscreen
document.getElementById("TiffViewer_FullscreenButton").onclick = function () {
var image = document.getElementById(`IMG${TiffViewer_current}`);
if (image.requestFullscreen) {
image.requestFullscreen();
}
else if (image.msRequestFullscreen) {
imagej.msRequestFullscreen();
}
else if (divObj.mozRequestFullScreen) {
image.mozRequestFullScreen();
}
else if (image.webkitRequestFullscreen) {
image.webkitRequestFullscreen();
} else {
console.log("Fullscreen API is not supported");
}
};
//Flip Horizontal
const flipH = document.getElementById("TiffViewer_FlipX");
flipH.addEventListener("click", flipHorizontal);
document.addEventListener("keydown", (e) => {
if (e.ctrlKey && e.shiftKey && e.key === "H") {
e.preventDefault();
flipHorizontal();
}
})
function flipHorizontal() {
if (flippedX[TiffViewer_current - 1] == 1) {
flippedX[TiffViewer_current - 1] = -1;
Edited();
}
else {
flippedX[TiffViewer_current - 1] = 1;
Edited();
}
};
//Flip Vertical
const flipV = document.getElementById("TiffViewer_FlipY");
flipV.addEventListener("click", flipVertical);
document.addEventListener("keydown", (e) => {
if (e.ctrlKey && e.shiftKey && e.key === "V") {
e.preventDefault();
flipVertical();
}
})
function flipVertical() {
if (flippedY[TiffViewer_current - 1] == '1') {
flippedY[TiffViewer_current - 1] = -1;
Edited();
}
else {
flippedY[TiffViewer_current - 1] = 1;
Edited();
}
};
//Rotate 90 degrees
const rotateR = document.getElementById("TiffViewer_RotateR");
rotateR.addEventListener("click", rotateClockwise);
document.addEventListener("keydown", (e) => {
if (e.shiftKey && e.key === "PageUp") {
e.preventDefault();
rotateClockwise();
}
})
function rotateClockwise() {
rot[TiffViewer_current - 1] += 90;
if ((rot[TiffViewer_current - 1] % 360) == 0) {
rot[TiffViewer_current - 1] = 0
}
Edited();
};
//Rotate -90 degrees
const rotateL = document.getElementById("TiffViewer_RotateL");
rotateL.addEventListener("click", rotateCounterClockwise);
document.addEventListener("keydown", (e) => {
if (e.shiftKey && e.key === "PageDown") {
e.preventDefault();
rotateCounterClockwise();
}
})
function rotateCounterClockwise() {
rot[TiffViewer_current - 1] -= 90;
if (rot[TiffViewer_current - 1] < 0) {
checker[TiffViewer_current - 1] = rot[TiffViewer_current - 1] * (-1);
}
if ((checker[TiffViewer_current - 1] % 360) == 0) {
rot[TiffViewer_current - 1] = 0
}
Edited();
};
//Zoom In
const zoomP = document.getElementById("TiffViewer_ZoomP");
zoomP.addEventListener("click", zoomIn);
document.addEventListener("keydown", (e) => {
if (e.ctrlKey && e.key === "=") {
e.preventDefault();
zoomIn();
}
})
function zoomIn() {
hzoom[TiffViewer_current - 1] += hpercent;
wzoom[TiffViewer_current - 1] += wpercent;
Edited();
};
//Zoom Out
const zoomM = document.getElementById("TiffViewer_ZoomM");
zoomM.addEventListener("click", zoomOut);
document.addEventListener("keydown", (e) => {
if (e.ctrlKey && e.key === "-") {
e.preventDefault();
zoomOut();
}
})
function zoomOut() {
hzoom[TiffViewer_current - 1] -= hpercent;
wzoom[TiffViewer_current - 1] -= wpercent;
if (wzoom[TiffViewer_current - 1] < wpercent && hzoom[TiffViewer_current - 1] < hpercent) {
hzoom[TiffViewer_current - 1] = hpercent;
wzoom[TiffViewer_current - 1] = wpercent;
}
Edited();
};
//Previous Page
const prevB = document.getElementById("TiffViewer_PrevButton");
prevB.addEventListener("click", previousPage);
document.addEventListener("keydown", (e) => {
if (e.key === "F11") {
e.preventDefault();
previousPage();
}
})
function previousPage() {
if (TiffViewer_pages > 1) {
if (TiffViewer_current != 1) {
document.getElementById("TiffViewer_ImageContainer").classList.remove("active");
document.getElementById(`IMG${TiffViewer_current}`).style.display = "none";
TiffViewer_current--;
document.getElementById("TiffViewer_PageCount").innerHTML = "Page: " + TiffViewer_current + " / " + TiffViewer_pages;
Edited();
}
}
};
//Next Page
const nextB = document.getElementById("TiffViewer_NextButton");
nextB.addEventListener("click", nextPage);
document.addEventListener("keydown", (e) => {
if (e.key === "F12") {
e.preventDefault();
nextPage();
}
})
function nextPage() {
if (TiffViewer_pages > 1) {
if (TiffViewer_current != TiffViewer_pages) {
document.getElementById("TiffViewer_ImageContainer").classList.remove("active");
document.getElementById(`IMG${TiffViewer_current}`).style = "display: none";
TiffViewer_current++;
document.getElementById("TiffViewer_PageCount").innerHTML = "Page: " + TiffViewer_current + " / " + TiffViewer_pages;
Edited();
}else{
alert("No more image to be fetched");
}
}
};
//Fit Content
const fitB = document.getElementById("TiffViewer_FitButton");
fitB.addEventListener("click", fitResize);
// document.addEventListener("keydown", (e) => {
// if (e.shiftKey && e.key === "F") {
// fitResize();
// }
// })
function fitResize() {
var FitText = this.textContent || this.innerHTML;
document.getElementById("TiffViewer_ImageContainer").classList.remove("active");
if (FitText === "Fit Content") {
setheight = origheight;
setwidth = origwidth;
wzoom[TiffViewer_current - 1] = origwidth;
hzoom[TiffViewer_current - 1] = origheight;
this.innerHTML = "Resize Content";
} else {
setheight = changedheight;
setwidth = changedwidth;
wzoom[TiffViewer_current - 1] = changedwidth;
hzoom[TiffViewer_current - 1] = changedheight;
this.innerHTML = "Fit Content";
}
Edited();
}
//Set Style per button click
function Edited() {
var TiffViewer_imgclass = document.getElementById("TiffViewer_FileContainer");
var TiffViewer_Screen = document.getElementById("TiffViewer_Screen");
var TiffViewer_ImageContainer = document.getElementById("TiffViewer_ImageContainer");
var image = document.getElementById(`IMG${TiffViewer_current}`);
//if the image is rotated 90 degrees
if (rot[TiffViewer_current - 1] == 90 || rot[TiffViewer_current - 1] == 270 || rot[TiffViewer_current - 1] == -90 || rot[TiffViewer_current - 1] == -270) {
image.style = `display: flex;
width: ${wzoom[TiffViewer_current] - 1};
height: ${hzoom[TiffViewer_current - 1]};
border: 1px groove white;
transform: rotate(${rot[TiffViewer_current - 1]}deg) scaleX(${flippedX[TiffViewer_current - 1]}) scaleY(${flippedY[TiffViewer_current - 1]});`;
image.style = `display: flex;
width: ${wzoom[TiffViewer_current - 1]};
height: ${hzoom[TiffViewer_current - 1]};
border: 1px groove white;
-ms-transform: rotate(${rot[TiffViewer_current - 1]}deg) scaleX(${flippedX[TiffViewer_current - 1]}) scaleY(${flippedY[TiffViewer_current - 1]});`; // IE
image.style = `display: flex;
width: ${wzoom[TiffViewer_current - 1]};
height: ${hzoom[TiffViewer_current - 1]};
border: 1px groove white;
-webkit-transform: rotate(${rot[TiffViewer_current - 1]}deg) scaleX(${flippedX[TiffViewer_current - 1]}) scaleY(${flippedY[TiffViewer_current - 1]});`; //Safari
TiffViewer_ImageContainer.style = `display: flex;
width: ${setheight};
height: ${setwidth};
position: relative;
justify-content: center;
align-items: center;`;
TiffViewer_Screen.style = `display: flex;
width: ${setheight};
height: ${setwidth};
position: relative;
justify-content: center;
align-items: center;`;
TiffViewer_imgclass.style = `display: flex;
width: ${setheight};
height: ${setwidth};
position: relative;
justify-content: center;
align-items: center;`;
width = TiffViewer_Screen.clientHeight;
height = TiffViewer_Screen.clientWidth;
} else {
image.style = `display: flex;
width: ${wzoom[TiffViewer_current - 1]};
height: ${hzoom[TiffViewer_current - 1]};
border: 1px groove white;
transform: rotate(${rot[TiffViewer_current - 1]}deg) scaleX(${flippedX[TiffViewer_current - 1]}) scaleY(${flippedY[TiffViewer_current - 1]});`;
image.style = `display: flex;
width: ${wzoom[TiffViewer_current - 1]};
height: ${hzoom[TiffViewer_current - 1]};
border: 1px groove white;
-ms-transform: rotate(${rot[TiffViewer_current - 1]}deg) scaleX(${flippedX[TiffViewer_current - 1]}) scaleY(${flippedY[TiffViewer_current - 1]});`;// IE
image.style = `display: flex;
width: ${wzoom[TiffViewer_current - 1]};
height: ${hzoom[TiffViewer_current - 1]};
border: 1px groove white;
-webkit-transform: rotate(${rot[TiffViewer_current - 1]}deg) scaleX(${flippedX[TiffViewer_current - 1]}) scaleY(${flippedY[TiffViewer_current - 1]});`;//Safari
TiffViewer_ImageContainer.style = `display: flex;
width: ${setwidth};
height: ${setheight};
position: relative;
justify-content: center;
align-items: center;`;
TiffViewer_Screen.style = `display: flex;
width: ${setwidth};
height: ${setheight};
position: relative;
justify-content: center;
align-items: center;`;
TiffViewer_imgclass.style = `display: flex;
width: ${setwidth};
height: ${setheight};
position: relative;
justify-content: center;
align-items: center;`;
width = TiffViewer_Screen.clientWidth;
height = TiffViewer_Screen.clientHeight;
}
editedwidth = image.clientWidth;
editedheight = image.clientHeight;
// document.getElementById(`IMG${TiffViewer_current + 1}`).style.display = 'none';
// document.getElementById("IMG2").style.display = 'none';
}
/* ADDED:
keyboard shortcut for fit/resize content
checks if the if it is the input field and if it is an alphanumeric/alphabet type
if so, keyboard shortcut will not bind
otherwise, the function will work
*/
document.addEventListener("keydown", function (e) {
if (e.shiftKey && e.key == 'F') {
if(e.target.tagName == "INPUT"){
// REMOVE COMMENT ONLY WHEN SPECIFIC FIELDS ARE NEEDED
// for (const key in getSection) {
// const validation = getValidation(key);
// if (`${key}` == e.target.id) {
// if (validation.collection == "alphanumeric" || validation.collection == "alphabet"){
// return;
// } else {
// console.log(`${key}`)
// console.log(e.target.id);
// fitResize();
// }
// }
// }
return;
}else{
fitResize();
}
}});
//scrolling shortcuts
document.addEventListener('keydown', function (e) {
let div = document.getElementById('TiffModalBody');
if (e.ctrlKey && e.keyCode === 37) {
e.preventDefault();
div.scrollLeft -= 20;
} else if (e.ctrlKey && e.keyCode === 38) {
e.preventDefault();
div.scrollTop -= 20;
} else if (e.ctrlKey && e.keyCode === 39) {
e.preventDefault();
div.scrollLeft += 20;
} else if (e.ctrlKey && e.keyCode === 40) {
e.preventDefault();
div.scrollTop += 20;
}
});
initHighlight();
}
/**
* AUTHOR: btsfelizardo
* DATE: 15 July 2022
* DESCRIPTION: WG-20: User: Validate input based on lookup tables and rules in schema. The main function
* is validateInput(fieldID, value), which checks if the validation is available for a given field
* fieldID then validates the value based on the collection stated in the validation. The function
* will always return an object with at keys: valid (Boolean) and errors (List). Value will specify
* whether the given parameter value is valid or not. errors will contain all errors detected if
* valid is false.
*/
/**
*
* @param {*} fieldID
* Key of input field in schema. Expected to be ID of the element.
* @param {*} value
* Actual input value
* @returns
* object containg:
* valid - true if no errors found after validation
* errors - list of errors found during validation
*/
// const validateInput = (fieldName, value, schema) => {
const validateInput = (fieldID, value, section) => {
try {
const { valid, error } = validateSchema()
if(!valid) return { valid: false, error: [`${error}`]}
const validation = getValidation(fieldID)
if(!validation) return { valid: false, error: [`FieldName: '${fieldID}' not in schema`] }
switch(validation.collection) {
case 'alphanumeric':
return validateAlphanumeric(validation, value)
case 'alphabet':
return validateAlphabet(validation, value)
case 'specific':
case 'dropdown':
return validateSpecific(validation, value)
case 'numeric':
return validateNumeric(validation, value)
case 'date':
case 'datepicker':
// console.log('date')
return validateDate(validation, value)
break
default:
return { valid: false, error: [`Collection of allowed values for field: ${fieldID} not found`]}
}
} catch(err) {
return { valid: false, error: [err]}
}
}
/**
*
* @param {*} fieldID
* Key of input field in schema. Expected to be ID of the element.
* @returns
* validation of given key in schema
*/
const getValidation = (fieldID) => {
// const { SECTION } = schema
const { ACCOUNTING_DOCUMENTS } = schema
const { SECTION1 } = ACCOUNTING_DOCUMENTS
const { BANK_APPLICATION_FORM } = schema
const { SECTION2 } = BANK_APPLICATION_FORM
const { HR_FILES } = schema
const { SECTION3 } = HR_FILES
try{
if (Object.keys(SECTION1).includes(fieldID)) return SECTION1[fieldID].validation;
if (Object.keys(SECTION2).includes(fieldID)) return SECTION2[fieldID].validation;
if (Object.keys(SECTION3).includes(fieldID)) return SECTION3[fieldID].validation;
return null;
} catch(err) {
return null
}
}
/**
*
* @param {*} validation
* object containing rules for validating alphanumeric inputs
* @param {*} value
* input to be checked
* @returns
* object containg:
* valid - true if no errors found after validation
* errors - list of errors found during validation
*/
const validateAlphanumeric = (validation, value) => {
let errors = []
const { mandatory, fieldLength, invalidchar } = validation
try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is empty'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters']
if(invalidchar) {
// method for escaping characters
// source: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
const escaped_pattern = invalidchar.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&')
const pattern = new RegExp(`[${escaped_pattern}]`)
if(pattern.test(value)) errors = [...errors, 'Contain invalid character/s']
}
return {
valid: errors.length===0,
errors
}
} catch(err) {
throw err
}
}
/**
*
* @param {*} validation
* object containing rules for validating alphabet inputs
* @param {*} value
* input to be checked
* @returns
* object containg:
* valid - true if no errors found after validation
* errors - list of errors found during validation
*/
const validateAlphabet = (validation, value) => {
const PATTERN_ALPHABET = /[^A-Za-z\s]/g
let errors = []
const { mandatory, fieldLength } = validation
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is empty'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters']
if(PATTERN_ALPHABET.test(value)) errors = [...errors, 'Contain invalid character/s']
return {
valid: errors.length===0,
errors
}
}
/**
*
* @param {*} validation
* object containing rules for validating numeric inputs
* @param {*} value
* input to be checked
* @returns
* object containg:
* valid - true if no errors found after validation
* errors - list of errors found during validation
*/
const validateNumeric = (validation, value) => {
const PATTERN_NUMERIC = /[^0-9/-]/g
let errors = []
const { mandatory, fieldLength } = validation
try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is empty'] }
if(fieldLength && value.length>fieldLength) errors = [...errors, 'Input exceed maximum characters']
if(PATTERN_NUMERIC.test(value)) errors = [...errors, 'Contain invalid character/s']
return {
valid: errors.length===0,
errors
}
} catch(err) {
throw err
}
}
/**
*
* @param {*} validation
* object containing rules for validating date inputs
* @param {*} value
* input to be checked
* @returns
* object containg:
* valid - true if no errors found after validation
* errors - list of errors found during validation
*/
const validateDate = (validation, value) => {
const { mandatory, regexformat } = validation
try{
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is empty'] }
return { valid: true }
} catch(err) {
throw err
}
}
/**
*
* @param {*} validation
* object containing rules for validating specific or dropdown inputs
* @param {*} value
* input to be checked
* @returns
* object containg:
* valid - true if no errors found after validation
* errors - list of errors found during validation
*/
const validateSpecific = (validation, value) => {
const { mandatory, validchars, options } = validation
try {
if(mandatory && (value.length===0 || !value.match(/\S/g))) return { valid: false, errors: ['Field is empty'] }
if(validchars && validchars.includes(value)) return { valid: true }
if(options && options.includes(value)) return {valid: true }
if(!mandatory) return { valid: true }
return { valid: false, errors: ['Not an option'] }
} catch(err) {
throw err
}
}
\ No newline at end of file
const validateSchema = () => {
const { ACCOUNTING_DOCUMENTS } = schema
if(!ACCOUNTING_DOCUMENTS) return { valid: false, error: 'SECTION is missing!' }
return { valid: true }
}
\ No newline at end of file
html {
min-height: 100vh;
}
*{
font-size: 13px;
font-family: Helvetica, sans-serif;
}
#with-config {
margin: 0;
grid-template-columns: auto auto 375px;
min-height: 100vh;
grid-template-areas:
"main main sidebar";
bottom: 0;
margin: 0;
padding: 0;
left: 0;
top: 0;
/* position: relative; */
overflow-y: hidden;
}
/* For the right pane */
.sidebar {
grid-area: sidebar;
display: flex;
position: sticky;
flex-direction: column;
background-color: #FBF0D9;
max-height: 100vh;
right: 0;
}
/* For the login credentials */
#username {
padding-left: 5px;
background-color: blue;
height: 30px;
display: inline-block;
margin-top: 0;
}
#user-settings {
left: 0;
height: 30px;
width: 30px;
border-radius: 100%;
}
#username-text {
float: right;
padding: 10px;
color: white;
}
/* For the project description */
#project-description {
padding-left: 5px;
background-color: pink;
min-height: 250px;
}
#project-description:after {
content: "";
display: table;
clear: both;
}
#column {
float: left;
width: 50%;
}
/* For the fields */
#fields {
padding-left: 5px;
width: auto;
display: flex;
flex: 1;
max-height: 100vh;
display: inline-block;
overflow-y: scroll;
}
/* For the viewer */
main#viewer {
grid-area: main;
/* background-color: gray; */
height: 100vh;
width: auto;
margin: 0;
padding: 0;
border: 0;
bottom: 0;
display: grid;
position: inherit;
}
.TiffViewercontainer {
margin-top: 10;
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
padding: 1px;
}
#TiffViewer_ButtonContainer {
/* CHANGED: changed to make button container scrollable when window is resized */
overflow-x: auto;
height: auto;
position: relative;
justify-content: center;
display: flex;
align-items: center;
}
#endDiv{
width: 100%;
text-align: right;
}
#endBtn{
width: 160px;
height: 28px;
margin-right: 10px;
}
#counter {
font-size: 22px;
padding: 10px;
position: absolute;
z-index: 1;
right: 199px;
bottom: -6px;
text-shadow:
-1px -1px 0 #000,
0 -1px 0 #000,
1px -1px 0 #000,
1px 0 0 #000,
1px 1px 0 #000,
0 1px 0 #000,
-1px 1px 0 #000,
-1px 0 0 #000;
}
.green{
color: green;
}
.red{
color: red;
}
textarea{
resize: none;
}
#pauseBtn {
background-color: #FBF0D9;
text-align: center;
}
#pause {
width: calc(38% - 40px);
margin: 20px;
padding: 6px;
}
/* ADDED: added to adjust button container when window is resized */
@media only screen and (max-width: 1150px) {
#TiffViewer_ButtonContainer {
justify-content: start;
}
}
#TiffViewerDetailscontainer {
/* overflow: hidden; */
height: auto;
width: auto;
position: relative;
justify-content: space-around;
display: flex;
align-items: center;
}
#TiffViewer_ButtonContainer>.TiffViewer_ButtonClass:not(:last-child) {
margin-right: 5px;
}
#TiffViewer_Screen {
clear: both;
position: relative;
}
.TiffViewer_imgclass {
justify-content: center;
-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
}
.TiffViewer_FullscreenButton:-webkit-fullscreen {
width: auto !important;
height: auto !important;
margin: auto !important;
}
.TiffViewer_FullscreenButton:-moz-fullscreen {
width: auto !important;
height: auto !important;
margin: auto !important;
}
.fullscreen:-ms-fullscreen {
width: auto !important;
height: auto !important;
margin: auto !important;
}
body {
overflow-y: auto;
margin: 0;
max-height: 100vh;
bottom: 0;
/* justify-content: center; */
}
body>div>button {
margin: 0;
position: absolute;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
/* CHANGED: changed to none, so that it will not display */
#TestTIFFDisplay {
display: none;
/* max-width: 0%;
max-height: 0%; */
}
/* The Modal (background) */
#TiffViewerModal {
display: block;
/* Hidden by default */
/* CHANGED: block by default */
position: relative;
/* Stay in place */
/* z-index: 1; */
/* Sit on top */
/* padding-top: 10px; */
/* Location of the box */
left: 0;
top: 0;
margin: 0;
border: 0;
width: 100%;
/* Full width */
max-height: 100vh;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Modal Content */
.TiffModalContent {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 5;
/* border: 1px solid #888;
width: 90%;
*/
width: calc(100% - 10px);
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s;
display: flex;
flex-direction: column;
overflow: auto;
max-height: calc(100% - 10px);
}
/* Add Animation */
@-webkit-keyframes animatetop {
from {
top: -300px;
opacity: 0
}
to {
top: 0;
opacity: 1
}
}
@keyframes animatetop {
from {
top: -300px;
opacity: 0
}
to {
top: 0;
opacity: 1
}
}
/* The Close Button */
.TiffModalClose {
color: black;
float: right;
font-size: 28px;
font-weight: bold;
}
.TiffModalClose:hover,
.TiffModalClose:focus {
color: red;
text-decoration: none;
cursor: pointer;
}
#TiffModalHeader {
font-family: Arial, Helvetica, sans-serif;
padding: 2px 16px;
background-color: white;
color: black;
}
#TiffModalBody {
display: inline-block;
align-items: center;
overflow: auto;
margin: auto;
width: 100%;
/* height: 90%; */
flex: 1;
}
#TiffModalFooter {
padding: 2px 16px;
background-color: white;
color: black;
/* overflow-x: auto; */
}
.bar {
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
#inputs {
display: flex;
flex-direction: column;
min-width: 500px;
}
.fieldContainer {
/* layout config */
display: flex;
flex-direction: row;
/* border config */
border-style: solid;
border-width: thin;
border-color: black;
padding: 0px;
}
.labelContainer {
display: flex;
flex-direction: row;
/* justify-content: flex-end; */
width: 42%;
padding: 3px;
}
.inputContainer {
display: flex;
flex-direction: row;
justify-content: flex-start;
width: 100%;
padding-left: 3px;
}
.input-invalid {
border-color: #ff3333 !important;
border-radius: 3px;
border-style: solid;
border-width: medium;
}
.input-valid {
border-color: #000000 !important;
border-radius: 3px;
border-style: solid;
border-width: thin;
}
input:focus, textarea:focus{
background-color: yellow;
border: 0px;
}
input[type=text] {
width: 100%;
}
select {
width: 100%;
}
#prompt{
backdrop-filter: blur(4px);
z-index: 999;
width: 100%;
height: 100%;
text-align: center;
margin: 0px auto;
position: fixed;
top: 50%;
left: 50%;
border: 1px solid gray;
transform: translate(-50%, -50%);
background-color: #555555a1;
padding: 10px;
display: block;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment