This commit is contained in:
Zoe
2022-11-30 20:16:07 -06:00
parent 68799f705e
commit f0dc32ceab
142 changed files with 36898 additions and 0 deletions

1
day68/.env Normal file
View File

@@ -0,0 +1 @@
VITE_VERBOSE = true

43
day68/.eslintrc.json Normal file
View File

@@ -0,0 +1,43 @@
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"overrides": [],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"indent": [
"error",
"tab",
{ "SwitchCase": 1 }
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"nonblock-statement-body-position": [
"error",
"beside"
]
}
}

3
day68/.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
}

23
day68/index.html Normal file
View File

@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<script async src="/src/entry-client.ts" type="module"></script>
<link rel="icon" type="image/png" href="/favicon.png">
</head>
<body>
<div id="app">
<noscript>
<div class="fixed bg-zinc-900 border-t border-neutral-700 shadow-md w-screen bottom-0 p-6 text-lg">Javascript is
reccommended to run this app</div>
</noscript>
</div>
</body>
</html>

474
day68/index.ts Normal file
View File

@@ -0,0 +1,474 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import express, { NextFunction, Request, Response } from 'express';
import compression from 'compression';
import { createServer as createViteServer } from 'vite';
import * as Vite from 'vite';
import cookies from 'cookie-parser';
import Cleancss from 'clean-css';
import * as terser from 'terser';
import Ip from 'ip';
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'];
function isHTML(tag: string) {
return tags.indexOf(tag.trim()) > -1;
}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const cheerio = (await import('cheerio'));
let time: number;
function parseFromRegex(template: string, regex: RegExp) {
let result = regex.exec(template);
regex.lastIndex = 0;
const arr: Array<string | undefined> = [];
let firstPos: number;
while (result) {
firstPos = result.index;
if (firstPos !== 0) {
arr.push(template.substring(0, firstPos));
template = template.slice(firstPos);
}
arr.push(result[0]);
template = template.slice(result[0]?.length);
result = regex.exec(template);
regex.lastIndex = 0;
}
if (template) arr.push(template);
return arr;
}
async function createServer() {
const start = (new Date).getTime();
const app = express();
// const cache: Record<string, string> = {};
const pages: Array<string> = [];
let basepath: string;
(process.env.NODE_ENV == 'production') ? basepath = './' : basepath = './src/';
app.use(express.static(__dirname + '/public', {
maxAge: 43200
}));
app.use((req: Request, res: Response, next: NextFunction) => {
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization,cache-control');
res.setHeader('Cache-Control', 'max-age=43200, public');
next();
});
app.use(cookies());
app.use(compression({ filter: shouldCompress }));
function shouldCompress(req: Request, res: Response) {
if (req.headers['x-no-compression']) {
// don't compress responses with this request header
return false;
}
// fallback to standard filter function
return compression.filter(req, res);
}
fs.readdirSync(path.join(__dirname, basepath + 'pages/')).forEach((e: string) => {
const pageName = e.split('.devto')[0];
if (!pageName) return;
pages.push(pageName);
});
// Create Vite server in middleware mode and configure the app type as
// 'custom', disabling Vite's own HTML serving logic so parent server
// can take control
const vite = await createViteServer({
server: { middlewareMode: true, port: 3000 },
appType: 'custom'
});
const { LRUCache } = await vite.ssrLoadModule('/src/lib/lruCache.ts');
const scriptCache = new LRUCache(10);
const styleCache = new LRUCache(10);
// use vite's connect instance as middleware
// if you use your own express router (express.Router()), you should use router.use
app.use(vite.middlewares);
async function renderPage(url: string) {
// 1. Read index.html
let template: string;
let status = 200;
template = fs.readFileSync(
path.resolve(__dirname, 'index.html'),
'utf-8'
);
let fileName: Array<string> | string = url.split('/');
if (fileName[1] === '') {
fileName = '/index';
} else {
fileName = fileName.join('/').toLowerCase().trim();
}
if (pages.indexOf(fileName.slice(1, fileName.length)) == -1) {
status = 404;
}
// 2. Apply Vite HTML transforms. This injects the Vite HMR client, and
// also applies HTML transforms from Vite plugins, e.g. global preambles
// from @vitejs/plugin-react
template = await vite.transformIndexHtml(url, template);
// 3. Load the server entry. vite.ssrLoadModule automatically transforms
// your ESM source code to be usable in Node.js! There is no bundling
// required, and provides efficient invalidation similar to HMR.
const { SSRPage } = await vite.ssrLoadModule('/src/entry-server.ts');
let pageData: string;
let layout;
const metaObj = { 'layout': 'default', 'reduceJavascript': false, 'suspendUntilHydrated': true };
try {
pageData = fs.readFileSync(
path.resolve(__dirname, basepath + '/pages' + fileName + '.devto'),
'utf8',
);
parseFromRegex(pageData, /<script>[\s\S]*?<\/script>/gi).forEach((e: string | undefined) => {
if (!e) return;
if (e.startsWith('<script>') && e.endsWith('</script>')) {
parseFromRegex(e, /definePageMeta\({(.*?)}\)(;){0,1}/g).forEach((metaElm: string | undefined) => {
if (!metaElm) return;
if (metaElm.startsWith('definePageMeta({')) {
let metaObjString = metaElm.split('(')[1]?.split(')')[0];
if (!metaObjString) return;
metaObjString = metaObjString.replaceAll(' ', '').replaceAll('{', '{\'').replaceAll(':', '\':').replaceAll(',', ',\'').replaceAll('\'', '"');
const newMetaObj = JSON.parse(metaObjString);
Object.keys(newMetaObj).forEach((key) => {
metaObj[key] = newMetaObj[key];
});
}
});
}
});
try {
layout = fs.readFileSync(
path.resolve(__dirname, `src/layouts/${metaObj.layout}.devto`),
'utf-8'
);
} catch {
layout = '<slot />';
}
pageData = layout.replaceAll('<slot />', pageData);
} catch (e) {
pageData = fs.readFileSync(
path.resolve(__dirname, basepath + '/layouts/404.devto'),
'utf8'
);
}
function renderImageToBase64(element: string) {
const fixedElm = element.split('>')[0];
if (!fixedElm) return false;
if (fixedElm.split(' ').length < 2) return false;
if (!fixedElm.includes('image:bundle')) return false;
let srcName = fixedElm.split('src')[1]?.split(' ')[0]?.slice(2);
if (!srcName) return false;
srcName = srcName.slice(0, srcName.length - 2);
let imageprefix;
let imageExt: string | Array<string> | undefined = srcName.split('.');
imageExt = imageExt[imageExt.length - 1];
if (!imageExt) return false;
switch (imageExt) {
case 'svg':
imageprefix = 'data:image/svg+xml;';
break;
case 'png':
imageprefix = 'data:image/png;';
break;
case 'jpg':
imageprefix = 'data:image/jpg;';
break;
case 'jpeg':
imageprefix = 'data:image/jpg;';
break;
default:
break;
}
if (!imageprefix) return false;
const imageBlob = fs.readFileSync(path.resolve(__dirname, './public' + srcName));
return { data: (imageprefix + 'base64,' + imageBlob.toString('base64')), srcName };
}
function prefetchLink(element: string) {
const fixedElm = element.split('>')[0];
if (!fixedElm) return false;
if (fixedElm.split(' ').length < 2) return false;
if (!fixedElm.includes('client:prefetch')) return false;
const href = fixedElm.split('href')[1]?.split(' ')[0]?.slice(2).slice(0, -1);
if (!href) return false;
if (href === url) return false;
if (!href.startsWith('/')) return false;
if (template.split('<head>')[1]?.split('</head>')[0]?.includes('"' + href + '"')) return false;
template = template.split('</head>').join('<link rel="prefetch" href="' + href + '" as="document">\n</head>');
}
async function renderComponent(component: string) {
const item = component.split(' ')[0];
try {
component = fs.readFileSync(
path.resolve(basepath + '/components/' + item + '.devto'),
'utf-8',
);
} catch (e) {
component = '';
}
const elements = component.split('<');
await Promise.all(elements.map(async (componentInComponent: string | undefined) => {
if (!componentInComponent) return;
const ogComponent = componentInComponent;
componentInComponent = componentInComponent.split(' ')[0];
if (componentInComponent?.includes('/') || componentInComponent?.includes('{') || !componentInComponent) return;
componentInComponent = componentInComponent.split('>')[0];
if (!componentInComponent) return;
if (componentInComponent === item) {
console.error('Cannot include a component in itself, ignoring component (rendering ' + componentInComponent + ')');
return;
}
if (componentInComponent === 'img') {
const imaegBlob = renderImageToBase64(ogComponent);
if (imaegBlob && typeof imaegBlob !== 'string') {
component = component.replaceAll(imaegBlob.srcName, imaegBlob.data);
}
}
if (componentInComponent === 'a') {
if (!ogComponent) return;
prefetchLink(ogComponent);
component = component.split('client:prefetch').join('');
}
if (isHTML(componentInComponent)) return;
const slottedComponent = component.split('<' + componentInComponent + '>');
let isSlotted = false;
let slotData: string | undefined;
if (slottedComponent.length > 1) {
isSlotted = true;
slottedComponent.forEach((splitComponent, i, arr) => {
if (splitComponent.includes('</' + componentInComponent + '>')) {
slotData = arr[i]?.split('</' + componentInComponent + '>')[0];
}
});
component = component.split('<' + componentInComponent + '>' + slotData + '</' + componentInComponent + '>').join('<!--' + componentInComponent + '-->');
}
let componentReplacement = await renderComponent(componentInComponent);
if (isSlotted && slotData) {
componentReplacement = componentReplacement.replaceAll('<slot />', slotData);
}
let replacementComponentName = '<' + componentInComponent;
(!isSlotted) ? replacementComponentName += ' />' : replacementComponentName = '<!--' + componentInComponent + '-->';
component = component.replaceAll(replacementComponentName, componentReplacement);
}));
return component;
}
await Promise.all(pageData.split('<').map(async e => {
let item = e.split(' ')[0];
if (!item) return;
if (item.includes('/') || item.includes('{') || item.includes('}') || !item) return;
item = item.split('>')[0];
if (!item) return;
if (item === 'img') {
const imaegBlob = renderImageToBase64(item);
if (imaegBlob && typeof imaegBlob !== 'string') {
pageData = pageData.replaceAll(imaegBlob.srcName, imaegBlob.data);
}
}
if (item === 'a') {
if (!item) return;
prefetchLink(item);
item = item.split('client:prefetch').join('');
}
if (isHTML(item)) return;
const slottedComponent = pageData.split('<' + item + '>');
let isSlotted = false;
let slotData: string | undefined;
if (slottedComponent.length > 1) {
isSlotted = true;
slottedComponent.forEach((splitComponent, i, arr) => {
if (splitComponent.includes('</' + item + '>')) {
slotData = arr[i]?.split('</' + item + '>')[0];
}
});
pageData = pageData.split('<' + item + '>' + slotData + '</' + item + '>').join('<!--' + item + '-->');
}
let component = await renderComponent(item);
if (isSlotted && slotData) {
component = component.replaceAll('<slot />', slotData);
}
let componentName = '<' + item;
(!isSlotted) ? componentName += ' />' : componentName = '<!--' + item + '-->';
pageData = pageData.replaceAll(componentName, component);
}));
// 4. render the app HTML. This assumes entry-server.js's exported `render`
// function calls appropriate framework SSR APIs,
// e.g. ReactDOMServer.renderToString()
const appHtml = await SSRPage(pageData);
const styles = await vite.ssrLoadModule(basepath.slice(1) + 'style.css');
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const main = await vite.ssrLoadModule(basepath.slice(1) + 'main.ts');
await main.initAppState();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const appState = main.getAppState();
const $ = cheerio.load(template, null, true);
$('html', null).children('head').children('script[src="/src/entry-client.ts"]').remove();
$('html', null).children('body').children('div#app').prop('data-server-rendered', 'true');
let appContent = eval(appHtml.fnStr);
const { renderSSRHydrationCode } = await vite.ssrLoadModule(basepath.slice(1) + 'lib/router/SSR/ssrHydrationGenerator');
const code = await renderSSRHydrationCode(appContent, metaObj.reduceJavascript);
let serverSideScriptInjection = '';
let script;
appContent = code.template;
async function inlineImports(content: string) {
const importRegex = /(const|let) \{{0,1} {0,1}([a-zA-Z0-9_-]*) {0,1}\}{0,1} {0,1}= {0,1}await import\(('|"|`)([a-zA-Z0-9_/.-]*)('|"|`)\);{0,1}/g;
const result = parseFromRegex(content, importRegex);
let newScript = result.join('\n');
await Promise.all(result.map(async (e) => {
if (!e) return;
if (!e.startsWith('const') && !e.startsWith('let')) return;
if (!e.includes('{') || !e.includes('}') || !e.includes('await import(')) return;
const functionName = e.split('{')[1]?.split('}')[0]?.trim();
if (!functionName) return;
let fileName = e.split('await import(')[1]?.slice(1)?.split(')')[0];
fileName = fileName?.substring(0,fileName?.length - 1);
if (!fileName) return false;
const file = await vite.ssrLoadModule(fileName);
newScript = newScript.replace(e, file[functionName].toString().replace('__vite_ssr_import_meta__.', 'import.meta.').replace('import.meta.env.SSR', 'false'));
}));
return newScript;
}
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;
}
const hash: number = stringToHash((appHtml.setupScript + appHtml.script + code.script));
if (scriptCache.get(fileName) && scriptCache.get(fileName).hash == hash) {
script = scriptCache.get(fileName).script;
} else {
if (!!appHtml.script || !!code.script) {
serverSideScriptInjection = 'document.dispatchEvent(new Event(\'router:client:load\'));';
if ((code.script).includes('appState')) {
appHtml.script = appHtml.script.replace('const { appState, initAppState } = await import("/src/main.ts");\nawait initAppState();', '');
}
if (metaObj.suspendUntilHydrated) appHtml.setupScript = 'document.documentElement.classList.add("loading");' + appHtml.setupScript;
let compiledScript: string | undefined = appHtml.setupScript + ' window.addEventListener("load", async () => { ' + appHtml.script + code.script + serverSideScriptInjection + ' });';
if (metaObj.suspendUntilHydrated) {
compiledScript += 'document.addEventListener("router:client:load", () => {document.documentElement.classList.remove("loading")});';
}
compiledScript = await inlineImports(compiledScript);
const options = {
mangle: false,
module: true
};
script = (await terser.minify(compiledScript, options)).code;
scriptCache.set(fileName, { script, hash });
}
}
if (script) {
$('html', null).children('head').append('<script async type="module">' + (script) + '</script>\n');
}
// 5. Inject the app-rendered HTML into the template.
let style;
if (styleCache.get(fileName)) {
style = styleCache.get(fileName);
} else {
style = new Cleancss().minify((styles.default + appHtml.styles));
styleCache.set(fileName, style);
}
$('html', null).children('head').append('<style type="text/css">' + style.styles + '</style>');
$('html', null).children('head').prepend(appHtml.head);
$('html', null).children('body').children('div#app').append(appContent);
template = $.html();
main.resetAppState();
return {
html: template, status
};
}
app.use('*', async (req: Request, res: Response, next: NextFunction) => {
const url: string = req.originalUrl;
const { setContext } = await vite.ssrLoadModule('/src/entry-server.ts');
setContext({ cookies: req.cookies });
try {
const page = await renderPage(url);
let fileName: Array<string> | string = url.split('/');
if (fileName[1] === '') {
fileName = '/index';
} else {
fileName = fileName.join('/').toLowerCase().trim();
}
if (!page) throw new Error;
// set the cache with key of fileName for example index to the pages content so it can be rendered at blazing speeds later
// 6. Send the rendered HTML back.
res.status(page.status).set({ 'Content-Type': 'text/html' }).end(page.html);
setContext({});
} catch (err: unknown) {
// If an error is caught, let Vite fix the stack trace so it maps back to
// your actual source code.
if (!(err instanceof Error)) return;
vite.ssrFixStacktrace(err);
res.status(500).end(err.stack);
next(err);
}
});
time = ((new Date).getTime() - start);
console.log('\n \x1b[32m\x1b[1m VITE SSR\x1b[0m\x1b[32m v' + Vite.version + ' \x1b[30mready in \x1b[1m\x1b[37m' + time + '\x1b[0m ms\n\n\x1b[32m ➜ \x1b[0m\x1b[37mLocal: \x1b[0m\x1b[36m http://localhost:\x1b[1m3000/\n\x1b[32m ➜ \x1b[0m\x1b[1mNetwork: \x1b[0m\x1b[36mhttp://' + Ip.address() + ':\x1b[1m3000/');
app.listen(3000);
}
createServer();

1
day68/next-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
declare module '*.css'

10143
day68/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

66
day68/package.json Normal file
View File

@@ -0,0 +1,66 @@
{
"name": "devto",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"type": "module",
"scripts": {
"dev:client": "vite --config vite.config.ts dev",
"dev:server": "ts-node-esm index.ts",
"dev": "concurrently 'npm run dev:client' 'npm run dev:server'",
"build": "rimraf dist && tsc && npm run build:client && npm run build:server && npm run copy-files",
"preview": "vite preview",
"lint": "eslint .",
"test": "vitest",
"test:coverage": "vitest run --coverage",
"build:client": "vite build --outDir dist/client --ssrManifest",
"build:server": "vite build --ssr index.ts --outDir dist/server",
"copy-files": "copyfiles public/* dist/assets && copyfiles index.html dist"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/compression": "^1.7.2",
"@types/cookie-parser": "^1.4.3",
"@types/express": "^4.17.14",
"@types/ip": "^1.1.0",
"@types/jsdom": "^20.0.1",
"@types/node": "^18.8.4",
"@types/uglify-es": "^3.0.0",
"@typescript-eslint/eslint-plugin": "^5.40.0",
"@typescript-eslint/parser": "^5.40.0",
"@vitest/coverage-c8": "^0.24.3",
"autoprefixer": "^10.4.12",
"eslint": "^8.25.0",
"postcss": "^8.4.17",
"tailwindcss": "^3.1.8",
"ts-node": "^10.9.1",
"typescript": "^4.8.4",
"vitest": "^0.24.1"
},
"dependencies": {
"@types/clean-css": "^4.2.6",
"@types/uglify-js": "^3.17.1",
"@xmldom/xmldom": "^0.8.6",
"autoprefixer": "10.4.7",
"cheerio": "^1.0.0-rc.12",
"clean-css": "^5.3.1",
"compression": "^1.7.4",
"concurrently": "7.3.0",
"cookie-parser": "^1.4.6",
"copyfiles": "^2.4.1",
"cssnano": "5.1.12",
"express": "^4.18.1",
"ip": "^1.1.8",
"jsdom": "^20.0.3",
"nodemon": "^2.0.20",
"postcss": "8.4.14",
"postcss-import": "14.1.0",
"postcss-nesting": "10.1.10",
"rimraf": "^3.0.2",
"tailwindcss": "3.1.6",
"terser": "^5.15.1",
"uglify-es": "^3.3.9",
"vite": "^3.1.4"
}
}

7
day68/postcss.config.js Normal file
View File

@@ -0,0 +1,7 @@
import tailwind from 'tailwindcss';
import tailwindConfig from './tailwind.config.js';
import autoprefixer from 'autoprefixer';
export default {
plugins:[tailwind(tailwindConfig),autoprefixer]
};

BIN
day68/public/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

1
day68/public/minus.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-5 -11 24 24" width="24" fill="white"><path d="M1 0h12a1 1 0 0 1 0 2H1a1 1 0 1 1 0-2z"></path></svg>

After

Width:  |  Height:  |  Size: 149 B

1
day68/public/pause.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -3 24 24" width="24" fill="white"><path d="M2 0h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2zm0 2v14h2V2H2zm10-2h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2zm0 2v14h2V2h-2z"></path></svg>

After

Width:  |  Height:  |  Size: 281 B

1
day68/public/play.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -3 24 24" width="24" fill="white"><path d="M13.82 9.523a.976.976 0 0 0-.324-1.363L3.574 2.128a1.031 1.031 0 0 0-.535-.149c-.56 0-1.013.443-1.013.99V15.03c0 .185.053.366.153.523.296.464.92.606 1.395.317l9.922-6.031c.131-.08.243-.189.325-.317zm.746 1.997l-9.921 6.031c-1.425.867-3.3.44-4.186-.951A2.918 2.918 0 0 1 0 15.03V2.97C0 1.329 1.36 0 3.04 0c.567 0 1.123.155 1.605.448l9.921 6.032c1.425.866 1.862 2.696.975 4.088-.246.386-.58.712-.975.952z"></path></svg>

After

Width:  |  Height:  |  Size: 512 B

1
day68/public/plus.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4.5 -4.5 24 24" width="24" fill="white"><path d="M8.9 6.9v-5a1 1 0 1 0-2 0v5h-5a1 1 0 1 0 0 2h5v5a1 1 0 1 0 2 0v-5h5a1 1 0 1 0 0-2h-5z"></path></svg>

After

Width:  |  Height:  |  Size: 199 B

1
day68/public/refresh.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-1.5 -2.5 24 24" width="24" fill="white"><path d="M17.83 4.194l.42-1.377a1 1 0 1 1 1.913.585l-1.17 3.825a1 1 0 0 1-1.248.664l-3.825-1.17a1 1 0 1 1 .585-1.912l1.672.511A7.381 7.381 0 0 0 3.185 6.584l-.26.633a1 1 0 1 1-1.85-.758l.26-.633A9.381 9.381 0 0 1 17.83 4.194zM2.308 14.807l-.327 1.311a1 1 0 1 1-1.94-.484l.967-3.88a1 1 0 0 1 1.265-.716l3.828.954a1 1 0 0 1-.484 1.941l-1.786-.445a7.384 7.384 0 0 0 13.216-1.792 1 1 0 1 1 1.906.608 9.381 9.381 0 0 1-5.38 5.831 9.386 9.386 0 0 1-11.265-3.328z"></path></svg>

After

Width:  |  Height:  |  Size: 561 B

0
day68/public/robots.txt Normal file
View File

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="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="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,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,2 @@
<Counter />
<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,6 @@
<div class="mb-2">
<h2 class="text-xl font-semibold text-center">I should be a nested slot component:</h2>
</div>
<div>
<slot />
</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.space="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>

19
day68/src/entry-client.ts Normal file
View File

@@ -0,0 +1,19 @@
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { appState, initAppState } from './main';
async function initClient() {
if (import.meta.env.SSR) return;
await initAppState();
await import('./style.css');
const { renderPage } = await import('./lib/router/pageRenderer');
await renderPage();
window.onpopstate = async (e: PopStateEvent) => {
if (e.state === null) {
return;
}
await renderPage();
};
}
await initClient();

17
day68/src/entry-server.ts Normal file
View File

@@ -0,0 +1,17 @@
import { compileToString } from './lib/templateRenderer';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { appState, initAppState } from './main';
export let ctx = {};
export async function SSRPage(template: string) {
await initAppState();
return compileToString(template);
}
export function setContext(context: Record<string, unknown>) {
ctx = context;
}
export function getContext() {
return ctx;
}

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="/" d-on:click="event.preventDefault(); renderPage('/')">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,42 @@
export class Reactive {
listeners: Record<string, Array<CallableFunction>>;
contents: Record<string, unknown>;
constructor(obj: Record<string, unknown>) {
this.contents = obj;
this.listeners = {};
this.makeReactive(obj);
}
makeReactive(obj: Record<string, unknown>) {
Object.keys(obj).forEach(prop => this.makePropReactive(obj, prop));
}
makePropReactive(obj: Record<string, unknown>, key: string) {
let value = obj[key];
// Gotta be careful with this here
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
Object.defineProperty(obj, key, {
get() {
return value;
},
set(newValue) {
value = newValue;
that.notify(key);
}
});
}
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;
this.listeners[prop]?.forEach((listener: CallableFunction) => listener(this.contents[prop]));
}
}

