add day 81 & 82

This commit is contained in:
Zoe
2022-12-13 22:30:17 -06:00
parent a7bd95eece
commit fb978aec32
99 changed files with 24510 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
export class Reactive {
listeners: Record<string, Array<CallableFunction>>;
contents: Record<string, unknown>;
constructor(obj: Record<string, unknown>) {
const createProxy = (target: unknown, propName: string) => {
if (propName !== '') {
propName = propName + '.';
}
function proxyObjects(obj: Record<string, unknown>) {
if (typeof obj !== 'object') {
return;
}
Object.keys(obj).forEach((key) => {
if (typeof obj[key] == 'object') {
proxyObjects(obj[key]);
obj[key] = createProxy(obj[key], `${propName}${key}`);
}
});
}
proxyObjects(target);
return new Proxy(target, {
set: (target, key, value) => {
if (typeof value === 'object') {
// Recursively create a proxy for nested objects
value = createProxy(value, `${propName}${key.toString()}`);
}
if (typeof key !== 'string') return false;
target[key] = value;
this.notify(`${propName}${key}`);
return true;
},
});
};
this.contents = createProxy(obj, '');
this.listeners = {};
}
listen(prop: string, handler: CallableFunction) {
if (!this.listeners[prop]) this.listeners[prop] = [];
this.listeners[prop]?.push(handler);
}
notify(prop: string) {
if (!this.listeners[prop]) return;
// Split the property name into its nested parts
const propParts = prop.split('.');
// Get the value of the nested property on the contents object
let value: unknown = this.contents;
propParts.forEach((part) => {
value = value[part];
});
this.listeners[prop]?.forEach((listener: CallableFunction) => listener(value));
}
}

View File

@@ -0,0 +1,43 @@
export function setCookie(name: string, value: string, expires: string | Date, sameSite: string, path?: string, domain?: string) {
if (import.meta.env.SSR) return;
let cookie = name.trimEnd() + '=' + escape(value) + ';SameSite=' + sameSite + ';';
if (expires) {
// If it's a date
if (expires instanceof Date) {
// If it isn't a valid date
if (isNaN(expires.getTime())) expires = new Date();
}
else expires = new Date(new Date().getTime() + parseInt(expires) * 1000 * 60 * 60 * 24);
cookie += 'expires=' + expires.toUTCString() + ';';
}
if (path) cookie += 'path=' + path + ';';
if (domain) cookie += 'domain=' + domain + ';';
document.cookie = cookie;
}
export function getCookie(name: string): string {
let decodedCookie: string | Record<string, Record<string, string>>;
if (import.meta.env.SSR) {
if (!global._ctx.cookies || !global._ctx.cookies[name]) return '';
return global._ctx.cookies[name];
} else {
decodedCookie = decodeURIComponent(document.cookie);
}
const cname = name + '=';
const ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
if (!c) return '';
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(cname) == 0) {
return c.substring(cname.length, c.length);
}
}
return '';
}

31
day82/src/lib/lruCache.ts Normal file
View File

@@ -0,0 +1,31 @@
// ruthlessly stolen from @trunarla on twitter
export class LRUCache {
#cache: Map<string, string | Record<string, string | Record<string, string | boolean>>>;
#capacity: number;
constructor(capacity: number) {
this.#capacity = capacity;
this.#cache = new Map<string, string | Record<string, string | Record<string, string | boolean>>>();
}
set(key: string, value: string | Record<string, string | Record<string, string | boolean>>) {
// If we're at capacity, we need to delete the least-recently-used item:
if (this.#cache.size >= this.#capacity) {
// Manually invoke the keys iterator to get the least-recently-used key:
const keyToDelete = this.#cache.keys().next().value;
this.#cache.delete(keyToDelete);
}
this.#cache.delete(key);
this.#cache.set(key, value);
}
get(key: string): Record<string, string | Record<string, string | boolean>> | string | undefined {
if (this.#cache.has(key)) {
const value = this.#cache.get(key);
if (!value) return;
this.#cache.delete(key);
this.#cache.set(key, value);
return value;
}
}
}

View File

