ajax test

This commit is contained in:
Bruno Rybársky 2024-02-05 21:21:04 +01:00
parent 5584a61560
commit 2b29d0df16
8 changed files with 147 additions and 14 deletions

@ -20,6 +20,39 @@ function doAccountAction(requestData, successMessage, failureMessage, silent=fal
});
}
function handlePageResponse(data){
if(data.Navigation){
document.getElementById("navbar").innerHTML = data.Navigation;
}
if(data.Page){
document.getElementById("pagearea").innerHTML = data.Page;
if(data.PageLocation){
history.pushState({}, "", data.PageLocation);
}
}
}
function doPageAction(requestData){
return fetch('/page', {
method: 'POST',
body: requestData,
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
handlePageResponse(data);
})
.catch((error) => {
console.error('Error:', error);
});
}
function displayList(data, element_id, delete_function=null) {
const tableContainer = document.getElementById(element_id);
tableContainer.innerHTML = ""; // Clear previous content
@ -86,13 +119,47 @@ function handleResponse(data, SuccessMessage, failureMessage) {
}, 3000);
}
function navigateTo(site, page){
const data = new URLSearchParams();
data.append("action", "getPage");
data.append("site", site);
data.append("page", page);
doPageAction(data);
}
function refreshNavbar(){
const data = new URLSearchParams();
data.append("action", "getNavigation");
doPageAction(data);
}
function logout() {
const data = new URLSearchParams();
data.append("action", "logout");
doAccountAction(data, "Logout Successful!", "Logout failed.").then(() => {
location.reload();
refreshNavbar();
navigateTo("", pageData.defaultPage);
// Expected output: "Success!"
});
}
let links = document.querySelectorAll('.navsite_link, .navpage_link');
// Add click event listener to each link
links.forEach(function(link) {
link.addEventListener('click', function(e) {
e.preventDefault();
// Get page and site information
let page = this.closest('.navpage_item').dataset.page;
let site = this.closest('.navsite_item').dataset.site;
if(site && page){
navigateTo(site, page);
}
// You can use this information to update the URL or perform other actions
});
});

13
endpoints/global/page.php Normal file

@ -0,0 +1,13 @@
<?php
require_once "lib/page.php";
require_once "lib/navigation.php";
function endpoint($endpoint_data): array
{
return match ($endpoint_data["action"]) {
"getNavigation" => getNavigationEndpoint(),
"getPage" => getPageEndpoint($endpoint_data["page"], $endpoint_data["site"]),
default => ["Status" => "Fail", "message" => "Invalid action"],
};
}

