add day 90

This commit is contained in:
Zoe
2022-12-21 20:07:55 -06:00
parent 373439cf1f
commit 7d4afb94b0
50 changed files with 12374 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
<div class="mb-2">
<h2 class="text-xl font-semibold text-center">count is: { appState.contents.count }</h2>
</div>
<div class="flex justify-center mb-3">
<button d-on:click="appState.contents.count--"
class="transition-colors p-3 duration-300 active:bg-red-700 hover:bg-red-600 hover:text-zinc-100 mr-1">
<img src='/minus.svg'
image:bundle
width="24px"
height="24px"
alt="minus" />
</button>
<button d-on:click.once.prevent="appState.contents.count = 0"
class="transition-colors p-3 duration-300 active:bg-zinc-700 hover:bg-zinc-800 hover:text-red-100 mr-1">
<img src='/refresh.svg'
image:bundle
width="24px"
height="24px"
alt="reset">
</button>
<button d-on:click.prevent="appState.contents.count++"
class="transition-colors p-3 duration-300 active:bg-green-700 hover:bg-green-600 hover:text-green-100">
<img src='/plus.svg'
image:bundle
width="24px"
height="24px"
alt="plus" />
</button>
</div>
<div>
<p d-if="appState.contents.count % 2 === 0 && !(appState.contents.count < 1)">count is even</p>
<p d-else-if="appState.contents.count == 0">count is 0</p>
<p d-else-if="appState.contents.count < 0">count is less than 0</p>
<p d-else>count is odd</p>
</div>

View File

@@ -0,0 +1,16 @@
<nav class="p-4 shadow-lg md:p-[1.375rem] dark:bg-zinc-900 border-b border-b-neutral-800 dark:text-white mb-2">
<ul class="flex flex-row items-baseline max-h-7">
<li class="mr-2 text-lg">
<a href="/" client:prefetch>Home</a>
</li>
<li class="mr-2">
<a href="/page2" client:prefetch>page 2</a>
</li>
<li class="mr-2">
<a href="/page3" client:prefetch>page 3</a>
</li>
<li class="mr-2">
<a href="/nojavascript" client:prefetch>No Javascript</a>
</li>
</ul>
</nav>

View File

@@ -0,0 +1,20 @@
<div class="mb-2">
<h2 class="text-xl font-semibold text-center">Username cookie is: {appState.contents.cookie}</h2>
</div>
<div class="flex justify-center flex-col mx-auto mb-2 w-fit">
<input placeholder="username..."
class="py-2 px-4 resize-none bg-zinc-800 rounded-md shadow-md my-2 border border-zinc-800 placeholder:italic placeholder:text-gray-300"
d-model="cookieData" />
<button
class="bg-blue-600 font-semibold rounded-md py-2.5 px-2 text-sm hover:bg-blue-700 active:bg-blue-800 transition-colors"
d-on:click="appState.contents.cookie = appState.contents.cookieData; setCookie('username', appState.contents.cookieData, '365', 'Lax');">Submit
Cookie</button>
</div>
<script setup>
console.log('page is first get')
</script>
<script>
console.log('page is fully loaded');
</script>

View File

@@ -0,0 +1,6 @@
<div class="flex justify-center">
<form d-on:submit.prevent="console.log('submit')" class="flex justify-center flex-col">
<input class="py-2 px-4 resize-none bg-zinc-800 rounded-md shadow-md my-2 border border-zinc-800 placeholder:italic placeholder:text-gray-300" type="text" />
<input class="py-2 px-4 resize-none bg-zinc-800 rounded-md shadow-md my-2 border border-zinc-800 hover:bg-zinc-700 active:bg-zinc-900 transition-colors cursor-pointer" type="submit">
</form>
</div>

View File

@@ -0,0 +1,11 @@
<div class="mb-2">
<h2 class="text-xl font-semibold text-center"
d-html>html input is: {appState.contents.html}</h2>
</div>
<div class="flex justify-center">
<div>
<input placeholder="text..."
class="py-2 px-4 resize-none bg-zinc-800 rounded-md shadow-md my-2 border border-zinc-800 placeholder:italic placeholder:text-gray-300"
d-model="html" />
</div>
</div>