@@ -0,0 +1,209 @@
import { ReactifyTemplate, hydrateModelAttributes, hydrateKeyDown, hydrateBindElements } from '../hydrationManager';
import { JSDOM } from 'jsdom';
import { Reactive } from '../../ReactiveObject';
import { initAppState } from '../../../main';
function SSRHydrateElement(querySelector: string, eventListenerName: string, removeAttribute?: boolean) {
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}');`;
}
const queryType = querySelector.split(':')[1];
const script = `const ${queryType}Elms = document.querySelectorAll('${querySelectorAll}');
${queryType}Elms.forEach((e) => {
const ${queryType}HydrationFunction = e.getAttribute('${querySelector}');
${removeAttributeString}
if (!${queryType}HydrationFunction) return;
e.addEventListener('${eventListenerName}', () => {
eval(${queryType}HydrationFunction);
});
});`;
return script;
}
export async function renderSSRHydrationCode(template: string, reduceJavascript = false, serverSideSPALikeRouting = true) {
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, i) => {
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';
}
const condition = element.getAttribute('d-' + statementDirective.split(' ').join('-'));
if (statementDirective == 'else if') {
statementDirective = `else if (${condition})`;
element.removeAttribute('d-else-if');
}
const siblingUuid = siblingUUIDMap[i.toString()];
ifStatement = ifStatement + statementDirective + `{
document.querySelector('*[uuid="${siblingUuid}"').innerHTML = ("${siblingHTML.toString()}")
}`;
});
if (!condition) return;
script += `resetHTML_${i}();`;
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_${i}();
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 || serverSideSPALikeRouting)) {
script += `const anchorElms = document.querySelectorAll('a');
anchorElms.forEach((e) => {`;
if (template.includes('client:prefetch') && serverSideSPALikeRouting) script += `e.addEventListener('click', async (event) => {
console.log(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();';
script += hydrateBindElements.toString() + 'hydrateBindElements(appState, document.getElementById("app"));';
}
if (template.includes('d-on:keydown.')) {
script += hydrateKeyDown.toString() + 'hydrateKeyDown(appState, document.getElementById("app"));';
}
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 };
}

View File

@@ -0,0 +1,307 @@
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 = false) {
if (import.meta.env.SSR) return;
const appState = await getAppState();
const documentBody = document.getElementById('app');
if (!documentBody) {
throw new Error('Fatal Error: element with id app not found');
}
const hydrateEvent = (eventName: string, elementSelector: string) => {
hydrateElement(elementSelector, appState, eventName, getCookie, setCookie);
};
ReactifyTemplate(appState);
hydrateHeadElements(appState);
hydrateIfAttributes(appState);
await hydrateAnchorElements(reduceJavascript);
// interactive hydration
hydrateBindElements(appState, documentBody);
hydrateEvent('click', '*[d-on:click]');
hydrateEvent('pointerenter', '*[d-on:pointerEnter]');
hydrateEvent('pointerleave', '*[d-on:pointerExit]');
hydrateEvent('mousedown', '*[d-on:mouseDown]');
hydrateEvent('mouseup', '*[d-on:mouseUp]');
// 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);
}
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 item = reactiveElm.name;
const uuid = item.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 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.split(':').join('\\3A ');
querySelector = queryName[0];
const elms = Array.from(document.querySelectorAll(querySelectorAll));
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 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 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: unknown) => {
let keyName = keydown.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;
// we use eval here because we want to be able to access the appState object
eval(itemCode);
}
});
});
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function hydrateBindElements(appState: Reactive, rootElement: Element) {
Array.from(rootElement.querySelectorAll('*')).forEach((e: Element) => {
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((attr: Attr) => {
const item = attr.name;
const key = item.split(':')[1]?.toLowerCase();
const originalValue = '(' + attr.value + ')';
let currentBinding = '';
e.removeAttribute(item);
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 || !attribute) return;
if (attribute) {
const originalAttributeValue = (attribute.toString()).split(`${currentBinding}`).join('');
currentBinding = value;
value = originalAttributeValue + ' ' + value;
}
e.setAttribute(key, 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();
});
});
}

View File

@@ -0,0 +1,350 @@
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];
});
});
});
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';
}
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) {
if (typeof stringifiedTemplate.setupScript !== 'string' || stringifiedTemplate.script !== 'string') return;
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);
}
// here we hydrate/re-hydrate the page content
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) 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;
}

View File

@@ -0,0 +1,241 @@
import { debugMode } from '../main';
import { LRUCache } from './lruCache';
const templateCache = new LRUCache(15);
function stringToHash(string: string) {
let hash = 0;
if (string.length == 0) return hash;
for (let i = 0; i < string.length; i++) {
const char = string.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash;
}
export const compileToString = async (template: string) => {
const templateHash = stringToHash(template).toString();
const cachedTemplate: string | Record<string, string | Record<string, string | boolean>> | undefined = templateCache.get(templateHash);
if (cachedTemplate && typeof cachedTemplate == 'object') {
const { fnStr, styles, script, setupScript, head, layouts } = cachedTemplate;
if (debugMode) {
console.groupCollapsed('🗃️ loaded template from cache');
console.info('Template String: ' + fnStr);
console.groupEnd();
}
return { fnStr, styles, script, setupScript, head, layouts };
}
let styles = '';
const style = parseFromRegex(template, /<style[\s\S]*?>[\s\S]*?<\/style>/gi);
if (style) {
style.forEach(async (styleData) => {
if (!styleData) return;
if (!styleData.startsWith('<style') || !styleData.endsWith('</style>')) return;
styles += styleData.split('<style')[1]?.split('>')[1]?.split('</style')[0];
template = template.split('<style>' + styles + '</style>').join('');
});
}
let scriptInjection = '';
let script = '';
const meta = { layout: 'default', reduceJavascript: false, suspendUntilHydrated: true };
const scriptContent = parseFromRegex(template, /<script>[\s\S]*?<\/script>/gi);
if (scriptContent) {
scriptContent.forEach(async (scriptData) => {
if (!scriptData) return;
if (!scriptData.startsWith('<script>') || !scriptData.endsWith('</script>')) return;
// if (scriptData.includes('appState.contents.')) {
// scriptInjection += 'const { getAppState, initAppState } = await import("/src/main.ts");\nasync initAppState();\nconst appState = getAppState();';
// }
const metaElms = parseFromRegex(scriptData, /definePageMeta\({(.*?)}\)(;){0,1}/g);
metaElms.forEach((metaElm: string | undefined) => {
if (!metaElm || !scriptData) return;
if (!metaElm.startsWith('definePageMeta({')) return;
scriptData = scriptData.split(metaElm).join('');
template = template.split(metaElm).join('');
let metaObjString = metaElm.split('(')[1]?.split(')')[0];
if (!metaObjString) return;
metaObjString = metaObjString.replaceAll(' ', '').replaceAll('{', '{\'').replaceAll(':', '\':').replaceAll(',', ',\'').replaceAll('\'', '"');
const newMeta = JSON.parse(metaObjString);
Object.keys(newMeta).forEach((key) => {
newMeta[key] = meta[key];
});
});
if (scriptData.includes('getCookie')) {
scriptInjection += 'const { getCookie } = await import("/src/lib/cookieManager.ts");';
}
if (scriptData.includes('setCookie')) {
scriptInjection += 'const { setCookie } = await import("/src/lib/cookieManager.ts");';
}
if (scriptData.includes('isSSR()')) {
scriptInjection += 'const { isSSR } = await import("/src/main.ts");';
}
script += scriptData.split('<script>')[1]?.split('</script>')[0];
const minishScript = script.replace(/[\n\r]/g, '').trim();
if (!minishScript) return;
template = template.split('<script>' + script + '</script>').join('');
scriptInjection += 'document.addEventListener(\'router:client:load\', () => {\n' + minishScript + '\n}, { once: true });';
// remove the script from the body
template = template.split('<script>' + script + '</script>').join('');
script = '';
});
}
const scriptContentSetup = parseFromRegex(template, /<script setup[\s\S]*?>[\s\S]*?<\/script>/gi);
let setupScriptInjection = '';
let setupScript = '';
if (scriptContentSetup) {
scriptContentSetup.forEach(async (scriptData) => {
if (!scriptData) return;
if (!scriptData.startsWith('<script setup') || !scriptData.endsWith('</script>')) return;
// if (scriptData.includes('appState.contents.') && !scriptInjection.includes('initAppState')) {
// scriptInjection = 'const { getAppState, initAppState } = await import("/src/main.ts"); //aaahahahahahahah' + scriptInjection;
// }
if (scriptData.includes('getCookie')) {
setupScriptInjection += 'const { getCookie } = await import("/src/lib/cookieManager.ts");';
}
if (scriptData.includes('setCookie')) {
setupScriptInjection += 'const { setCookie } = await import("/src/lib/cookieManager.ts");';
}
if (scriptData.includes('isSSR()')) {
setupScriptInjection += 'const { isSSR } = await import("/src/main.ts");';
}
setupScript += scriptData.split('<script setup>')[1]?.split('</script>')[0];
setupScriptInjection = scriptData.split('<script setup>')[1]?.split('</script>')[0] + setupScriptInjection;
// remove the script from the body
template = template.split('<script setup>' + setupScript + '</script>').join('');
});
}
let headInjection = '';
let head = '';
if (import.meta.env.SSR) {
const headInjectionContent = parseFromRegex(template, /<devto:head[\s\S]*?>[\s\S]*?<\/devto:head>/gi);
if (headInjectionContent) {
headInjectionContent.forEach(async (headData) => {
if (!headData) return;
if (!headData.startsWith('<devto:head>') || !headData.endsWith('</devto:head>')) return;
const newHeadContent = headData.split('<devto:head>')[1]?.split('</devto:head>')[0];
if (!newHeadContent) return;
head = newHeadContent;
const elements = newHeadContent.split('\n');
elements.forEach((e, i, arr) => {
if (!e.trim()) return;
function isCompleteElement() {
return e.endsWith('>');
}
if (!isCompleteElement()) {
arr[i] = '';
arr[i + 1] = e + arr[i + 1];
}
if (!isCompleteElement()) return;
headInjection += e;
});
});
template = template.split('<devto:head>' + head + '</devto:head>').join('');
}
}
if (template.includes('getCookie') && !script.includes('getCookie')) {
scriptInjection += 'const getCookie = await import("/src/lib/cookieManager.ts");';
}
if (template.includes('setCookie') && !script.includes('setCookie')) {
scriptInjection += 'const { setCookie } = await import("/src/lib/cookieManager.ts");';
}
const ast: (string | undefined)[] = parseFromRegex(template, /{(.*?)}/g);
let fnStr = '``';
if (!ast) return;
ast.forEach(async (t: string | undefined) => {
if (!t) return;
// checking to see if it is an template string
if (t.startsWith('{') && t.endsWith('}')) {
// TODO: rewrite comment
const bracketVariable = t.split(/{|}/).filter(Boolean)[0]?.trim();
if (!bracketVariable) return;
const parentElement = fnStr.split(t)[0]?.split('>');
if (!parentElement || !parentElement[parentElement.length - 2] || typeof parentElement[parentElement.length - 2] == 'undefined') return;
const isRawHTML = parentElement[parentElement.length - 2]?.includes('d-html');
if (bracketVariable.startsWith('appState.contents.')) {
const uuid = bracketVariable.substring(bracketVariable.length, 18).split('').map((c: string) => c.charCodeAt(0).toString(16).padStart(2, '0')).join('');
fnStr = fnStr.substring(0, fnStr.length - 1) + `<span data-token-${uuid}>\``;
} else {
fnStr = fnStr.substring(0, fnStr.length - 1) + '<span>`';
}
let runVar = `((${bracketVariable}).toString().replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'))`;
if (isRawHTML) {
runVar = `(${bracketVariable})`;
}
fnStr += `+ (${runVar})` + '+`</span>`';
} else {
// append the string to the fnStr
fnStr += `+\`${t}\``;
}
});
if (debugMode) {
console.groupCollapsed('⚒️ Compiled template to String');
console.info('Template String: ' + fnStr);
console.groupEnd();
}
templateCache.set(templateHash, { fnStr, styles, script: scriptInjection, setupScript: setupScriptInjection, head: headInjection, layouts: meta });
return { fnStr, styles, script: scriptInjection, setupScript: setupScriptInjection, head: headInjection, layouts: meta };
};
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;
}