add day 22
This commit is contained in:
1
day22/.env
Normal file
1
day22/.env
Normal file
@@ -0,0 +1 @@
|
||||
VITE_VERBOSE = true
|
||||
42
day22/.eslintrc.json
Normal file
42
day22/.eslintrc.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"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"
|
||||
],
|
||||
"linebreak-style": [
|
||||
"error",
|
||||
"unix"
|
||||
],
|
||||
"quotes": [
|
||||
"error",
|
||||
"single"
|
||||
],
|
||||
"semi": [
|
||||
"error",
|
||||
"always"
|
||||
],
|
||||
"nonblock-statement-body-position": [
|
||||
"error",
|
||||
"beside"
|
||||
]
|
||||
}
|
||||
}
|
||||
27
day22/index.html
Normal file
27
day22/index.html
Normal file
@@ -0,0 +1,27 @@
|
||||
<!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">
|
||||
<meta name="description"
|
||||
content="A devto app.">
|
||||
<title>Document</title>
|
||||
<script async src="/src/entry-client.ts" type="module"></script>
|
||||
<!--script-outlet-->
|
||||
<!--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>
|
||||
155
day22/index.ts
Normal file
155
day22/index.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
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';
|
||||
|
||||
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: string) {
|
||||
return tags.indexOf(tag.trim().toLowerCase()) > -1;
|
||||
}
|
||||
|
||||
async function createServer() {
|
||||
const app = express();
|
||||
|
||||
app.use(express.static(__dirname + '/public'));
|
||||
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(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);
|
||||
}
|
||||
|
||||
|
||||
// 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: Request, res: Response, next: NextFunction) => {
|
||||
const url: string = req.originalUrl;
|
||||
|
||||
try {
|
||||
// 1. Read index.html
|
||||
let template: string;
|
||||
template = fs.readFileSync(
|
||||
path.resolve(__dirname, 'index.html'),
|
||||
'utf-8'
|
||||
);
|
||||
|
||||
let fileName: Array<string> | string = url.split('/');
|
||||
if (fileName[1] === '') {
|
||||
fileName = '/index';
|
||||
} else {
|
||||
fileName = fileName.join('/').toLowerCase().trim();
|
||||
}
|
||||
|
||||
// 2. Apply Vite HTML transforms. This injects the Vite HMR client, and
|
||||
// also applies HTML transforms from Vite plugins, e.g. global preambles
|
||||
// from @vitejs/plugin-react
|
||||
template = await vite.transformIndexHtml(url, template);
|
||||
|
||||
// 3. Load the server entry. vite.ssrLoadModule automatically transforms
|
||||
// your ESM source code to be usable in Node.js! There is no bundling
|
||||
// required, and provides efficient invalidation similar to HMR.
|
||||
const { SSRPage } = await vite.ssrLoadModule('/src/entry-server.ts');
|
||||
|
||||
let pageData: string;
|
||||
let basepath: string;
|
||||
|
||||
(process.env.NODE_ENV == 'production') ? basepath = './' : basepath = './src/';
|
||||
try {
|
||||
pageData = fs.readFileSync(
|
||||
path.resolve(__dirname, basepath + '/pages' + fileName + '.devto'),
|
||||
'utf-8',
|
||||
);
|
||||
} catch (e) {
|
||||
pageData = fs.readFileSync(
|
||||
path.resolve(__dirname, basepath + '/layouts/404.devto'),
|
||||
'utf-8'
|
||||
);
|
||||
}
|
||||
|
||||
pageData.split('<').forEach(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 (isHTML(item)) return;
|
||||
const component = fs.readFileSync(
|
||||
path.resolve(basepath + '/components/' + item + '.devto'),
|
||||
'utf-8',
|
||||
);
|
||||
pageData = pageData.replace('<' + item + ' />', component);
|
||||
});
|
||||
|
||||
// 4. render the app HTML. This assumes entry-server.js's exported `render`
|
||||
// function calls appropriate framework SSR APIs,
|
||||
// e.g. ReactDOMServer.renderToString()
|
||||
const appHtml = await SSRPage(pageData);
|
||||
|
||||
const styles = await vite.ssrLoadModule(basepath.slice(1) + 'style.css');
|
||||
|
||||
const main = await vite.ssrLoadModule(basepath.slice(1) + 'main');
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const appState = main.appState;
|
||||
|
||||
template = template.replace('<script async src="/src/entry-client.ts" type="module"></script>', '');
|
||||
|
||||
template = template.replace('id="app"', 'id="app" data-server-rendered="true"');
|
||||
|
||||
let scriptedTemplate = template;
|
||||
|
||||
const { renderSSRHydrationCode } = await vite.ssrLoadModule(basepath.slice(1) + 'lib/router/ssrHydrationGenerator');
|
||||
|
||||
const code = await renderSSRHydrationCode(eval(appHtml.fnStr));
|
||||
|
||||
if (appHtml.script || code) {
|
||||
scriptedTemplate = template.replace('<!--script-outlet-->', '<script async type="module">' + appHtml.script + code + '</script>');
|
||||
}
|
||||
|
||||
// 5. Inject the app-rendered HTML into the template.
|
||||
const stylizedTemplate = scriptedTemplate.replace('<!--style-outlet-->', '<style type="text/css">' + styles.default + appHtml.styles + '</style>');
|
||||
|
||||
const html = stylizedTemplate.replace('<!--ssr-outlet-->', eval(appHtml.fnStr));
|
||||
|
||||
// 6. Send the rendered HTML back.
|
||||
res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
||||
} 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);
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(3000);
|
||||
}
|
||||
|
||||
createServer();
|
||||
1
day22/next-env.d.ts
vendored
Normal file
1
day22/next-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
declare module '*.css'
|
||||
8205
day22/package-lock.json
generated
Normal file
8205
day22/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
49
day22/package.json
Normal file
49
day22/package.json
Normal file
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "devto",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev:client": "vite --config vite.config.ts dev",
|
||||
"dev:server": "nodemon --watch index.ts --watch src/ --exec 'ts-node-esm index.ts'",
|
||||
"dev": "concurrently \"npm run dev:client\" \"npm run dev:server\"",
|
||||
"build": "rimraf dist && npm run build:client && npm run build:server && npm run copy-files",
|
||||
"lint": "eslint .",
|
||||
"test": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"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/compression": "^1.7.2",
|
||||
"@types/express": "^4.17.14",
|
||||
"@types/node": "^18.8.4",
|
||||
"@typescript-eslint/eslint-plugin": "^5.40.0",
|
||||
"@typescript-eslint/parser": "^5.40.0",
|
||||
"autoprefixer": "^10.4.12",
|
||||
"eslint": "^8.25.0",
|
||||
"postcss": "^8.4.17",
|
||||
"tailwindcss": "^3.1.8",
|
||||
"vitest": "^0.24.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"autoprefixer": "10.4.7",
|
||||
"compression": "^1.7.4",
|
||||
"concurrently": "7.3.0",
|
||||
"copyfiles": "^2.4.1",
|
||||
"cssnano": "5.1.12",
|
||||
"express": "^4.18.1",
|
||||
"nodemon": "^2.0.20",
|
||||
"postcss": "8.4.14",
|
||||
"postcss-import": "14.1.0",
|
||||
"postcss-nesting": "10.1.10",
|
||||
"rimraf": "^3.0.2",
|
||||
"tailwindcss": "3.1.6",
|
||||
"typescript": "^4.8.4",
|
||||
"vite": "^3.1.4"
|
||||
}
|
||||
}
|
||||
7
day22/postcss.config.js
Normal file
7
day22/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
day22/public/favicon.ico
Normal file
BIN
day22/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
1
day22/public/minus.svg
Normal file
1
day22/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
day22/public/plus.svg
Normal file
1
day22/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
day22/public/refresh.svg
Normal file
1
day22/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
day22/public/robots.txt
Normal file
0
day22/public/robots.txt
Normal file
23
day22/src/components/Counter.devto
Normal file
23
day22/src/components/Counter.devto
Normal file
@@ -0,0 +1,23 @@
|
||||
<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'
|
||||
width="24px"
|
||||
alt="minus" />
|
||||
</button>
|
||||
<button d-on:click="appState.contents.count = 0"
|
||||
class="transition-colors p-3 duration-300 active:bg-zinc-700 hover:bg-zinc-800 hover:text-red-100 mr-1">
|
||||
<img src='/refresh.svg'
|
||||
width="24px"
|
||||
alt="reset">
|
||||
</button>
|
||||
<button d-on:click="appState.contents.count++"
|
||||
class="transition-colors p-3 duration-300 active:bg-green-700 hover:bg-green-600 hover:text-green-100">
|
||||
<img src='/plus.svg'
|
||||
width="24px"
|
||||
alt="plus" />
|
||||
</button>
|
||||
</div>
|
||||
1
day22/src/components/RouterLink.devto
Normal file
1
day22/src/components/RouterLink.devto
Normal file
@@ -0,0 +1 @@
|
||||
<p>TODO</p>
|
||||
12
day22/src/components/cookieInput.devto
Normal file
12
day22/src/components/cookieInput.devto
Normal file
@@ -0,0 +1,12 @@
|
||||
<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>
|
||||
11
day22/src/components/htmlInput.devto
Normal file
11
day22/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>
|
||||
25
day22/src/components/myDad.devto
Normal file
25
day22/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>
|
||||
10
day22/src/components/textInput.devto
Normal file
10
day22/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 d-on:keydown.enter="alert('pressed enter')" 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>
|
||||
43
day22/src/entry-client.ts
Normal file
43
day22/src/entry-client.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { setCtrl } from './lib/router/hydrationManager';
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import { appState } from './main';
|
||||
|
||||
let SSR: boolean;
|
||||
|
||||
export function isSSR() {
|
||||
if (!import.meta.env.SSR) {
|
||||
if (SSR !== undefined) return SSR;
|
||||
SSR = !!document.getElementById('app')?.getAttribute('data-server-rendered');
|
||||
return SSR;
|
||||
}
|
||||
}
|
||||
|
||||
async function initClient() {
|
||||
await import('./style.css');
|
||||
const { renderPage } = await import('./lib/router/pageRenderer');
|
||||
await renderPage();
|
||||
|
||||
document.body.addEventListener('keydown', (e) => {
|
||||
setCtrl(e.ctrlKey);
|
||||
});
|
||||
|
||||
document.body.addEventListener('keyup', (e) => {
|
||||
setCtrl(e.ctrlKey);
|
||||
});
|
||||
|
||||
window.onpopstate = async (e: PopStateEvent) => {
|
||||
if (e.state === null) {
|
||||
return;
|
||||
}
|
||||
await renderPage();
|
||||
};
|
||||
}
|
||||
|
||||
// async function initSSR() {
|
||||
// const { hydratePage } = await import('./lib/router/hydrationManager');
|
||||
// await hydratePage();
|
||||
// }
|
||||
|
||||
if (!import.meta.env.SSR) {
|
||||
if (!isSSR()) initClient();
|
||||
}
|
||||
7
day22/src/entry-server.ts
Normal file
7
day22/src/entry-server.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { render } from './lib/templateRenderer';
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import { appState } from './main';
|
||||
|
||||
export function SSRPage(pageName: string) {
|
||||
return render(pageName);
|
||||
}
|
||||
5
day22/src/layouts/404.devto
Normal file
5
day22/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>
|
||||
42
day22/src/lib/ReactiveObject.ts
Normal file
42
day22/src/lib/ReactiveObject.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
export class Reactive {
|
||||
listeners: Record<string, Array<CallableFunction>>;
|
||||
contents: Record<string, unknown>;
|
||||
constructor(obj: Record<string, unknown>) {
|
||||
this.contents = obj;
|
||||
this.listeners = {};
|
||||
this.makeReactive(obj);
|
||||
}
|
||||
|
||||
makeReactive(obj: Record<string, unknown>) {
|
||||
Object.keys(obj).forEach(prop => this.makePropReactive(obj, prop));
|
||||
}
|
||||
|
||||
makePropReactive(obj: Record<string, unknown>, key: string) {
|
||||
let value = obj[key];
|
||||
|
||||
// Gotta be careful with this here
|
||||
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
||||
const that = this;
|
||||
|
||||
Object.defineProperty(obj, key, {
|
||||
get() {
|
||||
return value;
|
||||
},
|
||||
set(newValue) {
|
||||
value = newValue;
|
||||
that.notify(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
listen(prop: string, handler: CallableFunction) {
|
||||
if (!this.listeners[prop]) this.listeners[prop] = [];
|
||||
|
||||
this.listeners[prop]?.push(handler);
|
||||
}
|
||||
|
||||
notify(prop: string) {
|
||||
if (!this.listeners[prop]) return;
|
||||
this.listeners[prop]?.forEach((listener: CallableFunction) => listener(this.contents[prop]));
|
||||
}
|
||||
}
|
||||
38
day22/src/lib/cookieManager.ts
Normal file
38
day22/src/lib/cookieManager.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
export function setCookie(name: string, value: string, expires: string | Date, path?: string, domain?: string) {
|
||||
if (import.meta.env.SSR) return;
|
||||
let 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.toUTCString() + ';';
|
||||
}
|
||||
|
||||
if (path) cookie += 'path=' + path + ';';
|
||||
if (domain) cookie += 'domain=' + domain + ';';
|
||||
|
||||
document.cookie = cookie;
|
||||
}
|
||||
|
||||
export function getCookie(name: string) {
|
||||
if (import.meta.env.SSR) return;
|
||||
const cname = name + '=';
|
||||
const decodedCookie = decodeURIComponent(document.cookie);
|
||||
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 '';
|
||||
}
|
||||
222
day22/src/lib/router/hydrationManager.ts
Normal file
222
day22/src/lib/router/hydrationManager.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
import { appState } from '../../main';
|
||||
|
||||
export let ctrlPressed = false;
|
||||
|
||||
export function setCtrl(ctrl: boolean) {
|
||||
ctrlPressed = ctrl;
|
||||
}
|
||||
|
||||
// function to turn the template into reactive content "hydating" a page
|
||||
export async function hydratePage() {
|
||||
if (import.meta.env.SSR) return;
|
||||
const documentBody = document.getElementById('app');
|
||||
if (!documentBody) {
|
||||
throw new Error('Fatal Error: element with id app not found');
|
||||
}
|
||||
const { renderPage } = await import('./pageRenderer');
|
||||
|
||||
// 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: string) => {
|
||||
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: string) => 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: string) => elm.innerHTML = change);
|
||||
elm.parentElement?.removeAttribute('d-html');
|
||||
} else {
|
||||
appState.listen(e, (change: string) => elm.textContent = change);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// here we look for elements with the d-on:click attribute and on click run the function in the attribute
|
||||
const 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
|
||||
const conditionalElms = document.querySelectorAll('*[d-if]');
|
||||
conditionalElms.forEach(async (e: Element) => {
|
||||
const condition = e.getAttribute('d-if');
|
||||
|
||||
const siblingConditionalElms: Array<Element> = [];
|
||||
// recursively check for subsequent elements with the d-else of d-else-if attribute
|
||||
function checkForConditionSibling(elm: Element) {
|
||||
if (!elm.nextElementSibling || typeof elm.nextElementSibling == 'undefined') return;
|
||||
if (elm.nextElementSibling?.getAttribute('d-else-if') !== null) {
|
||||
siblingConditionalElms.push(elm.nextElementSibling);
|
||||
if (!elm.nextElementSibling) return;
|
||||
checkForConditionSibling(elm.nextElementSibling);
|
||||
}
|
||||
|
||||
if (elm.nextElementSibling?.getAttribute('d-else') !== null) {
|
||||
siblingConditionalElms.push(elm.nextElementSibling);
|
||||
}
|
||||
}
|
||||
checkForConditionSibling(e);
|
||||
|
||||
if (siblingConditionalElms == undefined) return;
|
||||
|
||||
function resetHTML() {
|
||||
e.innerHTML = '<!-- d-if -->';
|
||||
for (let i = 0; i < siblingConditionalElms.length; i++) {
|
||||
const element = siblingConditionalElms[i];
|
||||
if (!element) return;
|
||||
element.innerHTML = '<!-- d-if -->';
|
||||
}
|
||||
}
|
||||
|
||||
let ifStatement = `if (!!eval(condition)) {
|
||||
e.innerHTML = originalHTML
|
||||
} `;
|
||||
|
||||
for (let i = 0; i < siblingConditionalElms.length; i++) {
|
||||
const element = siblingConditionalElms[i];
|
||||
if (!element) return;
|
||||
const originHTML = element.innerHTML;
|
||||
element.innerHTML = '<!-- d-if -->';
|
||||
let statementDirective = 'else';
|
||||
if (element.getAttribute('d-else-if') !== null) {
|
||||
statementDirective = 'else if';
|
||||
}
|
||||
const condition = eval('element.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 || originalHTML == undefined) return;
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
eval(ifStatement);
|
||||
});
|
||||
|
||||
const 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', () => {
|
||||
eval(enterFunction);
|
||||
});
|
||||
});
|
||||
|
||||
const 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', () => {
|
||||
eval(exitFunction);
|
||||
});
|
||||
});
|
||||
|
||||
const 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', () => {
|
||||
eval(downFunction);
|
||||
});
|
||||
});
|
||||
|
||||
const 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', () => {
|
||||
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
|
||||
const modelElms = document.querySelectorAll('input[d-model], textarea[d-model]');
|
||||
modelElms.forEach((e: Element) => {
|
||||
const modelName = e.getAttribute('d-model');
|
||||
if (!modelName) return;
|
||||
e.addEventListener('input', (input: Event) => {
|
||||
const target = input.target as HTMLInputElement;
|
||||
if (!target || !target.value) return;
|
||||
appState.contents[modelName] = target.value;
|
||||
});
|
||||
});
|
||||
|
||||
const anchorElms = document.querySelectorAll('a');
|
||||
anchorElms.forEach((e: HTMLAnchorElement) => {
|
||||
e.addEventListener('click', async (click: MouseEvent) => {
|
||||
if (!event) 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);
|
||||
});
|
||||
});
|
||||
|
||||
function hydrateKeyDown() {
|
||||
document.body.querySelectorAll('*').forEach((e) => {
|
||||
for (let i = 0; i < e.attributes.length; i++) {
|
||||
const item = e.attributes.item(i)?.name;
|
||||
if (!item) return;
|
||||
if (item.startsWith('d-on:keydown')) {
|
||||
const key = item.split('.')[1]?.toLowerCase();
|
||||
let correctedKey = '';
|
||||
if (key && key?.length > 1) {
|
||||
key.split('').forEach((e, i, arr) => {
|
||||
if (i === 0) {
|
||||
arr[i] = e.toUpperCase();
|
||||
}
|
||||
correctedKey += arr[i];
|
||||
});
|
||||
}
|
||||
e.addEventListener('keydown', (keydown) => {
|
||||
const keyboardEvent = <KeyboardEvent> keydown;
|
||||
if (keyboardEvent.key == correctedKey) {
|
||||
const itemCode = e.getAttribute(item);
|
||||
if (!itemCode) return;
|
||||
eval(itemCode);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
hydrateKeyDown();
|
||||
}
|
||||
52
day22/src/lib/router/linkPrefetcher.ts
Normal file
52
day22/src/lib/router/linkPrefetcher.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
export default (anchorElms: NodeListOf<HTMLAnchorElement>) => {
|
||||
const prefetchedPages: Array<string> = [];
|
||||
|
||||
function prefetchLink(url: string) {
|
||||
const prefetchElm = document.createElement('link');
|
||||
prefetchElm.rel = 'prefetch';
|
||||
prefetchElm.href = url;
|
||||
prefetchElm.as = 'document';
|
||||
|
||||
if (import.meta.env.VITE_VERBOSE && !import.meta.env.PROD) {
|
||||
prefetchElm.onload = () => { console.log('prefetched url: ' + url); };
|
||||
prefetchElm.onerror = (err) => { console.error('cant prefetch url: ' + url, err); };
|
||||
}
|
||||
|
||||
document.head.appendChild(prefetchElm);
|
||||
prefetchedPages.push(url);
|
||||
}
|
||||
|
||||
if (!('IntersectionObserver' in window)) return;
|
||||
const visibleObserver = new IntersectionObserver((entries, observer) => {
|
||||
entries.forEach((entry) => {
|
||||
const url = entry.target.getAttribute('href');
|
||||
if (!url) return;
|
||||
if (prefetchedPages.includes(url)) {
|
||||
observer.unobserve(entry.target);
|
||||
return;
|
||||
}
|
||||
if (entry.isIntersecting) {
|
||||
prefetchLink(url);
|
||||
observer.unobserve(entry.target);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
anchorElms.forEach((e: HTMLAnchorElement) => {
|
||||
const prefetch = e.getAttribute('client:prefetch');
|
||||
let method;
|
||||
if (prefetch == null) return;
|
||||
if (prefetch) method = prefetch;
|
||||
if (e.href.includes(document.location.origin) && !e.href.includes('#') && e.href !== (document.location.href || document.location.href + '/')) {
|
||||
// page would be a valid prefetch
|
||||
if (method == 'hover') {
|
||||
const url = e.getAttribute('href');
|
||||
if (!url) return;
|
||||
e.addEventListener('pointerenter', () => prefetchLink(url), { once: true });
|
||||
} else {
|
||||
// method is empty, visible, or invalid, either way we so the default of visible
|
||||
visibleObserver.observe(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
172
day22/src/lib/router/pageRenderer.ts
Normal file
172
day22/src/lib/router/pageRenderer.ts
Normal file
@@ -0,0 +1,172 @@
|
||||
import { compileToString } from '../templateRenderer';
|
||||
import { isSSR } from '../../entry-client';
|
||||
import { ctrlPressed } from './hydrationManager';
|
||||
import { appState } from '../../main';
|
||||
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'];
|
||||
// let enabled = true;
|
||||
|
||||
function isHTML(tag: string) {
|
||||
return tags.indexOf(tag.trim().toLowerCase()) > -1;
|
||||
}
|
||||
|
||||
if (!appState) console.error('no reactive data found');
|
||||
|
||||
let documentBody: string | HTMLElement | null;
|
||||
|
||||
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 (ctrlPressed && route) {
|
||||
window.open(route, '__blank');
|
||||
return;
|
||||
}
|
||||
|
||||
// Gotta remove all the style and script tags from this page so they dont leak into other pages
|
||||
let decimateMode = false;
|
||||
document.head.childNodes.forEach((e, i, arr) => {
|
||||
if (!arr[i - 2]) return;
|
||||
if (decimateMode) {
|
||||
document.head.removeChild(e);
|
||||
}
|
||||
if (arr[i - 2]?.nodeName == '#comment' && arr[i - 2]?.textContent == 'style-outlet') {
|
||||
decimateMode = true;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
if (!window.history) {
|
||||
// enabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!documentBody) {
|
||||
throw new Error('Fatal Error: element with id app not found');
|
||||
}
|
||||
|
||||
if (route) history.pushState('', '', route);
|
||||
|
||||
let fileName: string | Array<string> = window.location.pathname.split('/');
|
||||
if (fileName[1] === '') {
|
||||
fileName = '/index';
|
||||
} else {
|
||||
fileName = fileName.join('/').toLowerCase().trim();
|
||||
}
|
||||
|
||||
const page: string | undefined = await loadPage(fileName);
|
||||
|
||||
if (!page) return;
|
||||
|
||||
// tell the web page that the router has loaded a new page, SSR is unaffected
|
||||
document.dispatchEvent(new CustomEvent('router:load', {
|
||||
detail: {
|
||||
page: fileName,
|
||||
url: window.location.pathname,
|
||||
tempalte: page,
|
||||
timeStamp: new Date().getTime()
|
||||
}
|
||||
}));
|
||||
|
||||
const stringifiedTemplate = await compileToString(page);
|
||||
|
||||
if (!stringifiedTemplate) return;
|
||||
|
||||
if (import.meta.env.VITE_VERBOSE && !import.meta.env.PROD && !import.meta.env.SSR) {
|
||||
console.groupCollapsed('Loaded page ' + fileName);
|
||||
console.info('Template: ' + page);
|
||||
console.info('stringified template: ' + stringifiedTemplate.fnStr);
|
||||
console.groupEnd();
|
||||
}
|
||||
|
||||
documentBody.innerHTML = await eval(stringifiedTemplate.fnStr);
|
||||
if (stringifiedTemplate.styles) {
|
||||
const cssElement = document.createElement('style');
|
||||
cssElement.type = 'text/css';
|
||||
cssElement.innerHTML = stringifiedTemplate.styles;
|
||||
document.head.appendChild(cssElement);
|
||||
}
|
||||
|
||||
if (stringifiedTemplate.script) {
|
||||
const scriptElement = document.createElement('script');
|
||||
scriptElement.type = 'text/javascript';
|
||||
scriptElement.innerHTML = stringifiedTemplate.script;
|
||||
document.head.appendChild(scriptElement);
|
||||
}
|
||||
// here we hydrate/re-hydrate the page content
|
||||
const { hydratePage } = await import('./hydrationManager');
|
||||
await hydratePage();
|
||||
}
|
||||
|
||||
async function loadPage(page: string) {
|
||||
if (import.meta.env.SSR) return;
|
||||
if (isSSR()) return;
|
||||
const file = await fetchPage(page);
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
async function fetchPage(url: string) {
|
||||
let path: string;
|
||||
(import.meta.env.PROD) ? path = '/' : path = '/src/';
|
||||
|
||||
let file: string | void | undefined = await fetch(path + `pages${url}.devto`).then((response) => {
|
||||
if (response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
throw new Error('Something went wrong');
|
||||
})
|
||||
.then((data) => {
|
||||
if (!data) return undefined;
|
||||
return data;
|
||||
})
|
||||
.catch(async () => {
|
||||
await fetch(path + 'layouts/404.devto').then((response) => {
|
||||
if (response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
throw new Error('Something went wrong');
|
||||
})
|
||||
.then((data) => {
|
||||
if (!data) return undefined;
|
||||
return data;
|
||||
});
|
||||
});
|
||||
|
||||
if (!file) return;
|
||||
|
||||
let template = file;
|
||||
const elements: Array<string> = file.split('<');
|
||||
|
||||
await Promise.all(elements.map(async (component: string | undefined) => {
|
||||
if (!component || !file) return;
|
||||
component = component.split(' ')[0];
|
||||
if (component?.includes('/') || component?.includes('{') || !component) return;
|
||||
component = component.split('>')[0];
|
||||
if (!component) return;
|
||||
if (isHTML(component)) return;
|
||||
await fetch(path + `components/${component}.devto`).then((response) => {
|
||||
if (response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
throw new Error('Something went wrong');
|
||||
})
|
||||
.then((data) => {
|
||||
file = data;
|
||||
});
|
||||
template = template.replace('<' + component + ' />', file);
|
||||
})
|
||||
);
|
||||
|
||||
return template;
|
||||
}
|
||||
219
day22/src/lib/router/ssrHydrationGenerator.ts
Normal file
219
day22/src/lib/router/ssrHydrationGenerator.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
export async function renderSSRHydrationCode(template: string) {
|
||||
let script = '';
|
||||
if (template.includes('appState.contents.') || template.includes('data-token')) {
|
||||
script += `
|
||||
const { appState } = await import('/src/main.ts');
|
||||
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);
|
||||
}
|
||||
});
|
||||
});
|
||||
`;
|
||||
}
|
||||
|
||||
if (template.includes('d-on:click')) {
|
||||
script += `
|
||||
const elms = document.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);
|
||||
});
|
||||
});
|
||||
`;
|
||||
}
|
||||
|
||||
if (template.includes('d-if')) {
|
||||
script += `
|
||||
const conditionalElms = document.querySelectorAll('*[d-if]');
|
||||
conditionalElms.forEach(async (e) => {
|
||||
const condition = e.getAttribute('d-if');
|
||||
|
||||
const siblingConditionalElms = [];
|
||||
// recursively check for subsequent elements with the d-else of d-else-if attribute
|
||||
function checkForConditionSibling(elm) {
|
||||
if (!elm.nextElementSibling || typeof elm.nextElementSibling == 'undefined') return;
|
||||
if (elm.nextElementSibling?.getAttribute('d-else-if') !== null) {
|
||||
siblingConditionalElms.push(elm.nextElementSibling);
|
||||
if (!elm.nextElementSibling) return;
|
||||
checkForConditionSibling(elm.nextElementSibling);
|
||||
}
|
||||
|
||||
if (elm.nextElementSibling?.getAttribute('d-else') !== null) {
|
||||
siblingConditionalElms.push(elm.nextElementSibling);
|
||||
}
|
||||
}
|
||||
checkForConditionSibling(e);
|
||||
|
||||
if (siblingConditionalElms == undefined) return;
|
||||
|
||||
function resetHTML() {
|
||||
e.innerHTML = '<!-- d-if -->';
|
||||
for (let i = 0; i < siblingConditionalElms.length; i++) {
|
||||
const element = siblingConditionalElms[i];
|
||||
if (!element) return;
|
||||
element.innerHTML = '<!-- d-if -->';
|
||||
}
|
||||
}
|
||||
|
||||
let ifStatement = \`if (!!eval(condition)) {
|
||||
e.innerHTML = originalHTML
|
||||
} \`;
|
||||
|
||||
for (let i = 0; i < siblingConditionalElms.length; i++) {
|
||||
const element = siblingConditionalElms[i];
|
||||
if (!element) return;
|
||||
const originHTML = element.innerHTML;
|
||||
element.innerHTML = '<!-- d-if -->';
|
||||
let statementDirective = 'else';
|
||||
if (element.getAttribute('d-else-if') !== null) {
|
||||
statementDirective = 'else if';
|
||||
}
|
||||
const condition = eval('element.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 || originalHTML == undefined) return;
|
||||
if (condition.includes('appState.contents.')) {
|
||||
let reactiveProp = /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);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
eval(ifStatement);
|
||||
});
|
||||
|
||||
const 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', () => {
|
||||
eval(enterFunction);
|
||||
});
|
||||
});
|
||||
|
||||
const 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', () => {
|
||||
eval(exitFunction);
|
||||
});
|
||||
});
|
||||
`;
|
||||
}
|
||||
|
||||
if (template.includes('d-on:mouseDown')) {
|
||||
script += `
|
||||
const 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', () => {
|
||||
eval(downFunction);
|
||||
});
|
||||
});`;
|
||||
}
|
||||
|
||||
if (template.includes('d-on:mouseUp')) {
|
||||
script += `
|
||||
const 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', () => {
|
||||
eval(dupFunction);
|
||||
});
|
||||
});`;
|
||||
}
|
||||
|
||||
if (template.includes('d-model')) {
|
||||
if (!script.includes('const { appState } = ')) script += 'const { appState } = await import(\'/src/main.ts\');';
|
||||
script += `
|
||||
const modelElms = document.querySelectorAll('input[d-model], textarea[d-model]');
|
||||
modelElms.forEach((e) => {
|
||||
const modelName = e.getAttribute('d-model');
|
||||
if (!modelName) return;
|
||||
e.addEventListener('input', (input) => {
|
||||
const target = input.target;
|
||||
if (!target || !target.value) return;
|
||||
appState.contents[modelName] = target.value;
|
||||
});
|
||||
});`;
|
||||
}
|
||||
|
||||
// check if there are links to prefetch
|
||||
if (template.includes('<a ') && template.includes('client:prefetch')) {
|
||||
script += `
|
||||
const anchorElms = document.querySelectorAll('a');
|
||||
const linkPrefetcher = await import('/src/lib/router/linkPrefetcher.ts');
|
||||
linkPrefetcher.default(anchorElms);`;
|
||||
}
|
||||
|
||||
if (template.includes('d-on:keydown.')) {
|
||||
script += `
|
||||
document.body.querySelectorAll('*').forEach((e) => {
|
||||
for (let i = 0; i < e.attributes.length; i++) {
|
||||
const item = e.attributes.item(i).name;
|
||||
if (!item) return;
|
||||
if (item.startsWith('d-on:keydown')) {
|
||||
const key = item.split('.')[1].toLowerCase();
|
||||
let correctedKey = '';
|
||||
if (key && key.length > 1) {
|
||||
key.split('').forEach((e, i, arr) => {
|
||||
if (i === 0) {
|
||||
arr[i] = e.toUpperCase();
|
||||
}
|
||||
correctedKey += arr[i];
|
||||
});
|
||||
}
|
||||
e.addEventListener('keydown', (keydown) => {
|
||||
const keyboardEvent = keydown;
|
||||
if (keyboardEvent.key == correctedKey) {
|
||||
const itemCode = e.getAttribute(item);
|
||||
if (!itemCode) return;
|
||||
eval(itemCode);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});`;
|
||||
}
|
||||
|
||||
return script;
|
||||
}
|
||||
109
day22/src/lib/templateRenderer.ts
Normal file
109
day22/src/lib/templateRenderer.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
export const compileToString = async (template: string) => {
|
||||
let styles = '';
|
||||
|
||||
function renderStyleBlock() {
|
||||
const style = parseFromRegex(template, /<style>|<\/style>/g);
|
||||
|
||||
if (!style) return;
|
||||
|
||||
style.map(async (style, i, arr) => {
|
||||
if (!style || !arr[i + 2]) return;
|
||||
if (style.startsWith('<style>') && arr[i + 2]?.startsWith('</style>')) {
|
||||
styles += arr[i + 1];
|
||||
}
|
||||
|
||||
// remove the style from the body
|
||||
template = template.split('<style>' + styles + '</style>').join('');
|
||||
});
|
||||
}
|
||||
renderStyleBlock();
|
||||
|
||||
let script = '';
|
||||
|
||||
function renderScriptBlock() {
|
||||
const scriptContent = parseFromRegex(template, /<script>|<\/script>/g);
|
||||
|
||||
if (!scriptContent) return;
|
||||
|
||||
scriptContent.map(async (scriptData, i, arr) => {
|
||||
if (!scriptData || !arr[i + 2]) return;
|
||||
if (scriptData.startsWith('<script') && arr[i + 2]?.startsWith('</script>')) {
|
||||
script += arr[i + 1];
|
||||
}
|
||||
|
||||
// remove the style from the body
|
||||
template = template.split('<script>' + script + '</script>').join('');
|
||||
});
|
||||
}
|
||||
|
||||
renderScriptBlock();
|
||||
|
||||
const ast: Array<string> | undefined = parseFromRegex(template, /{(.*?)}/g);
|
||||
let fnStr = '``';
|
||||
|
||||
if (!ast) return;
|
||||
|
||||
ast.map(async (t: string) => {
|
||||
// checking to see if it is an interpolation
|
||||
if (t.startsWith('{') && t.endsWith('}')) {
|
||||
// TODO: rewrite comment
|
||||
const bracketVariable = t.split(/{|}/).filter(Boolean)[0]?.trim();
|
||||
if (!bracketVariable) return;
|
||||
const parentElement = fnStr.split(t)[0]?.split('>');
|
||||
if (!parentElement || !parentElement[parentElement.length - 2] || typeof parentElement[parentElement.length - 2] == 'undefined') return;
|
||||
const isRawHTML = parentElement[parentElement.length - 2]?.includes('d-html');
|
||||
if (bracketVariable.startsWith('appState.contents.')) {
|
||||
const uuid = bracketVariable.substring(bracketVariable.length, 18).split('').map((c: string) => c.charCodeAt(0).toString(16).padStart(2, '0')).join('');
|
||||
fnStr = fnStr.substring(0, fnStr.length - 1) + `<span data-token-${uuid}>\``;
|
||||
} else {
|
||||
fnStr = fnStr.substring(0, fnStr.length - 1) + '<span>`';
|
||||
}
|
||||
let runVar = `((${bracketVariable}).toString().replace(/&/g,'&').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 && !import.meta.env.SSR) {
|
||||
console.groupCollapsed('Compiled tempalte to String');
|
||||
console.info('Template String: ' + fnStr);
|
||||
console.groupEnd();
|
||||
}
|
||||
|
||||
|
||||
return { fnStr, styles, script };
|
||||
};
|
||||
|
||||
const parseFromRegex = (template: string, regex: RegExp) => {
|
||||
let result = regex.exec(template);
|
||||
const arr = [];
|
||||
let firstPos;
|
||||
|
||||
while (result) {
|
||||
firstPos = result.index;
|
||||
if (firstPos !== 0) {
|
||||
arr.push(template.substr(0, firstPos));
|
||||
template = template.slice(firstPos);
|
||||
}
|
||||
|
||||
if (!result[0]) return;
|
||||
|
||||
arr.push(result[0]);
|
||||
template = template.slice(result[0].length);
|
||||
result = regex.exec(template);
|
||||
}
|
||||
|
||||
if (template) arr.push(template);
|
||||
return arr;
|
||||
};
|
||||
|
||||
export const render = (template: string) => {
|
||||
return compileToString(template);
|
||||
};
|
||||
11
day22/src/main.ts
Normal file
11
day22/src/main.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Reactive } from './lib/ReactiveObject';
|
||||
const { getCookie } = await import('./lib/cookieManager');
|
||||
|
||||
export const appState: Reactive = new Reactive({
|
||||
count: 0,
|
||||
cookie: getCookie('username'),
|
||||
text: '',
|
||||
html: '',
|
||||
year: '',
|
||||
cookiedata: '',
|
||||
});
|
||||
12
day22/src/pages/index.devto
Normal file
12
day22/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">
|
||||
<Counter />
|
||||
<textInput />
|
||||
<div>
|
||||
<a href="/page2"
|
||||
client:prefetch>Navigate</a>
|
||||
<a href="/page3"
|
||||
client:prefetch>Navigate</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
7
day22/src/pages/nojavascript.devto
Normal file
7
day22/src/pages/nojavascript.devto
Normal file
@@ -0,0 +1,7 @@
|
||||
<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">
|
||||
<h1 class="text-xl font-semibold">This page has no javascript!!</h1>
|
||||
<a href="/" client:prefetch>Home</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
7
day22/src/pages/page2.devto
Normal file
7
day22/src/pages/page2.devto
Normal file
@@ -0,0 +1,7 @@
|
||||
<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">
|
||||
<htmlInput />
|
||||
<myDad />
|
||||
<a href="/" client:prefetch>Home</a>
|
||||
</div>
|
||||
</div>
|
||||
9
day22/src/pages/page3.devto
Normal file
9
day22/src/pages/page3.devto
Normal file
@@ -0,0 +1,9 @@
|
||||
<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">
|
||||
<a href="/"
|
||||
client:prefetch>Home</a>
|
||||
<br/>
|
||||
<a href="/nojavascript"
|
||||
client:prefetch>No javascript</a>
|
||||
</div>
|
||||
</div>
|
||||
21
day22/src/style.css
Normal file
21
day22/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;
|
||||
}
|
||||
27
day22/tailwind.config.js
Normal file
27
day22/tailwind.config.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
|
||||
export default {
|
||||
content: [
|
||||
'./index.html',
|
||||
'./src/**/*.{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: [],
|
||||
};
|
||||
27
day22/tsconfig.json
Normal file
27
day22/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"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,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"incremental": true,
|
||||
"jsx": "preserve",
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"baseUrl": ".",
|
||||
},
|
||||
"include": ["src/**/*", "types/*", "server.ts", "node_modules/vite/types/*", "next-env.d.ts"],
|
||||
}
|
||||
11
day22/vite.config.ts
Normal file
11
day22/vite.config.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
/** @type {import('vite').UserConfig} */
|
||||
export default {
|
||||
build: {
|
||||
target: 'es2020',
|
||||
},
|
||||
|
||||
server: {
|
||||
port: 8080,
|
||||
host: '0.0.0.0'
|
||||
}
|
||||
};
|
||||
2
ssr+templates+misc
Normal file
2
ssr+templates+misc
Normal file
@@ -0,0 +1,2 @@
|
||||
const aa = ''
|
||||
// not in any dange
|
||||
Reference in New Issue
Block a user