nice
This commit is contained in:
175
day68/src/lib/router/SSR/ssrHydrationGenerator.ts
Normal file
175
day68/src/lib/router/SSR/ssrHydrationGenerator.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
import { ReactifyTemplate, hydrateModelAttributes, hydrateKeyDown } from '../hydrationManager';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { Reactive } from '../../ReactiveObject';
|
||||
import { initAppState } from '../../../main';
|
||||
|
||||
function SSRHydrateElement(querySelector: string, eventListenerName: string, removeAttribute?: boolean) {
|
||||
let script = '';
|
||||
const queryName: Array<string> | null = /(?<=\[).+?(?=\])/.exec(querySelector);
|
||||
if (!queryName || !queryName[0]) return;
|
||||
const querySelectorAll = (querySelector.replace(':', '\\\\\\\\3A '));
|
||||
querySelector = queryName[0];
|
||||
let removeAttributeString = '';
|
||||
if (removeAttribute === undefined || removeAttribute === true) {
|
||||
removeAttributeString = `e.removeAttribute('${querySelector}');`;
|
||||
}
|
||||
script += `const ${querySelector.split(':')[1]}Elms = eval("document.querySelectorAll('${querySelectorAll}')");
|
||||
${querySelector.split(':')[1]}Elms.forEach((e) => {
|
||||
const ${querySelector.split(':')[1]}HydartionFunction = e.getAttribute('${querySelector}');
|
||||
${removeAttributeString}
|
||||
if (!${querySelector.split(':')[1]}HydartionFunction) return;
|
||||
e.addEventListener('${eventListenerName}', () => {
|
||||
eval(${querySelector.split(':')[1]}HydartionFunction);
|
||||
});
|
||||
});`;
|
||||
return script;
|
||||
}
|
||||
|
||||
export async function renderSSRHydrationCode(template: string, reduceJavascript = false) {
|
||||
const dom = new JSDOM(template);
|
||||
let script = '';
|
||||
|
||||
if (template.includes('appState.contents.') || template.includes('data-token')) {
|
||||
script += `
|
||||
const { getAppState, initAppState } = await import('/src/main.ts');await initAppState();const appState = getAppState();
|
||||
` + ReactifyTemplate.toString() + 'ReactifyTemplate(appState);';
|
||||
}
|
||||
|
||||
if (template.includes('d-if')) {
|
||||
const conditionalElms = Array.from(dom.window.document.querySelectorAll('*[d-if]'));
|
||||
if (conditionalElms.length === 0) return;
|
||||
conditionalElms.forEach(async (e: Element) => {
|
||||
const condition = e.getAttribute('d-if');
|
||||
e.removeAttribute('d-if');
|
||||
|
||||
const siblingConditionalElms: Array<Element> = [];
|
||||
// recursively check for subsequent elements with the d-else of d-else-if attribute
|
||||
function checkForConditionSibling(elm: Element) {
|
||||
if (!elm.nextElementSibling || typeof elm.nextElementSibling == 'undefined') return;
|
||||
if (elm.nextElementSibling?.getAttribute('d-else-if') !== null) {
|
||||
siblingConditionalElms.push(elm.nextElementSibling);
|
||||
if (!elm.nextElementSibling) return;
|
||||
checkForConditionSibling(elm.nextElementSibling);
|
||||
}
|
||||
|
||||
if (elm.nextElementSibling?.getAttribute('d-else') !== null) {
|
||||
siblingConditionalElms.push(elm.nextElementSibling);
|
||||
}
|
||||
}
|
||||
checkForConditionSibling(e);
|
||||
|
||||
if (siblingConditionalElms == undefined) return;
|
||||
|
||||
const uniqueSelector = generateLabel(e.textContent);
|
||||
e.setAttribute('uuid', uniqueSelector);
|
||||
function generateLabel(textContent: string, count = 1) {
|
||||
if (script.includes(textContent + '-' + count) || template.includes(textContent + '-' + count)) {
|
||||
generateLabel(textContent, count++);
|
||||
} else {
|
||||
return textContent + '-' + count;
|
||||
}
|
||||
}
|
||||
script += 'function resetHTML() {';
|
||||
script += `document.querySelector('*[uuid="${uniqueSelector}"]').innerHTML = '<!-- d-if -->';`;
|
||||
const sublingUUIDMap = new Map();
|
||||
siblingConditionalElms.forEach((elm, i) => {
|
||||
if (!elm) return;
|
||||
const siblingUniqueSelector = generateLabel(elm.textContent);
|
||||
elm.setAttribute('uuid', siblingUniqueSelector);
|
||||
script += `document.querySelector('*[uuid="${siblingUniqueSelector}"').innerHTML = '<!-- d-if -->';`;
|
||||
sublingUUIDMap[i.toString()] = siblingUniqueSelector;
|
||||
});
|
||||
script += '}';
|
||||
|
||||
let ifStatement = `if (${condition}) {
|
||||
document.querySelector('*[uuid="${uniqueSelector}"').innerHTML = "${e.innerHTML}"
|
||||
} `;
|
||||
|
||||
siblingConditionalElms.forEach((element, i) => {
|
||||
if (!element) return;
|
||||
const siblingHTML = element.innerHTML;
|
||||
let statementDirective = 'else';
|
||||
element.removeAttribute('d-else');
|
||||
if (element.getAttribute('d-else-if') !== null) {
|
||||
statementDirective = 'else if';
|
||||
}
|
||||
const condition = element.getAttribute('d-' + statementDirective.split(' ').join('-'));
|
||||
|
||||
if (statementDirective == 'else if') {
|
||||
statementDirective = `else if (${condition})`;
|
||||
element.removeAttribute('d-else-if');
|
||||
}
|
||||
|
||||
const siblingUuid = sublingUUIDMap[i.toString()];
|
||||
ifStatement = ifStatement + statementDirective + `{
|
||||
document.querySelector('*[uuid="${siblingUuid}"').innerHTML = ("${siblingHTML.toString()}")
|
||||
}`;
|
||||
});
|
||||
|
||||
if (!condition) return;
|
||||
script += 'resetHTML();';
|
||||
script += `eval(\`${ifStatement}\`);`;
|
||||
|
||||
if (condition.includes('appState.contents.')) {
|
||||
let reactiveProp: Array<string> | string | null | undefined = /appState\.contents\.[a-zA-Z]+/.exec(condition);
|
||||
if (!reactiveProp || !reactiveProp[0]) return;
|
||||
reactiveProp = reactiveProp[0].split('.')[2];
|
||||
if (!reactiveProp) return;
|
||||
script += `appState.listen("${reactiveProp}", () => {
|
||||
resetHTML();
|
||||
eval(\`${ifStatement}\`);
|
||||
});`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (template.includes('d-on:click')) {
|
||||
script += SSRHydrateElement('*[d-on:click]', 'click');
|
||||
}
|
||||
|
||||
if (template.includes('d-on:mouseDown')) {
|
||||
script += SSRHydrateElement('*[d-on:mouseDown]', 'mousedown');
|
||||
}
|
||||
|
||||
if (template.includes('d-on:mouseUp')) {
|
||||
script += SSRHydrateElement('*[d-on:mouseUp]', 'mouseup');
|
||||
}
|
||||
|
||||
if (template.includes('d-model')) {
|
||||
if (!script.includes('const { getAppState, initAppState } = ')) script += 'const { getAppState, initAppState } = await import(\'/src/main.ts\');';
|
||||
if (!script.includes('const appState =')) script += 'await initAppState();const appState = getAppState();';
|
||||
script += hydrateModelAttributes.toString() + 'hydrateModelAttributes(appState);';
|
||||
}
|
||||
|
||||
// check if there are links to hydrate
|
||||
if (template.includes('<a') && !reduceJavascript) {
|
||||
script += `
|
||||
const anchorElms = document.querySelectorAll('a');
|
||||
anchorElms.forEach((e) => {
|
||||
if (e.href === window.location.href) {
|
||||
e.setAttribute('link:active', '');
|
||||
e.setAttribute('tabindex', '-1');
|
||||
}
|
||||
}); `;
|
||||
}
|
||||
|
||||
if (template.includes('d-on:keydown.')) {
|
||||
script += hydrateKeyDown.toString() + 'hydrateKeyDown();';
|
||||
}
|
||||
|
||||
if (template.includes('d-on:pointerEnter')) {
|
||||
script += SSRHydrateElement('*[d-on:pointerEnter]', 'pointerenter');
|
||||
}
|
||||
|
||||
if (template.includes('d-on:pointerExit')) {
|
||||
script += SSRHydrateElement('*[d-on:pointerExit]', 'pointerleave');
|
||||
}
|
||||
|
||||
if (script.includes('const { getAppState, initAppState } = await import(\'/src/main.ts\');await initAppState();const appState = getAppState();')) {
|
||||
script = script.replace('const { getAppState, initAppState } = await import(\'/src/main.ts\');await initAppState();const appState = getAppState();', Reactive.toString() + 'let appState;' + initAppState.toString() + ' await initAppState();').replace('__vite_ssr_import_0__.', '').replace('__vite_ssr_dynamic_import__', 'import');
|
||||
}
|
||||
|
||||
template = dom.window.document.body.innerHTML;
|
||||
|
||||
return { script, template };
|
||||
}
|
||||
259
day68/src/lib/router/hydrationManager.ts
Normal file
259
day68/src/lib/router/hydrationManager.ts
Normal file
@@ -0,0 +1,259 @@
|
||||
import { getAppState, initAppState } from '../../main';
|
||||
import { renderPage } from './pageRenderer';
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import { getCookie, setCookie } from '../cookieManager';
|
||||
import { Reactive } from '../ReactiveObject';
|
||||
|
||||
// function to turn the template into reactive content "hydating" a page
|
||||
export async function hydratePage(reduceJavascript?: boolean) {
|
||||
if (import.meta.env.SSR) return;
|
||||
if (reduceJavascript === undefined) reduceJavascript = false;
|
||||
await initAppState();
|
||||
const appState = getAppState();
|
||||
const documentBody = document.getElementById('app');
|
||||
if (!documentBody) {
|
||||
throw new Error('Fatal Error: element with id app not found');
|
||||
}
|
||||
|
||||
ReactifyTemplate(appState);
|
||||
|
||||
// here we look for elements with the d-on:click attribute and on click run the function in the attribute
|
||||
hydrateElement('*[d-on:click]', appState, 'click', getCookie, setCookie);
|
||||
|
||||
// here we determine if an element should be deleted form the DOM via the d-if directive
|
||||
hydrateIfAttributes(appState);
|
||||
|
||||
hydrateElement('*[d-on:pointerEnter]', appState, 'pointerenter', getCookie, setCookie);
|
||||
|
||||
hydrateElement('*[d-on:pointerExit]', appState, 'pointerleave', getCookie, setCookie);
|
||||
|
||||
hydrateElement('*[d-on:mouseDown]', appState, 'mousedown', getCookie, setCookie);
|
||||
|
||||
hydrateElement('*[d-on:mouseUp]', appState, 'mouseup', getCookie, setCookie);
|
||||
|
||||
// here we look for elements with the d-model attribute and if there is any input in the element then we update the appState item with the name
|
||||
// of the attribute value
|
||||
// example: if the user types "hello" into a text field with the d-model attribute of "text" then we update the appState item with the name "text"
|
||||
// to "hello"
|
||||
// similar to vue.js v-model attribute
|
||||
hydrateModelAttributes(appState);
|
||||
|
||||
hydrateHeadElements(appState);
|
||||
|
||||
hydrateAnchorElements(reduceJavascript);
|
||||
|
||||
hydrateKeyDown(appState);
|
||||
}
|
||||
|
||||
export function ReactifyTemplate(appState: Reactive) {
|
||||
Array.from(document.querySelectorAll('span')).forEach((e) => {
|
||||
const reactiveElms = Array.from(e.attributes).filter((arrElm) => {
|
||||
return arrElm.name.startsWith('data-token-');
|
||||
});
|
||||
|
||||
if (reactiveElms.length === 0) return;
|
||||
reactiveElms.forEach((elm) => {
|
||||
const item = elm.name;
|
||||
const uuid = item.split('data-token-')[1];
|
||||
if (!uuid) throw new Error('Internal error: decoded uuid not found');
|
||||
let decodedUuid = '';
|
||||
for (let i = 0; i < uuid.length; i += 2) {
|
||||
decodedUuid += String.fromCharCode(parseInt(uuid.substr(i, 2), 16));
|
||||
}
|
||||
|
||||
if (e.parentElement?.hasAttribute('d-once')) {
|
||||
e.parentElement.removeAttribute('d-once');
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.parentElement?.hasAttribute('d-html')) {
|
||||
appState.listen(decodedUuid, (change: string) => e.innerHTML = change);
|
||||
} else {
|
||||
appState.listen(decodedUuid, (change: string) => e.textContent = change);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export function hydrateIfAttributes(appState: Reactive) {
|
||||
const conditionalElms = Array.from(document.querySelectorAll('*[d-if]'));
|
||||
if (conditionalElms.length === 0) return;
|
||||
conditionalElms.forEach(async (e: Element) => {
|
||||
const condition = e.getAttribute('d-if');
|
||||
|
||||
const siblingConditionalElms: Array<Element> = [];
|
||||
// recursively check for subsequent elements with the d-else of d-else-if attribute
|
||||
function checkForConditionSibling(elm: Element) {
|
||||
if (!elm.nextElementSibling || typeof elm.nextElementSibling == 'undefined') return;
|
||||
if (elm.nextElementSibling?.getAttribute('d-else-if') !== null) {
|
||||
siblingConditionalElms.push(elm.nextElementSibling);
|
||||
if (!elm.nextElementSibling) return;
|
||||
checkForConditionSibling(elm.nextElementSibling);
|
||||
}
|
||||
|
||||
if (elm.nextElementSibling?.getAttribute('d-else') !== null) {
|
||||
siblingConditionalElms.push(elm.nextElementSibling);
|
||||
}
|
||||
}
|
||||
checkForConditionSibling(e);
|
||||
|
||||
if (siblingConditionalElms == undefined) return;
|
||||
|
||||
function resetHTML() {
|
||||
e.innerHTML = '<!-- d-if -->';
|
||||
siblingConditionalElms.forEach((elm) => {
|
||||
if (!elm) return;
|
||||
elm.innerHTML = '<!-- d-if -->';
|
||||
});
|
||||
}
|
||||
|
||||
let ifStatement = `if (${condition}) {
|
||||
e.innerHTML = "${e.innerHTML}"
|
||||
} `;
|
||||
|
||||
siblingConditionalElms.forEach((element, i) => {
|
||||
if (!element) return;
|
||||
const siblingHTML = element.innerHTML;
|
||||
element.innerHTML = '<!-- d-if -->';
|
||||
let statementDirective = 'else';
|
||||
element.removeAttribute('d-else');
|
||||
if (element.getAttribute('d-else-if') !== null) {
|
||||
statementDirective = 'else if';
|
||||
}
|
||||
const condition = element.getAttribute('d-' + statementDirective.split(' ').join('-'));
|
||||
|
||||
if (statementDirective == 'else if') {
|
||||
statementDirective = `else if (${condition})`;
|
||||
element.removeAttribute('d-else-if');
|
||||
}
|
||||
|
||||
ifStatement = ifStatement + statementDirective + `{
|
||||
siblingConditionalElms[${i}].innerHTML = "${siblingHTML}"
|
||||
}`;
|
||||
});
|
||||
|
||||
e.removeAttribute('d-if');
|
||||
if (!condition) return;
|
||||
resetHTML();
|
||||
eval(ifStatement);
|
||||
|
||||
if (condition.includes('appState.contents.')) {
|
||||
let reactiveProp: Array<string> | string | null | undefined = /appState\.contents\.[a-zA-Z]+/.exec(condition);
|
||||
if (!reactiveProp || !reactiveProp[0]) return;
|
||||
reactiveProp = reactiveProp[0].split('.')[2];
|
||||
if (!reactiveProp) return;
|
||||
appState.listen(reactiveProp, () => {
|
||||
resetHTML();
|
||||
eval(ifStatement);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function hydrateElement(querySelector: string, appState: Reactive, eventListenerName: string, getCookie: CallableFunction, setCookie: CallableFunction, removeAttribute?: boolean) {
|
||||
const queryName: Array<string> | null = /(?<=\[).+?(?=\])/.exec(querySelector);
|
||||
if (!queryName || !queryName[0]) return;
|
||||
const querySelectorAll = (querySelector.replace(':', '\\\\3A '));
|
||||
querySelector = queryName[0];
|
||||
const elms = eval(`Array.from(document.querySelectorAll('${querySelectorAll.toString()}'))`);
|
||||
if (elms.length === 0) return;
|
||||
elms.forEach(async (e: Element) => {
|
||||
const hydrationFunction = e.getAttribute(`${querySelector}`);
|
||||
|
||||
if (removeAttribute === undefined || removeAttribute === true) {
|
||||
e.removeAttribute(`${querySelector}`);
|
||||
}
|
||||
if (!hydrationFunction) return;
|
||||
e.addEventListener(eventListenerName, () => {
|
||||
eval(hydrationFunction);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function hydrateModelAttributes(appState: Reactive) {
|
||||
const modelElms = Array.from(document.querySelectorAll('input[d-model], textarea[d-model]'));
|
||||
if (modelElms.length === 0) return;
|
||||
modelElms.forEach((e: Element) => {
|
||||
const modelName = e.getAttribute('d-model');
|
||||
if (!modelName) return;
|
||||
e.addEventListener('input', (input: Event) => {
|
||||
const target = input.target as HTMLInputElement;
|
||||
appState.contents[modelName] = target.value;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export function hydrateHeadElements(appState: Reactive) {
|
||||
const headContent = document.head.innerHTML;
|
||||
const headElements = Array.from(document.querySelectorAll('devto\\3A head'));
|
||||
if (headElements.length === 0) return;
|
||||
headElements.forEach((e: Element) => {
|
||||
if (e.childNodes.length == 0) return;
|
||||
e.childNodes.forEach((elm) => {
|
||||
const child = elm as Element;
|
||||
if (child.nodeType !== 1) return;
|
||||
if (!document.head.querySelectorAll(child.tagName)) return;
|
||||
document.head.appendChild(child);
|
||||
});
|
||||
e.remove();
|
||||
});
|
||||
|
||||
document.addEventListener('router:naviagte', () => {
|
||||
document.head.innerHTML = headContent;
|
||||
}, { once: true });
|
||||
}
|
||||
|
||||
export function hydrateAnchorElements(reduceJavascript: boolean) {
|
||||
const anchorElms = Array.from(document.querySelectorAll('a'));
|
||||
anchorElms.forEach((e: HTMLAnchorElement) => {
|
||||
if (!reduceJavascript && e.href === window.location.href) {
|
||||
e.setAttribute('link:active', '');
|
||||
e.setAttribute('tabindex', '-1');
|
||||
}
|
||||
e.addEventListener('click', async (click: MouseEvent) => {
|
||||
if (!event || click.ctrlKey) return;
|
||||
const target = click.target as HTMLElement;
|
||||
event.preventDefault();
|
||||
|
||||
if (!target) return;
|
||||
const url: string | null = target.getAttribute('href');
|
||||
|
||||
if (!url) return;
|
||||
await renderPage(url);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
export function hydrateKeyDown(appState: Reactive) {
|
||||
Array.from(document.body.querySelectorAll('*')).forEach((e) => {
|
||||
const keydownElms = Array.from(e.attributes).filter((arrElm) => {
|
||||
return arrElm.name.startsWith('d-on:keydown');
|
||||
});
|
||||
|
||||
if (keydownElms.length === 0) return;
|
||||
keydownElms.forEach((attr) => {
|
||||
const item = attr.name;
|
||||
let key = item.split('.')[1]?.toLowerCase();
|
||||
if (key && key?.length > 0) {
|
||||
key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
|
||||
}
|
||||
e.addEventListener('keydown', (keydown) => {
|
||||
const keyboardEvent = <KeyboardEvent>keydown;
|
||||
let keyName = keyboardEvent.key;
|
||||
if (keyName === ' ') {
|
||||
keyName = 'Space';
|
||||
}
|
||||
const firstLetter = keyName.split('')[0];
|
||||
keyName = firstLetter?.toUpperCase() + keyName.slice(1).toLowerCase();
|
||||
if (keyName == key) {
|
||||
const itemCode = e.getAttribute(item);
|
||||
if (!itemCode) return;
|
||||
eval(itemCode);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
320
day68/src/lib/router/pageRenderer.ts
Normal file
320
day68/src/lib/router/pageRenderer.ts
Normal file
@@ -0,0 +1,320 @@
|
||||
import { compileToString } from '../templateRenderer';
|
||||
import { appState, isSSR, isHTML, debugMode } from '../../main';
|
||||
import { LRUCache } from '../lruCache';
|
||||
|
||||
if (!appState) console.error('no reactive data found');
|
||||
|
||||
let documentBody: string | HTMLElement | null;
|
||||
const cache = new LRUCache(15);
|
||||
|
||||
if (import.meta.env.SSR) {
|
||||
const fs = await import('fs');
|
||||
const path = await import('path');
|
||||
documentBody = fs.readFileSync(
|
||||
path.resolve('index.html'),
|
||||
'utf-8'
|
||||
);
|
||||
} else {
|
||||
documentBody = document.getElementById('app');
|
||||
}
|
||||
|
||||
|
||||
// Global function to handle rendering a page and navigation
|
||||
export async function renderPage(route?: string) {
|
||||
if (isSSR() || typeof documentBody == 'string') return;
|
||||
|
||||
if (!window.history) {
|
||||
throw new Error('window.history is not supported, please update your browser');
|
||||
}
|
||||
|
||||
if (!documentBody) {
|
||||
throw new Error('Fatal Error: element with id app not found');
|
||||
}
|
||||
|
||||
if (route && route === window.location.pathname) return;
|
||||
|
||||
if (route) {
|
||||
history.pushState('', '', route);
|
||||
document.dispatchEvent(new Event('router:naviagte'));
|
||||
}
|
||||
|
||||
let fileName: string | Array<string> = window.location.pathname.split('/');
|
||||
if (fileName[1] === '') {
|
||||
fileName = '/index';
|
||||
} else {
|
||||
fileName = fileName.join('/').toLowerCase().trim();
|
||||
}
|
||||
|
||||
let page: string = await fetchPage(fileName, 'pages');
|
||||
|
||||
if (!page) return;
|
||||
|
||||
const metaObj = { 'layout': 'default', 'reduceJavascript': false, 'suspendUntilHydrated': true };
|
||||
|
||||
parseFromRegex(page, /<script>[\s\S]*?<\/script>/gi).forEach((e: string | undefined) => {
|
||||
if (!e) return;
|
||||
if (e.startsWith('<script>') && e.endsWith('</script>')) {
|
||||
parseFromRegex(e, /definePageMeta\({(.*?)}\)(;){0,1}/g).forEach((metaElm: string | undefined) => {
|
||||
if (!metaElm) return;
|
||||
if (metaElm.startsWith('definePageMeta({')) {
|
||||
let metaObjString = metaElm.split('(')[1]?.split(')')[0];
|
||||
if (!metaObjString) return;
|
||||
metaObjString = metaObjString.replaceAll(' ', '').replaceAll('{', '{\'').replaceAll(':', '\':').replaceAll(',', ',\'').replaceAll('\'', '"');
|
||||
const newMetaObj = JSON.parse(metaObjString);
|
||||
Object.keys(newMetaObj).forEach((key) => {
|
||||
metaObj[key] = newMetaObj[key];
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
let layout: string;
|
||||
try {
|
||||
layout = await fetchPage(`/${metaObj.layout}`, 'layouts', false);
|
||||
} catch {
|
||||
layout = '<slot />';
|
||||
}
|
||||
|
||||
if (!layout) return;
|
||||
|
||||
page = layout.replaceAll('<slot />', page);
|
||||
|
||||
const stringifiedTemplate = await compileToString(page);
|
||||
|
||||
if (!stringifiedTemplate) return;
|
||||
|
||||
if (debugMode) {
|
||||
console.groupCollapsed('✨ Redered page ' + fileName.slice(1));
|
||||
console.log('Template: ' + page);
|
||||
console.info('stringified template: ' + stringifiedTemplate.fnStr);
|
||||
console.groupEnd();
|
||||
}
|
||||
|
||||
// since we have all the html content ready to place in the app, we first need to remove all the old injected content
|
||||
if (route) {
|
||||
const childrenToRemove = document.head.querySelectorAll('*[local]');
|
||||
childrenToRemove.forEach(child => document.head.removeChild(child));
|
||||
}
|
||||
|
||||
if (metaObj.suspendUntilHydrated) {
|
||||
// here we are hiding the body and hydrating the page "suspending"
|
||||
document.body.style.display = 'none';
|
||||
}
|
||||
|
||||
documentBody.innerHTML = await eval(stringifiedTemplate.fnStr);
|
||||
|
||||
if (stringifiedTemplate.styles) {
|
||||
const cssElement = document.createElement('style');
|
||||
cssElement.type = 'text/css';
|
||||
cssElement.setAttribute('local', 'true');
|
||||
cssElement.innerHTML = stringifiedTemplate.styles;
|
||||
document.head.appendChild(cssElement);
|
||||
}
|
||||
|
||||
if (stringifiedTemplate.script || stringifiedTemplate.setupScript) {
|
||||
const scriptElement = document.createElement('script');
|
||||
scriptElement.async = true;
|
||||
scriptElement.type = 'module';
|
||||
scriptElement.setAttribute('local', 'true');
|
||||
scriptElement.innerHTML = stringifiedTemplate.setupScript + stringifiedTemplate.script;
|
||||
document.head.appendChild(scriptElement);
|
||||
}
|
||||
|
||||
// here we hydrate/re-hydrate the page content
|
||||
const { hydratePage } = await import('./hydrationManager');
|
||||
await hydratePage(metaObj.reduceJavascript);
|
||||
|
||||
if (metaObj.suspendUntilHydrated) {
|
||||
// here we show the page as its been hydtated
|
||||
document.body.style.display = 'block';
|
||||
}
|
||||
|
||||
// tell the document that the client has fully rendered and hydrated the page
|
||||
document.dispatchEvent(new Event('router:client:load'));
|
||||
}
|
||||
|
||||
async function fetchPage(url: string, dir: string, return404?: boolean): Promise<string> {
|
||||
if (import.meta.env.SSR) return '';
|
||||
if (isSSR()) throw new Error('page shouldnt be loaded on server side');
|
||||
if (return404 === undefined) return404 = true;
|
||||
let path: string;
|
||||
(import.meta.env.PROD) ? path = '/' : path = '/src/';
|
||||
|
||||
let file: string | undefined;
|
||||
const cachedFile = cache.get(dir + url);
|
||||
|
||||
if (cachedFile) {
|
||||
if (debugMode) {
|
||||
console.groupCollapsed(`🗃️ Loaded page ${dir}${url} from cache`);
|
||||
console.log(cachedFile);
|
||||
console.groupEnd();
|
||||
}
|
||||
|
||||
file = cachedFile;
|
||||
} else {
|
||||
file = await fetch(path + `${dir}${url}.devto`).then((response) => {
|
||||
if (response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
throw new Error('File not found');
|
||||
})
|
||||
.then((data) => {
|
||||
if (!data) return undefined;
|
||||
cache.set(dir + url, data);
|
||||
console.groupCollapsed(`🌐 Fetched page ${dir}${url}`);
|
||||
console.log(data);
|
||||
console.groupEnd();
|
||||
return data;
|
||||
})
|
||||
.catch(async () => {
|
||||
if (!return404) {
|
||||
throw new Error('object not found and not returning a 404 page');
|
||||
}
|
||||
return (await fetch(path + 'layouts/404.devto').then((response) => {
|
||||
if (response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
throw new Error('Error fetching 404 page');
|
||||
})
|
||||
.then((data) => {
|
||||
if (!data) return undefined;
|
||||
return data;
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (!file) return '';
|
||||
|
||||
let template = file;
|
||||
const elements: Array<string> = file.split('<');
|
||||
const renderedComponents: Array<string> = [];
|
||||
|
||||
await Promise.all(elements.map(async (component: string | undefined) => {
|
||||
if (!component || !file) return;
|
||||
component = component.split(' ')[0];
|
||||
if (component?.includes('/') || component?.includes('{') || !component) return;
|
||||
component = component.split('>')[0];
|
||||
if (!component) return;
|
||||
if (isHTML(component)) return;
|
||||
const slotedComponent = template.split('<' + component + '>');
|
||||
let isSloted = false;
|
||||
let slotData: string | undefined;
|
||||
if (slotedComponent.length > 1) {
|
||||
isSloted = true;
|
||||
slotedComponent.forEach((splitComponent, i, arr) => {
|
||||
if (splitComponent.includes('</' + component + '>')) {
|
||||
slotData = arr[i]?.split('</' + component + '>')[0];
|
||||
}
|
||||
});
|
||||
template = template.split('<' + component + '>' + slotData + '</' + component + '>').join('<!--' + component + '-->');
|
||||
}
|
||||
|
||||
if (renderedComponents.indexOf(component) == -1) {
|
||||
renderedComponents.push(component);
|
||||
file = await renderComponent(component, path);
|
||||
if (isSloted && slotData) {
|
||||
file = file.replaceAll('<slot />', slotData);
|
||||
}
|
||||
|
||||
let componentName = '<' + component;
|
||||
(!isSloted) ? componentName += ' />' : componentName = '<!--' + component + '-->';
|
||||
|
||||
template = template.replaceAll(componentName, file);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
return template;
|
||||
}
|
||||
|
||||
async function renderComponent(component: string, path: string) {
|
||||
const componentName = component;
|
||||
const cachedComponent = cache.get('components/' + component);
|
||||
|
||||
if (cachedComponent) {
|
||||
if (debugMode) {
|
||||
console.groupCollapsed(`🗃️ Loaded component ${component} from cache`);
|
||||
console.log(cachedComponent);
|
||||
console.groupEnd();
|
||||
}
|
||||
|
||||
component = cachedComponent;
|
||||
} else {
|
||||
await fetch(path + `components/${component}.devto`).then((response) => {
|
||||
if (response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
return '';
|
||||
})
|
||||
.then((data) => {
|
||||
cache.set('components/' + component, data);
|
||||
if (debugMode) {
|
||||
console.groupCollapsed(`🌐 Fetched component ${component}`);
|
||||
console.log('Template:', data);
|
||||
console.groupEnd();
|
||||
}
|
||||
component = data;
|
||||
});
|
||||
}
|
||||
|
||||
const elements = component.split('<');
|
||||
await Promise.all(elements.map(async (componentInComponent: string | undefined) => {
|
||||
if (!componentInComponent) return;
|
||||
componentInComponent = componentInComponent.split(' ')[0];
|
||||
if (componentInComponent?.includes('/') || componentInComponent?.includes('{') || !componentInComponent) return;
|
||||
componentInComponent = componentInComponent.split('>')[0];
|
||||
if (!componentInComponent) return;
|
||||
if (isHTML(componentInComponent)) return;
|
||||
if (componentInComponent === componentName) {
|
||||
console.error('Cannot include a component in itself, ignoring component (rendering ' + componentInComponent + ')');
|
||||
return;
|
||||
}
|
||||
const slotedComponent = component.split('<' + componentInComponent + '>');
|
||||
let isSloted = false;
|
||||
let slotData: string | undefined;
|
||||
if (slotedComponent.length > 1) {
|
||||
isSloted = true;
|
||||
slotedComponent.forEach((splitComponent, i, arr) => {
|
||||
if (splitComponent.includes('</' + componentInComponent + '>')) {
|
||||
slotData = arr[i]?.split('</' + componentInComponent + '>')[0];
|
||||
}
|
||||
});
|
||||
component = component.split('<' + componentInComponent + '>' + slotData + '</' + componentInComponent + '>').join('<!--' + componentInComponent + '-->');
|
||||
}
|
||||
|
||||
let componentReplacement = await renderComponent(componentInComponent, path);
|
||||
if (isSloted && slotData) {
|
||||
componentReplacement = componentReplacement.replaceAll('<slot />', slotData);
|
||||
}
|
||||
let replacementComponentName = '<' + componentInComponent;
|
||||
(!isSloted) ? replacementComponentName += ' />' : replacementComponentName = '<!--' + componentInComponent + '-->';
|
||||
component = component.replaceAll(replacementComponentName, componentReplacement);
|
||||
}));
|
||||
|
||||
return component;
|
||||
}
|
||||
|
||||
function parseFromRegex(template: string, regex: RegExp) {
|
||||
let result = regex.exec(template);
|
||||
regex.lastIndex = 0;
|
||||
const arr = [];
|
||||
let firstPos;
|
||||
|
||||
while (result) {
|
||||
firstPos = result.index;
|
||||
if (firstPos !== 0) {
|
||||
arr.push(template.substring(0, firstPos));
|
||||
template = template.slice(firstPos);
|
||||
}
|
||||
|
||||
arr.push(result[0]);
|
||||
template = template.slice(result[0]?.length);
|
||||
result = regex.exec(template);
|
||||
regex.lastIndex = 0;
|
||||
}
|
||||
|
||||
if (template) arr.push(template);
|
||||
return arr;
|
||||
}
|
||||
Reference in New Issue
Block a user