Skip to content

Commit

Permalink
added push state history to the spa so that the browser forward and b…
Browse files Browse the repository at this point in the history
…ackwards button work without reloading the page fully letsgoooooo
  • Loading branch information
Jonas Kauker committed Feb 16, 2025
1 parent 53d3039 commit e51a5f6
Show file tree
Hide file tree
Showing 7 changed files with 135 additions and 1 deletion.
33 changes: 33 additions & 0 deletions app/static/js/auth/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"use strict";
document.addEventListener('DOMContentLoaded', () => {
const registerForm = document.querySelector('#register-form');
if (registerForm) {
registerForm.addEventListener('submit', async (event) => {
event.preventDefault();
const username = document.querySelector('#username').value;
const email = document.querySelector('#email').value;
const password = document.querySelector('#password').value;
try {
const response = await fetch('/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, email, password })
});
const data = await response.json();
if (response.ok) {
alert('User registered successfully');
// Optionally, redirect to another page or update the UI
}
else {
alert(`Error: ${data.message}`);
}
}
catch (error) {
console.error('Error:', error);
alert('An error occurred. Please try again.');
}
});
}
});
1 change: 1 addition & 0 deletions app/static/js/auth/register.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"use strict";
1 change: 1 addition & 0 deletions app/static/js/auth/session.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"use strict";
1 change: 1 addition & 0 deletions app/static/js/fastifyInstance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"use strict";
87 changes: 87 additions & 0 deletions app/static/js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"use strict";
const fastify = require("fastify")();
const fastifyView = require("@fastify/view");
const fastifyFormbody = require("@fastify/formbody");
const path = require('path');
const fastifyStatic = require('@fastify/static');
fastify.register(fastifyView, {
engine: {
ejs: require("ejs")
},
options: {
context: {
get: (obj, prop) => obj && obj[prop]
}
}
});
fastify.register(fastifyStatic, {
root: path.join(__dirname, '../static'),
prefix: '/static/'
});
fastify.register(fastifyStatic, {
root: path.join(__dirname, '../build'),
prefix: '/js/'
});
fastify.register(fastifyFormbody);
fastify.get("/partial/:page", async (req, reply) => {
const page = req.params.page;
const dataSample = { name: "Jonas" }; // fetch data here
return reply.view(`pages/${page}.ejs`, dataSample);
});
fastify.get("/", async (req, reply) => {
return reply.viewAsync("pages/index.ejs", { name: "Jonas" }, {
layout: "layouts/basic.ejs"
});
});
fastify.post("/login", async (req, reply) => {
const { username, password } = req.body;
try {
const res = await fetch("http://localhost:4242/login", {
method: "POST",
body: JSON.stringify({ username, password }),
headers: { "Content-Type": "application/json" }
});
const data = await res.json();
if (res.ok) {
console.log(data);
return reply.viewAsync("pages/index.ejs", { user: "yes!" }, {
layout: "layouts/basic.ejs"
});
}
else {
reply.status(401).send({ message: 'Invalid username or password' });
}
}
catch (err) {
reply.status(401).send({ message: 'Something went wrong whilst trying to perfrom the login action' });
}
});
fastify.post("/register", async (req, reply) => {
const { username, password, email } = req.body;
console.log(username, password, email);
try {
const res = await fetch("http://localhost:4242/register", {
method: "POST",
body: JSON.stringify({ username, password, email }),
headers: { "Content-Type": "application/json" }
});
const data = await res.json();
if (res.ok) {
console.log(data);
return reply.viewAsync("pages/index.ejs", { user: "registered yes!" }, {
layout: "layouts/basic.ejs"
});
}
else {
reply.status(401).send({ message: 'Invalid username or password' });
}
}
catch (err) {
reply.status(401).send({ message: 'Something went wrong whilst trying to perfrom the register action' });
}
});
fastify.listen({ port: 3000 }, (err) => {
if (err)
throw err;
console.log(`Server on port ${fastify.server.address().port}`);
});
1 change: 1 addition & 0 deletions app/static/js/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"use strict";
12 changes: 11 additions & 1 deletion app/static/js/script.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
let pageScript = null;

async function loadPartialView(page) {
async function loadPartialView(page, pushState = true) {
const response = await fetch(`/partial/${page}`);
const html = await response.text();
console.log("switching to page: " + page);
Expand All @@ -19,8 +19,18 @@ async function loadPartialView(page) {
pageScript = script;
}

if (pushState) {
history.pushState({ page }, '', `/${page}`);
}

}

window.addEventListener('popstate', (event) => {
if (event.state && event.state.page) {
loadPartialView(event.state.page, false);
}
});

function toggleDarkMode() {
document.body.classList.toggle('dark');
const isDarkMode = document.body.classList.contains('dark');
Expand Down

0 comments on commit e51a5f6

Please sign in to comment.