Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created June 18, 2023 02:16
Show Gist options
  • Save code-boxx/54949c0de5e19657e896ba49bb6bc75a to your computer and use it in GitHub Desktop.
Save code-boxx/54949c0de5e19657e896ba49bb6bc75a to your computer and use it in GitHub Desktop.
Javascript Appointment Web App

JAVASCRIPT APPOINTMENT PWA

https://code-boxx.com/javascript-appointment-scheduler/

NOTES

  1. Access https://your-site.com/1-js-appo.html in your browser.
  2. Not newbie-friendly, but it's a good study for progressive web apps.

IMAGES

favicon icon-512

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<!-- TITLE + CHARSET + DESCRIPTION + VIEWPORT + FAVICON -->
<title>JS Appointment Scheduler</title>
<meta charset="utf-8">
<meta name="description" content="Appointment Scheduler">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.5">
<link rel="icon" href="favicon.png" type="image/png">
<!-- ANDROID + CHROME + APPLE + WINDOWS APP -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="white">
<link rel="apple-touch-icon" href="icon-512.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Scheduler">
<meta name="msapplication-TileImage" content="icon-512.png">
<meta name="msapplication-TileColor" content="#ffffff">
<!-- WEB APP MANIFEST -->
<!-- https://web.dev/add-manifest/ -->
<link rel="manifest" href="3a-manifest.json">
<!-- SERVICE WORKER -->
<script>
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("3b-worker.js");
}
</script>
<!-- STYLESHEET + JAVASCRIPT -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="2-js-appo.js"></script>
<link rel="stylesheet" href="2-js-appo.css">
</head>
<body>
<!-- (A) APPOINTMENTS -->
<div id="appoWrap">
<!-- (A1) HEADER -->
<div id="appoHead">
<div id="appoLast" class="mi" onclick="appo.cycle(false)">
arrow_back_ios
</div>
<div id="appoNow"></div>
<div id="appoAdd" class="mi" onclick="appo.toggle(true)">
add
</div>
<div id="appoNext" class="mi" onclick="appo.cycle(true)">
arrow_forward_ios
</div>
</div>
<!-- (A2) APPOINTMENTS LIST -->
<div id="appoList"></div>
</div>
<!-- (B) APPOINTMENT EVENT FORM -->
<div id="appoFormWrap"><form id="appoForm" onsubmit="return appo.save()">
<div id="formClose" class="mi" onclick="appo.toggle(false)">
close
</div>
<input type="hidden" id="formID">
<label>From</label>
<input type="datetime-local" id="formFrom" required>
<label>To</label>
<input type="datetime-local" id="formTo" required>
<label>Details</label>
<input type="text" id="formTxt" required>
<label>Text Color</label>
<input type="color" id="formTC" required value="#ffffff">
<label>Background Color</label>
<input type="color" id="formBC" required value="#000000">
<input type="submit" value="Save">
</form></div>
</body>
</html>
/* (A) WHOLE PAGE */
.mi{font-family:"Material Icons";font-weight:400;font-style:normal;text-decoration:none;letter-spacing:normal;text-transform:none;display:inline-block;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:"liga";-webkit-font-smoothing:antialiased}
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
padding: 0;
margin: 0;
background: #f2f2f2;
}
#appoLast, #appoNext, #appoAdd, #appoList .row .del, #appoList .row .txt { cursor: pointer; }
/* (B) APPOINTMENTS WRAPPER */
#appoWrap {
max-width: 1000px;
padding: 15px;
margin: 0 auto;
}
/* (C) APPOINTMENTS HEADER */
#appoHead {
display: flex;
font-size: 20px;
color: #fff;
background: #0a3687;
}
#appoLast, #appoNext, #appoAdd, #appoNow { padding: 15px; }
#appoNow {
flex-grow: 1;
text-align: center;
}
/* (D) APPOINTMENTS LIST */
#appoList {
display: grid;
width: 100%;
overflow: auto;
}
#appoList .cell, #appoList .row .del, #appoList .row .txt { padding: 10px; }
#appoList .head {
font-weight: 700;
color: #fff;
background: #204a97;
}
#appoList .row { display: flex; }
#appoList .row .del {
color: #fff;
background: #972020;
}
#appoList .row .txt { flex-grow: 1; }
/* (E) APPOINTMENT FORM WRAPPER */
#appoFormWrap {
/* (E1) FULL PAGE */
position: fixed;
top: 0; left: 0; z-index: 99;
width: 100vw; height: 100vh;
/* (E2) CENTERED */
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.5);
/* (E3) HIDDEN */
visibility: hidden; opacity: 0;
transition: opacity 0.3s;
}
#appoFormWrap.show { visibility: visible; opacity: 1; }
/* (F) APPOINTMENT FORM */
#appoForm {
position: relative;
width: 380px;
padding: 20px;
background: #fff;
}
#formClose {
position: absolute;
top: 0; right: 0;
padding: 10px;
color: #fff;
background: #972020;
cursor: pointer;
}
#appoForm label, #appoForm input {
display: block;
width: 100%;
}
#appoForm input { padding: 10px; }
#appoForm label { padding: 10px 0; }
#appoForm input[type=color] {
border: 0;
padding: 0;
background: 0;
height: 30px;
}
#appoForm input[type=submit] {
margin-top: 20px;
padding: 15px 0;
border: 0;
color: #fff;
background: #0a3687;
cursor: pointer;
}
var appo = {
// (A) PROPERTIES
// (A1) INDEXED DB
iName : "jsAppo", // idb name
iDB : null, iTX : null, // idb objects
// (A2) HTML ELEMENTS
hNow : null, // html current year month
hList : null, // html appointment list
hForm : null, // html appointment form
fID : null, fFrom : null, fTo : null, // html form
fTxt : null, fTC : null, fBC : null, // html form
// (A3) PERIOD
month : null, // current month
year : null, // current year
days : null, // days in month for current month/year
// (B) INIT
init : () => {
// (B1) IDB SUPPORT CHECK
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
if (!window.indexedDB) {
alert("Your browser does not support indexed database.");
return;
}
// (B2) OPEN "MYLIB" DATABASE
let req = window.indexedDB.open(appo.iName, 1);
// (B3) ON DATABASE ERROR
req.onerror = evt => {
alert("Indexed DB init error - " + evt.message);
console.error(evt);
};
// (B4) UPGRADE NEEDED
req.onupgradeneeded = evt => {
// (B4-1) INIT UPGRADE
appo.iDB = evt.target.result;
appo.iDB.onerror = evt => {
alert("Indexed DB upgrade error - " + evt.message);
console.error(evt);
};
// (B4-2) VERSION 1
if (evt.oldVersion < 1) {
let store = appo.iDB.createObjectStore(appo.iName, {
keyPath: "id",
autoIncrement: true
});
store.createIndex("from", "from");
store.createIndex("to", "to");
}
};
// (B5) OPEN DATABASE OK
req.onsuccess = evt => {
// (B5-1) REGISTER IDB OBJECTS
appo.iDB = evt.target.result;
appo.iTX = () => {
return appo.iDB
.transaction(appo.iName, "readwrite")
.objectStore(appo.iName);
};
// (B5-2) GET HTML ELEMENTS
appo.hNow = document.getElementById("appoNow");
appo.hList = document.getElementById("appoList");
appo.hForm = document.getElementById("appoFormWrap");
appo.fID = document.getElementById("formID");
appo.fFrom = document.getElementById("formFrom");
appo.fTo = document.getElementById("formTo");
appo.fTxt = document.getElementById("formTxt");
appo.fTC = document.getElementById("formTC");
appo.fBC = document.getElementById("formBC");
// (B5-3) CURRENT DATE
let today = new Date();
appo.month = today.getMonth() + 1; // jan is 0!
appo.year = today.getFullYear();
// (B5-4) DRAW APPOINTMENTS
appo.draw();
};
},
// (C) HELPER FUNCTION - DATE TO UNIX TIMESTAMP
dtu : date => Math.floor((+new Date(date)) / 1000),
// (D) HELPER FUNCTION - UNIX TIMESTAMP TO DATE
utd : unix => new Date(unix*1000).toISOString().substring(0,16),
// (E) DRAW APPOINTMENTS FOR SELECTED MONTH
draw : () => {
// (E1) CURRENT MONTH YEAR
let months = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
appo.hNow.innerHTML = `${months[appo.month]} ${appo.year}`;
delete months;
// (E2) FIRST ROW - DAYS IN MONTH
let cell;
appo.days = new Date(appo.year, appo.month, 0).getDate();
appo.hList.style.gridTemplateColumns = `repeat(${appo.days}, 100px)`;
appo.hList.innerHTML = "";
for (let d=1; d<=appo.days; d++) {
cell = document.createElement("div");
cell.className = "cell head";
cell.innerHTML = d;
appo.hList.append(cell);
}
// (E3) FOLLOWING ROWS - APPOINTMENT EVENTS
// (E3-1) FLAGS & VARS
let first = appo.dtu(`${appo.year}-${appo.month<10?"0"+appo.month:appo.month}-01T00:00`),
last = appo.dtu(`${appo.year}-${appo.month<10?"0"+appo.month:appo.month}-${appo.days}T00:00`),
idx = null, more = true, drawn = {}, row = 2;
// (E3-2) HELPER FUNCTION - DRAW APPOINTMENT EVENT
let rower = evt => {
const cursor = evt.target.result;
if (cursor) {
if (drawn[cursor.value.id]==undefined) {
let cx = cursor.value.from < first ? 1 : new Date(cursor.value.from * 1000).getDate(),
cy = cursor.value.to > last ? appo.days + 1 : new Date(cursor.value.to * 1000).getDate() + 1;
cell = document.createElement("div");
cell.className = "row";
cell.style.gridRow = row;
cell.style.gridColumn = `${cx}/${cy}`;
cell.style.color = cursor.value.tc;
cell.style.background = cursor.value.bc;
cell.innerHTML = `<div class="mi del" onclick="appo.del(${cursor.value.id});">clear</div>
<div class="txt" onclick="appo.toggle(${cursor.value.id});">${cursor.value.txt}</div>`;
appo.hList.append(cell);
drawn[cursor.value.id] = 1; row++;
}
cursor.continue();
} else { if (more) {
more = false;
idx = appo.iTX().index("to").openCursor(range = IDBKeyRange.bound(first, last));
idx.onsuccess = rower;
}}
};
// (E3-3) GET & DRAW ENTRIES
idx = appo.iTX().index("from").openCursor(range = IDBKeyRange.bound(first, last));
idx.onsuccess = rower;
},
// (F) CYCLE MONTH
cycle : next => {
if (next) { appo.month++; } else { appo.month--; }
if (appo.month==13) { appo.month = 1; appo.year++; }
if (appo.month==0) { appo.month = 12; appo.year--; }
appo.draw();
},
// (G) TOGGLE APPOINTMENT FORM
toggle : id => {
// (G1) HIDE
if (id == false) {
appo.hForm.classList.remove("show");
appo.fID.value = "";
appo.fFrom.value = "";
appo.fTo.value = "";
appo.fTxt.value = "";
appo.fTC.value = "#ffffff";
appo.fBC.value = "#000000";
}
// (G2) SHOW
else {
if (Number.isInteger(id)) {
let req = appo.iTX().get(id);
req.onsuccess = evt => {
appo.fID.value = req.result.id;
appo.fFrom.value = appo.utd(req.result.from);
appo.fTo.value = appo.utd(req.result.to);
appo.fTxt.value = req.result.txt;
appo.fTC.value = req.result.tc;
appo.fBC.value = req.result.bc;
};
}
appo.hForm.classList.add("show");
}
},
// (H) SAVE APPOINTMENT EVENT
save : () => {
// (H1) FORM DATA
let data = {
id : appo.fID.value,
from : appo.dtu(appo.fFrom.value),
to : appo.dtu(appo.fTo.value),
txt : appo.fTxt.value,
tc : appo.fTC.value,
bc : appo.fBC.value
};
// (H2) DATE/TIME CHECK
if (data.to < data.from) {
alert("'Date From' cannot be later than 'Date To'");
return false;
}
// (H3) SAVE EVENT
if (data.id == "") { delete data.id; }
else { data.id = parseInt(data.id); }
appo.iTX().put(data);
// (H4) UPDATE HTML INTERFACE
appo.toggle(false);
appo.draw();
return false;
},
// (I) DELETE APPOINTMENT EVENT
del : id => { if (confirm("Delete event?")) {
appo.iTX().delete(id);
appo.draw();
}}
};
window.onload = appo.init;
{
"short_name": "Scheduler",
"name": "Appointment Scheduler",
"icons": [{
"src": "favicon.png",
"sizes": "64x64",
"type": "image/png"
}, {
"src": "icon-512.png",
"sizes": "512x512",
"type": "image/png"
}],
"start_url": "1-js-appo.html",
"scope": "/",
"background_color": "white",
"theme_color": "white",
"display": "standalone"
}
// (A) CREATE/INSTALL CACHE
self.addEventListener("install", evt => {
self.skipWaiting();
evt.waitUntil(
caches.open("JSAppo")
.then(cache => cache.addAll([
"favicon.png",
"icon-512.png",
"maticon.woff2",
"1-js-appo.html",
"2-js-appo.js",
"2-js-appo.css"
]))
.catch(err => console.error(err))
);
});
// (B) CLAIM CONTROL INSTANTLY
self.addEventListener("activate", evt => self.clients.claim());
// (C) LOAD FROM CACHE FIRST, FALLBACK TO NETWORK IF NOT FOUND
self.addEventListener("fetch", evt => evt.respondWith(
caches.match(evt.request).then(res => res || fetch(evt.request))
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment