dev
This commit is contained in:
17
ssr+templates+misc/index.html
Normal file
17
ssr+templates+misc/index.html
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<!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"
|
||||||
|
class="flex min-h-screen flex-col items-center justify-between py-8 text-center"
|
||||||
|
>
|
||||||
|
<!--ssr-outlet--><noscript>You need javascript to run this app</noscript></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
97
ssr+templates+misc/index.js
Normal file
97
ssr+templates+misc/index.js
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
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 = 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) {
|
||||||
|
throw new Error(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
console.log(appHtml)
|
||||||
|
|
||||||
|
const styles = fs.readFileSync(
|
||||||
|
path.resolve(__dirname, './src/style.css'), 'utf8'
|
||||||
|
)
|
||||||
|
|
||||||
|
// 5. Inject the app-rendered HTML into the template.
|
||||||
|
const stylizedTemplate = template.replace('<!--style-outlet-->', '<style>' + styles + '</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
ssr+templates+misc/package-lock.json
generated
Normal file
4675
ssr+templates+misc/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
32
ssr+templates+misc/package.json
Normal file
32
ssr+templates+misc/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
ssr+templates+misc/postcss.config.cjs
Normal file
6
ssr+templates+misc/postcss.config.cjs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
BIN
ssr+templates+misc/public/favicon.ico
Normal file
BIN
ssr+templates+misc/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
12
ssr+templates+misc/src/components/cookieInput.ts
Normal file
12
ssr+templates+misc/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
ssr+templates+misc/src/components/counter.ts
Normal file
22
ssr+templates+misc/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
ssr+templates+misc/src/components/htmlInput.ts
Normal file
12
ssr+templates+misc/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
ssr+templates+misc/src/components/myDad.ts
Normal file
23
ssr+templates+misc/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
ssr+templates+misc/src/components/routerLink.ts
Normal file
5
ssr+templates+misc/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
ssr+templates+misc/src/components/textInput.ts
Normal file
12
ssr+templates+misc/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>
|
||||||
|
`
|
||||||
|
}
|
||||||
31
ssr+templates+misc/src/entry-client.js
Normal file
31
ssr+templates+misc/src/entry-client.js
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { Reactive } from './lib/ReactiveObject'
|
||||||
|
import { renderPage, hydratePage } from './lib/router';
|
||||||
|
import { getCookie } from './lib/cookieManager';
|
||||||
|
import { isSSR } from '/src/main';
|
||||||
|
import '/src/style.css';
|
||||||
|
|
||||||
|
export const appState = new Reactive({
|
||||||
|
count: 0,
|
||||||
|
cookie: getCookie('username'),
|
||||||
|
text: '',
|
||||||
|
html: '',
|
||||||
|
year: '',
|
||||||
|
cookiedata: "",
|
||||||
|
jsonData: { 'data': 'e' }
|
||||||
|
});
|
||||||
|
|
||||||
|
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
ssr+templates+misc/src/entry-server.js
Normal file
7
ssr+templates+misc/src/entry-server.js
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { render } from './lib/templateRenderer';
|
||||||
|
import { setSSR } from './main';
|
||||||
|
|
||||||
|
export function SSRPage(pageName) {
|
||||||
|
setSSR()
|
||||||
|
return render(pageName)
|
||||||
|
}
|
||||||
12
ssr+templates+misc/src/layouts/404.ts
Normal file
12
ssr+templates+misc/src/layouts/404.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { RouterLink } from '../components/routerLink';
|
||||||
|
|
||||||
|
|
||||||
|
export default () => {
|
||||||
|
return `
|
||||||
|
<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">${RouterLink('/', 'return home')}</h3>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
}
|
||||||
39
ssr+templates+misc/src/lib/ReactiveObject.js
Normal file
39
ssr+templates+misc/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
ssr+templates+misc/src/lib/cookieManager.js
Normal file
41
ssr+templates+misc/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 "";
|
||||||
|
}
|
||||||
227
ssr+templates+misc/src/lib/router.js
Normal file
227
ssr+templates+misc/src/lib/router.js
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
import { compileToString } from './templateRenderer'
|
||||||
|
import { appState, mount } from '../entry-client'
|
||||||
|
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 (!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;
|
||||||
|
|
||||||
|
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
ssr+templates+misc/src/lib/templateRenderer.js
Normal file
65
ssr+templates+misc/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)
|
||||||
|
}
|
||||||
9
ssr+templates+misc/src/main.js
Normal file
9
ssr+templates+misc/src/main.js
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
let SSR = false;
|
||||||
|
|
||||||
|
export function isSSR() {
|
||||||
|
return SSR;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setSSR() {
|
||||||
|
SSR = true;
|
||||||
|
}
|
||||||
5
ssr+templates+misc/src/pages/index.devto
Normal file
5
ssr+templates+misc/src/pages/index.devto
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<h1 class="bg-gradient-to-r from-green-600 to-sky-400 bg-clip-text text-5xl font-black text-transparent selection:bg-transparent">
|
||||||
|
Hello world!
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<p>hi</p>
|
||||||
21
ssr+templates+misc/src/style.css
Normal file
21
ssr+templates+misc/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
ssr+templates+misc/tailwind.config.cjs
Normal file
17
ssr+templates+misc/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
ssr+templates+misc/vite.config.js
Normal file
11
ssr+templates+misc/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'
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// vite.config.js
|
||||||
|
var vite_config_default = {
|
||||||
|
build: {
|
||||||
|
target: "es2020"
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 3e3,
|
||||||
|
host: "0.0.0.0"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
export {
|
||||||
|
vite_config_default as default
|
||||||
|
};
|
||||||
|
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcuanMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvaG9tZS9qdWxzMDcvQ29kZS9ub2RlLXByb2plY3RzLzEwMERheXNPZkNvZGUvc3NyK3RlbXBsYXRlcyttaXNjXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ZpbGVuYW1lID0gXCIvaG9tZS9qdWxzMDcvQ29kZS9ub2RlLXByb2plY3RzLzEwMERheXNPZkNvZGUvc3NyK3RlbXBsYXRlcyttaXNjL3ZpdGUuY29uZmlnLmpzXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ltcG9ydF9tZXRhX3VybCA9IFwiZmlsZTovLy9ob21lL2p1bHMwNy9Db2RlL25vZGUtcHJvamVjdHMvMTAwRGF5c09mQ29kZS9zc3IrdGVtcGxhdGVzK21pc2Mvdml0ZS5jb25maWcuanNcIjsvKiogQHR5cGUge2ltcG9ydCgndml0ZScpLlVzZXJDb25maWd9ICovXG5leHBvcnQgZGVmYXVsdCB7XG4gICAgYnVpbGQ6IHtcbiAgICAgICAgdGFyZ2V0OiAnZXMyMDIwJyxcbiAgICB9LFxuICAgIFxuICAgIHNlcnZlcjoge1xuICAgICAgICBwb3J0OiAzMDAwLFxuICAgICAgICBob3N0OiAnMC4wLjAuMCdcbiAgICB9XG59XG4iXSwKICAibWFwcGluZ3MiOiAiO0FBQ0EsSUFBTyxzQkFBUTtBQUFBLEVBQ1gsT0FBTztBQUFBLElBQ0gsUUFBUTtBQUFBLEVBQ1o7QUFBQSxFQUVBLFFBQVE7QUFBQSxJQUNKLE1BQU07QUFBQSxJQUNOLE1BQU07QUFBQSxFQUNWO0FBQ0o7IiwKICAibmFtZXMiOiBbXQp9Cg==
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// vite.config.js
|
||||||
|
var vite_config_default = {
|
||||||
|
build: {
|
||||||
|
target: "es2020"
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 3e3,
|
||||||
|
host: "0.0.0.0"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
export {
|
||||||
|
vite_config_default as default
|
||||||
|
};
|
||||||
|
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcuanMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvaG9tZS9qdWxzMDcvQ29kZS9ub2RlLXByb2plY3RzLzEwMERheXNPZkNvZGUvc3NyK3RlbXBsYXRlcyttaXNjXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ZpbGVuYW1lID0gXCIvaG9tZS9qdWxzMDcvQ29kZS9ub2RlLXByb2plY3RzLzEwMERheXNPZkNvZGUvc3NyK3RlbXBsYXRlcyttaXNjL3ZpdGUuY29uZmlnLmpzXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ltcG9ydF9tZXRhX3VybCA9IFwiZmlsZTovLy9ob21lL2p1bHMwNy9Db2RlL25vZGUtcHJvamVjdHMvMTAwRGF5c09mQ29kZS9zc3IrdGVtcGxhdGVzK21pc2Mvdml0ZS5jb25maWcuanNcIjsvKiogQHR5cGUge2ltcG9ydCgndml0ZScpLlVzZXJDb25maWd9ICovXG5leHBvcnQgZGVmYXVsdCB7XG4gICAgYnVpbGQ6IHtcbiAgICAgICAgdGFyZ2V0OiAnZXMyMDIwJyxcbiAgICB9LFxuICAgIFxuICAgIHNlcnZlcjoge1xuICAgICAgICBwb3J0OiAzMDAwLFxuICAgICAgICBob3N0OiAnMC4wLjAuMCdcbiAgICB9XG59XG4iXSwKICAibWFwcGluZ3MiOiAiO0FBQ0EsSUFBTyxzQkFBUTtBQUFBLEVBQ1gsT0FBTztBQUFBLElBQ0gsUUFBUTtBQUFBLEVBQ1o7QUFBQSxFQUVBLFFBQVE7QUFBQSxJQUNKLE1BQU07QUFBQSxJQUNOLE1BQU07QUFBQSxFQUNWO0FBQ0o7IiwKICAibmFtZXMiOiBbXQp9Cg==
|
||||||
Reference in New Issue
Block a user