View File

@@ -0,0 +1,3 @@
<Counter />
<formInput />
<textInput />

View File

@@ -0,0 +1,25 @@
<div class="mb-2">
<h2 class="text-xl font-semibold text-center">My dad {appState.contents.year}</h2>
</div>
<div class="flex justify-center">
<input placeholder="ex: 1985"
class="no-arrows py-2 px-4 resize-none bg-zinc-800 rounded-md shadow-md my-2 border border-zinc-800 placeholder:italic placeholder:text-gray-300"
type="number"
d-model="year">
</div>
<style>
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
</style>
<script>
console.log('loaded myDad')
</script>

View File

@@ -0,0 +1,7 @@
<div class="mb-2">
<h2 class="text-xl font-semibold text-center">I should be a nested slot component:</h2>
</div>
<div>
<slot />
<Counter />
</div>

View File

@@ -0,0 +1,16 @@
<div class="mb-2">
<h2 class="text-xl font-semibold text-center">Slot data is:</h2>
</div>
<div>
<slot />
</div>
<div class="md-2">
<h2 class="text-xl font-semibold text-center">nested slot:</h2>
</div>
<div class="flex justify-center">
<div class="border border-neutral-600 p-3 rounded-md mb-2 w-3/4">
<nestedSlotComponent>
<p>Im nested</p>
</nestedSlotComponent>
</div>
</div>

View File

@@ -0,0 +1,10 @@
<div class="mb-2">
<h2 class="text-xl font-semibold text-center">Input is: {appState.contents.text}</h2>
</div>
<div class="flex justify-center">
<div>
<input d-on:keydown="console.log('aaa')" placeholder="text..."
class="py-2 px-4 resize-none bg-zinc-800 rounded-md shadow-md my-2 border border-zinc-800 placeholder:italic placeholder:text-gray-300"
d-model="text" />
</div>
</div>

12
day90/src/entry-client.ts Normal file
View File

@@ -0,0 +1,12 @@
import { renderPage } from './lib/router/pageRenderer';
await import('./style.css');
await renderPage();
window.onpopstate = async e => {
if (e.state === null) {
return;
}
await renderPage();
};

View File

@@ -0,0 +1,3 @@
// stub
export {};

View File

@@ -0,0 +1,5 @@
<div class="grid place-items-center p-3 content-center h-full">
<h1 class="text-4xl font-bold">404</h1>
<h2 class="text-2xl font-semibold">Looks like you're lost</h3>
<h3 class="text-xl font-semibold">Go <a href="/">home</a></h3>
</div>

View File