View File

@@ -0,0 +1,49 @@
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;
}
let getContext: () => Record<string, string>;
if (import.meta.env.SSR) {
getContext = (await import('../entry-server')).getContext;
}
export function getCookie(name: string): string {
let decodedCookie: string | Record<string, Record<string, string>>;
if (import.meta.env.SSR) {
const ctx = getContext();
if (!ctx.cookies || !ctx.cookies[name]) return '';
return 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 '';
}

35
day68/src/lib/lruCache.ts Normal file
View File

@@ -0,0 +1,35 @@
// retuhlessly stolen from @trunarla on twitter
export class LRUCache {
#cache: Map<string, string>;
#capacity: number;
constructor(capacity: number) {
this.#capacity = capacity;
this.#cache = new Map<string, string>();
}
set(key: string, value: string) {
// 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) {
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;
}
}
getCache() {
return this.#cache;
}
}

View File

@@ -0,0 +1,175 @@
import { ReactifyTemplate, hydrateModelAttributes, hydrateKeyDown } from '../hydrationManager';
import { JSDOM } from 'jsdom';
import { Reactive } from '../../ReactiveObject';
import { initAppState } from '../../../main';
function SSRHydrateElement(querySelector: string, eventListenerName: string, removeAttribute?: boolean) {
let script = '';
const queryName: Array<string> | null = /(?<=\[).+?(?=\])/.exec(querySelector);
if (!queryName || !queryName[0]) return;
const querySelectorAll = (querySelector.replace(':', '\\\\\\\\3A '));
querySelector = queryName[0];
let removeAttributeString = '';
if (removeAttribute === undefined || removeAttribute === true) {
removeAttributeString = `e.removeAttribute('${querySelector}');`;
}
script += `const ${querySelector.split(':')[1]}Elms = eval("document.querySelectorAll('${querySelectorAll}')");
${querySelector.split(':')[1]}Elms.forEach((e) => {
const ${querySelector.split(':')[1]}HydartionFunction = e.getAttribute('${querySelector}');
${removeAttributeString}
if (!${querySelector.split(':')[1]}HydartionFunction) return;
e.addEventListener('${eventListenerName}', () => {
eval(${querySelector.split(':')[1]}HydartionFunction);
});
});`;
return script;
}
export async function renderSSRHydrationCode(template: string, reduceJavascript = false) {
const dom = new JSDOM(template);
let script = '';
if (template.includes('appState.contents.') || template.includes('data-token')) {
script += `
const { getAppState, initAppState } = await import('/src/main.ts');await initAppState();const appState = getAppState();
` + ReactifyTemplate.toString() + 'ReactifyTemplate(appState);';
}
if (template.includes('d-if')) {
const conditionalElms = Array.from(dom.window.document.querySelectorAll('*[d-if]'));
if (conditionalElms.length === 0) return;
conditionalElms.forEach(async (e: Element) => {
const condition = e.getAttribute('d-if');
e.removeAttribute('d-if');
const siblingConditionalElms: Array<Element> = [];
// recursively check for subsequent elements with the d-else of d-else-if attribute
function checkForConditionSibling(elm: Element) {
if (!elm.nextElementSibling || typeof elm.nextElementSibling == 'undefined') return;
if (elm.nextElementSibling?.getAttribute('d-else-if') !== null) {
siblingConditionalElms.push(elm.nextElementSibling);
if (!elm.nextElementSibling) return;
checkForConditionSibling(elm.nextElementSibling);
}
if (elm.nextElementSibling?.getAttribute('d-else') !== null) {
siblingConditionalElms.push(elm.nextElementSibling);
}
}
checkForConditionSibling(e);
if (siblingConditionalElms == undefined) return;
const uniqueSelector = generateLabel(e.textContent);
e.setAttribute('uuid', uniqueSelector);
function generateLabel(textContent: string, count = 1) {
if (script.includes(textContent + '-' + count) || template.includes(textContent + '-' + count)) {
generateLabel(textContent, count++);
} else {
return textContent + '-' + count;
}
}
script += 'function resetHTML() {';
script += `document.querySelector('*[uuid="${uniqueSelector}"]').innerHTML = '<!-- d-if -->';`;
const sublingUUIDMap = new Map();
siblingConditionalElms.forEach((elm, i) => {
if (!elm) return;
const siblingUniqueSelector = generateLabel(elm.textContent);
elm.setAttribute('uuid', siblingUniqueSelector);
script += `document.querySelector('*[uuid="${siblingUniqueSelector}"').innerHTML = '<!-- d-if -->';`;
sublingUUIDMap[i.toString()] = siblingUniqueSelector;
});
script += '}';
let ifStatement = `if (${condition}) {
document.querySelector('*[uuid="${uniqueSelector}"').innerHTML = "${e.innerHTML}"
} `;
siblingConditionalElms.forEach((element, i) => {
if (!element) return;
const siblingHTML = element.innerHTML;
let statementDirective = 'else';
element.removeAttribute('d-else');
if (element.getAttribute('d-else-if') !== null) {
statementDirective = 'else if';
}
const condition = element.getAttribute('d-' + statementDirective.split(' ').join('-'));
if (statementDirective == 'else if') {
statementDirective = `else if (${condition})`;
element.removeAttribute('d-else-if');
}
const siblingUuid = sublingUUIDMap[i.toString()];
ifStatement = ifStatement + statementDirective + `{
document.querySelector('*[uuid="${siblingUuid}"').innerHTML = ("${siblingHTML.toString()}")
}`;
});
if (!condition) return;
script += 'resetHTML();';
script += `eval(\`${ifStatement}\`);`;
if (condition.includes('appState.contents.')) {
let reactiveProp: Array<string> | string | null | undefined = /appState\.contents\.[a-zA-Z]+/.exec(condition);
if (!reactiveProp || !reactiveProp[0]) return;
reactiveProp = reactiveProp[0].split('.')[2];
if (!reactiveProp) return;
script += `appState.listen("${reactiveProp}", () => {
resetHTML();
eval(\`${ifStatement}\`);
});`;
}
});
}
if (template.includes('d-on:click')) {
script += SSRHydrateElement('*[d-on:click]', 'click');
}
if (template.includes('d-on:mouseDown')) {
script += SSRHydrateElement('*[d-on:mouseDown]', 'mousedown');
}
if (template.includes('d-on:mouseUp')) {
script += SSRHydrateElement('*[d-on:mouseUp]', 'mouseup');
}
if (template.includes('d-model')) {
if (!script.includes('const { getAppState, initAppState } = ')) script += 'const { getAppState, initAppState } = await import(\'/src/main.ts\');';
if (!script.includes('const appState =')) script += 'await initAppState();const appState = getAppState();';
script += hydrateModelAttributes.toString() + 'hydrateModelAttributes(appState);';
}
// check if there are links to hydrate
if (template.includes('<a') && !reduceJavascript) {
script += `
const anchorElms = document.querySelectorAll('a');
anchorElms.forEach((e) => {
if (e.href === window.location.href) {
e.setAttribute('link:active', '');
e.setAttribute('tabindex', '-1');
}
}); `;
}
if (template.includes('d-on:keydown.')) {
script += hydrateKeyDown.toString() + 'hydrateKeyDown();';
}
if (template.includes('d-on:pointerEnter')) {
script += SSRHydrateElement('*[d-on:pointerEnter]', 'pointerenter');
}
if (template.includes('d-on:pointerExit')) {
script += SSRHydrateElement('*[d-on:pointerExit]', 'pointerleave');
}
if (script.includes('const { getAppState, initAppState } = await import(\'/src/main.ts\');await initAppState();const appState = getAppState();')) {
script = script.replace('const { getAppState, initAppState } = await import(\'/src/main.ts\');await initAppState();const appState = getAppState();', Reactive.toString() + 'let appState;' + initAppState.toString() + ' await initAppState();').replace('__vite_ssr_import_0__.', '').replace('__vite_ssr_dynamic_import__', 'import');
}
template = dom.window.document.body.innerHTML;
return { script, template };
}

