add day19
This commit is contained in:
42
day19/src/lib/ReactiveObject.ts
Normal file
42
day19/src/lib/ReactiveObject.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
export class Reactive {
|
||||
listeners: any;
|
||||
contents: any;
|
||||
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: any) {
|
||||
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: any) => listener(this.contents[prop]));
|
||||
}
|
||||
}
|
||||
38
day19/src/lib/cookieManager.ts
Normal file
38
day19/src/lib/cookieManager.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
export function setCookie(name: string, value: string, expires: any, 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.toGMTString() + ';';
|
||||
}
|
||||
|
||||
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 '';
|
||||
}
|
||||
194
day19/src/lib/router/hydrationManager.ts
Normal file
194
day19/src/lib/router/hydrationManager.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import { appState } from '../../main';
|
||||
import { isSSR } from '../../entry-client';
|
||||
|
||||
export let ctrlPressed = false;
|
||||
|
||||
// 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');
|
||||
|
||||
console.log(documentBody);
|
||||
|
||||
// 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: any) => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
document.body.addEventListener('keydown', (e) => {
|
||||
ctrlPressed = e.ctrlKey;
|
||||
});
|
||||
|
||||
document.body.addEventListener('keyup', (e) => {
|
||||
ctrlPressed = e.ctrlKey;
|
||||
});
|
||||
|
||||
// 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: any) => {
|
||||
const condition = e.getAttribute('d-if');
|
||||
|
||||
const siblingConditionalElms: Array<any> = [];
|
||||
// recursively check for subsequent elements with the d-else of d-else-if attribute
|
||||
function checkForConditionSibling(elm: any) {
|
||||
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);
|
||||
|
||||
function resetHTML() {
|
||||
e.innerHTML = '<!-- d-if -->';
|
||||
for (let i = 0; i < siblingConditionalElms.length; i++) {
|
||||
if (!siblingConditionalElms[i]) return;
|
||||
siblingConditionalElms[i].innerHTML = '<!-- d-if -->';
|
||||
}
|
||||
}
|
||||
|
||||
let ifStatement = `if (!!eval(condition)) {
|
||||
e.innerHTML = originalHTML
|
||||
} `;
|
||||
|
||||
for (let i = 0; i < siblingConditionalElms.length; 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: any = /appState\.contents\.[a-zA-Z]+/.exec(condition);
|
||||
if (!reactiveProp) return;
|
||||
reactiveProp = reactiveProp[0].split('.')[2];
|
||||
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', (event) => {
|
||||
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', (event) => {
|
||||
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', (event) => {
|
||||
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', (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
|
||||
const modelElms = document.querySelectorAll('input[d-model], textarea[d-model]');
|
||||
modelElms.forEach((e: any) => {
|
||||
const modelName = e.getAttribute('d-model');
|
||||
if (!modelName) return;
|
||||
e.addEventListener('input', (event: any) => {
|
||||
if (!event?.target || !event.target.value) return;
|
||||
appState.contents[modelName] = event.target.value;
|
||||
});
|
||||
});
|
||||
|
||||
const anchorElms = document.querySelectorAll('a');
|
||||
anchorElms.forEach((e: HTMLAnchorElement) => {
|
||||
e.addEventListener('click', async (click: any) => {
|
||||
if (!event) return;
|
||||
event.preventDefault();
|
||||
if (!click.target || !click.target.getAttribute('href')) return;
|
||||
await renderPage(click.target.getAttribute('href'));
|
||||
});
|
||||
});
|
||||
|
||||
// if SSR is enabled then we should prefetch pages so that they will render instantly when navigated to
|
||||
if (isSSR()) {
|
||||
const linkPrefetcher = await import('./linkPrefetcher.js');
|
||||
linkPrefetcher.default(anchorElms);
|
||||
}
|
||||
}
|
||||
52
day19/src/lib/router/linkPrefetcher.ts
Normal file
52
day19/src/lib/router/linkPrefetcher.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
export default (anchorElms: any) => {
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
175
day19/src/lib/router/pageRenderer.ts
Normal file
175
day19/src/lib/router/pageRenderer.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
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 (ctrlPressed && route) {
|
||||
window.open(route, '__blank');
|
||||
return;
|
||||
}
|
||||
if (isSSR() && route) {
|
||||
window.location.href = route;
|
||||
return;
|
||||
}
|
||||
if (isSSR()) return;
|
||||
if (typeof documentBody == 'string') 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 file: any;
|
||||
let path: string;
|
||||
|
||||
(import.meta.env.PROD) ? path = '/' : path = '/src/';
|
||||
|
||||
await fetch(path + `pages${url}.devto`).then((response) => {
|
||||
if (response.ok) {
|
||||
return response.text();
|
||||
}
|
||||
throw new Error('Something went wrong');
|
||||
})
|
||||
.then((data) => {
|
||||
file = 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) => {
|
||||
file = data;
|
||||
});
|
||||
});
|
||||
|
||||
let template = file;
|
||||
const elements: Array<string> = file.split('<');
|
||||
|
||||
await Promise.all(elements.map(async (component: string | undefined) => {
|
||||
if (!component) 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;
|
||||
}
|
||||
109
day19/src/lib/templateRenderer.ts
Normal file
109
day19/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);
|
||||
};
|
||||
Reference in New Issue
Block a user