@@ -0,0 +1,16 @@
<Nav />
<div class="container__body">
<slot />
</div>
<style>
html,
body {
height: 100vh;
}
.container__body {
height: calc(100vh - 73px - 0.75rem);
width: 100vw;
}
</style>

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
day90/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,321 @@
import { ReactifyTemplate, hydrateModelAttributes, hydrateKeyDown } 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 = '';
const domElements = Array.from(dom.window.document.body.querySelectorAll('*'));
domElements.forEach((e) => {
const hexCode = Math.random().toString(16).substring(2, 8);
e.setAttribute('data-d', hexCode);
});
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);
if (!script.includes('const hiddenTag = ')) {
script += 'const hiddenTag = "<!-- d-if -->";';
}
script += `function resetHTML_${i}() {`;
script += `document.querySelector('*[uuid="${uniqueSelector}"]').innerHTML = hiddenTag;`;
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 = hiddenTag;`;
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:'));
});
eventElements.forEach((e) => {
const label = e.getAttribute('data-d');
const dOnAttrs = Array.from(e.attributes).filter(attr => attr.name.startsWith('d-on:'));
dOnAttrs.forEach((attr) => {
const [eventType, ...modifiers] = attr.name.split(':')[1].split('.');
const inlineCode = attr.value;
const isKeyboardEvent = (eventType.startsWith('key')) ? true : false;
const keyName = (isKeyboardEvent && modifiers[0]) ? modifiers[0].charAt(0).toUpperCase() + modifiers[0].slice(1).toLowerCase() : '';
e.removeAttribute(attr.name);
script += `document.querySelector('*[data-d="${label}"]').addEventListener("${eventType}", () => {`;
if (isKeyboardEvent) {
script += `
let eventKey = (event.key === ' ') ? 'Space' : 'event.key';
const firstLetter = eventKey.split('')[0];
eventKey = firstLetter?.toUpperCase() + eventKey.slice(1).toLowerCase();
`;
}
// god forgive me for what I'm about to do
for (let i = 0; i < modifiers.length; i++) {
const modifier = modifiers[i];
if (modifier === 'stop') {
script += 'event.stopPropagation();';
}
if (modifier === 'prevent') {
script += 'event.preventDefault();';
}
if (modifier === 'self') {
script += 'if (e !== event.target) return;';
}
}
if (!isKeyboardEvent || !keyName) {
script += `${inlineCode} `;
} else {
script += `
if (eventKey === "${keyName}") {
${inlineCode}
}`;
}
script += `}, { ${(modifiers.some(mod => mod === 'once')) ? 'once: true,' : ''}
${(modifiers.some(mod => mod === 'capture')) ? 'capture: true,' : ''}
${(modifiers.some(mod => mod === 'passive')) ? 'passive: true,' : ''} });`;
});
});
}
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) {
script += `const originalValue_${i} = "${originalValue}";
let currentBinding_${i} = "${currentBinding}";`;
}
if (originalValue.includes('appState')) {
const label = e.getAttribute('data-d');
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('*[data-d="${label}"]').setAttribute("${key}", value);
}`;
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 (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,294 @@
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);
}
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:'));
});
eventElements.forEach((e) => {
const dOnAttrs = Array.from(e.attributes).filter(attr => attr.name.startsWith('d-on:'));
dOnAttrs.forEach((attr) => {
const [eventType, ...modifiers] = attr.name.split(':')[1].split('.');
const code = attr.value;
const isKeyboardEvent = (eventType.startsWith('key')) ? true : false;
const keyName = (isKeyboardEvent && modifiers[0]) ? modifiers[0].charAt(0).toUpperCase() + modifiers[0].slice(1).toLowerCase() : '';
e.removeAttribute(attr.name);
e.addEventListener(eventType, (event) => {
let eventKey = event.key;
if (isKeyboardEvent && eventKey === ' ') {
eventKey = 'Space';
}
const firstLetter = eventKey.split('')[0];
eventKey = firstLetter?.toUpperCase() + eventKey.slice(1).toLowerCase();
for (let i = 0; i < modifiers.length; i++) {
const modifier = modifiers[i];
if (modifier === 'stop') {
event.stopPropagation();
}
if (modifier === 'prevent') {
event.preventDefault();
}
if (modifier === 'self') {
if (e !== event.target) return;
}
}
if (!isKeyboardEvent || !keyName) {
eval(code);
} else if (eventKey === keyName) {
eval(code);
}
}, { once: modifiers.some(mod => mod === 'once'), capture: modifiers.some(mod => mod === 'capture'), passive: modifiers.some(mod => mod === 'passive') });
});
});
}
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
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();
});
});
}

View 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;
}

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;
}

40
day90/src/main.ts Normal file
View File