View File

@@ -0,0 +1,259 @@
import { getAppState, initAppState } from '../../main';
import { renderPage } from './pageRenderer';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { getCookie, setCookie } from '../cookieManager';
import { Reactive } from '../ReactiveObject';
// function to turn the template into reactive content "hydating" a page
export async function hydratePage(reduceJavascript?: boolean) {
if (import.meta.env.SSR) return;
if (reduceJavascript === undefined) reduceJavascript = false;
await initAppState();
const appState = getAppState();
const documentBody = document.getElementById('app');
if (!documentBody) {
throw new Error('Fatal Error: element with id app not found');
}
ReactifyTemplate(appState);
// here we look for elements with the d-on:click attribute and on click run the function in the attribute
hydrateElement('*[d-on:click]', appState, 'click', getCookie, setCookie);
// here we determine if an element should be deleted form the DOM via the d-if directive
hydrateIfAttributes(appState);
hydrateElement('*[d-on:pointerEnter]', appState, 'pointerenter', getCookie, setCookie);
hydrateElement('*[d-on:pointerExit]', appState, 'pointerleave', getCookie, setCookie);
hydrateElement('*[d-on:mouseDown]', appState, 'mousedown', getCookie, setCookie);
hydrateElement('*[d-on:mouseUp]', appState, 'mouseup', getCookie, setCookie);
// here we look for elements with the d-model attribute and if there is any input in the element then we update the appState item with the name
// of the attribute value
// example: if the user types "hello" into a text field with the d-model attribute of "text" then we update the appState item with the name "text"
// to "hello"
// similar to vue.js v-model attribute
hydrateModelAttributes(appState);
hydrateHeadElements(appState);
hydrateAnchorElements(reduceJavascript);
hydrateKeyDown(appState);
}
export function ReactifyTemplate(appState: Reactive) {
Array.from(document.querySelectorAll('span')).forEach((e) => {
const reactiveElms = Array.from(e.attributes).filter((arrElm) => {
return arrElm.name.startsWith('data-token-');
});
if (reactiveElms.length === 0) return;
reactiveElms.forEach((elm) => {
const item = elm.name;
const uuid = item.split('data-token-')[1];
if (!uuid) throw new Error('Internal error: decoded uuid not found');
let decodedUuid = '';
for (let i = 0; i < uuid.length; i += 2) {
decodedUuid += String.fromCharCode(parseInt(uuid.substr(i, 2), 16));
}
if (e.parentElement?.hasAttribute('d-once')) {
e.parentElement.removeAttribute('d-once');
return;
}
if (e.parentElement?.hasAttribute('d-html')) {
appState.listen(decodedUuid, (change: string) => e.innerHTML = change);
} else {
appState.listen(decodedUuid, (change: string) => e.textContent = change);
}
});
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function hydrateIfAttributes(appState: Reactive) {
const conditionalElms = Array.from(document.querySelectorAll('*[d-if]'));
if (conditionalElms.length === 0) return;
conditionalElms.forEach(async (e: Element) => {
const condition = e.getAttribute('d-if');
const siblingConditionalElms: Array<Element> = [];
// recursively check for subsequent elements with the d-else of d-else-if attribute
function checkForConditionSibling(elm: Element) {
if (!elm.nextElementSibling || typeof elm.nextElementSibling == 'undefined') return;
if (elm.nextElementSibling?.getAttribute('d-else-if') !== null) {
siblingConditionalElms.push(elm.nextElementSibling);
if (!elm.nextElementSibling) return;
checkForConditionSibling(elm.nextElementSibling);
}
if (elm.nextElementSibling?.getAttribute('d-else') !== null) {
siblingConditionalElms.push(elm.nextElementSibling);
}
}
checkForConditionSibling(e);
if (siblingConditionalElms == undefined) return;
function resetHTML() {
e.innerHTML = '<!-- d-if -->';
siblingConditionalElms.forEach((elm) => {
if (!elm) return;
elm.innerHTML = '<!-- d-if -->';
});
}
let ifStatement = `if (${condition}) {
e.innerHTML = "${e.innerHTML}"
} `;
siblingConditionalElms.forEach((element, i) => {
if (!element) return;
const siblingHTML = element.innerHTML;
element.innerHTML = '<!-- d-if -->';
let statementDirective = 'else';
element.removeAttribute('d-else');
if (element.getAttribute('d-else-if') !== null) {
statementDirective = 'else if';
}
const condition = element.getAttribute('d-' + statementDirective.split(' ').join('-'));
if (statementDirective == 'else if') {
statementDirective = `else if (${condition})`;
element.removeAttribute('d-else-if');
}
ifStatement = ifStatement + statementDirective + `{
siblingConditionalElms[${i}].innerHTML = "${siblingHTML}"
}`;
});
e.removeAttribute('d-if');
if (!condition) return;
resetHTML();
eval(ifStatement);
if (condition.includes('appState.contents.')) {
let reactiveProp: Array<string> | string | null | undefined = /appState\.contents\.[a-zA-Z]+/.exec(condition);
if (!reactiveProp || !reactiveProp[0]) return;
reactiveProp = reactiveProp[0].split('.')[2];
if (!reactiveProp) return;
appState.listen(reactiveProp, () => {
resetHTML();
eval(ifStatement);
});
}
});
}
export function hydrateElement(querySelector: string, appState: Reactive, eventListenerName: string, getCookie: CallableFunction, setCookie: CallableFunction, removeAttribute?: boolean) {
const queryName: Array<string> | null = /(?<=\[).+?(?=\])/.exec(querySelector);
if (!queryName || !queryName[0]) return;
const querySelectorAll = (querySelector.replace(':', '\\\\3A '));
querySelector = queryName[0];
const elms = eval(`Array.from(document.querySelectorAll('${querySelectorAll.toString()}'))`);
if (elms.length === 0) return;
elms.forEach(async (e: Element) => {
const hydrationFunction = e.getAttribute(`${querySelector}`);
if (removeAttribute === undefined || removeAttribute === true) {
e.removeAttribute(`${querySelector}`);
}
if (!hydrationFunction) return;
e.addEventListener(eventListenerName, () => {
eval(hydrationFunction);
});
});
}
export function hydrateModelAttributes(appState: Reactive) {
const modelElms = Array.from(document.querySelectorAll('input[d-model], textarea[d-model]'));
if (modelElms.length === 0) return;
modelElms.forEach((e: Element) => {
const modelName = e.getAttribute('d-model');
if (!modelName) return;
e.addEventListener('input', (input: Event) => {
const target = input.target as HTMLInputElement;
appState.contents[modelName] = target.value;
});
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function hydrateHeadElements(appState: Reactive) {
const headContent = document.head.innerHTML;
const headElements = Array.from(document.querySelectorAll('devto\\3A head'));
if (headElements.length === 0) return;
headElements.forEach((e: Element) => {
if (e.childNodes.length == 0) return;
e.childNodes.forEach((elm) => {
const child = elm as Element;
if (child.nodeType !== 1) return;
if (!document.head.querySelectorAll(child.tagName)) return;
document.head.appendChild(child);
});
e.remove();
});
document.addEventListener('router:naviagte', () => {
document.head.innerHTML = headContent;
}, { once: true });
}
export function hydrateAnchorElements(reduceJavascript: boolean) {
const anchorElms = Array.from(document.querySelectorAll('a'));
anchorElms.forEach((e: HTMLAnchorElement) => {
if (!reduceJavascript && e.href === window.location.href) {
e.setAttribute('link:active', '');
e.setAttribute('tabindex', '-1');
}
e.addEventListener('click', async (click: MouseEvent) => {
if (!event || click.ctrlKey) return;
const target = click.target as HTMLElement;
event.preventDefault();
if (!target) return;
const url: string | null = target.getAttribute('href');
if (!url) return;
await renderPage(url);
});
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function hydrateKeyDown(appState: Reactive) {
Array.from(document.body.querySelectorAll('*')).forEach((e) => {
const keydownElms = Array.from(e.attributes).filter((arrElm) => {
return arrElm.name.startsWith('d-on:keydown');
});
if (keydownElms.length === 0) return;
keydownElms.forEach((attr) => {
const item = attr.name;
let key = item.split('.')[1]?.toLowerCase();
if (key && key?.length > 0) {
key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
}
e.addEventListener('keydown', (keydown) => {
const keyboardEvent = <KeyboardEvent>keydown;
let keyName = keyboardEvent.key;
if (keyName === ' ') {
keyName = 'Space';
}
const firstLetter = keyName.split('')[0];
keyName = firstLetter?.toUpperCase() + keyName.slice(1).toLowerCase();
if (keyName == key) {
const itemCode = e.getAttribute(item);
if (!itemCode) return;
eval(itemCode);
}
});
});
});
}

View File

@@ -0,0 +1,320 @@
import { compileToString } from '../templateRenderer';
import { appState, isSSR, isHTML, debugMode } from '../../main';
import { LRUCache } from '../lruCache';
if (!appState) console.error('no reactive data found');
let documentBody: string | HTMLElement | null;
const cache = new LRUCache(15);
if (import.meta.env.SSR) {
const fs = await import('fs');
const path = await import('path');
documentBody = fs.readFileSync(
path.resolve('index.html'),
'utf-8'
);
} else {
documentBody = document.getElementById('app');
}
// Global function to handle rendering a page and navigation
export async function renderPage(route?: string) {
if (isSSR() || typeof documentBody == 'string') return;
if (!window.history) {
throw new Error('window.history is not supported, please update your browser');
}
if (!documentBody) {
throw new Error('Fatal Error: element with id app not found');
}
if (route && route === window.location.pathname) return;
if (route) {
history.pushState('', '', route);
document.dispatchEvent(new Event('router:naviagte'));
}
let fileName: string | Array<string> = window.location.pathname.split('/');
if (fileName[1] === '') {
fileName = '/index';
} else {
fileName = fileName.join('/').toLowerCase().trim();
}
let page: string = await fetchPage(fileName, 'pages');
if (!page) return;
const metaObj = { 'layout': 'default', 'reduceJavascript': false, 'suspendUntilHydrated': true };
parseFromRegex(page, /<script>[\s\S]*?<\/script>/gi).forEach((e: string | undefined) => {
if (!e) return;
if (e.startsWith('<script>') && e.endsWith('</script>')) {
parseFromRegex(e, /definePageMeta\({(.*?)}\)(;){0,1}/g).forEach((metaElm: string | undefined) => {
if (!metaElm) return;
if (metaElm.startsWith('definePageMeta({')) {
let metaObjString = metaElm.split('(')[1]?.split(')')[0];
if (!metaObjString) return;
metaObjString = metaObjString.replaceAll(' ', '').replaceAll('{', '{\'').replaceAll(':', '\':').replaceAll(',', ',\'').replaceAll('\'', '"');
const newMetaObj = JSON.parse(metaObjString);
Object.keys(newMetaObj).forEach((key) => {
metaObj[key] = newMetaObj[key];
});
}
});
}
});
let layout: string;
try {
layout = await fetchPage(`/${metaObj.layout}`, 'layouts', false);
} catch {
layout = '<slot />';
}
if (!layout) return;
page = layout.replaceAll('<slot />', page);
const stringifiedTemplate = await compileToString(page);
if (!stringifiedTemplate) return;
if (debugMode) {
console.groupCollapsed('✨ Redered page ' + fileName.slice(1));
console.log('Template: ' + page);
console.info('stringified template: ' + stringifiedTemplate.fnStr);
console.groupEnd();
}
// since we have all the html content ready to place in the app, we first need to remove all the old injected content
if (route) {
const childrenToRemove = document.head.querySelectorAll('*[local]');
childrenToRemove.forEach(child => document.head.removeChild(child));
}
if (metaObj.suspendUntilHydrated) {
// here we are hiding the body and hydrating the page "suspending"
document.body.style.display = 'none';
}
documentBody.innerHTML = await eval(stringifiedTemplate.fnStr);
if (stringifiedTemplate.styles) {
const cssElement = document.createElement('style');
cssElement.type = 'text/css';
cssElement.setAttribute('local', 'true');
cssElement.innerHTML = stringifiedTemplate.styles;
document.head.appendChild(cssElement);
}
if (stringifiedTemplate.script || stringifiedTemplate.setupScript) {
const scriptElement = document.createElement('script');
scriptElement.async = true;
scriptElement.type = 'module';
scriptElement.setAttribute('local', 'true');
scriptElement.innerHTML = stringifiedTemplate.setupScript + stringifiedTemplate.script;
document.head.appendChild(scriptElement);
}
// here we hydrate/re-hydrate the page content
const { hydratePage } = await import('./hydrationManager');
await hydratePage(metaObj.reduceJavascript);
if (metaObj.suspendUntilHydrated) {
// here we show the page as its been hydtated
document.body.style.display = 'block';
}
// tell the document that the client has fully rendered and hydrated the page
document.dispatchEvent(new Event('router:client:load'));
}
async function fetchPage(url: string, dir: string, return404?: boolean): Promise<string> {
if (import.meta.env.SSR) return '';
if (isSSR()) throw new Error('page shouldnt be loaded on server side');
if (return404 === undefined) return404 = true;
let path: string;
(import.meta.env.PROD) ? path = '/' : path = '/src/';
let file: string | undefined;
const cachedFile = cache.get(dir + url);
if (cachedFile) {
if (debugMode) {
console.groupCollapsed(`🗃️ Loaded page ${dir}${url} from cache`);
console.log(cachedFile);
console.groupEnd();
}
file = cachedFile;
} else {
file = await fetch(path + `${dir}${url}.devto`).then((response) => {
if (response.ok) {
return response.text();
}
throw new Error('File not found');
})
.then((data) => {
if (!data) return undefined;
cache.set(dir + url, data);
console.groupCollapsed(`🌐 Fetched page ${dir}${url}`);
console.log(data);
console.groupEnd();
return data;
})
.catch(async () => {
if (!return404) {
throw new Error('object not found and not returning a 404 page');
}
return (await fetch(path + 'layouts/404.devto').then((response) => {
if (response.ok) {
return response.text();
}
throw new Error('Error fetching 404 page');
})
.then((data) => {
if (!data) return undefined;
return data;
}));
});
}
if (!file) return '';
let template = file;
const elements: Array<string> = file.split('<');
const renderedComponents: Array<string> = [];
await Promise.all(elements.map(async (component: string | undefined) => {
if (!component || !file) return;
component = component.split(' ')[0];
if (component?.includes('/') || component?.includes('{') || !component) return;
component = component.split('>')[0];
if (!component) return;
if (isHTML(component)) return;
const slotedComponent = template.split('<' + component + '>');
let isSloted = false;
let slotData: string | undefined;
if (slotedComponent.length > 1) {
isSloted = true;
slotedComponent.forEach((splitComponent, i, arr) => {
if (splitComponent.includes('</' + component + '>')) {
slotData = arr[i]?.split('</' + component + '>')[0];
}
});
template = template.split('<' + component + '>' + slotData + '</' + component + '>').join('<!--' + component + '-->');
}
if (renderedComponents.indexOf(component) == -1) {
renderedComponents.push(component);
file = await renderComponent(component, path);
if (isSloted && slotData) {
file = file.replaceAll('<slot />', slotData);
}
let componentName = '<' + component;
(!isSloted) ? componentName += ' />' : componentName = '<!--' + component + '-->';
template = template.replaceAll(componentName, file);
}
})
);
return template;
}
async function renderComponent(component: string, path: string) {
const componentName = component;
const cachedComponent = cache.get('components/' + component);
if (cachedComponent) {
if (debugMode) {
console.groupCollapsed(`🗃️ Loaded component ${component} from cache`);
console.log(cachedComponent);
console.groupEnd();
}
component = cachedComponent;
} else {
await fetch(path + `components/${component}.devto`).then((response) => {
if (response.ok) {
return response.text();
}
return '';
})
.then((data) => {
cache.set('components/' + component, data);
if (debugMode) {
console.groupCollapsed(`🌐 Fetched component ${component}`);
console.log('Template:', data);
console.groupEnd();
}
component = data;
});
}
const elements = component.split('<');
await Promise.all(elements.map(async (componentInComponent: string | undefined) => {
if (!componentInComponent) return;
componentInComponent = componentInComponent.split(' ')[0];
if (componentInComponent?.includes('/') || componentInComponent?.includes('{') || !componentInComponent) return;
componentInComponent = componentInComponent.split('>')[0];
if (!componentInComponent) return;
if (isHTML(componentInComponent)) return;
if (componentInComponent === componentName) {
console.error('Cannot include a component in itself, ignoring component (rendering ' + componentInComponent + ')');
return;
}
const slotedComponent = component.split('<' + componentInComponent + '>');
let isSloted = false;
let slotData: string | undefined;
if (slotedComponent.length > 1) {
isSloted = true;
slotedComponent.forEach((splitComponent, i, arr) => {
if (splitComponent.includes('</' + componentInComponent + '>')) {
slotData = arr[i]?.split('</' + componentInComponent + '>')[0];
}
});
component = component.split('<' + componentInComponent + '>' + slotData + '</' + componentInComponent + '>').join('<!--' + componentInComponent + '-->');
}
let componentReplacement = await renderComponent(componentInComponent, path);
if (isSloted && slotData) {
componentReplacement = componentReplacement.replaceAll('<slot />', slotData);
}
let replacementComponentName = '<' + componentInComponent;
(!isSloted) ? replacementComponentName += ' />' : replacementComponentName = '<!--' + componentInComponent + '-->';
component = component.replaceAll(replacementComponentName, componentReplacement);
}));
return component;
}
function parseFromRegex(template: string, regex: RegExp) {
let result = regex.exec(template);
regex.lastIndex = 0;
const arr = [];
let firstPos;
while (result) {
firstPos = result.index;
if (firstPos !== 0) {
arr.push(template.substring(0, firstPos));
template = template.slice(firstPos);
}
arr.push(result[0]);
template = template.slice(result[0]?.length);
result = regex.exec(template);
regex.lastIndex = 0;
}
if (template) arr.push(template);
return arr;
}

View File

@@ -0,0 +1,214 @@
import { debugMode } from '../main';
export const compileToString = async (template: string) => {
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>')) {
styles += styleData.split('<style')[1]?.split('>')[1]?.split('</style')[0];
}
// remove the style from the body
template = template.split('<style>' + styles + '</style>').join('');
});
}
let scriptInjection = '';
let script = '';
const meta = { layout: 'default', reduceJavascript: false };
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>')) {
// 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({')) {
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>')) {
// 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>')) {
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() {
if (!e.endsWith('>')) {
return false;
} else {
return true;
}
}
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 interpolation
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 tempalte to String');
console.info('Template String: ' + fnStr);
console.groupEnd();
}
return { fnStr, styles, script: scriptInjection, setupScript: setupScriptInjection, head: headInjection, layouts: meta };
};
const parseFromRegex = (template: string, regex: RegExp) => {
let result = regex.exec(template);
regex.lastIndex = 0;
const arr = [];
let firstPos;
while (result) {
firstPos = result.index;
if (firstPos !== 0) {
arr.push(template.substring(0, firstPos));
template = template.slice(firstPos);
}
arr.push(result[0]);
template = template.slice(result[0]?.length);
result = regex.exec(template);
regex.lastIndex = 0;
}
if (template) arr.push(template);
return arr;
};

43
day68/src/main.ts Normal file
View File

@@ -0,0 +1,43 @@
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 function resetAppState() {
appState = new Reactive({});
}
export function getAppState() {
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,26 @@
<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>
<a href="/page2"
client:prefetch>Navigate</a>
<a href="/page3"
client:prefetch>Navigate</a>
</div>
</div>
</div>
<script>
definePageMeta({ layout: 'default', suspendUntilHydrated: false });
</script>

23
day68/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">{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 });
</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('make this pg because its open source teheheheh')
</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>

31
day68/src/style.css Normal file
View File

@@ -0,0 +1,31 @@
@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;
}
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;
}

29
day68/tailwind.config.js Normal file
View File

@@ -0,0 +1,29 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
'./index.html',
'./src/components/*.{devto,js,ts,jsx,tsx}',
'./src/pages/*.{devto,js,ts,jsx,tsx}',
'./src/layouts/*.{devto,js,ts,jsx,tsx}'
],
theme: {
extend: {
colors: {
gray: {
'50': '#fafafa',
'100': '#f4f4f5',
'200': '#e4e4e7',
'300': '#d4d4d8',
'400': '#a1a1aa',
'500': '#71717a',
'600': '#52525b',
'700': '#3f3f46',
'800': '#27272a',
'900': '#18181b'
}
}
},
},
plugins: [],
};

28
day68/tsconfig.json Normal file
View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"alwaysStrict": true,
"allowSyntheticDefaultImports": true,
"checkJs": true,
"declaration": true,
"declarationMap": true,
"target": "ES2022",
"lib": ["ESNext", "ESNext.AsyncIterable", "DOM"],
"allowJs": true,
"sourceMap": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"suppressImplicitAnyIndexErrors": true,
"noEmit": true,
"esModuleInterop": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"incremental": true,
"jsx": "preserve",
"noUncheckedIndexedAccess": true,
"baseUrl": ".",
},
"include": ["src/**/*", "types/*", "index.ts", "node_modules/vite/types/*", "next-env.d.ts"],
}

14
day68/vite.config.ts Normal file
View File

@@ -0,0 +1,14 @@
/** @type {import('vite').UserConfig} */
export default {
build: {
target: 'es2022',
},
server: {
port: 8080,
host: '0.0.0.0',
watch: {
include: ['./**/pages/**.devto', './public/**', './**/components/**.devto']
}
},
};