add day 87
This commit is contained in:
291
day87/src/lib/router/SSR/ssrHydrationGenerator.ts
Normal file
291
day87/src/lib/router/SSR/ssrHydrationGenerator.ts
Normal file
@@ -0,0 +1,291 @@
|
||||
import { ReactifyTemplate, hydrateModelAttributes, hydrateKeyDown, hydrateSubmit } from '../hydrationManager';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import * as terser from 'terser';
|
||||
import { Reactive } from '../../ReactiveObject';
|
||||
import { getAppState, initAppState } from '../../../main';
|
||||
|
||||
const appState = await getAppState();
|
||||
|
||||
async function minify(code: string) {
|
||||
try {
|
||||
code = (await terser.minify(code)).code;
|
||||
} catch (err) {
|
||||
const { message, line, col, pos } = err;
|
||||
console.log({ message, line, col, pos, code });
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
export async function renderSSRHydrationCode(template: string, reduceJavascript = false, serverSideSPALikeRouting = true) {
|
||||
const dom: JSDOM = 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;
|
||||
await Promise.all(conditionalElms.map(async (e: Element, i) => {
|
||||
const { document } = dom.window;
|
||||
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;
|
||||
|
||||
function generateLabel(textContent: string, count?: number) {
|
||||
if (count === undefined) count = 1;
|
||||
let label = '';
|
||||
if (script.includes(textContent + '-' + count) || template.includes(textContent + '-' + count)) {
|
||||
label = generateLabel(textContent, count + 1);
|
||||
} else {
|
||||
label = textContent + '-' + count.toString();
|
||||
}
|
||||
return label;
|
||||
}
|
||||
|
||||
if (!e.textContent) return;
|
||||
const uniqueSelector = generateLabel(e.textContent);
|
||||
e.setAttribute('uuid', uniqueSelector);
|
||||
|
||||
script += `function resetHTML_${i}() {`;
|
||||
script += `document.querySelector('*[uuid="${uniqueSelector}"]').innerHTML = '<!-- d-if -->';`;
|
||||
const siblingUUIDMap = new Map();
|
||||
siblingConditionalElms.forEach((elm, i) => {
|
||||
if (!elm || !elm.textContent) return;
|
||||
const siblingUniqueSelector = generateLabel(elm.textContent);
|
||||
elm.setAttribute('uuid', siblingUniqueSelector);
|
||||
script += `document.querySelector('*[uuid="${siblingUniqueSelector}"').innerHTML = '<!-- d-if -->';`;
|
||||
siblingUUIDMap[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';
|
||||
}
|
||||
|
||||
if (statementDirective == 'else if') {
|
||||
statementDirective = `else if (${element.getAttribute('d-else-if')})`;
|
||||
element.removeAttribute('d-else-if');
|
||||
}
|
||||
|
||||
const siblingUuid = siblingUUIDMap[i.toString()];
|
||||
ifStatement = ifStatement + statementDirective + `{
|
||||
document.querySelector('*[uuid="${siblingUuid}"').innerHTML = ("${siblingHTML.toString()}")
|
||||
}`;
|
||||
});
|
||||
|
||||
ifStatement = await minify(ifStatement, condition);
|
||||
|
||||
script += `const ifStatement_${i} = \`${ifStatement}\`;
|
||||
resetHTML_${i}();
|
||||
eval(ifStatement_${i});`;
|
||||
|
||||
if (condition && 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_${i}();
|
||||
eval(ifStatement_${i});
|
||||
});`;
|
||||
}
|
||||
|
||||
/* reset HTML */
|
||||
document.querySelector('*[uuid="' + uniqueSelector + '"]').innerHTML = '<!-- d-if -->';
|
||||
siblingConditionalElms.forEach((elm, i) => {
|
||||
if (!elm || !elm.textContent) return;
|
||||
const siblingUniqueSelector = siblingUUIDMap[i.toString()];
|
||||
document.querySelector(`*[uuid="${siblingUniqueSelector}"`).innerHTML = '<!-- d-if -->';
|
||||
});
|
||||
|
||||
eval(ifStatement);
|
||||
}));
|
||||
}
|
||||
|
||||
if (template.includes('d-on:')) {
|
||||
const elements = Array.from(dom.window.document.body.querySelectorAll('*'));
|
||||
|
||||
const eventElements = elements.filter((e) => {
|
||||
return Array.from(e.attributes).some(attr => attr.name.startsWith('d-on:') && !attr.name.includes('.'));
|
||||
});
|
||||
|
||||
eventElements.forEach((e) => {
|
||||
|
||||
function generateLabel(textContent: string, count?: number) {
|
||||
if (count === undefined) count = 1;
|
||||
let label = '';
|
||||
if (script.includes(textContent + '-' + count) || template.includes(textContent + '-' + count)) {
|
||||
label = generateLabel(textContent, count + 1);
|
||||
} else {
|
||||
label = textContent + '-' + count.toString();
|
||||
}
|
||||
return label;
|
||||
}
|
||||
|
||||
const label = generateLabel('d-id');
|
||||
|
||||
e.setAttribute('data-dOnId', label);
|
||||
|
||||
const dOnAttrs = Array.from(e.attributes).filter(attr => attr.name.startsWith('d-on:'));
|
||||
|
||||
dOnAttrs.forEach((attr) => {
|
||||
const [, eventType] = attr.name.split(':');
|
||||
|
||||
const inlineCode = escape(attr.value);
|
||||
|
||||
script += `document.querySelector('*[data-dOnId="${label}"]').addEventListener("${eventType}", () => {
|
||||
eval(unescape(\`${inlineCode}\`));
|
||||
});`;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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 || serverSideSPALikeRouting)) {
|
||||
script += `const anchorElms = document.querySelectorAll('a');
|
||||
anchorElms.forEach((e) => {`;
|
||||
|
||||
if (template.includes('client:prefetch') && serverSideSPALikeRouting) script += `e.addEventListener('click', async (event) => {
|
||||
const route = event.target.href;
|
||||
if (route === window.location.pathname) return;
|
||||
if (event.ctrlKey) return;
|
||||
event.preventDefault();
|
||||
if (!('history' in window)) return;
|
||||
history.pushState('', '', route);
|
||||
await fetch(route)
|
||||
.then((response) => response.text())
|
||||
.then((data) => {
|
||||
document.write(data);
|
||||
document.close();
|
||||
});
|
||||
return false;
|
||||
}); e.removeAttribute('client:prefetch');`;
|
||||
|
||||
if (!reduceJavascript) script += `if (e.href === window.location.href) {
|
||||
e.setAttribute('link:active', '');
|
||||
e.setAttribute('tabindex', '-1');
|
||||
}`;
|
||||
script += '}); ';
|
||||
}
|
||||
|
||||
if (template.includes('d-bind:') || template.includes(' :')) {
|
||||
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();';
|
||||
|
||||
|
||||
Array.from(dom.window.document.querySelectorAll('*')).forEach((e: Element, i) => {
|
||||
const bindElms = Array.from(e.attributes).filter((arrElm: Attr) => {
|
||||
return arrElm.name.startsWith('d-bind:') || arrElm.name.startsWith(':');
|
||||
});
|
||||
|
||||
if (bindElms.length === 0) return;
|
||||
bindElms.forEach(async (attr: Attr, attri) => {
|
||||
const item = attr.name;
|
||||
const key = item.split(':')[1]?.toLowerCase();
|
||||
const originalValue = '(' + attr.value + ')';
|
||||
let currentBinding = '';
|
||||
|
||||
e.removeAttribute(item);
|
||||
|
||||
async function setAttribute() {
|
||||
|
||||
if (!key) return;
|
||||
let value = 'return "' + originalValue + '"';
|
||||
const attribute = e.getAttribute(key) || '';
|
||||
if (value.includes('(') || value.includes(')') || value.includes('?') || value.includes(':')) {
|
||||
value = eval(originalValue);
|
||||
}
|
||||
if (value == undefined || attribute == undefined) return;
|
||||
if (attribute) {
|
||||
const originalAttributeValue = (attribute.toString()).split(`${currentBinding}`).join('');
|
||||
currentBinding = value;
|
||||
value = originalAttributeValue + ' ' + value;
|
||||
}
|
||||
e.setAttribute(key, value);
|
||||
}
|
||||
|
||||
if (attri === 0) {
|
||||
e.setAttribute('d-bind-index', i);
|
||||
script += `const originalValue_${i} = "${originalValue}";
|
||||
let currentBinding_${i} = "${currentBinding}";`;
|
||||
}
|
||||
script += `function setAttribute_${attri}() {
|
||||
let value = \`return '${originalValue}'\`;
|
||||
const attribute = \`${e.getAttribute(key)}\`;
|
||||
if (value.includes('(') || value.includes(')') || value.includes('?') || value.includes(':')) {
|
||||
value = eval(originalValue_${i});
|
||||
}
|
||||
if (attribute) {
|
||||
const originalAttributeValue = (attribute.toString()).split(\`${currentBinding}\`).join('');
|
||||
currentBinding_${i} = value;
|
||||
value = originalAttributeValue + ' ' + value;
|
||||
}
|
||||
document.querySelector('*[d-bind-index="${i}"]').setAttribute("${key}", value);
|
||||
}`;
|
||||
|
||||
if (originalValue.includes('appState')) {
|
||||
originalValue.split(' ').forEach((value) => {
|
||||
const propName = value.split('appState.contents.')[1];
|
||||
if (!propName || !value.includes('appState')) return;
|
||||
script += `appState.listen("${propName.replace(')', '')}", () => setAttribute_${attri}());`;
|
||||
});
|
||||
}
|
||||
|
||||
setAttribute();
|
||||
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (template.includes('d-on:keydown.')) {
|
||||
script += hydrateKeyDown.toString() + 'hydrateKeyDown(appState, document.getElementById("app"));';
|
||||
}
|
||||
|
||||
if (template.includes('d-on:submit')) {
|
||||
script += hydrateSubmit.toString() + 'hydrateSubmit(appState, document.getElementById("app"));';
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
319
day87/src/lib/router/hydrationManager.ts
Normal file
319
day87/src/lib/router/hydrationManager.ts
Normal file
@@ -0,0 +1,319 @@
|
||||
import { getAppState } 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;
|
||||
const appState = await getAppState();
|
||||
const documentBody = document.getElementById('app');
|
||||
|
||||
if (!documentBody) {
|
||||
throw new Error('Fatal Error: element with id app not found');
|
||||
}
|
||||
|
||||
ReactifyTemplate(appState);
|
||||
|
||||
hydrateHeadElements(appState);
|
||||
hydrateIfAttributes(appState);
|
||||
hydrateAnchorElements(reduceJavascript);
|
||||
|
||||
// interactive hydration
|
||||
hydrateBindElements(appState, documentBody);
|
||||
hydrateElements(appState);
|
||||
|
||||
// Update app state items with input values from elements with the "d-model" attribute.
|
||||
// Similar to Vue.js' v-model attribute.
|
||||
hydrateModelAttributes(appState);
|
||||
hydrateKeyDown(appState, documentBody);
|
||||
hydrateSubmit(appState, documentBody);
|
||||
}
|
||||
|
||||
export function ReactifyTemplate(appState: Reactive) {
|
||||
const spanElements = Array.from(document.querySelectorAll('span'));
|
||||
|
||||
spanElements.forEach(spanElement => {
|
||||
// Get all attributes that start with "data-token-"
|
||||
const reactiveElms = Array.from(spanElement.attributes).filter(attr => attr.name.startsWith('data-token-'));
|
||||
|
||||
if (reactiveElms.length === 0) return;
|
||||
|
||||
reactiveElms.forEach(reactiveElm => {
|
||||
const attributeName = reactiveElm.name;
|
||||
const uuid = attributeName.split('data-token-')[1];
|
||||
|
||||
// If the uuid is not found, throw an error
|
||||
if (!uuid) throw new Error('Internal error: decoded uuid not found');
|
||||
|
||||
// Decode the uuid
|
||||
let decodedUuid = '';
|
||||
for (let i = 0; i < uuid.length; i += 2) {
|
||||
decodedUuid += String.fromCharCode(parseInt(uuid.substr(i, 2), 16));
|
||||
}
|
||||
|
||||
// If the span element's parent has the "d-once" attribute, remove it and return since we're only doing it once
|
||||
if (spanElement.parentElement?.hasAttribute('d-once')) {
|
||||
spanElement.parentElement.removeAttribute('d-once');
|
||||
return;
|
||||
}
|
||||
|
||||
// If the span element's parent has the "d-html" attribute, listen to the decoded uuid
|
||||
// and set the span element's innerHTML to the change value
|
||||
if (spanElement.parentElement?.hasAttribute('d-html')) {
|
||||
appState.listen(decodedUuid, (change: string) => spanElement.innerHTML = change);
|
||||
return;
|
||||
}
|
||||
|
||||
appState.listen(decodedUuid, (change: string | null) => spanElement.textContent = change);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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> = [];
|
||||
let currentElm = e;
|
||||
// recursively check for subsequent elements with the d-else of d-else-if attribute
|
||||
while (currentElm.nextElementSibling) {
|
||||
const nextElm = currentElm.nextElementSibling;
|
||||
if (nextElm.getAttribute('d-else-if') !== null) {
|
||||
siblingConditionalElms.push(nextElm);
|
||||
} else if (nextElm.getAttribute('d-else') !== null) {
|
||||
siblingConditionalElms.push(nextElm);
|
||||
break;
|
||||
}
|
||||
currentElm = nextElm;
|
||||
}
|
||||
|
||||
if (siblingConditionalElms == undefined) return;
|
||||
|
||||
const resetHTML = () => {
|
||||
e.innerHTML = '<!-- d-if -->';
|
||||
siblingConditionalElms.forEach((elm) => {
|
||||
elm.innerHTML = '<!-- d-if -->';
|
||||
});
|
||||
};
|
||||
|
||||
let ifStatement = `if (${condition}) {
|
||||
e.innerHTML = "${e.innerHTML}"
|
||||
} `;
|
||||
|
||||
siblingConditionalElms.forEach((element, i) => {
|
||||
const siblingHTML = element.innerHTML;
|
||||
element.innerHTML = '<!-- d-if -->';
|
||||
let statementDirective = 'else';
|
||||
element.removeAttribute('d-else');
|
||||
if (element.hasAttribute('d-else-if')) 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 hydrateElements(appState: Reactive) {
|
||||
const elements = Array.from(document.getElementById('app').querySelectorAll('*'));
|
||||
|
||||
const eventElements = elements.filter((e) => {
|
||||
return Array.from(e.attributes).some(attr => attr.name.startsWith('d-on:') && !attr.name.includes('.'));
|
||||
});
|
||||
|
||||
eventElements.forEach((e) => {
|
||||
const dOnAttrs = Array.from(e.attributes).filter(attr => attr.name.startsWith('d-on:'));
|
||||
|
||||
dOnAttrs.forEach((attr) => {
|
||||
const [, eventType] = attr.name.split(':');
|
||||
|
||||
e.addEventListener(eventType, () => {
|
||||
eval(attr.value);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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 async function hydrateAnchorElements(reduceJavascript: boolean) {
|
||||
const anchorElms = document.querySelectorAll('a');
|
||||
|
||||
Array.from(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, rootElement: Element) {
|
||||
Array.from(rootElement.querySelectorAll('*')).forEach((e: Element) => {
|
||||
const keydownElms = Array.from(e.attributes).filter((arrElm: Attr) => {
|
||||
return arrElm.name.startsWith('d-on:keydown');
|
||||
});
|
||||
|
||||
if (keydownElms.length === 0) return;
|
||||
keydownElms.forEach((attr: Attr) => {
|
||||
const attributeName = attr.name;
|
||||
let keyName = attributeName.split('.')[1]?.toLowerCase();
|
||||
if (keyName && keyName?.length > 0) {
|
||||
keyName = keyName.charAt(0).toUpperCase() + keyName.slice(1).toLowerCase();
|
||||
}
|
||||
e.addEventListener('keydown', (keydown: unknown) => {
|
||||
let eventKey = keydown.key;
|
||||
if (eventKey === ' ') {
|
||||
eventKey = 'Space';
|
||||
}
|
||||
const firstLetter = eventKey.split('')[0];
|
||||
const itemCode = e.getAttribute(attributeName);
|
||||
eventKey = firstLetter?.toUpperCase() + eventKey.slice(1).toLowerCase();
|
||||
if (!keyName) eval(itemCode);
|
||||
if (eventKey === keyName) {
|
||||
if (!itemCode) return;
|
||||
// we use eval here because we want to be able to access the appState object
|
||||
eval(itemCode);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function hydrateSubmit(appState: Reactive, rootElement: Element) {
|
||||
Array.from(rootElement.querySelectorAll('*')).forEach((e: Element) => {
|
||||
const submitElms = Array.from(e.attributes).filter((arrElm: Attr) => {
|
||||
return arrElm.name.startsWith('d-on:submit');
|
||||
});
|
||||
|
||||
if (submitElms.length === 0) return;
|
||||
submitElms.forEach((attr) => {
|
||||
const attributeName = attr.name;
|
||||
const submitExtension = attributeName.split('.')[1]?.toLowerCase();
|
||||
e.addEventListener('submit', (event: Event) => {
|
||||
if (submitExtension === 'prevent') {
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
eval(e.getAttribute(attributeName));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function hydrateBindElements(appState: Reactive, rootElement: Element) {
|
||||
const bindRegex = /^(?:d-bind:|:)/;
|
||||
|
||||
Array.from(rootElement.querySelectorAll('*')).forEach((e: Element) => {
|
||||
const bindElms = Array.from(e.attributes).filter((arrElm: Attr) => {
|
||||
return bindRegex.test(arrElm.name);
|
||||
});
|
||||
|
||||
if (bindElms.length === 0) return;
|
||||
bindElms.forEach((attr: Attr) => {
|
||||
const keyName = attr.name.split(':')[1];
|
||||
const originalValue = '(' + attr.value + ')';
|
||||
let currentBinding = '';
|
||||
|
||||
e.removeAttribute(attr.name);
|
||||
|
||||
function setAttribute() {
|
||||
if (!keyName) return;
|
||||
let value = 'return "' + originalValue + '"';
|
||||
const attribute = e.getAttribute(keyName);
|
||||
if (value.includes('(') || value.includes(')') || value.includes('?') || value.includes(':')) {
|
||||
value = eval(originalValue);
|
||||
}
|
||||
if (!value || !attribute) return;
|
||||
if (attribute) {
|
||||
const originalAttributeValue = (attribute.toString()).split(`${currentBinding}`).join('');
|
||||
currentBinding = value;
|
||||
value = originalAttributeValue + ' ' + value;
|
||||
}
|
||||
e.setAttribute(keyName, value);
|
||||
}
|
||||
|
||||
if (originalValue.includes('appState')) {
|
||||
originalValue.split(' ').forEach((value) => {
|
||||
const propName = value.split('appState.contents.')[1];
|
||||
if (!propName || !value.includes('appState')) return;
|
||||
appState.listen(propName.replace(')', ''), () => setAttribute());
|
||||
});
|
||||
}
|
||||
|
||||
setAttribute();
|
||||
|
||||
});
|
||||
});
|
||||
}
|
||||
353
day87/src/lib/router/pageRenderer.ts
Normal file
353
day87/src/lib/router/pageRenderer.ts
Normal file
@@ -0,0 +1,353 @@
|
||||
import { compileToString } from '../templateRenderer';
|
||||
import { isSSR, isHTML, debugMode, getAppState } from '../../main';
|
||||
import { LRUCache } from '../lruCache';
|
||||
import { hydratePage } from './hydrationManager';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const appState = await getAppState();
|
||||
|
||||
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, 'serverSideSPALikeRouting': true };
|
||||
|
||||
parseFromRegex(page, /<script>[\s\S]*?<\/script>/gi).forEach((e) => {
|
||||
if (!e || !e.startsWith('<script>') || !e.endsWith('</script>')) return;
|
||||
|
||||
parseFromRegex(e, /definePageMeta\({(.*?)}\)(;){0,1}/g).forEach((metaElm) => {
|
||||
if (!metaElm || !metaElm.startsWith('definePageMeta({')) return;
|
||||
|
||||
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];
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
console.log(metaObj)
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
const fnStr = stringifiedTemplate.fnStr;
|
||||
if (!fnStr || typeof fnStr !== 'string') return;
|
||||
documentBody.innerHTML = await eval(fnStr);
|
||||
|
||||
if (stringifiedTemplate.styles && typeof stringifiedTemplate.styles == 'string') {
|
||||
const cssElement = document.createElement('style');
|
||||
cssElement.setAttribute('local', 'true');
|
||||
cssElement.innerHTML = stringifiedTemplate.styles;
|
||||
document.head.appendChild(cssElement);
|
||||
}
|
||||
|
||||
if (stringifiedTemplate.script || stringifiedTemplate.setupScript && (typeof stringifiedTemplate.setupScript == 'string' || stringifiedTemplate.script == 'string')) {
|
||||
const scriptElement = document.createElement('script');
|
||||
const script = (stringifiedTemplate.script) ? stringifiedTemplate.script : '';
|
||||
const setupScript = (stringifiedTemplate.setupScript) ? stringifiedTemplate.setupScript : '';
|
||||
scriptElement.async = true;
|
||||
scriptElement.type = 'module';
|
||||
scriptElement.setAttribute('local', 'true');
|
||||
scriptElement.innerHTML = setupScript + script;
|
||||
document.head.appendChild(scriptElement);
|
||||
}
|
||||
|
||||
if (metaObj.suspendUntilHydrated) {
|
||||
// here we are hiding the body and hydrating the page "suspending"
|
||||
document.body.style.display = 'none';
|
||||
}
|
||||
|
||||
// here we hydrate/re-hydrate the page content
|
||||
console.log('hydration start');
|
||||
await hydratePage(metaObj.reduceJavascript);
|
||||
console.log('hydration complete');
|
||||
|
||||
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) throw new Error('page shouldnt be loaded on server side');
|
||||
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/';
|
||||
|
||||
const cachedFile = cache.get(dir + url);
|
||||
|
||||
async function render() {
|
||||
let file: string | undefined;
|
||||
if (cachedFile && typeof cachedFile == 'string') {
|
||||
if (debugMode) {
|
||||
console.groupCollapsed(`🗃️ Loaded page ${dir}${url} from cache`);
|
||||
console.log(cachedFile);
|
||||
console.groupEnd();
|
||||
}
|
||||
|
||||
file = cachedFile;
|
||||
return file;
|
||||
}
|
||||
|
||||
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;
|
||||
}));
|
||||
});
|
||||
return file;
|
||||
}
|
||||
|
||||
let file = await render();
|
||||
|
||||
if (!file) return '';
|
||||
|
||||
let template = file;
|
||||
const elements: Array<string> = file.split('<').filter(e => e !== undefined);
|
||||
const renderedComponents: Array<string> = [];
|
||||
|
||||
const promises = elements.map(async (component: string) => {
|
||||
const componentName = component.split(' ')[0]?.split('>')[0];
|
||||
if (!componentName) return;
|
||||
component = componentName;
|
||||
if (component?.includes('/') || component?.includes('{') || !component) return;
|
||||
|
||||
if (!component) return;
|
||||
if (isHTML(component)) return;
|
||||
|
||||
const slottedComponent = template.split('<' + component + '>');
|
||||
let isSlotted = false;
|
||||
let slotData: string | undefined;
|
||||
if (slottedComponent.length > 1) {
|
||||
isSlotted = true;
|
||||
slottedComponent.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 (isSlotted && slotData) {
|
||||
file = file.replaceAll('<slot />', slotData);
|
||||
}
|
||||
|
||||
let componentName = '<' + component;
|
||||
(!isSlotted) ? componentName += ' />' : componentName = '<!--' + component + '-->';
|
||||
|
||||
template = template.replaceAll(componentName, file);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(promises);
|
||||
|
||||
|
||||
return template;
|
||||
}
|
||||
|
||||
async function renderComponent(component: string, path: string) {
|
||||
|
||||
const componentName = component;
|
||||
|
||||
async function render(): Promise<string> {
|
||||
const cachedComponent = cache.get('components/' + component);
|
||||
if (cachedComponent && typeof cachedComponent == 'string') {
|
||||
if (debugMode) {
|
||||
console.groupCollapsed(`🗃️ Loaded component ${component} from cache`);
|
||||
console.log(cachedComponent);
|
||||
console.groupEnd();
|
||||
}
|
||||
|
||||
return cachedComponent;
|
||||
}
|
||||
const data = await fetch(path + `components/${component}.devto`)
|
||||
.then(response => response.ok ? response.text() : '');
|
||||
|
||||
cache.set('components/' + component, data);
|
||||
|
||||
if (debugMode) {
|
||||
console.groupCollapsed(`🌐 Fetched component ${component}`);
|
||||
console.log('Template:', data);
|
||||
console.groupEnd();
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
component = await render();
|
||||
|
||||
const elements = component.split('<').filter(e => !!e);
|
||||
|
||||
const promises = elements.map(async (componentInComponent: string) => {
|
||||
const tagName = componentInComponent.split(' ')[0];
|
||||
if (!tagName) return;
|
||||
componentInComponent = tagName;
|
||||
|
||||
if (componentInComponent?.includes('/') || componentInComponent?.includes('{')) return;
|
||||
|
||||
const [name] = componentInComponent.split('>');
|
||||
|
||||
if (!name || isHTML(name)) return;
|
||||
|
||||
if (name === componentName) {
|
||||
console.error(`Cannot include a component in itself, ignoring component (rendering ${name})`);
|
||||
return;
|
||||
}
|
||||
|
||||
const slottedComponent = component.split(`<${name}>`);
|
||||
let isSlotted = false;
|
||||
let slotData: string | undefined;
|
||||
|
||||
if (slottedComponent.length > 1) {
|
||||
isSlotted = true;
|
||||
const splitComponent = slottedComponent.find(e => e.includes(`</${name}>`));
|
||||
if (splitComponent) {
|
||||
slotData = splitComponent.split(`</${name}>`)[0];
|
||||
}
|
||||
component = component.split(`<${name}>${slotData}</${name}>`).join(`<!--${name}-->`);
|
||||
}
|
||||
|
||||
let componentReplacement = await renderComponent(name, path);
|
||||
|
||||
if (isSlotted && slotData) {
|
||||
componentReplacement = componentReplacement.replaceAll('<slot />', slotData);
|
||||
}
|
||||
|
||||
const replacementComponentName = isSlotted ? `<!--${name}-->` : `<${name} />`;
|
||||
component = component.replaceAll(replacementComponentName, componentReplacement);
|
||||
});
|
||||
|
||||
await Promise.all(promises);
|
||||
|
||||
return component;
|
||||
}
|
||||
|
||||
function parseFromRegex(template: string, regex: RegExp) {
|
||||
const matches = template.match(regex);
|
||||
if (!matches) {
|
||||
return [template];
|
||||
}
|
||||
|
||||
const arr = [];
|
||||
let startIndex = 0;
|
||||
for (const match of matches) {
|
||||
const matchIndex = template.indexOf(match, startIndex);
|
||||
if (matchIndex > 0) {
|
||||
arr.push(template.substring(startIndex, matchIndex));
|
||||
}
|
||||
arr.push(match);
|
||||
startIndex = matchIndex + match.length;
|
||||
}
|
||||
|
||||
if (startIndex < template.length) {
|
||||
arr.push(template.substring(startIndex));
|
||||
}
|
||||
|
||||
return arr;
|
||||
}
|
||||
Reference in New Issue
Block a user