@@ -0,0 +1,40 @@
import { Reactive } from './lib/ReactiveObject';
export let appState: Reactive;
export const debugMode = import.meta.env.VITE_VERBOSE && !import.meta.env.PROD && !import.meta.env.SSR;
export async function initAppState() {
const { getCookie } = await import('./lib/cookieManager');
appState = new Reactive({
count: 0,
text: '',
cookie: getCookie('username'),
html: '',
year: '',
cookieData: '',
audioObj: {data: '', playing: false, time: 0},
});
}
export async function getAppState() {
if (!appState) await initAppState();
return appState;
}
let SSR: boolean;
export function isSSR() {
if (import.meta.env.SSR) return true;
if (SSR !== undefined) return SSR;
const documentRoot = document.getElementById('app');
if (!documentRoot) {
throw new Error('fatal error: app root not found');
}
SSR = documentRoot.hasAttribute('data-server-rendered');
return SSR;
}
export function isHTML(tag: string) {
const tags = ['a', 'abbr', 'acronym', 'address', 'applet', 'area', 'article', 'aside', 'audio', 'b', 'base', 'basefont', 'bdi', 'bdo', 'bgsound', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'devto:head', 'dfn', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'isindex', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'listing', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'nobr', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'plaintext', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr', 'xmp'];
return tags.indexOf(tag.trim()) > -1;
}

View File

@@ -0,0 +1,30 @@
<devto:head>
<title>special head</title>
<meta name="description"
content="realistic app description">
</devto:head>
<div class="grid place-items-center p-3 content-center h-full">
<div class="p-6 border-neutral-800 rounded-lg container__content border">
<slotComponent>
<div class="text-center mb-2">
<p>we get it</p>
</div>
</slotComponent>
<indexComponent />
<div class="bg-rose-600" d-bind:class="(appState.contents.count == 0) ? 'bg-gray-500' : 'bg-emerald-600'" :aria-label="2+2">
<a href="/page2"
client:prefetch>Navigate</a>
<a href="/page3"
client:prefetch>Navigate</a>
</div>
</div>
</div>
<script>
definePageMeta({ layout: 'default', suspendUntilHydrated: false });
</script>
<script serverSideScript>
console.log(req.path)
</script>

23
day90/src/pages/l.devto Normal file
View File

@@ -0,0 +1,23 @@
<devto:head>
<title>take this L</title>
</devto:head>
<div class="grid place-items-center p-3 content-center h-full">
<div class="p-6 border-neutral-800 rounded-lg container__content border">
<Counter />
<Counter />
<Counter />
<Counter />
<Counter />
<div>
<a href="/page2"
client:prefetch>Navigate</a>
<a href="/page3"
client:prefetch>Navigate</a>
</div>
</div>
</div>
<script>
definePageMeta({ layout: 'default' });
</script>

View File

@@ -0,0 +1,7 @@
<div class="grid place-items-center p-3 content-center h-full">
<div class="p-6 border-neutral-800 rounded-lg container__content border">
<MusicPlayer />
<button d-on:click="appState.contents.audioObj.playing=!appState.contents.audioObj.playing; console.log(appState.contents.audioObj.playing)">{appState.contents.audioObj.playing}</button>
<a client:prefetch href="/">Home</a>
</div>
</div>

View File

@@ -0,0 +1,11 @@
<div class="grid place-items-center p-3 content-center h-full">
<div class="p-6 border-neutral-800 rounded-lg container__content border">
<h1 class="text-xl font-semibold">This page has no javascript!!</h1>
<a href="/">Home</a>
</div>
</div>
</div>
<script>
definePageMeta({ reduceJavascript: true, suspendUntilHydrated: false, serverSideSPALikeRouting: false });
</script>

View File

@@ -0,0 +1,25 @@
<div class="grid place-items-center p-3 content-center h-full">
<div class="p-6 border-neutral-800 rounded-lg container__content border">
<htmlInput />
<myDad />
<div>
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
{Math.floor(Math.random() * 50)}
</div>
<a href="/"
client:prefetch>Home</a>
</div>
</div>
<script>
console.log('page2')
</script>

View File

@@ -0,0 +1,13 @@
<div class="grid place-items-center p-3 content-center h-full">
<div class="p-6 border-neutral-800 rounded-lg container__content border">
<cookieInput />
<htmlInput />
<a href="/"
client:prefetch>Home</a>
<br/>
<a href="/nojavascript"
client:prefetch>No javascript</a>
<br/>
<a href="/music" client:prefetch>Music</a>
</div>
</div>

35
day90/src/style.css Normal file
View File

@@ -0,0 +1,35 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html,
body {
background-color: #101010;
color: #FEFEFE;
font-family: Helvetica, Arial, Sans-Serif;
padding: 0;
margin: 0;
min-height: 100vh;
}
p:empty {
display: none;
}
a:not([link\:active]):hover {
text-decoration: underline;
}
a[link\:active] {
pointer-events: none;
cursor: default;
font-weight: 600;
}
.container__content {
box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
}
.loading > * {
display: none;
}