add day 6
This commit is contained in:
12
day6/src/components/cookieInput.ts
Normal file
12
day6/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: {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" />
|
||||
{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
day6/src/components/counter.ts
Normal file
22
day6/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: {count}</h2>
|
||||
</div>
|
||||
<div class="flex justify-center">
|
||||
<button d-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-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-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>
|
||||
`
|
||||
}
|
||||
23
day6/src/components/myDad.ts
Normal file
23
day6/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 {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
day6/src/components/routerLink.ts
Normal file
5
day6/src/components/routerLink.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export const RouterLink = (link: string, name: string) => {
|
||||
return `
|
||||
<a href="${link}" d-click="event.preventDefault(); loadPage('${link}')">${name}</a>
|
||||
`
|
||||
}
|
||||
10
day6/src/components/textInput.ts
Normal file
10
day6/src/components/textInput.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
export const TextInput = () => {
|
||||
return `
|
||||
<div class="mb-2">
|
||||
<h2 class="text-xl font-semibold text-center">Input is: {text}</h2>
|
||||
</div>
|
||||
<div class="flex justify-center">
|
||||
<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>
|
||||
`
|
||||
}
|
||||
1
day6/src/icons/minus.svg
Normal file
1
day6/src/icons/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
day6/src/icons/plus.svg
Normal file
1
day6/src/icons/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
day6/src/icons/refresh.svg
Normal file
1
day6/src/icons/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 |
11
day6/src/layouts/404.ts
Normal file
11
day6/src/layouts/404.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
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-semibold">Looks like you're lost</h1>
|
||||
<h3 class="text-xl font-semibold">${RouterLink('/', 'return home')}</h3>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
39
day6/src/lib/ReactiveObject.ts
Normal file
39
day6/src/lib/ReactiveObject.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
export class Reactive {
|
||||
[x: string]: any;
|
||||
constructor(obj: any) {
|
||||
this.contents = obj;
|
||||
this.listeners = {};
|
||||
this.makeReactive(obj);
|
||||
}
|
||||
|
||||
makeReactive(obj: any) {
|
||||
Object.keys(obj).forEach(prop => this.makePropReactive(obj, prop));
|
||||
}
|
||||
|
||||
makePropReactive(obj: any, key: string) {
|
||||
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: any, handler: any) {
|
||||
if (!this.listeners[prop]) this.listeners[prop] = [];
|
||||
|
||||
this.listeners[prop].push(handler);
|
||||
}
|
||||
|
||||
notify(prop: any) {
|
||||
this.listeners[prop].forEach((listener: (arg0: any) => any) => listener(this.contents[prop]));
|
||||
}
|
||||
}
|
||||
39
day6/src/lib/cookieManager.ts
Normal file
39
day6/src/lib/cookieManager.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
export function setCookie(name: string, value: string, expires: any, path?: string, domain?: string) {
|
||||
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: string) {
|
||||
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 "";
|
||||
}
|
||||
77
day6/src/lib/router.ts
Normal file
77
day6/src/lib/router.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { render } from './templateRenderer'
|
||||
import { appState } from '../main'
|
||||
import { setCookie, getCookie } from './cookieManager'
|
||||
const documentBody = document.getElementById('app')
|
||||
|
||||
setCookie('test', 'yee', 365)
|
||||
console.log(getCookie('username'))
|
||||
|
||||
// Global function to handle rendering a page and navigation
|
||||
export async function loadPage(route?: string) {
|
||||
let templatedVirtualDom
|
||||
if (!documentBody) {
|
||||
throw new Error('Fatal Error: element with id app not found')
|
||||
}
|
||||
|
||||
if (route) history.pushState('', '', route)
|
||||
|
||||
let fileName: any = window.location.pathname.split('/');
|
||||
if (fileName[1] === '') {
|
||||
fileName = '/index'
|
||||
} else {
|
||||
fileName = fileName.join('/').toLowerCase().trim()
|
||||
}
|
||||
|
||||
let file
|
||||
try {
|
||||
file = await import(/* @vite-ignore */ '../pages' + fileName)
|
||||
} catch (e) {
|
||||
file = await import(/* @vite-ignore */ '../layouts/404');
|
||||
}
|
||||
const template = await file.default()
|
||||
|
||||
templatedVirtualDom = await eval(render(template))
|
||||
documentBody.innerHTML = templatedVirtualDom
|
||||
// here we hydrate/re-hydrate the page content
|
||||
await hydratePage()
|
||||
}
|
||||
|
||||
// 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 querySelector = "data-token-" + e.split("").map(c => c.charCodeAt(0).toString(16).padStart(2, "0")).join("")
|
||||
const listeningElements = document.querySelectorAll(`[${querySelector}]`)
|
||||
listeningElements.forEach((elm) => {
|
||||
appState.listen(e, (change: any) => elm.textContent = change);
|
||||
})
|
||||
})
|
||||
// here we look for elements with the d-click attribute and on click run the function in the attribute
|
||||
let elms = documentBody.querySelectorAll('*[d-click]')
|
||||
elms.forEach((e) => {
|
||||
const clickFunction = e.getAttribute("d-click")
|
||||
if (!clickFunction) return;
|
||||
e.addEventListener('click', () => {
|
||||
eval(clickFunction)
|
||||
})
|
||||
})
|
||||
|
||||
// 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: any) => {
|
||||
appState.contents[modelName] = event.target.value
|
||||
})
|
||||
})
|
||||
}
|
||||
48
day6/src/lib/templateRenderer.ts
Normal file
48
day6/src/lib/templateRenderer.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
export const compileToString = (template: string) => {
|
||||
const ast = parse(template);
|
||||
let fnStr = `\`\``;
|
||||
|
||||
ast.map(t => {
|
||||
// checking to see if it is an interpolation
|
||||
if (t.startsWith("{") && t.endsWith("}")) {
|
||||
// so first we calculate the hex value of the variable, which is needed so we can use reactivity properly
|
||||
// then after that we append a span element with the data-token-<hex value> attribute to the span
|
||||
// finally we add the appState.contents.variables to the string so we have the value of the variable in the raw html.
|
||||
const uuid = t.split(/{|}/).filter(Boolean)[0].trim().split("").map(c => c.charCodeAt(0).toString(16).padStart(2, "0")).join("");
|
||||
fnStr = fnStr.substring(0, fnStr.length - 1) + `<span data-token-${uuid}>\``;
|
||||
fnStr += `+appState.contents.${t.split(/{|}/).filter(Boolean)[0].trim()}` + `+\`</span>\``;
|
||||
} else {
|
||||
// append the string to the fnStr
|
||||
fnStr += `+\`${t}\``;
|
||||
}
|
||||
});
|
||||
|
||||
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: string) => {
|
||||
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: string) => {
|
||||
return compileToString(template)
|
||||
}
|
||||
25
day6/src/main.ts
Normal file
25
day6/src/main.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Reactive } from './lib/ReactiveObject'
|
||||
import { loadPage, hydratePage } from './lib/router';
|
||||
import { getCookie } from './lib/cookieManager';
|
||||
import '/src/style.css';
|
||||
|
||||
export const appState = new Reactive({
|
||||
count: 0,
|
||||
cookie: getCookie('username'),
|
||||
text: '',
|
||||
year: '',
|
||||
cookiedata: ""
|
||||
});
|
||||
|
||||
// equivalent to mounted() on svelte or vue
|
||||
window.addEventListener('load', async () => {
|
||||
// loadPage after all the index is loaded
|
||||
if (!import.meta.env.SSR) {
|
||||
await loadPage()
|
||||
} else {
|
||||
await hydratePage()
|
||||
}
|
||||
window.onpopstate = async () => {
|
||||
await loadPage()
|
||||
}
|
||||
})
|
||||
28
day6/src/pages/index.ts
Normal file
28
day6/src/pages/index.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { Counter } from '../components/counter';
|
||||
import { TextInput } from '../components/textInput';
|
||||
import { MyDad } from '../components/myDad';
|
||||
import { RouterLink } from '../components/routerLink';
|
||||
import { CookieInput } from '../components/cookieInput';
|
||||
|
||||
|
||||
export default () => {
|
||||
return `
|
||||
<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()}
|
||||
<br/>
|
||||
${TextInput()}
|
||||
<br/>
|
||||
${MyDad()}
|
||||
<br/>
|
||||
${CookieInput()}
|
||||
<br/>
|
||||
<div class="flex gap-1 justify-center">
|
||||
Go to ${RouterLink('/page2', 'Page 2')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
export const layout = 'default'
|
||||
19
day6/src/pages/page2.ts
Normal file
19
day6/src/pages/page2.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Counter } from '../components/counter';
|
||||
import { TextInput } from '../components/textInput';
|
||||
import { RouterLink } from '../components/routerLink';
|
||||
|
||||
export default () => {
|
||||
return `
|
||||
<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()}
|
||||
<br/>
|
||||
${TextInput()}
|
||||
<br/>
|
||||
<div class="flex gap-1 justify-center">
|
||||
Go to ${RouterLink('/subroute/page', 'subroute page')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
16
day6/src/pages/subroute/page.ts
Normal file
16
day6/src/pages/subroute/page.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Counter } from '../../components/counter';
|
||||
import { RouterLink } from '../../components/routerLink';
|
||||
|
||||
export default () => {
|
||||
return `
|
||||
<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()}
|
||||
<br/>
|
||||
<div class="flex gap-1 justify-center">
|
||||
return ${RouterLink('/', 'home')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
21
day6/src/style.css
Normal file
21
day6/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;
|
||||
}
|
||||
1
day6/src/vite-env.d.ts
vendored
Normal file
1
day6/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
Reference in New Issue
Block a user