@ -16,7 +16,7 @@ $canRender = initRouter();
if ($canRender) {
/** @noinspection PhpArrayIsAlwaysEmptyInspection */
/** @noinspection PhpArrayIsAlwaysEmptyInspection */
session_set_cookie_params(0, '/', "." . $routerRequest["domain"] . "." . $routerRequest["tld"], true, true);
; session_set_cookie_params(0, '/', "." . $routerRequest["domain"] . "." . $routerRequest["tld"], true, true);
session_start();
if (!isLoggedIn()) {

14
lib/dynamic_style.php Normal file

@ -0,0 +1,14 @@
<?php
function doDynamicStyling() :string
{
$dynamic_style = "";
if(isLoggedIn() && !empty($_SESSION["favorite_color"]) && is_int($_SESSION["favorite_color"]) && $_SESSION["favorite_color"] <= 4294967295){
$dynamic_style = "<style>";
$color = dechex($_SESSION["favorite_color"]);
$dynamic_style .= "--root{ --favorite-color: #$color;";
$dynamic_style .= "</style>";
}
return $dynamic_style;
}

@ -94,4 +94,9 @@ function generateNavigation(): string
return $nav_out;
}
function getNavigationEndpoint() :array{
return [
"Status" => "Success",
"Navigation" => generateNavigation(),
];
}

@ -1,5 +1,7 @@
<?php
require_once "lib/inliner.php";
require_once "lib/dynamic_style.php";
require_once "lib/script_data.php";
function renderDynamicPage($page_file): array
{
return require $page_file;
@ -30,17 +32,21 @@ function parsePageTag($input): array
return ['parameters' => [], 'output' => $input];
}
function getPage($page_name = null): array|false|string
function getPage($page_name = null, $site_name = null): string
{
global $routerConfig;
global $routerRequest;
if(!$site_name) {
$site_name = $routerRequest["subdomain"];
}
if(!$page_name){
$page_name = $routerRequest["page_name"];
}
$dynamic_page_file = $routerConfig["page_dir"] . $routerRequest["subdomain"] . "/" . $page_name . ".php";
$page_file = $routerConfig["page_dir"] . $routerRequest["subdomain"] . "/" . $page_name . ".html";
$dynamic_page_file = $routerConfig["page_dir"] . $site_name . "/" . $page_name . ".php";
$page_file = $routerConfig["page_dir"] . $site_name . "/" . $page_name . ".html";
$skeleton = file_get_contents($routerConfig["template_dir"] . "skeleton.html");
$nav = file_get_contents($routerConfig["template_dir"] . "nav.html");
@ -113,13 +119,15 @@ function getPage($page_name = null): array|false|string
$page_title = $page_name;
}
$dynamic_style = "<style>";
if(isLoggedIn() && !empty($_SESSION["favorite_color"]) && is_int($_SESSION["favorite_color"]) && $_SESSION["favorite_color"] <= 4294967295){
$color = dechex($_SESSION["favorite_color"]);
$dynamic_style .= "--root{ --favorite-color: #$color;";
}
$dynamic_style .= "</style>";
$dynamic_style = doDynamicStyling();
$dynamic_script = generateScriptData([
"currentPage" => $page_name,
"currentSite" => $site_name,
"currentTitle" => $page_title,
"defaultPage" => $routerConfig["default_page"],
]);
$navpages = generateNavigation();
$nav = str_replace("__NAV_PAGES__", $navpages, $nav);
@ -127,8 +135,20 @@ function getPage($page_name = null): array|false|string
$out = $skeleton;
$out = str_replace("__TEMPLATE__NAV__", $nav, $out);
$out = str_replace("__TEMPLATE__PAGE__", $page, $out);
$out = str_replace("__TEMPLATE__DYNASCRIPT__", $dynamic_script, $out);
$out = str_replace("__TEMPLATE__DYNASTYLE__", $dynamic_style, $out);
$out = inlineLocalStylesFromHref($out);
$out = inlineScriptFromSrc($out);
return str_replace("__TEMPLATE_PAGE_TITLE__", $page_title, $out);
}
function getPageEndpoint($page_name, $site_name) :array
{
global $routerRequest, $routerConfig;
$page_location = $routerConfig["protocol"] . $site_name . $routerRequest["domain"] . "." . $routerRequest["tld"] . "/" . $page_name;
return [
"Status" => "Success",
"Page" => getPage($page_name, $site_name),
"PageLocation" => $page_location,
];
}

9
lib/script_data.php Normal file

@ -0,0 +1,9 @@
<?php
function generateScriptData($input) :string
{
// Convert PHP array to JSON string
$jsonString = json_encode($input);
// Output JavaScript code with the JSON string
return "<script>let pageData = JSON.parse('$jsonString');</script>";
}

@ -9,9 +9,14 @@
<script async src="https://umami.brn.systems/script.js" data-website-id="95e93885-5c19-4cab-ba9b-2f746a316a2a"></script>
<title>Adlerka __TEMPLATE_PAGE_TITLE__</title>
__TEMPLATE__DYNASTYLE__
__TEMPLATE__DYNASCRIPT__
</head>
<body>
<div id="navbar">
__TEMPLATE__NAV__
</div>
<div id="pagearea">
__TEMPLATE__PAGE__
</div>
</body>
</html>