Compare commits

..

6 Commits

Author SHA1 Message Date
Fred Boniface 5a8f3f0d85 Frontend: Begin refactoring boards.js and public-board.js
Signed-off-by: Fred Boniface <fred@fjla.uk>
2023-01-23 21:00:53 +00:00
Fred Boniface 5e9f9e13bc Frontend: Refactor settings.js
Signed-off-by: Fred Boniface <fred@fjla.uk>
2023-01-23 20:25:05 +00:00
Fred Boniface 018ddf8c47 Frontend: Further refactoring find-code.js
Signed-off-by: Fred Boniface <fred@fjla.uk>
2023-01-23 20:11:23 +00:00
Fred Boniface 7ea8f153cd Frontend: Refactor fine-code.js - Will need work
Signed-off-by: Fred Boniface <fred@fjla.uk>
2023-01-23 19:46:41 +00:00
Fred Boniface 0958bc92f5 Frontend: Refactor indexjs
Signed-off-by: Fred Boniface <fred@fjla.uk>
2023-01-23 19:29:20 +00:00
Fred Boniface 67cc929158 Frontend: lib.main.js replaces main.js
Signed-off-by: Fred Boniface <fred@fjla.uk>
2023-01-23 18:46:33 +00:00
14 changed files with 131 additions and 160 deletions

View File

@ -13,19 +13,11 @@
- Also include other details from the API such as: - Also include other details from the API such as:
- Platform number - Platform number
- Operator - Operator
* Frontend code refactoring: - If only one callingPoint, a string is returned instead of an array.
- Refactor into files:
- lib.main.js
- lib.board.js
- simple-board.js
- index.js
- settings.js
- find-code.js
- service-worker.js
### In Progress: ### In Progress:
* Frontend code refactoring: --- Pre-Refactor /static/js folder size: 22132B * Frontend code refactoring: --- Pre-Refactor /static/js folder size: 22132B *Check Compressed Size Before Next Build*
- Refactor into files: - Refactor into files:
- lib.main.js - lib.main.js
- lib.board.js - lib.board.js
@ -33,7 +25,7 @@
- index.js - index.js
- settings.js - settings.js
- find-code.js - find-code.js
- service-worker.js - service-worker.js *in / not /js*
### Completed - Testing: ### Completed - Testing:

View File

@ -12,7 +12,7 @@
<link rel="stylesheet" type="text/css" href="./styles/boards.css"/> <link rel="stylesheet" type="text/css" href="./styles/boards.css"/>
<link rel="icon" type="image/svg+xml" href="./images/icon.svg"/> <link rel="icon" type="image/svg+xml" href="./images/icon.svg"/>
<link rel="manifest" type="application/json" href="./manifest.json"/> <link rel="manifest" type="application/json" href="./manifest.json"/>
<script src="./js/main.js" defer></script> <script src="./js/lib.main.js" defer></script>
<script src="./js/boards.js" defer></script> <script src="./js/boards.js" defer></script>
<script src="./js/public-board.js" defer></script> <script src="./js/public-board.js" defer></script>
</head> </head>

View File

@ -12,7 +12,7 @@
<link rel="icon" type="image/svg+xml" href="./images/icon.svg"/> <link rel="icon" type="image/svg+xml" href="./images/icon.svg"/>
<link rel="manifest" type="application/json" href="./manifest.json"/> <link rel="manifest" type="application/json" href="./manifest.json"/>
<title>OwlBoard - Code Lookup</title> <title>OwlBoard - Code Lookup</title>
<script src="./js/main.js" defer></script> <script src="./js/lib.main.js" defer></script>
<script src="./js/find-code.js" defer></script> <script src="./js/find-code.js" defer></script>
</head> </head>

View File

