Compare commits
84 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 95acc39c99 | |||
| 4dd7bdfb4c | |||
| 565d348f24 | |||
| 99aca3ff40 | |||
| e3e1a8a648 | |||
| 162aa8a222 | |||
| 888e351615 | |||
| 2afca5c906 | |||
| 173e834dc3 | |||
| 7d4afb94b0 | |||
| 373439cf1f | |||
| eb3a3c5aa9 | |||
| d51c6bd291 | |||
| 5d639644eb | |||
| 9cfa458b1c | |||
| 88677915b4 | |||
| 0d8d8138f0 | |||
| fb978aec32 | |||
| a7bd95eece | |||
| 7598643b68 | |||
| a7f59529b7 | |||
| 7b38fde2bd | |||
| 59c0d008e5 | |||
| 228edcdb03 | |||
| 7002d0fbe6 | |||
| dac034af7b | |||
| fe98d7ec77 | |||
| 2a33574680 | |||
| f0dc32ceab | |||
| 68799f705e | |||
| 54b8164d0f | |||
| 5df19f5d84 | |||
| 0ec2d0b6e7 | |||
| 5f06ed07b1 | |||
| 45b1bd12c5 | |||
| fad3d1b777 | |||
| ffa74048fb | |||
| 8791b700b3 | |||
| e19c11991d | |||
| 855ef8fd69 | |||
| b5cf6f8ed6 | |||
| e373819d42 | |||
| f1eebb02a6 | |||
| c18f52de89 | |||
| 8e98a80221 | |||
| 85b6782552 | |||
| 2eb6a70088 | |||
| 4ed008a755 | |||
| 9d955e014b | |||
| 0dd896da10 | |||
| f56e01f9da | |||
| 6313f331da | |||
| 1ef5dd5b1f | |||
| 37da2156ad | |||
| a1129718c3 | |||
| a2a6889d8a | |||
| 1bcbb36f28 | |||
| 6e1dc303eb | |||
| 2ccfe1e8c0 | |||
| 92dc4426d4 | |||
| 1fd61cc054 | |||
| caba702b1e | |||
| 55993f37a5 | |||
| bf1490cad7 | |||
| 310f11511e | |||
| 11912b17dd | |||
| b60a398627 | |||
| 59c755501b | |||
| e017cbf418 | |||
| ed55d7c9a2 | |||
| e505c78616 | |||
| 4e485b421c | |||
| 651c1d87a2 | |||
| a9817c7911 | |||
| e81e847312 | |||
| cb3a18a9fd | |||
| 252f9b3a78 | |||
| dcac066e2b | |||
| a977e76597 | |||
| 29e2f8b4e3 | |||
| a00c923e08 | |||
| b37cfee924 | |||
| f3718a1229 | |||
| 6855cb94f3 |
1
day100/.env
Normal file
@@ -0,0 +1 @@
|
|||||||
|
VITE_VERBOSE = true
|
||||||
43
day100/.eslintrc.json
Normal 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
day100/.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"typescript.tsdk": "node_modules/typescript/lib"
|
||||||
|
}
|
||||||
4
day100/devto.config.js
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export default {
|
||||||
|
ssr: false,
|
||||||
|
port: 3000
|
||||||
|
};
|
||||||
25
day100/index.html
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<title>devto app</title>
|
||||||
|
<meta name="description" content="a devto application">
|
||||||
|
<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>
|
||||||
505
day100/index.ts
Normal file
@@ -0,0 +1,505 @@
|
|||||||
|
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';
|
||||||
|
import { JSDOM } from 'jsdom';
|
||||||
|
import devtoConfig from './devto.config.js';
|
||||||
|
|
||||||
|
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));
|
||||||
|
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();
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = { port: devtoConfig.port, mode: (devtoConfig.ssr) ? 'ssr' : 'spa' };
|
||||||
|
|
||||||
|
const appType = (config.mode === 'ssr') ? 'custom' : 'spa';
|
||||||
|
|
||||||
|
|
||||||
|
// 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: config.port },
|
||||||
|
appType
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
async function renderPage(url: string, req: Request) {
|
||||||
|
// 1. Read index.html
|
||||||
|
let template: string;
|
||||||
|
let status = 200;
|
||||||
|
template = await fs.promises.readFile(
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 { compileToString } = await vite.ssrLoadModule('/src/lib/templateRenderer');
|
||||||
|
|
||||||
|
let pageData: string;
|
||||||
|
|
||||||
|
let layout;
|
||||||
|
const metaObj = { 'layout': 'default', 'reduceJavascript': false, 'serverSideSPALikeRouting': true };
|
||||||
|
|
||||||
|
try {
|
||||||
|
layout = await fs.promises.readFile(
|
||||||
|
path.resolve(__dirname, `src/layouts/${metaObj.layout}.devto`),
|
||||||
|
'utf-8'
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
layout = '<slot />';
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
pageData = await fs.promises.readFile(
|
||||||
|
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>')) return;
|
||||||
|
|
||||||
|
parseFromRegex(e, /definePageMeta\({(.*?)}\)(;){0,1}/g).forEach((metaElm: string | undefined) => {
|
||||||
|
if (!metaElm) return;
|
||||||
|
if (!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];
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
parseFromRegex(pageData, /<script serverSideScript>[\s\S]*?<\/script>/gi).forEach((e: string | undefined) => {
|
||||||
|
if (!e) return;
|
||||||
|
if (!e.startsWith('<script serverSideScript>') || !e.endsWith('</script>')) return;
|
||||||
|
|
||||||
|
pageData = pageData.split(e).join('');
|
||||||
|
|
||||||
|
const fn = e.split('<script serverSideScript>')[1]?.split('</script>')[0];
|
||||||
|
|
||||||
|
if (!fn) return;
|
||||||
|
|
||||||
|
eval(fn);
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
status = 404;
|
||||||
|
pageData = await fs.promises.readFile(
|
||||||
|
path.resolve(__dirname, basepath + '/layouts/404.devto'),
|
||||||
|
'utf8'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pageData = layout.replaceAll('<slot />', pageData);
|
||||||
|
|
||||||
|
async 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 = await fs.promises.readFile(path.resolve(__dirname, './public' + srcName));
|
||||||
|
return { data: (imageprefix + 'base64,' + imageBlob.toString('base64')), srcName };
|
||||||
|
}
|
||||||
|
|
||||||
|
const dom = new JSDOM(template);
|
||||||
|
|
||||||
|
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;
|
||||||
|
dom.window.document.head.innerHTML += '<link rel="prefetch" href="' + href + '" as="document">\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renderComponent(component: string) {
|
||||||
|
const item = component.split(' ')[0];
|
||||||
|
try {
|
||||||
|
component = await fs.promises.readFile(
|
||||||
|
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 = await renderImageToBase64(ogComponent);
|
||||||
|
if (imaegBlob && typeof imaegBlob !== 'string') {
|
||||||
|
component = component.replaceAll(imaegBlob.srcName, imaegBlob.data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (componentInComponent === 'a') {
|
||||||
|
if (!ogComponent) return;
|
||||||
|
prefetchLink(ogComponent);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = await renderImageToBase64(item);
|
||||||
|
if (imaegBlob && typeof imaegBlob !== 'string') {
|
||||||
|
pageData = pageData.replaceAll(imaegBlob.srcName, imaegBlob.data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item === 'a') {
|
||||||
|
if (!item) return;
|
||||||
|
prefetchLink(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 compileToString(pageData);
|
||||||
|
|
||||||
|
const styles = await vite.ssrLoadModule(basepath.slice(1) + 'style.css');
|
||||||
|
|
||||||
|
const main = await vite.ssrLoadModule(basepath.slice(1) + 'main.ts');
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
const appState = await main.getAppState();
|
||||||
|
|
||||||
|
dom.window.document.head.querySelector('script[src="/src/entry-client.ts"]')?.remove();
|
||||||
|
dom.window.document.body.querySelector('div#app')?.setAttribute('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, metaObj.serverSideSPALikeRouting);
|
||||||
|
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 scriptHash: number = stringToHash((appHtml.setupScript + appHtml.script + code.script));
|
||||||
|
|
||||||
|
if (scriptCache.get(fileName) && scriptCache.get(fileName).hash == scriptHash) {
|
||||||
|
script = scriptCache.get(fileName).script;
|
||||||
|
} else {
|
||||||
|
if (!!appHtml.script || !!code.script) {
|
||||||
|
serverSideScriptInjection = (!metaObj.reduceJavascript) ? '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();', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
let compiledScript = await inlineImports(`${appHtml.setupScript} window.addEventListener("load", async () => { ${appHtml.script} ${code.script} ${serverSideScriptInjection} });`);
|
||||||
|
|
||||||
|
compiledScript = compiledScript.replace('debugMode', main.debugMode);
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
mangle: true,
|
||||||
|
module: true,
|
||||||
|
toplevel: true,
|
||||||
|
compress: {
|
||||||
|
passes: 2,
|
||||||
|
booleans_as_integers: true,
|
||||||
|
loops: true
|
||||||
|
},
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
script = (await terser.minify(compiledScript, options)).code;
|
||||||
|
} catch (err) {
|
||||||
|
console.log(err);
|
||||||
|
console.log(compiledScript);
|
||||||
|
}
|
||||||
|
|
||||||
|
scriptCache.set(fileName, { script, hash: scriptHash });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (script) {
|
||||||
|
dom.window.document.head.innerHTML += '<script async type="module">' + (script) + '</script>\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Inject the app-rendered HTML into the template.
|
||||||
|
let style;
|
||||||
|
const styleHash = stringToHash((styles.default + appHtml.styles));
|
||||||
|
|
||||||
|
if (styleCache.get(fileName) && styleCache.get(fileName).hash == styleHash) {
|
||||||
|
style = styleCache.get(fileName).style;
|
||||||
|
} else {
|
||||||
|
style = new Cleancss({
|
||||||
|
level: 2
|
||||||
|
}).minify((styles.default + appHtml.styles));
|
||||||
|
styleCache.set(fileName, { style, hash: styleHash });
|
||||||
|
}
|
||||||
|
dom.window.document.head.innerHTML = dom.window.document.head.innerHTML + '<style type="text/css">' + style.styles + '</style>\n';
|
||||||
|
|
||||||
|
dom.window.document.head.innerHTML = appHtml.head + dom.window.document.head.innerHTML;
|
||||||
|
|
||||||
|
const appContainer = dom.window.document.body.querySelector('div#app');
|
||||||
|
if (!appContainer) return;
|
||||||
|
appContainer.innerHTML = appContent;
|
||||||
|
const newTemplate = dom.serialize();
|
||||||
|
if (!newTemplate) throw new Error('internal fatal error: template content not found');
|
||||||
|
template = newTemplate;
|
||||||
|
return {
|
||||||
|
html: template, status
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
app.use('*', async (req: any, res: Response, next: NextFunction) => {
|
||||||
|
const url: string = req._parsedOriginalUrl.pathname;
|
||||||
|
global._ctx = { cookies: req.cookies };
|
||||||
|
|
||||||
|
try {
|
||||||
|
const page = await renderPage(url, req);
|
||||||
|
let fileName: Array<string> | string = url.split('/');
|
||||||
|
if (fileName[1] === '') {
|
||||||
|
fileName = '/index';
|
||||||
|
} else {
|
||||||
|
fileName = fileName.join('/').toLowerCase().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!page) throw new Error;
|
||||||
|
|
||||||
|
// 6. Send the rendered HTML back.
|
||||||
|
res.status(page.status).set({ 'Content-Type': 'text/html' }).end(page.html);
|
||||||
|
global._ctx = {};
|
||||||
|
} 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(`\x1b[32m\x1b[1m Devto\x1b[0m\x1b[32m v${Vite.version} \x1b[30mready in \x1b[1m\x1b[37m${time}\x1b[0m ms
|
||||||
|
${(config.mode === 'ssr') ? '\x1b[32m' : '\x1b[31m'} \x1b[1mSSR: ${config.mode === 'ssr'}
|
||||||
|
|
||||||
|
\x1b[32m ➜ \x1b[0m\x1b[37mLocal: \x1b[0m\x1b[36m http://localhost:\x1b[1m${config.port}\x1b[36m/\x1b[0m
|
||||||
|
\x1b[32m ➜ \x1b[0mNetwork: \x1b[0m\x1b[36mhttp://` + Ip.address() + `:\x1b[1m${config.port}\x1b[36m/\x1b[0m`);
|
||||||
|
app.listen(config.port);
|
||||||
|
}
|
||||||
|
|
||||||
|
createServer();
|
||||||
9951
day100/package-lock.json
generated
Normal file
63
day100/package.json
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
{
|
||||||
|
"name": "devto",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"main": "index.ts",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "ts-node-esm --files index.ts",
|
||||||
|
"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 && copyfiles src/pages/* dist/pages"
|
||||||
|
},
|
||||||
|
"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.20",
|
||||||
|
"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/cssnano": "^5.1.0",
|
||||||
|
"@types/uglify-js": "^3.17.1",
|
||||||
|
"@xmldom/xmldom": "^0.8.6",
|
||||||
|
"autoprefixer": "10.4.7",
|
||||||
|
"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.14",
|
||||||
|
"express": "^4.18.1",
|
||||||
|
"ip": "^1.1.8",
|
||||||
|
"jsdom": "^20.0.3",
|
||||||
|
"nodemon": "^2.0.20",
|
||||||
|
"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
day100/postcss.config.js
Normal 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
day100/public/favicon.png
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
1
day100/public/minus.svg
Normal 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
day100/public/pause.svg
Normal 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
day100/public/play.svg
Normal 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
day100/public/plus.svg
Normal 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
day100/public/refresh.svg
Normal 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
day100/public/robots.txt
Normal file
35
day100/src/components/Counter.devto
Normal 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>
|
||||||
16
day100/src/components/Nav.devto
Normal 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>
|
||||||
20
day100/src/components/cookieInput.devto
Normal 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>
|
||||||
6
day100/src/components/formInput.devto
Normal 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>
|
||||||
11
day100/src/components/htmlInput.devto
Normal 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>
|
||||||
3
day100/src/components/indexComponent.devto
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
<Counter />
|
||||||
|
<formInput />
|
||||||
|
<textInput />
|
||||||
25
day100/src/components/myDad.devto
Normal 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>
|
||||||
7
day100/src/components/nestedSlotComponent.devto
Normal 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>
|
||||||
16
day100/src/components/slotComponent.devto
Normal 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>
|
||||||
9
day100/src/components/textInput.devto
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<div class="mb-2">
|
||||||
|
<h2 class="text-xl font-semibold text-center">Input is: {appState.contents.text}</h2>
|
||||||
|
</div>
|
||||||
|
<div class="flex justify-center">
|
||||||
|
<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>
|
||||||
12
day100/src/entry-client.ts
Normal 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();
|
||||||
|
};
|
||||||
3
day100/src/entry-server.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
// stub
|
||||||
|
|
||||||
|
export {};
|
||||||
5
day100/src/layouts/404.devto
Normal 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>
|
||||||
16
day100/src/layouts/default.devto
Normal 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>
|
||||||
65
day100/src/lib/ReactiveObject.ts
Normal 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
44
day100/src/lib/cookieManager.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
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
day100/src/lib/lruCache.ts
Normal 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, cache: undefined | Map<string, string | Record<string, string | Record<string, string | boolean>>>) {
|
||||||
|
this.#capacity = capacity;
|
||||||
|
this.#cache = (cache) ? 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
349
day100/src/lib/router/SSR/ssrHydrationGenerator.ts
Normal file
@@ -0,0 +1,349 @@
|
|||||||
|
import { JSDOM } from 'jsdom';
|
||||||
|
import * as terser from 'terser';
|
||||||
|
import { Reactive } from '../../ReactiveObject';
|
||||||
|
import { getAppState, initAppState } from '../../../main';
|
||||||
|
import { getCookie } from '../../cookieManager';
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
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('data-token')) {
|
||||||
|
script += 'const { getAppState, initAppState } = await import(\'/src/main.ts\');await initAppState();const appState = getAppState();';
|
||||||
|
const reactiveElms = Array.from(dom.window.document.querySelectorAll('span'));
|
||||||
|
if (reactiveElms.length === 0) return;
|
||||||
|
reactiveElms.forEach((e) => {
|
||||||
|
const label = e.getAttribute('data-d');
|
||||||
|
const reactiveAttributes = Array.from(e.attributes).filter(attr => attr.name.startsWith('data-token-'));
|
||||||
|
reactiveAttributes.forEach((attr) => {
|
||||||
|
const attributeName = attr.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 (e.parentElement?.hasAttribute('d-once')) {
|
||||||
|
e.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 (e.parentElement?.hasAttribute('d-html')) {
|
||||||
|
script += `appState.listen("${decodedUuid}", (change) => document.querySelector("[data-d='${label}']").innerHTML = change);`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
script += `appState.listen("${decodedUuid}", (change) => document.querySelector("[data-d='${label}']").textContent = change);`;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
const uniqueSelector = e.getAttribute('data-d');
|
||||||
|
|
||||||
|
if (!script.includes('const hiddenTag = ')) {
|
||||||
|
script += 'const hiddenTag = "<!-- d-if -->";';
|
||||||
|
}
|
||||||
|
script += `function resetHTML_${i}() {`;
|
||||||
|
script += `document.querySelector('*[data-d="${uniqueSelector}"]').innerHTML = hiddenTag;`;
|
||||||
|
const siblingUUIDMap = new Map();
|
||||||
|
siblingConditionalElms.forEach((elm, i) => {
|
||||||
|
if (!elm || !elm.textContent) return;
|
||||||
|
const siblingUniqueSelector = elm.getAttribute('data-d');
|
||||||
|
script += `document.querySelector('*[data-d="${siblingUniqueSelector}"').innerHTML = hiddenTag;`;
|
||||||
|
siblingUUIDMap[i.toString()] = siblingUniqueSelector;
|
||||||
|
});
|
||||||
|
script += '}';
|
||||||
|
|
||||||
|
let ifStatement = `if (${condition}) {
|
||||||
|
document.querySelector('*[data-d="${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('*[data-d="${siblingUuid}"').innerHTML = (\`${siblingHTML.toString()}\`)
|
||||||
|
}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
ifStatement = await minify(ifStatement, condition);
|
||||||
|
|
||||||
|
script += `const ifStatement_${i} = new Function('appState', \`${ifStatement}\`);
|
||||||
|
resetHTML_${i}();
|
||||||
|
ifStatement_${i}(appState);`;
|
||||||
|
|
||||||
|
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}();
|
||||||
|
ifStatement_${i}(appState);
|
||||||
|
});`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* reset HTML */
|
||||||
|
document.querySelector('*[data-d="' + uniqueSelector + '"]').innerHTML = '<!-- d-if -->';
|
||||||
|
siblingConditionalElms.forEach((elm, i) => {
|
||||||
|
if (!elm || !elm.textContent) return;
|
||||||
|
const siblingUniqueSelector = siblingUUIDMap[i.toString()];
|
||||||
|
document.querySelector(`*[data-d="${siblingUniqueSelector}"`).innerHTML = '<!-- d-if -->';
|
||||||
|
});
|
||||||
|
|
||||||
|
eval(ifStatement);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
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,' : ''} });`;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const modelElements = elements.filter((e) => {
|
||||||
|
return Array.from(e.attributes).some(attr => attr.name.startsWith('d-model'));
|
||||||
|
});
|
||||||
|
|
||||||
|
modelElements.forEach((modelElement) => {
|
||||||
|
const modelName = modelElement.getAttribute('d-model');
|
||||||
|
modelElement.removeAttribute('d-model');
|
||||||
|
if (modelName === undefined || modelName === null) return;
|
||||||
|
|
||||||
|
const label = modelElement.getAttribute('data-d');
|
||||||
|
script += `document.querySelector('*[data-d="${label}"]').addEventListener('input', (input) => {
|
||||||
|
const target = input.target;
|
||||||
|
appState.contents["${modelName}"] = target.value;
|
||||||
|
});`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const bindElements = elements.filter((e) => {
|
||||||
|
return Array.from(e.attributes).some(attr => /^(?:d-bind:|:)/.test(attr.name));
|
||||||
|
});
|
||||||
|
|
||||||
|
bindElements.forEach((e, i) => {
|
||||||
|
const modelAttrs = Array.from(e.attributes).filter(attr => attr.name.startsWith('d-bind:') || attr.name.startsWith(':'));
|
||||||
|
|
||||||
|
modelAttrs.forEach((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 (!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 (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');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (script.includes('getCookie(')) {
|
||||||
|
const regex = /getCookie\((['"])(.*?)\1\)/g;
|
||||||
|
|
||||||
|
const replacedString = script.replace(regex, (match, quote, value) => {
|
||||||
|
// Replace getCookie with the return value of the getCookie function
|
||||||
|
return `"${getCookie(value)}"`;
|
||||||
|
});
|
||||||
|
|
||||||
|
script = replacedString;
|
||||||
|
}
|
||||||
|
|
||||||
|
template = dom.window.document.body.innerHTML;
|
||||||
|
|
||||||
|
return { script, template };
|
||||||
|
}
|
||||||
259
day100/src/lib/router/hydrationManager.ts
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
import { getAppState } from '../../main';
|
||||||
|
import { renderPage } from './pageRenderer';
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
import { getCookie, setCookie } from '../cookieManager';
|
||||||
|
|
||||||
|
// function to turn the template into reactive content "hydating" a page
|
||||||
|
export async function hydratePage(virtDOM: HTMLBodyElement, reduceJavascript: boolean) {
|
||||||
|
if (import.meta.env.SSR) return;
|
||||||
|
const appState = await getAppState();
|
||||||
|
const documentBody = document.querySelector('div[id="app"]');
|
||||||
|
|
||||||
|
if (!documentBody) {
|
||||||
|
throw new Error('Fatal Error: element with id app not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reduceJavascript === undefined) reduceJavascript = false;
|
||||||
|
const elements = Array.from(virtDOM.querySelectorAll('*'));
|
||||||
|
|
||||||
|
elements.forEach((e) => {
|
||||||
|
const hexCode = Math.random().toString(16).substring(2, 8);
|
||||||
|
e.setAttribute('data-d', hexCode);
|
||||||
|
});
|
||||||
|
|
||||||
|
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;
|
||||||
|
let firstLetter;
|
||||||
|
if (isKeyboardEvent && eventKey === ' ') {
|
||||||
|
eventKey = 'Space';
|
||||||
|
}
|
||||||
|
if (isKeyboardEvent) {
|
||||||
|
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') });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const modelElements = elements.filter((e) => {
|
||||||
|
return Array.from(e.attributes).some(attr => attr.name.startsWith('d-model'));
|
||||||
|
});
|
||||||
|
|
||||||
|
modelElements.forEach((modelElement) => {
|
||||||
|
const modelName = modelElement.getAttribute('d-model');
|
||||||
|
modelElement.removeAttribute('d-model');
|
||||||
|
if (modelName === undefined || modelName === null) return;
|
||||||
|
modelElement.addEventListener('input', (input: Event) => {
|
||||||
|
const target = input.target as HTMLInputElement;
|
||||||
|
appState.contents[modelName] = target.value;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const bindElements = elements.filter((e) => {
|
||||||
|
return Array.from(e.attributes).some(attr => /^(?:d-bind:|:)/.test(attr.name));
|
||||||
|
});
|
||||||
|
|
||||||
|
bindElements.forEach((modelElm) => {
|
||||||
|
const modelAttrs = Array.from(modelElm.attributes).filter(attr => attr.name.startsWith('d-bind:') || attr.name.startsWith(':'));
|
||||||
|
|
||||||
|
modelAttrs.forEach((attr) => {
|
||||||
|
const keyName = attr.name.split(':')[1];
|
||||||
|
const originalValue = '(' + attr.value + ')';
|
||||||
|
let currentBinding = '';
|
||||||
|
|
||||||
|
modelElm.removeAttribute(attr.name);
|
||||||
|
|
||||||
|
function setAttribute() {
|
||||||
|
if (!keyName) return;
|
||||||
|
let value = 'return "' + originalValue + '"';
|
||||||
|
const attribute = modelElm.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;
|
||||||
|
}
|
||||||
|
modelElm.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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const anchorElms = elements.filter((e) => {
|
||||||
|
return e.tagName.toLowerCase() === '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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const reactiveElms = elements.filter((e) => {
|
||||||
|
return e.tagName.toLowerCase() === 'span' && Array.from(e.attributes).filter(el => el.name.startsWith('data-token-'));
|
||||||
|
});
|
||||||
|
|
||||||
|
reactiveElms.forEach((e) => {
|
||||||
|
const reactiveAttributes = Array.from(e.attributes).filter(attr => attr.name.startsWith('data-token-'));
|
||||||
|
|
||||||
|
reactiveAttributes.forEach((attr) => {
|
||||||
|
const attributeName = attr.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 (e.parentElement?.hasAttribute('d-once')) {
|
||||||
|
e.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 (e.parentElement?.hasAttribute('d-html')) {
|
||||||
|
appState.listen(decodedUuid, (change: string) => e.innerHTML = change);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
appState.listen(decodedUuid, (change: string | null) => e.textContent = change);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const conditionalElms = elements.filter((e) => {
|
||||||
|
return Array.from(e.attributes).some(attr => attr.name === 'd-if');
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('app')?.children[0].replaceWith(virtDOM);
|
||||||
|
}
|
||||||
340
day100/src/lib/router/pageRenderer.ts
Normal file
@@ -0,0 +1,340 @@
|
|||||||
|
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, 'serverSideSPALikeRouting': true };
|
||||||
|
|
||||||
|
parseFromRegex(page, /<script>[\s\S]*?<\/script>/gi).forEach((e) => {
|
||||||
|
if (!e || !e.startsWith('<script>') || !e.endsWith('</script>')) return;
|
||||||
|
|
||||||
|
parseFromRegex(e, /definePageMeta\({(.*?)}\)(;){0,1}/g).forEach((metaElm) => {
|
||||||
|
if (!metaElm || !metaElm.startsWith('definePageMeta({')) return;
|
||||||
|
|
||||||
|
let metaObjString = metaElm.split('(')[1]?.split(')')[0];
|
||||||
|
if (!metaObjString) return;
|
||||||
|
|
||||||
|
metaObjString = metaObjString
|
||||||
|
.replaceAll(' ', '')
|
||||||
|
.replaceAll('{', '{\'')
|
||||||
|
.replaceAll(':', '\':')
|
||||||
|
.replaceAll(',', ',\'')
|
||||||
|
.replaceAll('\'', '"');
|
||||||
|
|
||||||
|
const newMetaObj = JSON.parse(metaObjString);
|
||||||
|
Object.keys(newMetaObj).forEach((key) => {
|
||||||
|
metaObj[key] = newMetaObj[key];
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
let layout: string;
|
||||||
|
try {
|
||||||
|
layout = await fetchPage(`/${metaObj.layout}`, 'layouts', false);
|
||||||
|
} catch {
|
||||||
|
layout = '<slot />';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!layout) return;
|
||||||
|
|
||||||
|
page = layout.replaceAll('<slot />', page);
|
||||||
|
|
||||||
|
const stringifiedTemplate = await compileToString(page);
|
||||||
|
|
||||||
|
if (!stringifiedTemplate) return;
|
||||||
|
|
||||||
|
if (debugMode) {
|
||||||
|
console.groupCollapsed('✨ Compiled 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;
|
||||||
|
const parser = new DOMParser();
|
||||||
|
const virtDOM = parser.parseFromString(await eval(fnStr), 'text/html');
|
||||||
|
|
||||||
|
if (stringifiedTemplate.styles && typeof stringifiedTemplate.styles == 'string') {
|
||||||
|
const cssElement = virtDOM.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 = virtDOM.createElement('script');
|
||||||
|
const script = (stringifiedTemplate.script) ? stringifiedTemplate.script : '';
|
||||||
|
const setupScript = (stringifiedTemplate.setupScript) ? stringifiedTemplate.setupScript : '';
|
||||||
|
scriptElement.async = true;
|
||||||
|
scriptElement.type = 'module';
|
||||||
|
scriptElement.setAttribute('local', 'true');
|
||||||
|
scriptElement.innerHTML = setupScript + script;
|
||||||
|
document.head.appendChild(scriptElement);
|
||||||
|
}
|
||||||
|
|
||||||
|
// here we hydrate/re-hydrate the page content and once done set the page content to the hydrated virtualDOM content
|
||||||
|
await hydratePage(virtDOM.body, metaObj.reduceJavascript);
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
241
day100/src/lib/templateRenderer.ts
Normal 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 };
|
||||||
|
|
||||||
|
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,'&').replace(/</g,'<').replace(/>/g,'>'))`;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
41
day100/src/main.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
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},
|
||||||
|
listElement: [{ message: 'Foo' }, { message: 'Bar' }]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
32
day100/src/pages/index.devto
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<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' });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script serverSideScript>
|
||||||
|
console.log(req.path)
|
||||||
|
</script>
|
||||||
23
day100/src/pages/l.devto
Normal 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>
|
||||||
7
day100/src/pages/music.devto
Normal 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>
|
||||||
11
day100/src/pages/nojavascript.devto
Normal 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, serverSideSPALikeRouting: false });
|
||||||
|
</script>
|
||||||
25
day100/src/pages/page2.devto
Normal 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>
|
||||||
13
day100/src/pages/page3.devto
Normal 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
day100/src/style.css
Normal 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;
|
||||||
|
}
|
||||||
29
day100/tailwind.config.js
Normal 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
day100/tsconfig.json
Normal 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/*"],
|
||||||
|
}
|
||||||
1
day100/tsconfig.tsbuildinfo
Normal file
9
day100/types/index.d.ts
vendored
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
/* eslint-disable no-var */
|
||||||
|
|
||||||
|
declare module '*.css'
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
var _ctx: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { };
|
||||||
14
day100/vite.config.ts
Normal 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', './devto.config.js']
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
16
day13/index.html
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<!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">
|
||||||
|
<title>Document</title>
|
||||||
|
<script async src="/src/entry-client.js" type="module"></script>
|
||||||
|
<!--style-outlet-->
|
||||||
|
</head>
|
||||||
|
<body><div
|
||||||
|
id="app"
|
||||||
|
>
|
||||||
|
<!--ssr-outlet--><noscript>You need javascript to run this app</noscript></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
100
day13/index.js
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
import fs from 'fs'
|
||||||
|
import path from 'path'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import express from 'express'
|
||||||
|
import { createServer as createViteServer } from 'vite'
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
|
||||||
|
async function createServer() {
|
||||||
|
const app = express()
|
||||||
|
|
||||||
|
app.use(express.static(__dirname + '/public'))
|
||||||
|
|
||||||
|
// 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 },
|
||||||
|
appType: 'custom'
|
||||||
|
})
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
|
||||||
|
app.use('*', async (req, res, next) => {
|
||||||
|
const url = req.originalUrl
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Read index.html
|
||||||
|
let template
|
||||||
|
template = fs.readFileSync(
|
||||||
|
path.resolve(__dirname, 'index.html'),
|
||||||
|
'utf-8'
|
||||||
|
)
|
||||||
|
|
||||||
|
let fileName = url.split('/');
|
||||||
|
if (fileName[1] === '') {
|
||||||
|
fileName = '/index';
|
||||||
|
} else {
|
||||||
|
fileName = fileName.join('/').toLowerCase().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(fileName);
|
||||||
|
|
||||||
|
// 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.js')
|
||||||
|
|
||||||
|
let pageData
|
||||||
|
try {
|
||||||
|
pageData = fs.readFileSync(
|
||||||
|
path.resolve(__dirname, './src/pages' + fileName + '.devto'),
|
||||||
|
'utf-8',
|
||||||
|
)
|
||||||
|
} catch (e) {
|
||||||
|
pageData = fs.readFileSync(
|
||||||
|
path.resolve(__dirname, './src/layouts/404.devto'),
|
||||||
|
'utf-8'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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('/src/style.css')
|
||||||
|
|
||||||
|
const main = await vite.ssrLoadModule('/src/main')
|
||||||
|
|
||||||
|
const appState = main.appState
|
||||||
|
|
||||||
|
const style = styles.default
|
||||||
|
// 5. Inject the app-rendered HTML into the template.
|
||||||
|
const stylizedTemplate = template.replace('<!--style-outlet-->', '<style type="text/css">' + style + '</style>')
|
||||||
|
|
||||||
|
const html = stylizedTemplate.replace(`<!--ssr-outlet-->`, eval(appHtml))
|
||||||
|
|
||||||
|
// 6. Send the rendered HTML back.
|
||||||
|
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
|
||||||
|
} catch (e) {
|
||||||
|
// If an error is caught, let Vite fix the stack trace so it maps back to
|
||||||
|
// your actual source code.
|
||||||
|
vite.ssrFixStacktrace(e)
|
||||||
|
res.status(500).end(e.stack)
|
||||||
|
next(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.listen(3000)
|
||||||
|
}
|
||||||
|
|
||||||
|
createServer()
|
||||||
4675
day13/package-lock.json
generated
Normal file
32
day13/package.json
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"name": "devto",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"main": "index.js",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev:client": "vite",
|
||||||
|
"dev:server": "nodemon index.js"
|
||||||
|
},
|
||||||
|
"author": "",
|
||||||
|
"license": "ISC",
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/express": "^4.17.14",
|
||||||
|
"autoprefixer": "^10.4.12",
|
||||||
|
"postcss": "^8.4.17",
|
||||||
|
"tailwindcss": "^3.1.8"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"express": "^4.18.1",
|
||||||
|
"nodemon": "^2.0.20",
|
||||||
|
"typescript": "^4.8.4",
|
||||||
|
"vite": "^3.1.4",
|
||||||
|
"@types/node": "18.0.6",
|
||||||
|
"autoprefixer": "10.4.7",
|
||||||
|
"cssnano": "5.1.12",
|
||||||
|
"postcss": "8.4.14",
|
||||||
|
"postcss-import": "14.1.0",
|
||||||
|
"postcss-nesting": "10.1.10",
|
||||||
|
"tailwindcss": "3.1.6"
|
||||||
|
}
|
||||||
|
}
|
||||||
6
day13/postcss.config.cjs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
BIN
day13/public/favicon.ico
Normal file
|
After Width: | Height: | Size: 16 KiB |
12
day13/src/components/cookieInput.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
export const CookieInput = () => {
|
||||||
|
return `
|
||||||
|
<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">
|
||||||
|
<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" />
|
||||||
|
{appState.contents.cookiedata}
|
||||||
|
<button class="bg-blue-600 font-semibold rounded-md py-1 px-2 text-sm" d-click="appState.contents.cookie = appState.contents.cookiedata; setCookie('username', appState.contents.cookiedata, '365');">Submit Cookie</button>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
}
|
||||||
22
day13/src/components/counter.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import minus from '../icons/minus.svg'
|
||||||
|
import plus from '../icons/plus.svg'
|
||||||
|
import refresh from '../icons/refresh.svg'
|
||||||
|
|
||||||
|
export const Counter = () => {
|
||||||
|
return `
|
||||||
|
<div class="mb-2">
|
||||||
|
<h2 class="text-xl font-semibold text-center">count is: { appState.contents.count }</h2>
|
||||||
|
</div>
|
||||||
|
<div class="flex justify-center">
|
||||||
|
<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} 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} 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} alt="plus" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
}
|
||||||
12
day13/src/components/htmlInput.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
export const HtmlInput = () => {
|
||||||
|
return `
|
||||||
|
<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>
|
||||||
|
`
|
||||||
|
}
|
||||||
23
day13/src/components/myDad.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
export const MyDad = () => {
|
||||||
|
return `
|
||||||
|
<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>
|
||||||
|
`
|
||||||
|
}
|
||||||
5
day13/src/components/routerLink.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
export const RouterLink = (link: string, name: string) => {
|
||||||
|
return `
|
||||||
|
<a href="${link}" d-on:click="event.preventDefault(); renderPage('${link}')">${name}</a>
|
||||||
|
`
|
||||||
|
}
|
||||||
12
day13/src/components/textInput.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
export const TextInput = () => {
|
||||||
|
return `
|
||||||
|
<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 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>
|
||||||
|
`
|
||||||
|
}
|
||||||
18
day13/src/entry-client.js
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { renderPage, hydratePage } from './lib/router';
|
||||||
|
import { isSSR, appState } from '/src/main';
|
||||||
|
|
||||||
|
export async function mount(mounted) {
|
||||||
|
eval(mounted)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!import.meta.env.SSR) {
|
||||||
|
// waits for the page to fully load to render the page from the virtDOM
|
||||||
|
if (!isSSR) {
|
||||||
|
await renderPage()
|
||||||
|
window.onpopstate = async () => {
|
||||||
|
await renderPage()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
hydratePage()
|
||||||
|
}
|
||||||
|
}
|
||||||
7
day13/src/entry-server.js
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { render } from './lib/templateRenderer';
|
||||||
|
import { setSSR, appState } from './main';
|
||||||
|
|
||||||
|
export function SSRPage(pageName) {
|
||||||
|
setSSR()
|
||||||
|
return render(pageName)
|
||||||
|
}
|
||||||
5
day13/src/layouts/404.devto
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<div class="grid place-items-center p-3 content-center min-h-screen">
|
||||||
|
<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>
|
||||||
39
day13/src/lib/ReactiveObject.js
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
export class Reactive {
|
||||||
|
constructor(obj) {
|
||||||
|
this.contents = obj;
|
||||||
|
this.listeners = {};
|
||||||
|
this.makeReactive(obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
makeReactive(obj) {
|
||||||
|
Object.keys(obj).forEach(prop => this.makePropReactive(obj, prop));
|
||||||
|
}
|
||||||
|
|
||||||
|
makePropReactive(obj, key) {
|
||||||
|
let value = obj[key];
|
||||||
|
|
||||||
|
// Gotta be careful with this here
|
||||||
|
const that = this;
|
||||||
|
|
||||||
|
Object.defineProperty(obj, key, {
|
||||||
|
get() {
|
||||||
|
return value;
|
||||||
|
},
|
||||||
|
set(newValue) {
|
||||||
|
value = newValue;
|
||||||
|
that.notify(key)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
listen(prop, handler) {
|
||||||
|
if (!this.listeners[prop]) this.listeners[prop] = [];
|
||||||
|
|
||||||
|
this.listeners[prop].push(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
notify(prop) {
|
||||||
|
if (!this.listeners[prop]) return
|
||||||
|
this.listeners[prop].forEach((listener) => listener(this.contents[prop]));
|
||||||
|
}
|
||||||
|
}
|
||||||
41
day13/src/lib/cookieManager.js
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
export function setCookie(name, value, expires, path, domain) {
|
||||||
|
if (import.meta.env.SSR) return
|
||||||
|
var cookie = name.trimEnd() + "=" + escape(value) + ";";
|
||||||
|
|
||||||
|
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.toGMTString() + ";";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path)
|
||||||
|
cookie += "path=" + path + ";";
|
||||||
|
if (domain)
|
||||||
|
cookie += "domain=" + domain + ";";
|
||||||
|
|
||||||
|
document.cookie = cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCookie(name) {
|
||||||
|
if (import.meta.env.SSR) return
|
||||||
|
let cname = name + "=";
|
||||||
|
let decodedCookie = decodeURIComponent(document.cookie);
|
||||||
|
let ca = decodedCookie.split(';');
|
||||||
|
for(let i = 0; i <ca.length; i++) {
|
||||||
|
let c = ca[i];
|
||||||
|
while (c.charAt(0) == ' ') {
|
||||||
|
c = c.substring(1);
|
||||||
|
}
|
||||||
|
if (c.indexOf(cname) == 0) {
|
||||||
|
return c.substring(cname.length, c.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
230
day13/src/lib/router.js
Normal file
@@ -0,0 +1,230 @@
|
|||||||
|
import { compileToString } from './templateRenderer'
|
||||||
|
import { mount } from '../entry-client'
|
||||||
|
import { isSSR, appState } from '../main'
|
||||||
|
let documentBody
|
||||||
|
|
||||||
|
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) {
|
||||||
|
if (import.meta.env.SSR) return;
|
||||||
|
if (isSSR) window.location.href = route
|
||||||
|
if (!documentBody) {
|
||||||
|
throw new Error('Fatal Error: element with id app not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (route) history.pushState('', '', route);
|
||||||
|
|
||||||
|
let fileName = window.location.pathname.split('/');
|
||||||
|
if (fileName[1] === '') {
|
||||||
|
fileName = '/index';
|
||||||
|
} else {
|
||||||
|
fileName = fileName.join('/').toLowerCase().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
const page = await loadPage(fileName);
|
||||||
|
|
||||||
|
const stringifiedTemplate = await compileToString(page.template);
|
||||||
|
|
||||||
|
if (import.meta.env.VITE_VERBOSE && !import.meta.env.PROD) {
|
||||||
|
console.groupCollapsed('Loaded page ' + fileName);
|
||||||
|
console.info('Template: ' + page.template)
|
||||||
|
console.info('stringified template: ' + stringifiedTemplate)
|
||||||
|
console.groupEnd()
|
||||||
|
}
|
||||||
|
|
||||||
|
documentBody.innerHTML = await eval(stringifiedTemplate);
|
||||||
|
mount(page.mountedFunction)
|
||||||
|
// here we hydrate/re-hydrate the page content
|
||||||
|
await hydratePage()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPage(page) {
|
||||||
|
if (import.meta.env.SSR) return;
|
||||||
|
if (isSSR) return;
|
||||||
|
|
||||||
|
let file
|
||||||
|
let mounted
|
||||||
|
try {
|
||||||
|
file = await import(/* @vite-ignore */ '../pages' + page);
|
||||||
|
if (file.mounted) {
|
||||||
|
mounted = file.mounted()
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e)
|
||||||
|
file = await import(/* @vite-ignore */ '../layouts/' + '404');
|
||||||
|
}
|
||||||
|
const template = await file.default();
|
||||||
|
const mountedFunction = mounted
|
||||||
|
|
||||||
|
return { template, mountedFunction };
|
||||||
|
}
|
||||||
|
|
||||||
|
// function to turn the template into reactive content "hydating" a page
|
||||||
|
export async function hydratePage() {
|
||||||
|
if (!documentBody) {
|
||||||
|
throw new Error('Fatal Error: element with id app not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
// for every item in the appState lets check for any element with the "checksum", a hex code equivalent of the item name
|
||||||
|
Object.keys(appState.contents).forEach((e) => {
|
||||||
|
if (e === undefined) return
|
||||||
|
// here we check for elements with the name of "data-token-<hex code of the item name>"
|
||||||
|
const uuid = e.split("").map(c => c.charCodeAt(0).toString(16).padStart(2, "0")).join("")
|
||||||
|
const listeningElements = document.querySelectorAll(`[${"data-token-" + uuid}]`)
|
||||||
|
listeningElements.forEach((elm) => {
|
||||||
|
if (elm.parentElement?.getAttribute('d-once') !== null) {
|
||||||
|
elm.parentElement?.removeAttribute('d-once');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (elm.parentElement?.getAttribute('d-html') !== null) {
|
||||||
|
appState.listen(e, (change) => elm.innerHTML = change);
|
||||||
|
elm.parentElement?.removeAttribute('d-html')
|
||||||
|
} else {
|
||||||
|
appState.listen(e, (change) => elm.textContent = change);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// here we look for elements with the d-on:click attribute and on click run the function in the attribute
|
||||||
|
let elms = documentBody.querySelectorAll('*[d-on\\3A click]')
|
||||||
|
elms.forEach((e) => {
|
||||||
|
const clickFunction = e.getAttribute("d-on\:click")
|
||||||
|
e.removeAttribute('d-on\:click')
|
||||||
|
if (!clickFunction) return;
|
||||||
|
e.addEventListener('click', () => {
|
||||||
|
eval(clickFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// here we determine if an element should be deleted form the DOM via the d-if directive
|
||||||
|
let conditionalElms = document.querySelectorAll('*[d-if]')
|
||||||
|
conditionalElms.forEach(async (e) => {
|
||||||
|
const condition = e.getAttribute('d-if')
|
||||||
|
|
||||||
|
let siblingConditionalElms = []
|
||||||
|
// recursively check for subsequent elements with the d-else of d-else-if attribute
|
||||||
|
function checkForConditionSibling(elm) {
|
||||||
|
if (elm.nextElementSibling?.getAttribute('d-else-if') !== null) {
|
||||||
|
siblingConditionalElms.push(elm.nextElementSibling)
|
||||||
|
checkForConditionSibling(elm.nextElementSibling)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (elm.nextElementSibling?.getAttribute('d-else') !== null) {
|
||||||
|
siblingConditionalElms.push(elm.nextElementSibling)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkForConditionSibling(e)
|
||||||
|
|
||||||
|
function resetHTML() {
|
||||||
|
e.innerHTML = '<!-- d-if -->'
|
||||||
|
for (let i = 0; i < siblingConditionalElms.length; i++) {
|
||||||
|
siblingConditionalElms[i].innerHTML = '<!-- d-if -->'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let ifStatement = `if (!!eval(condition)) {
|
||||||
|
e.innerHTML = originalHTML
|
||||||
|
} `
|
||||||
|
|
||||||
|
for (let i = 0; i < siblingConditionalElms.length; i++) {
|
||||||
|
console.log(i)
|
||||||
|
const originHTML = siblingConditionalElms[i].innerHTML
|
||||||
|
siblingConditionalElms[i].innerHTML = '<!-- d-if -->'
|
||||||
|
let statementDirective = 'else'
|
||||||
|
if (siblingConditionalElms[i].getAttribute('d-else-if') !== null) {
|
||||||
|
statementDirective = 'else if'
|
||||||
|
}
|
||||||
|
const condition = eval(`siblingConditionalElms[i].getAttribute('d-' + statementDirective.split(' ').join('-'))`)
|
||||||
|
|
||||||
|
if (statementDirective == 'else if') {
|
||||||
|
statementDirective = 'else if (' + condition + ')'
|
||||||
|
}
|
||||||
|
|
||||||
|
ifStatement = ifStatement + statementDirective + `{
|
||||||
|
siblingConditionalElms[${i}].innerHTML = "${originHTML}"
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
|
||||||
|
e.removeAttribute('d-if')
|
||||||
|
const originalHTML = e.innerHTML
|
||||||
|
if (!condition) return;
|
||||||
|
if (condition.includes("appState.contents.")) {
|
||||||
|
let reactiveProp = /appState\.contents\.[a-zA-Z]+/.exec(condition)
|
||||||
|
if (!reactiveProp) return;
|
||||||
|
reactiveProp = reactiveProp[0].split('.')[2]
|
||||||
|
appState.listen(reactiveProp, () => {
|
||||||
|
resetHTML()
|
||||||
|
eval(ifStatement)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
eval(ifStatement)
|
||||||
|
})
|
||||||
|
|
||||||
|
let pointerEnterElms = document.querySelectorAll('*[d-on\\3A pointerEnter]')
|
||||||
|
pointerEnterElms.forEach((e) => {
|
||||||
|
const enterFunction = e.getAttribute('d-on\:pointerEnter')
|
||||||
|
e.removeAttribute('d-on\:pointerEnter')
|
||||||
|
if (!enterFunction) return;
|
||||||
|
e.addEventListener('pointerenter', (event) => {
|
||||||
|
eval(enterFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
let pointerExitElms = document.querySelectorAll('*[d-on\\3A pointerExit]')
|
||||||
|
pointerExitElms.forEach((e) => {
|
||||||
|
const exitFunction = e.getAttribute('d-on\:pointerExit')
|
||||||
|
e.removeAttribute('d-on\:pointerExit')
|
||||||
|
if (!exitFunction) return;
|
||||||
|
e.addEventListener('pointerleave', (event) => {
|
||||||
|
eval(exitFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
let mouseDownElms = document.querySelectorAll('*[d-on\\3A mouseDown]')
|
||||||
|
mouseDownElms.forEach((e) => {
|
||||||
|
const downFunction = e.getAttribute('d-on\:mouseDown')
|
||||||
|
e.removeAttribute('d-on\:mouseDown')
|
||||||
|
if (!downFunction) return;
|
||||||
|
e.addEventListener('mousedown', (event) => {
|
||||||
|
eval(downFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
let mouseUpElms = document.querySelectorAll('*[d-on\\3A mouseUp]')
|
||||||
|
mouseUpElms.forEach((e) => {
|
||||||
|
const dupFunction = e.getAttribute('d-on\:mouseUp')
|
||||||
|
e.removeAttribute('d-on\:mouseUp')
|
||||||
|
if (!dupFunction) return;
|
||||||
|
e.addEventListener('mouseup', (event) => {
|
||||||
|
eval(dupFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// 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
|
||||||
|
let modelElms = document.querySelectorAll('input[d-model], textarea[d-model]');
|
||||||
|
modelElms.forEach((e) => {
|
||||||
|
const modelName = e.getAttribute("d-model")
|
||||||
|
if (!modelName) return;
|
||||||
|
e.addEventListener('input', (event) => {
|
||||||
|
appState.contents[modelName] = event.target.value
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
65
day13/src/lib/templateRenderer.js
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
export const compileToString = async (template) => {
|
||||||
|
const ast = parse(template);
|
||||||
|
let fnStr = `\`\``;
|
||||||
|
|
||||||
|
ast.map(async t => {
|
||||||
|
// checking to see if it is an interpolation
|
||||||
|
if (t.startsWith("{") && t.endsWith("}")) {
|
||||||
|
// TODO: rewrite comment
|
||||||
|
let bracketVariable = t.split(/{|}/).filter(Boolean)[0].trim();
|
||||||
|
const parentElement = fnStr.split(t)[0].split('>')
|
||||||
|
const isRawHTML = parentElement[parentElement.length-2].includes('d-html')
|
||||||
|
if (bracketVariable.startsWith("appState.contents.")) {
|
||||||
|
const uuid = bracketVariable.substring(bracketVariable.length, 18).split('').map(c => 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,'&').replace(/</g,'<').replace(/>/g,'>'))`
|
||||||
|
|
||||||
|
if (isRawHTML) {
|
||||||
|
runVar = `(${bracketVariable})`
|
||||||
|
}
|
||||||
|
|
||||||
|
fnStr += `+ (${runVar})` + `+\`</span>\``;
|
||||||
|
} else {
|
||||||
|
// append the string to the fnStr
|
||||||
|
fnStr += `+\`${t}\``;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (import.meta.env.VITE_VERBOSE && !import.meta.env.PROD) {
|
||||||
|
console.groupCollapsed('Compiled tempalte to String')
|
||||||
|
console.info('Template String: ' + fnStr)
|
||||||
|
console.groupEnd()
|
||||||
|
}
|
||||||
|
|
||||||
|
return fnStr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// this function will turn a string like "hi {user}" into an array that looks something like "["hi", "{user}"] so we can loop over the array elements
|
||||||
|
// when compiling the template
|
||||||
|
var parse = (template) => {
|
||||||
|
let result = /{(.*?)}/g.exec(template);
|
||||||
|
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 = /{(.*?)}/g.exec(template);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (template) arr.push(template);
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const render = (template) => {
|
||||||
|
return compileToString(template)
|
||||||
|
}
|
||||||
21
day13/src/main.js
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { Reactive } from './lib/ReactiveObject'
|
||||||
|
import { getCookie } from './lib/cookieManager';
|
||||||
|
|
||||||
|
export const appState = new Reactive({
|
||||||
|
count: 0,
|
||||||
|
cookie: getCookie('username'),
|
||||||
|
text: '',
|
||||||
|
html: '',
|
||||||
|
year: '',
|
||||||
|
cookiedata: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
let SSR = false;
|
||||||
|
|
||||||
|
export function isSSR() {
|
||||||
|
return SSR;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setSSR() {
|
||||||
|
SSR = true;
|
||||||
|
}
|
||||||
12
day13/src/pages/index.devto
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
<div class="grid place-items-center p-3 content-center min-h-screen">
|
||||||
|
<div class="p-6 border-neutral-800 rounded-lg container__content border">
|
||||||
|
<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 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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
21
day13/src/style.css
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
@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:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container__content {
|
||||||
|
box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
|
||||||
|
}
|
||||||
17
day13/tailwind.config.cjs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
const colors = require('tailwindcss/colors')
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
content: [
|
||||||
|
"./index.html",
|
||||||
|
"./src/**/*.{devto,js,ts,jsx,tsx}",
|
||||||
|
],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
gray: colors.zinc
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
}
|
||||||
11
day13/vite.config.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
/** @type {import('vite').UserConfig} */
|
||||||
|
export default {
|
||||||
|
build: {
|
||||||
|
target: 'es2020',
|
||||||
|
},
|
||||||
|
|
||||||
|
server: {
|
||||||
|
port: 3000,
|
||||||
|
host: '0.0.0.0'
|
||||||
|
}
|
||||||
|
}
|
||||||
16
day14/index.html
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<!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">
|
||||||
|
<title>Document</title>
|
||||||
|
<script async src="/src/entry-client.js" type="module"></script>
|
||||||
|
<!--style-outlet-->
|
||||||
|
</head>
|
||||||
|
<body><div
|
||||||
|
id="app"
|
||||||
|
>
|
||||||
|
<!--ssr-outlet--><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>
|
||||||
118
day14/index.js
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
import fs from 'fs'
|
||||||
|
import path from 'path'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import express from 'express'
|
||||||
|
import { createServer as createViteServer } from 'vite'
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
|
||||||
|
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", "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", "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) {
|
||||||
|
return tags.indexOf(tag.trim().toLowerCase()) > -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createServer() {
|
||||||
|
const app = express()
|
||||||
|
|
||||||
|
app.use(express.static(__dirname + '/public'))
|
||||||
|
|
||||||
|
// 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 },
|
||||||
|
appType: 'custom'
|
||||||
|
})
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
|
||||||
|
app.use('*', async (req, res, next) => {
|
||||||
|
const url = req.originalUrl
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Read index.html
|
||||||
|
let template
|
||||||
|
template = fs.readFileSync(
|
||||||
|
path.resolve(__dirname, 'index.html'),
|
||||||
|
'utf-8'
|
||||||
|
)
|
||||||
|
|
||||||
|
let fileName = url.split('/');
|
||||||
|
if (fileName[1] === '') {
|
||||||
|
fileName = '/index';
|
||||||
|
} else {
|
||||||
|
fileName = fileName.join('/').toLowerCase().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(fileName);
|
||||||
|
|
||||||
|
// 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.js')
|
||||||
|
|
||||||
|
let pageData
|
||||||
|
try {
|
||||||
|
pageData = fs.readFileSync(
|
||||||
|
path.resolve(__dirname, './src/pages' + fileName + '.devto'),
|
||||||
|
'utf-8',
|
||||||
|
)
|
||||||
|
} catch (e) {
|
||||||
|
pageData = fs.readFileSync(
|
||||||
|
path.resolve(__dirname, './src/layouts/404.devto'),
|
||||||
|
'utf-8'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
let test
|
||||||
|
|
||||||
|
pageData.split('<').forEach(e => {
|
||||||
|
let item = e.split(' ')[0]
|
||||||
|
if (item.includes('/') || item.includes('{') || item.includes('}') || !item) return
|
||||||
|
item = item.split('>')[0]
|
||||||
|
if (isHTML(item)) return
|
||||||
|
const component = fs.readFileSync(
|
||||||
|
path.resolve('./src/components/' + item + '.devto'),
|
||||||
|
'utf-8',
|
||||||
|
)
|
||||||
|
pageData = pageData.replace('<' + item + ' />', component)
|
||||||
|
test = pageData
|
||||||
|
console.log(pageData)
|
||||||
|
})
|
||||||
|
|
||||||
|
// 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('/src/style.css')
|
||||||
|
|
||||||
|
const main = await vite.ssrLoadModule('/src/main')
|
||||||
|
|
||||||
|
const appState = main.appState
|
||||||
|
// 5. Inject the app-rendered HTML into the template.
|
||||||
|
const stylizedTemplate = template.replace('<!--style-outlet-->', '<style type="text/css">' + styles.default + '</style>')
|
||||||
|
|
||||||
|
const html = stylizedTemplate.replace(`<!--ssr-outlet-->`, eval(appHtml))
|
||||||
|
|
||||||
|
// 6. Send the rendered HTML back.
|
||||||
|
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
|
||||||
|
} catch (e) {
|
||||||
|
// If an error is caught, let Vite fix the stack trace so it maps back to
|
||||||
|
// your actual source code.
|
||||||
|
vite.ssrFixStacktrace(e)
|
||||||
|
res.status(500).end(e.stack)
|
||||||
|
next(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.listen(3000)
|
||||||
|
}
|
||||||
|
|
||||||
|
createServer()
|
||||||
5556
day14/package-lock.json
generated
Normal file
39
day14/package.json
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"name": "devto",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"main": "index.js",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev:client": "vite --config vite.config.js dev",
|
||||||
|
"dev:server": "nodemon --watch index.js --watch src/ index.js",
|
||||||
|
"build": "rimraf dist && npm run build:client && npm run build:server && npm run copy-files",
|
||||||
|
"build:client": "vite build --outDir dist/client --ssrManifest",
|
||||||
|
"build:server": "vite build --ssr index.js --outDir dist/server",
|
||||||
|
"copy-files": "copyfiles public/* dist/assets && copyfiles index.html dist"
|
||||||
|
},
|
||||||
|
"author": "",
|
||||||
|
"license": "ISC",
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/express": "^4.17.14",
|
||||||
|
"autoprefixer": "^10.4.12",
|
||||||
|
"postcss": "^8.4.17",
|
||||||
|
"tailwindcss": "^3.1.8"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"express": "^4.18.1",
|
||||||
|
"nodemon": "^2.0.20",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^4.8.4",
|
||||||
|
"concurrently": "7.3.0",
|
||||||
|
"copyfiles": "^2.4.1",
|
||||||
|
"vite": "^3.1.4",
|
||||||
|
"@types/node": "18.0.6",
|
||||||
|
"autoprefixer": "10.4.7",
|
||||||
|
"cssnano": "5.1.12",
|
||||||
|
"postcss": "8.4.14",
|
||||||
|
"postcss-import": "14.1.0",
|
||||||
|
"postcss-nesting": "10.1.10",
|
||||||
|
"tailwindcss": "3.1.6"
|
||||||
|
}
|
||||||
|
}
|
||||||
6
day14/postcss.config.cjs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
BIN
day14/public/favicon.ico
Normal file
|
After Width: | Height: | Size: 16 KiB |
1
day14/public/minus.svg
Normal 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
day14/public/plus.svg
Normal 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
day14/public/refresh.svg
Normal 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 |
20
day14/src/components/Counter.devto
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<div class="mb-2">
|
||||||
|
<h2 class="text-xl font-semibold text-center">count is: { appState.contents.count }</h2>
|
||||||
|
</div>
|
||||||
|
<div class="flex justify-center">
|
||||||
|
<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'
|
||||||
|
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'
|
||||||
|
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'
|
||||||
|
alt="plus" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
12
day14/src/components/cookieInput.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
export const CookieInput = () => {
|
||||||
|
return `
|
||||||
|
<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">
|
||||||
|
<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" />
|
||||||
|
{appState.contents.cookiedata}
|
||||||
|
<button class="bg-blue-600 font-semibold rounded-md py-1 px-2 text-sm" d-click="appState.contents.cookie = appState.contents.cookiedata; setCookie('username', appState.contents.cookiedata, '365');">Submit Cookie</button>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
}
|
||||||
12
day14/src/components/htmlInput.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
export const HtmlInput = () => {
|
||||||
|
return `
|
||||||
|
<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>
|
||||||
|
`
|
||||||
|
}
|
||||||
23
day14/src/components/myDad.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
export const MyDad = () => {
|
||||||
|
return `
|
||||||
|
<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>
|
||||||
|
`
|
||||||
|
}
|
||||||
5
day14/src/components/routerLink.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
export const RouterLink = (link: string, name: string) => {
|
||||||
|
return `
|
||||||
|
<a href="${link}" d-on:click="event.preventDefault(); renderPage('${link}')">${name}</a>
|
||||||
|
`
|
||||||
|
}
|
||||||
10
day14/src/components/textInput.devto
Normal 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 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
day14/src/entry-client.js
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { renderPage, hydratePage } from './lib/router';
|
||||||
|
import { isSSR, appState } from '/src/main';
|
||||||
|
|
||||||
|
export async function mount(mounted) {
|
||||||
|
eval(mounted)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!import.meta.env.SSR) {
|
||||||
|
// waits for the page to fully load to render the page from the virtDOM
|
||||||
|
if (document.getElementById('app').childNodes.length == 1) {
|
||||||
|
await import('/src/style.css')
|
||||||
|
await renderPage()
|
||||||
|
window.onpopstate = async () => {
|
||||||
|
await renderPage()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
hydratePage()
|
||||||
|
}
|
||||||
|
}
|
||||||
7
day14/src/entry-server.js
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { render } from './lib/templateRenderer';
|
||||||
|
import { setSSR, appState } from './main';
|
||||||
|
|
||||||
|
export function SSRPage(pageName) {
|
||||||
|
setSSR()
|
||||||
|
return render(pageName)
|
||||||
|
}
|
||||||
5
day14/src/layouts/404.devto
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<div class="grid place-items-center p-3 content-center min-h-screen">
|
||||||
|
<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>
|
||||||
39
day14/src/lib/ReactiveObject.js
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
export class Reactive {
|
||||||
|
constructor(obj) {
|
||||||
|
this.contents = obj;
|
||||||
|
this.listeners = {};
|
||||||
|
this.makeReactive(obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
makeReactive(obj) {
|
||||||
|
Object.keys(obj).forEach(prop => this.makePropReactive(obj, prop));
|
||||||
|
}
|
||||||
|
|
||||||
|
makePropReactive(obj, key) {
|
||||||
|
let value = obj[key];
|
||||||
|
|
||||||
|
// Gotta be careful with this here
|
||||||
|
const that = this;
|
||||||
|
|
||||||
|
Object.defineProperty(obj, key, {
|
||||||
|
get() {
|
||||||
|
return value;
|
||||||
|
},
|
||||||
|
set(newValue) {
|
||||||
|
value = newValue;
|
||||||
|
that.notify(key)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
listen(prop, handler) {
|
||||||
|
if (!this.listeners[prop]) this.listeners[prop] = [];
|
||||||
|
|
||||||
|
this.listeners[prop].push(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
notify(prop) {
|
||||||
|
if (!this.listeners[prop]) return
|
||||||
|
this.listeners[prop].forEach((listener) => listener(this.contents[prop]));
|
||||||
|
}
|
||||||
|
}
|
||||||
41
day14/src/lib/cookieManager.js
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
export function setCookie(name, value, expires, path, domain) {
|
||||||
|
if (import.meta.env.SSR) return
|
||||||
|
var cookie = name.trimEnd() + "=" + escape(value) + ";";
|
||||||
|
|
||||||
|
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.toGMTString() + ";";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path)
|
||||||
|
cookie += "path=" + path + ";";
|
||||||
|
if (domain)
|
||||||
|
cookie += "domain=" + domain + ";";
|
||||||
|
|
||||||
|
document.cookie = cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCookie(name) {
|
||||||
|
if (import.meta.env.SSR) return
|
||||||
|
let cname = name + "=";
|
||||||
|
let decodedCookie = decodeURIComponent(document.cookie);
|
||||||
|
let ca = decodedCookie.split(';');
|
||||||
|
for(let i = 0; i <ca.length; i++) {
|
||||||
|
let c = ca[i];
|
||||||
|
while (c.charAt(0) == ' ') {
|
||||||
|
c = c.substring(1);
|
||||||
|
}
|
||||||
|
if (c.indexOf(cname) == 0) {
|
||||||
|
return c.substring(cname.length, c.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
242
day14/src/lib/router.js
Normal file
@@ -0,0 +1,242 @@
|
|||||||
|
import { compileToString } from './templateRenderer'
|
||||||
|
import { mount } from '../entry-client'
|
||||||
|
import { isSSR, appState } from '../main'
|
||||||
|
let documentBody
|
||||||
|
|
||||||
|
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) {
|
||||||
|
if (isSSR() && route) window.location.href = route
|
||||||
|
if (isSSR()) return;
|
||||||
|
|
||||||
|
if (!documentBody) {
|
||||||
|
throw new Error('Fatal Error: element with id app not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (route) history.pushState('', '', route);
|
||||||
|
|
||||||
|
let fileName = window.location.pathname.split('/');
|
||||||
|
if (fileName[1] === '') {
|
||||||
|
fileName = '/index';
|
||||||
|
} else {
|
||||||
|
fileName = fileName.join('/').toLowerCase().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
const page = await loadPage(fileName);
|
||||||
|
|
||||||
|
const stringifiedTemplate = await compileToString(page);
|
||||||
|
|
||||||
|
if (import.meta.env.VITE_VERBOSE && !import.meta.env.PROD) {
|
||||||
|
console.groupCollapsed('Loaded page ' + fileName);
|
||||||
|
console.info('Template: ' + page)
|
||||||
|
console.info('stringified template: ' + stringifiedTemplate)
|
||||||
|
console.groupEnd()
|
||||||
|
}
|
||||||
|
|
||||||
|
documentBody.innerHTML = await eval(stringifiedTemplate);
|
||||||
|
// here we hydrate/re-hydrate the page content
|
||||||
|
await hydratePage()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPage(page) {
|
||||||
|
if (import.meta.env.SSR) return;
|
||||||
|
if (isSSR()) return;
|
||||||
|
|
||||||
|
let file
|
||||||
|
|
||||||
|
await fetch('/src/pages' + page + '.devto').then((response) => {
|
||||||
|
if (response.ok) {
|
||||||
|
return response.text();
|
||||||
|
}
|
||||||
|
throw new Error('Something went wrong');
|
||||||
|
})
|
||||||
|
.then((data) => {
|
||||||
|
file = data
|
||||||
|
})
|
||||||
|
.catch(async (error) => {
|
||||||
|
await fetch('/src/layouts/404.devto').then((response) => {
|
||||||
|
if (response.ok) {
|
||||||
|
return response.text();
|
||||||
|
}
|
||||||
|
throw new Error('Something went wrong');
|
||||||
|
})
|
||||||
|
.then((data) => {
|
||||||
|
file = data
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const template = file
|
||||||
|
|
||||||
|
return template;
|
||||||
|
}
|
||||||
|
|
||||||
|
// function to turn the template into reactive content "hydating" a page
|
||||||
|
export async function hydratePage() {
|
||||||
|
if (import.meta.env.SSR) return
|
||||||
|
if (!documentBody) {
|
||||||
|
throw new Error('Fatal Error: element with id app not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
// for every item in the appState lets check for any element with the "checksum", a hex code equivalent of the item name
|
||||||
|
Object.keys(appState.contents).forEach((e) => {
|
||||||
|
if (e === undefined) return
|
||||||
|
// here we check for elements with the name of "data-token-<hex code of the item name>"
|
||||||
|
const uuid = e.split("").map(c => c.charCodeAt(0).toString(16).padStart(2, "0")).join("")
|
||||||
|
const listeningElements = document.querySelectorAll(`[${"data-token-" + uuid}]`)
|
||||||
|
listeningElements.forEach((elm) => {
|
||||||
|
if (elm.parentElement?.getAttribute('d-once') !== null) {
|
||||||
|
elm.parentElement?.removeAttribute('d-once');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (elm.parentElement?.getAttribute('d-html') !== null) {
|
||||||
|
appState.listen(e, (change) => elm.innerHTML = change);
|
||||||
|
elm.parentElement?.removeAttribute('d-html')
|
||||||
|
} else {
|
||||||
|
appState.listen(e, (change) => elm.textContent = change);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// here we look for elements with the d-on:click attribute and on click run the function in the attribute
|
||||||
|
let elms = documentBody.querySelectorAll('*[d-on\\3A click]')
|
||||||
|
elms.forEach((e) => {
|
||||||
|
const clickFunction = e.getAttribute("d-on\:click")
|
||||||
|
e.removeAttribute('d-on\:click')
|
||||||
|
if (!clickFunction) return;
|
||||||
|
e.addEventListener('click', () => {
|
||||||
|
eval(clickFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// here we determine if an element should be deleted form the DOM via the d-if directive
|
||||||
|
let conditionalElms = document.querySelectorAll('*[d-if]')
|
||||||
|
conditionalElms.forEach(async (e) => {
|
||||||
|
const condition = e.getAttribute('d-if')
|
||||||
|
|
||||||
|
let siblingConditionalElms = []
|
||||||
|
// recursively check for subsequent elements with the d-else of d-else-if attribute
|
||||||
|
function checkForConditionSibling(elm) {
|
||||||
|
if (elm.nextElementSibling?.getAttribute('d-else-if') !== null) {
|
||||||
|
siblingConditionalElms.push(elm.nextElementSibling)
|
||||||
|
checkForConditionSibling(elm.nextElementSibling)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (elm.nextElementSibling?.getAttribute('d-else') !== null) {
|
||||||
|
siblingConditionalElms.push(elm.nextElementSibling)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkForConditionSibling(e)
|
||||||
|
|
||||||
|
function resetHTML() {
|
||||||
|
e.innerHTML = '<!-- d-if -->'
|
||||||
|
for (let i = 0; i < siblingConditionalElms.length; i++) {
|
||||||
|
siblingConditionalElms[i].innerHTML = '<!-- d-if -->'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let ifStatement = `if (!!eval(condition)) {
|
||||||
|
e.innerHTML = originalHTML
|
||||||
|
} `
|
||||||
|
|
||||||
|
for (let i = 0; i < siblingConditionalElms.length; i++) {
|
||||||
|
console.log(i)
|
||||||
|
const originHTML = siblingConditionalElms[i].innerHTML
|
||||||
|
siblingConditionalElms[i].innerHTML = '<!-- d-if -->'
|
||||||
|
let statementDirective = 'else'
|
||||||
|
if (siblingConditionalElms[i].getAttribute('d-else-if') !== null) {
|
||||||
|
statementDirective = 'else if'
|
||||||
|
}
|
||||||
|
const condition = eval(`siblingConditionalElms[i].getAttribute('d-' + statementDirective.split(' ').join('-'))`)
|
||||||
|
|
||||||
|
if (statementDirective == 'else if') {
|
||||||
|
statementDirective = 'else if (' + condition + ')'
|
||||||
|
}
|
||||||
|
|
||||||
|
ifStatement = ifStatement + statementDirective + `{
|
||||||
|
siblingConditionalElms[${i}].innerHTML = "${originHTML}"
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
|
||||||
|
e.removeAttribute('d-if')
|
||||||
|
const originalHTML = e.innerHTML
|
||||||
|
if (!condition) return;
|
||||||
|
if (condition.includes("appState.contents.")) {
|
||||||
|
let reactiveProp = /appState\.contents\.[a-zA-Z]+/.exec(condition)
|
||||||
|
if (!reactiveProp) return;
|
||||||
|
reactiveProp = reactiveProp[0].split('.')[2]
|
||||||
|
appState.listen(reactiveProp, () => {
|
||||||
|
resetHTML()
|
||||||
|
eval(ifStatement)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
eval(ifStatement)
|
||||||
|
})
|
||||||
|
|
||||||
|
let pointerEnterElms = document.querySelectorAll('*[d-on\\3A pointerEnter]')
|
||||||
|
pointerEnterElms.forEach((e) => {
|
||||||
|
const enterFunction = e.getAttribute('d-on\:pointerEnter')
|
||||||
|
e.removeAttribute('d-on\:pointerEnter')
|
||||||
|
if (!enterFunction) return;
|
||||||
|
e.addEventListener('pointerenter', (event) => {
|
||||||
|
eval(enterFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
let pointerExitElms = document.querySelectorAll('*[d-on\\3A pointerExit]')
|
||||||
|
pointerExitElms.forEach((e) => {
|
||||||
|
const exitFunction = e.getAttribute('d-on\:pointerExit')
|
||||||
|
e.removeAttribute('d-on\:pointerExit')
|
||||||
|
if (!exitFunction) return;
|
||||||
|
e.addEventListener('pointerleave', (event) => {
|
||||||
|
eval(exitFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
let mouseDownElms = document.querySelectorAll('*[d-on\\3A mouseDown]')
|
||||||
|
mouseDownElms.forEach((e) => {
|
||||||
|
const downFunction = e.getAttribute('d-on\:mouseDown')
|
||||||
|
e.removeAttribute('d-on\:mouseDown')
|
||||||
|
if (!downFunction) return;
|
||||||
|
e.addEventListener('mousedown', (event) => {
|
||||||
|
eval(downFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
let mouseUpElms = document.querySelectorAll('*[d-on\\3A mouseUp]')
|
||||||
|
mouseUpElms.forEach((e) => {
|
||||||
|
const dupFunction = e.getAttribute('d-on\:mouseUp')
|
||||||
|
e.removeAttribute('d-on\:mouseUp')
|
||||||
|
if (!dupFunction) return;
|
||||||
|
e.addEventListener('mouseup', (event) => {
|
||||||
|
eval(dupFunction)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// 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
|
||||||
|
let modelElms = document.querySelectorAll('input[d-model], textarea[d-model]');
|
||||||
|
modelElms.forEach((e) => {
|
||||||
|
const modelName = e.getAttribute("d-model")
|
||||||
|
if (!modelName) return;
|
||||||
|
e.addEventListener('input', (event) => {
|
||||||
|
appState.contents[modelName] = event.target.value
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
106
day14/src/lib/templateRenderer.js
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
export const compileToString = async (template) => {
|
||||||
|
const ast = parse(template);
|
||||||
|
let fnStr = `\`\``;
|
||||||
|
|
||||||
|
ast.map(async t => {
|
||||||
|
// const elements = t.split('<')
|
||||||
|
// elements.forEach(async (e, index, array) => {
|
||||||
|
// if (!e) return
|
||||||
|
// let element = e.split(' ')[0]
|
||||||
|
// if (element.includes('/') || element.includes('{') || element.includes('}')) return
|
||||||
|
// if (!isHTML(element.split('>')[0])) {
|
||||||
|
// let component
|
||||||
|
// if (!import.meta.env.SSR) {
|
||||||
|
// await fetch('/src/components/' + element.split('>')[0] + '.devto').then((response) => {
|
||||||
|
// if (response.ok) {
|
||||||
|
// return response.text();
|
||||||
|
// }
|
||||||
|
// throw new Error('Something went wrong');
|
||||||
|
// })
|
||||||
|
// .then((data) => {
|
||||||
|
// component = data
|
||||||
|
// })
|
||||||
|
// .catch(async (error) => {
|
||||||
|
// // component does not exist
|
||||||
|
// });
|
||||||
|
// } else {
|
||||||
|
// const fs = await import('fs')
|
||||||
|
// const path = await import('path')
|
||||||
|
// component = fs.readFileSync(
|
||||||
|
// path.resolve('./src/components/' + element.split('>')[0] + '.devto'),
|
||||||
|
// 'utf-8',
|
||||||
|
// )
|
||||||
|
// }
|
||||||
|
// component = await compileToString(component)
|
||||||
|
|
||||||
|
// component = '`' + component.slice(2) + '+`'
|
||||||
|
|
||||||
|
// if (!component) return;
|
||||||
|
// const componentsElement = '<' + element + ' />'
|
||||||
|
// fnStr = fnStr.replace(componentsElement, component)
|
||||||
|
// console.log('compiled component')
|
||||||
|
// }
|
||||||
|
// })
|
||||||
|
|
||||||
|
console.log('running extra render steps')
|
||||||
|
// checking to see if it is an interpolation
|
||||||
|
if (t.startsWith("{") && t.endsWith("}")) {
|
||||||
|
// TODO: rewrite comment
|
||||||
|
let bracketVariable = t.split(/{|}/).filter(Boolean)[0].trim();
|
||||||
|
const parentElement = fnStr.split(t)[0].split('>')
|
||||||
|
const isRawHTML = parentElement[parentElement.length - 2].includes('d-html')
|
||||||
|
if (bracketVariable.startsWith("appState.contents.")) {
|
||||||
|
const uuid = bracketVariable.substring(bracketVariable.length, 18).split('').map(c => 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,'&').replace(/</g,'<').replace(/>/g,'>'))`
|
||||||
|
|
||||||
|
if (isRawHTML) {
|
||||||
|
runVar = `(${bracketVariable})`
|
||||||
|
}
|
||||||
|
|
||||||
|
fnStr += `+ (${runVar})` + `+\`</span>\``;
|
||||||
|
} else {
|
||||||
|
// append the string to the fnStr
|
||||||
|
fnStr += `+\`${t}\``;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (import.meta.env.VITE_VERBOSE && !import.meta.env.PROD) {
|
||||||
|
console.groupCollapsed('Compiled tempalte to String')
|
||||||
|
console.info('Template String: ' + fnStr)
|
||||||
|
console.groupEnd()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return fnStr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// this function will turn a string like "hi {user}" into an array that looks something like "["hi", "{user}"] so we can loop over the array elements
|
||||||
|
// when compiling the template
|
||||||
|
var parse = (template) => {
|
||||||
|
let result = /{(.*?)}/g.exec(template);
|
||||||
|
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 = /{(.*?)}/g.exec(template);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (template) arr.push(template);
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const render = (template) => {
|
||||||
|
return compileToString(template)
|
||||||
|
}
|
||||||
21
day14/src/main.js
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { Reactive } from './lib/ReactiveObject'
|
||||||
|
import { getCookie } from './lib/cookieManager';
|
||||||
|
|
||||||
|
export const appState = new Reactive({
|
||||||
|
count: 0,
|
||||||
|
cookie: getCookie('username'),
|
||||||
|
text: '',
|
||||||
|
html: '',
|
||||||
|
year: '',
|
||||||
|
cookiedata: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
let SSR = false;
|
||||||
|
|
||||||
|
export function isSSR() {
|
||||||
|
return SSR;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setSSR() {
|
||||||
|
SSR = true;
|
||||||
|
}
|
||||||
6
day14/src/pages/index.devto
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<div class="grid place-items-center p-3 content-center min-h-screen">
|
||||||
|
<div class="p-6 border-neutral-800 rounded-lg container__content border">
|
||||||
|
<Counter />
|
||||||
|
<textInput />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
21
day14/src/style.css
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
@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:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container__content {
|
||||||
|
box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
|
||||||
|
}
|
||||||
17
day14/tailwind.config.cjs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
const colors = require('tailwindcss/colors')
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
content: [
|
||||||
|
"./index.html",
|
||||||
|
"./src/**/*.{devto,js,ts,jsx,tsx}",
|
||||||
|
],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
gray: colors.zinc
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
}
|
||||||