add day 7
This commit is contained in:
39
day7/src/lib/ReactiveObject.ts
Normal file
39
day7/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
day7/src/lib/cookieManager.ts
Normal file
39
day7/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 "";
|
||||
}
|
||||
81
day7/src/lib/router.ts
Normal file
81
day7/src/lib/router.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { compileToString } from './templateRenderer'
|
||||
import { appState } from '../main'
|
||||
const documentBody = document.getElementById('app')
|
||||
|
||||
// Global function to handle rendering a page and navigation
|
||||
export async function renderPage(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();
|
||||
}
|
||||
|
||||
const template = await loadPage(fileName);
|
||||
|
||||
const stringifiedTemplate = await compileToString(template);
|
||||
templatedVirtualDom = eval(stringifiedTemplate);
|
||||
documentBody.innerHTML = templatedVirtualDom;
|
||||
// here we hydrate/re-hydrate the page content
|
||||
await hydratePage()
|
||||
}
|
||||
|
||||
async function loadPage(page: string) {
|
||||
let file
|
||||
try {
|
||||
file = await import(/* @vite-ignore */ '../pages' + page);
|
||||
} catch (e) {
|
||||
file = await import(/* @vite-ignore */ '../layouts/404');
|
||||
}
|
||||
const template = await file.default();
|
||||
|
||||
return template;
|
||||
}
|
||||
|
||||
// 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 querySelector = "data-token-" + uuid
|
||||
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
|
||||
})
|
||||
})
|
||||
}
|
||||
65
day7/src/lib/templateRenderer.ts
Normal file
65
day7/src/lib/templateRenderer.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
export const compileToString = async (template: string) => {
|
||||
const ast = parse(template);
|
||||
let fnStr = `\`\``;
|
||||
|
||||
ast.map(async t => {
|
||||
// checking to see if it is an interpolation
|
||||
if (t.startsWith("{") && t.endsWith("}")) {
|
||||
// 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}\``;
|
||||
// }
|
||||
// // 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 bracketVariable = t.split(/{|}/).filter(Boolean)[0].trim();
|
||||
if (bracketVariable.startsWith("appState.contents.")) {
|
||||
const uuid = bracketVariable.split('.')[2].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>\``;
|
||||
}
|
||||
fnStr += `+ (${bracketVariable})` + `+\`</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)
|
||||
}
|
||||
Reference in New Issue
Block a user