@ -10,6 +10,7 @@
<link rel="stylesheet" type="text/css" href="./styles/main.css"/> <link rel="stylesheet" type="text/css" href="./styles/main.css"/>
<link rel="icon" type="image/svg+xml" href="./images/icon.svg"/> <link rel="icon" type="image/svg+xml" href="./images/icon.svg"/>
<link rel="manifest" type="application/json" href="./manifest.json"/> <link rel="manifest" type="application/json" href="./manifest.json"/>
<!-- NO SCRIPTS LOADED - NOT REQUIRED AT PRESENT -->
<title>OwlBoard</title> <title>OwlBoard</title>
</head> </head>

View File

@ -10,7 +10,7 @@
<link rel="stylesheet" type="text/css" href="./styles/main.css"/> <link rel="stylesheet" type="text/css" href="./styles/main.css"/>
<link rel="icon" type="image/svg+xml" href="./images/icon.svg"/> <link rel="icon" type="image/svg+xml" href="./images/icon.svg"/>
<link rel="manifest" type="application/json" href="./manifest.json"/> <link rel="manifest" type="application/json" href="./manifest.json"/>
<script src="./js/main.js" defer></script> <script src="./js/lib.main.js" defer></script>
<script src="./js/index.js" defer></script> <script src="./js/index.js" defer></script>
<title>OwlBoard</title> <title>OwlBoard</title>
</head> </head>

View File

@ -9,6 +9,7 @@
<link rel="stylesheet" type="text/css" href="./styles/main.css"/> <link rel="stylesheet" type="text/css" href="./styles/main.css"/>
<link rel="icon" type="image/svg+xml" href="./images/icon.svg"/> <link rel="icon" type="image/svg+xml" href="./images/icon.svg"/>
<link rel="manifest" type="application/json" href="./manifest.json"/> <link rel="manifest" type="application/json" href="./manifest.json"/>
<!-- NO SCRIPTS LOADED - NOT REQUIRED AT PRESENT -->
<title>OwlBoard - Report</title> <title>OwlBoard - Report</title>
</head> </head>
<body> <body>

View File

@ -1,20 +1,9 @@
// Fetch a known query parameter from the pages URL
async function getQuery(param) {
var params = new URLSearchParams(window.location.search)
var query = params.get(param)
if (query) {
return query
} else {
return 'false'
}
}
// Set page headers // Set page headers
async function setHeaders(title,time) { async function setHeaders(title,time) {
var prefix = `OwlBoard - ` var prefix = `OwlBoard - `
document.title = `${prefix}${title}` document.title = `${prefix}${title}`
document.getElementById("stn_name").innerHTML = title document.getElementById("stn_name").textContent = title
document.getElementById("fetch_time").innerHTML = time.toLocaleTimeString() document.getElementById("fetch_time").textContent = time.toLocaleTimeString()
} }
// Determine what should display in 'platform' column // Determine what should display in 'platform' column
@ -24,7 +13,7 @@ async function parsePlatform(svc){
} else { } else {
var platform = "-"; var platform = "-";
} }
if (svc.platformChanged) { if (svc.platformChanged) { // Not present in public API, ready for staff version.
var changed = "changed"; var changed = "changed";
} else { } else {
var changed = ""; var changed = "";
@ -56,7 +45,7 @@ async function parseTime(string){
var change = ""; var change = "";
break; break;
case "No report": case "No report":
var output = "?"; var output = "-";
var change = ""; var change = "";
break; break;
default: default:
@ -66,7 +55,7 @@ async function parseTime(string){
return {data: output, changed: change}; return {data: output, changed: change};
} }
// Sometimes the origin or destination names are undefined, need to catch that // Convert multiple Origin/Destinations to single string
async function parseName(location) { async function parseName(location) {
if (Array.isArray(location)) { if (Array.isArray(location)) {
var name = `${location[0]['locationName']} & ${location[1]['locationName']}` var name = `${location[0]['locationName']} & ${location[1]['locationName']}`
@ -77,7 +66,7 @@ async function parseName(location) {
} }
} }
// Build calling list: // Build calling list: -- This is a string if only one callingPoint is present, needs adapting to work with that
async function buildCallLists(data) { async function buildCallLists(data) {
try { try {
if (data.previousCallingPoints.callingPointList.callingPoint) { if (data.previousCallingPoints.callingPointList.callingPoint) {
@ -141,7 +130,7 @@ async function buildCallLists(data) {
return; return;
} }
// Display calling list: // Display calling list: - The calling list should be built on demand.
async function showCalls(id) { async function showCalls(id) {
document.getElementById(id).style = "display: block;"; document.getElementById(id).style = "display: block;";
return; return;
@ -155,18 +144,18 @@ async function hideCalls(id) {
// Display Alert Messages // Display Alert Messages
async function displayAlerts(array) { async function displayAlerts(array) {
var counter = 0 var counter = 0
var messages = ""
for(var i = 0; i < array.length; i++) { for(var i = 0; i < array.length; i++) {
// Increment counter // Increment counter
counter += 1; counter += 1;
// Reset Vars // Reset Vars
var msg = array[i]; messages += `<p>${array[i]}</p>`;
console.log(`Alert: ${msg}`);
document.getElementById("alerts_msg").insertAdjacentHTML("beforeend", `<p>${msg}</p>`);
} }
document.getElementById("alerts_msg").insertAdjacentHTML("beforeend", messages);
if (counter == 1) { if (counter == 1) {
document.getElementById("alert_bar_note").innerHTML = `There is ${counter} active alert` document.getElementById("alert_bar_note").textContent = `There is ${counter} active alert`
} else if (counter > 1) { } else if (counter > 1) {
document.getElementById("alert_bar_note").innerHTML = `There are ${counter} active alerts` document.getElementById("alert_bar_note").textContent = `There are ${counter} active alerts`
} }
document.getElementById("alerts").style = "display:block" document.getElementById("alerts").style = "display:block"
@ -186,6 +175,22 @@ async function deflateAlerts() {
document.getElementById("alerts_bar").setAttribute("onclick", "inflateAlerts()") document.getElementById("alerts_bar").setAttribute("onclick", "inflateAlerts()")
} }
/*
Compress buildCalls() and buildPastCalls() into a single function
that can selectively work with either data.et or data.at.
async function buildCalls(data) {
if (typeof data.et != "undefined") {
var time = await parseTime(data.et)
} else if (typeof data.at != "undefined") {
var time = await parseTime(data.at)
}
return `<tr>
<td class="detail-name detail-table-content">${data.locationName}</td>
<td class="detail-table-content">${data.st}</td>
<td class="detail-table-content ${time.changed}">${time.data}</td>
</tr>`
}
*/
async function buildCalls(data) { async function buildCalls(data) {
var timeEt = await parseTime(data.et) var timeEt = await parseTime(data.et)
return `<tr> return `<tr>

View File

@ -1,4 +1,4 @@
clearLoading(); hideLoading();
async function fetchEntry(){ // This can be condensed async function fetchEntry(){ // This can be condensed
showLoading(); showLoading();
@ -15,10 +15,7 @@ async function fetchEntry(){ // This can be condensed
tiploc: tiploc.value, tiploc: tiploc.value,
stanox: stanox.value stanox: stanox.value
} }
parseData(values)
console.log(`Read values: ${JSON.stringify(values)}`)
parseData(values)
} }
async function parseData(values){ async function parseData(values){
@ -35,40 +32,54 @@ async function parseData(values){
setLoadingDesc(`Searching\n${values.stanox.toUpperCase()}`) setLoadingDesc(`Searching\n${values.stanox.toUpperCase()}`)
var data = await getData("stanox", values.stanox) var data = await getData("stanox", values.stanox)
} else if (values.name != ""){ } else if (values.name != ""){
setLoadingDesc(`Searching\n${values.name.capitalize()}`) setLoadingDesc(`Searching\n${values.name}`)
var data = await getData("name", values.name) var data = await getData("name", values.name)
} else { } else {
errorNoData() log("find-code.parseData: No data entered", "WARN")
hideLoading() await clearForm();
document.getElementById("name").value = "No data entered"
hideLoading();
return; return;
} }
displayData(data); displayData(data);
} }
async function getData(type, value){ async function getData(type, value){
console.log(`Looking for: ${type} ${value}`) log(`find-code.getData: Looking for: ${type} '${value}'`, "INFO")
try { try {
var url = `${window.location.origin}/api/v1/find/${type}/${value}`; var url = `${window.location.origin}/api/v1/find/${type}/${value}`;
var resp = await fetch(url); var resp = await fetch(url);
console.log(`Response: ${resp.json}`)
return await resp.json() return await resp.json()
} catch (err) { } catch (err) {
errorFetch(err) log(`find-code.getData: Error getting data: ${err}`, "WARN")
return "";
} }
} }
async function displayData(data){ async function displayData(data){
hideLoading(); hideLoading();
if (data.status === "failed" || data == ""){ if (data.status === "failed" || data == ""){
errorNotFound() log(`find-code.displayData: Unable to find data`, "WARN")
clearForm();
document.getElementById("name").value = "Not Found";
} else {
log(`find-code.displayData: Inserting data`, "INFO")
try {
document.getElementById("name").value = data['0']['NLCDESC']
} catch (err) {}
try {
document.getElementById("3alpha").value = data['0']['3ALPHA']
} catch (err) {}
try {
document.getElementById("nlc").value = data['0']['NLC']
} catch (err) {}
try {
document.getElementById("tiploc").value = data['0']['TIPLOC']
} catch (err) {}
try {
document.getElementById("stanox").value = data['0']['STANOX']
} catch (err) {}
} }
document.getElementById("name").value = data['0']['NLCDESC']
document.getElementById("3alpha").value = data['0']['3ALPHA']
document.getElementById("nlc").value = data['0']['NLC']
document.getElementById("tiploc").value = data['0']['TIPLOC']
document.getElementById("stanox").value = data['0']['STANOX']
// document.getElementById("stanme").value = data['0']['STANME'] // NOT PRESENT IN CORPUS
} }
async function clearForm(){ async function clearForm(){
@ -78,27 +89,4 @@ async function clearForm(){
document.getElementById("tiploc").value = "" document.getElementById("tiploc").value = ""
document.getElementById("stanox").value = "" document.getElementById("stanox").value = ""
hideLoading(); hideLoading();
}
async function showLoading(){
document.getElementById("loading").style = "display: block;";
}
async function hideLoading(){
document.getElementById("loading").style = "display: none;";
}
async function errorNoData(){
console.log("No data entered")
window.alert("You haven't entered any data")
}
async function errorFetch(err){
console.log("Error fetching data")
console.log(err)
}
async function errorNotFound(){
console.log("Location not found")
window.alert("No location was found. Check and try again.")
} }

View File

@ -1,38 +1,21 @@
// Init: // Init:
setQls(); pageInit();
clearLoading();
async function sidebarOpen() { async function pageInit() {
document.getElementById("sidebar").style.width = "50%"; await loadQuickLinks();
document.getElementById("sidebar_open_short").style.display = "none"; hideLoading(); // From lib.main
document.getElementById("sidebar_close_short").style.display = "block";
}
async function sidebarClose() {
document.getElementById("sidebar").style.width = "0%"
document.getElementById("sidebar_open_short").style.display = "block";
document.getElementById("sidebar_close_short").style.display = "none";
} }
async function gotoBoard(station){ async function gotoBoard(station){
window.location.assign(`${window.location.origin}/board.html?stn=${station}`) window.location.assign(`${window.location.origin}/board.html?stn=${station}`);
} }
async function setQls(){ async function loadQuickLinks(){
var qlOpt = JSON.parse(localStorage.getItem("qlOpt")) var data = await getQuickLinks(); // From lib.main
var qlDef = ["bri","lwh","srd","mtp","rda","cfn","sml","shh","pri","avn","sar","svb"] var buttons = "";
if (qlOpt) { for(var i = 0; i < data.length; i++) {
for(var i = 0; i < qlOpt.length; i++) { buttons += `
console.log(`Button: ${qlOpt[i]}`) <button class="actionbutton" onclick="gotoBoard('${data[i]}')">${data[i].toUpperCase()}</button>`
var btn = `<button class="actionbutton" onclick="gotoBoard('${qlOpt[i]}')">${qlOpt[i].toUpperCase()}</button>`
console.log(btn);
document.getElementById("quick_links").insertAdjacentHTML("beforeend", btn) // Append btn
}
} else {
for(var i = 0; i < qlDef.length; i++) {
console.log(`Button: ${qlDef[i]}`)
var btn = `<button class="actionbutton" onclick="gotoBoard('${qlDef[i]}')">${qlDef[i].toUpperCase()}</button>`
document.getElementById("quick_links").insertAdjacentHTML("beforeend", btn) // Append btn
} }
} document.getElementById("quick_links").insertAdjacentHTML("beforeend", buttons)
} }

View File

@ -1,20 +1,22 @@
/* Feature Detectors */ /* Feature Detectors */
/* Valid values for ${type}: localstorage, sessionstorage */ /* Valid values for ${type}: localstorage, sessionstorage */
async function storageAvailable(type) { async function storageAvailable(type) { // Currently not used
try { try {
var storage = window[type], let storage = window[type];
x = '__storage_test__'; let x = '__storage_test__';
storage.setItem(x, x); storage.setItem(x, "test");
storage.getItem(x); storage.getItem(x);
log(`lib.main.storageAvailable: ${type} is available`, "INFO")
return true; return true;
} catch (err) { } catch (err) {
log(`lib.main.storageAvailable: ${type} is not available`, "ERR")
return false; return false;
} }
} }
/* Delays */ /* Timeouts */
/* Usage: '' */ /* Usage: '' */
const delay = ms => new Promise(res => setTimeout(res, ms)); const delay = ms => new Promise(res => setTimeout(res, ms));
@ -41,6 +43,19 @@ async function log(msg, type) {
}; };
}; };
/* Menu Control */
async function sidebarOpen() {
document.getElementById("sidebar").style.width = "50%";
document.getElementById("sidebar_open_short").style.display = "none";
document.getElementById("sidebar_close_short").style.display = "block";
}
async function sidebarClose() {
document.getElementById("sidebar").style.width = "0%"
document.getElementById("sidebar_open_short").style.display = "block";
document.getElementById("sidebar_close_short").style.display = "none";
}
/* Loading Box Control */ /* Loading Box Control */
async function hideLoading() { async function hideLoading() {
document.getElementById("loading").style = "display: none;"; document.getElementById("loading").style = "display: none;";
@ -48,7 +63,7 @@ async function hideLoading() {
/* DEPRECIATED: Alias for hideLoading() - Marked for removal*/ /* DEPRECIATED: Alias for hideLoading() - Marked for removal*/
async function clearLoading() { async function clearLoading() {
log("Depreciated function called - clearLoading()", "WARN") log("Depreciated function called - clearLoading() - Alias to hideLoading()", "WARN")
await hideLoading(); await hideLoading();
} }
@ -58,4 +73,27 @@ async function showLoading() {
async function setLoadingDesc(desc) { async function setLoadingDesc(desc) {
document.getElementById("loading_desc").textContent = `${desc}`; document.getElementById("loading_desc").textContent = `${desc}`;
}
/* Fetch User Settings */
async function getQuickLinks() {
try {
var data = JSON.parse(localStorage.getItem("qlOpt"));
} catch (err) {
var data =
["bri","lwh","srd","mtp","rda","cfn",
"sml","shh","pri","avn","sar","svb"];
}
return data;
}
/* Fetch a known query parameter from the pages URL */
async function getQuery(param) {
var params = new URLSearchParams(window.location.search)
var query = params.get(param)
if (query) {
return query
} else {
return 'false'
}
} }

View File

@ -1,21 +0,0 @@
// Loading Box
async function clearLoading() {
document.getElementById("loading").style = "display: none;";
}
async function showLoading() {
document.getElementById("loading").style = "display: block;";
}
async function setLoadingDesc(desc) {
document.getElementById("loading_desc").textContent = `${desc}`;
}
// Enable delays
const delay = ms => new Promise(res => setTimeout(res, ms));
// Log Helper
function log(msg) {
var time = new Date().toISOString();
console.log(`${time} - ${msg}`)
}

View File

@ -29,8 +29,8 @@ async function init() {
async function publicLdb(stn) { async function publicLdb(stn) {
var url = `${window.location.origin}/api/v1/ldb/${stn}`; var url = `${window.location.origin}/api/v1/ldb/${stn}`;
var resp = await fetch(url); var resp = await fetch(url);
return await resp.json();} return await resp.json();
}
async function parseLdb(data) { async function parseLdb(data) {
if (data.ERROR == "NOT_FOUND") { // Station not found if (data.ERROR == "NOT_FOUND") { // Station not found

View File

@ -1,31 +1,15 @@
// Init: // Init:
const ql = ["ql0","ql1","ql2","ql3","ql4","ql5","ql6","ql7","ql8","ql9","ql10","ql11"] const ql = ["ql0","ql1","ql2","ql3","ql4","ql5","ql6","ql7","ql8","ql9","ql10","ql11"]
checkStorageSupport(); storageAvailable("localStorage");
getQl(); getQl();
clearLoading(); hideLoading();
async function checkStorageSupport(){
if (window.localStorage){
localStorage.setItem("support-check","8441");
if (localStorage.getItem("support-check")=="8441"){
console.log("Local Storage supported.")
localStorage.removeItem("support-check")
} else if (localStorage.getItem("support-check" != "8441")){
console.log("Error fetching test value.")
}
} else {
console.log("Local Storage is not supported")
window.alert("Settings cannot be saved on your device, try updating your browser.")
}
}
async function getQl(){ async function getQl(){
var qlOpt = JSON.parse(localStorage.getItem("qlOpt")) var qlOpt = await getQuickLinks()
if (qlOpt){ if (qlOpt){
var i = 0 var i = 0
while (i < 12) { while (i < 12) {
if (qlOpt[i] != 'undefined') { if (qlOpt[i] != 'undefined') {
console.log(`Setting box ql${i} to ${qlOpt[i]}`)
document.getElementById(`ql${i}`).value = qlOpt[i] document.getElementById(`ql${i}`).value = qlOpt[i]
i +=1 i +=1
} }
@ -43,9 +27,9 @@ async function setQl(){
} }
qlSet.sort() qlSet.sort()
} }
console.log(qlSet)
localStorage.setItem("qlOpt", JSON.stringify(qlSet)) localStorage.setItem("qlOpt", JSON.stringify(qlSet))
clearLoading(); log(`settings.setQl: User settings saved`, "INFO")
hideLoading();
} }
async function clearQl(){ async function clearQl(){

View File

@ -12,7 +12,7 @@
<link rel="icon" type="image/svg+xml" href="./images/icon.svg"/> <link rel="icon" type="image/svg+xml" href="./images/icon.svg"/>
<link rel="manifest" type="application/json" href="./manifest.json"/> <link rel="manifest" type="application/json" href="./manifest.json"/>
<title>OwlBoard - Settings</title> <title>OwlBoard - Settings</title>
<script src="./js/main.js" defer></script> <script src="./js/lib.main.js" defer></script>
<script src="./js/settings.js" defer></script> <script src="./js/settings.js" defer></script>
</head> </head>
@ -50,7 +50,7 @@
<input type="text" maxlength="3" id="ql10" name="ql10" autocomplete="off" class="small-lookup-box"> <input type="text" maxlength="3" id="ql10" name="ql10" autocomplete="off" class="small-lookup-box">
<input type="text" maxlength="3" id="ql11" name="ql11" autocomplete="off" class="small-lookup-box"><br> <input type="text" maxlength="3" id="ql11" name="ql11" autocomplete="off" class="small-lookup-box"><br>
<button onclick="setQl()" class="lookup-button">Apply</button> <button onclick="setQl()" class="lookup-button">Apply</button>
<button onclick="clearQl()" class="lookup-button">Reset</button> <button onclick="clearQl()" class="lookup-button">Defaults</button>
</body> </body>
</html> </html>