Aeolin Ferjünnoz 870630063a - fixed two way binding
- added support for list like attributes to toggle classes for example
2026-04-14 15:00:11 +02:00

433 lines
12 KiB
JavaScript

import "./linq.js";
import { Template } from "./template.js";
class RouteMatch {
constructor(route, path, params) {
this.route = route;
this.path = path;
this.params = params;
this.segmentCount = route.fragments.length;
}
}
export class Route {
constructor(pattern, componentClass) {
this.id = crypto.randomUUID();
this.componentClass = componentClass;
this.ComponentDefinition = componentClass.definition;
this.fragments = pattern.split("/");
}
match(path) {
const parsedUrl = new URL(path, window.location.origin);
const params = {};
parsedUrl.searchParams.forEach((value, key) => {
params[key] = value;
});
const pathFragments = parsedUrl.pathname
.split("/")
.filter((f) => f.length > 0);
for (let i = 0; i < this.fragments.length; i++) {
const fragment = this.fragments[i];
const pathFragment = pathFragments[i];
if (fragment.startsWith(":")) {
params[fragment.substring(1)] = pathFragment;
continue;
} else if (fragment === "*") {
continue;
} else if (fragment === "**") {
return new RouteMatch(this, path, params);
} else if (fragment !== pathFragment) {
return null;
}
}
return new RouteMatch(this, path, params);
}
}
export class ComponentInput {
constructor(defaultValue, options = {}) {
this._value = defaultValue;
this.transform = options.transform || ((v) => v);
this.validate = options.validate || (() => true);
this.alias = options.alias || null;
this._isComponentInput = true;
this._owner = null;
const self = this;
const fn = function () {
return self._value;
};
return new Proxy(fn, {
get(target, prop) {
if (prop === "set") return (v) => self._set(v);
if (prop === "_isComponentInput") return true;
if (prop === "_self") return self;
if (prop === "alias") return self.alias;
if (prop === Symbol.toPrimitive) return () => self._value;
if (prop === "valueOf") return () => self._value;
if (prop === "toString") return () => String(self._value);
const inner = self._value;
if (inner == null) return undefined;
const val = inner[prop];
return typeof val === "function" ? val.bind(inner) : val;
},
set(target, prop, value) {
if (self._value != null) {
self._value[prop] = value;
if (self._owner) self._owner.requestUpdate();
}
return true;
},
apply(target, thisArg, args) {
return self._value;
},
});
}
_set(newValue) {
const transformed = this.transform(newValue);
if (!this.validate(transformed)) {
throw new Error("Invalid value");
}
this._value = transformed;
if (this._owner) this._owner.requestUpdate();
}
static [Symbol.hasInstance](instance) {
return instance?._isComponentInput === true;
}
}
export class ViewChild {
constructor(options = { selector: null, id: null, multiple: false }) {
this._selector = options.selector;
this._id = options.id;
this._multiple = options.multiple;
this._element = null;
this._isViewChild = true;
return new Proxy(this, {
get(target, prop) {
if (prop in target) return target[prop];
if (target._element) {
const value = target._element[prop];
return typeof value === "function"
? value.bind(target._element)
: value;
}
},
});
}
_setValue(element) {
this._element = element;
}
static [Symbol.hasInstance](instance) {
return instance?._isViewChild === true;
}
}
export class ComponentDefinition {
constructor(
options = {
templatesPath: null,
template: null,
stylesPath: null,
style: null,
scriptsPath: null,
},
) {
this.templatesPath = options.templatesPath;
this.template = options.template;
this.stylesPath = options.stylesPath;
this.scriptsPath = options.scriptsPath;
}
}
class EventListener {
constructor(event, element, handler) {
this.event = event;
this.element = element;
this.handler = handler;
}
attach() {
this.element.addEventListener(this.event, this.handler);
}
detach() {
this.element.removeEventListener(this.event, this.handler);
}
}
export class Component extends EventTarget {
constructor() {
super();
this._eventListeners = [];
return new Proxy(this, {
get(target, prop, receiver) {
const value = Reflect.get(target, prop, target);
if (typeof value === "function" && typeof value.bind === "function") {
return prop in EventTarget.prototype
? value.bind(target)
: value.bind(receiver);
}
return value;
},
set(target, prop, value) {
if (target[prop] instanceof ComponentInput) {
target[prop].set(value);
return true;
} else if (target[prop] instanceof ViewChild) {
target[prop]._setValue(value);
} else {
target[prop] = value;
}
target.requestUpdate();
return true;
},
});
}
requestUpdate() {
this.dispatchEvent(new Event("requestUpdate", { component: this }));
}
static get definition() {
throw new Error("Component definition is not defined");
}
onInit() { }
onBeforeRender() { }
onAfterRender() { }
onDestroy() {
this._eventListeners.forEach((listener) => listener.detach());
}
}
export function initRouter(outletId, includeId, routes) {
const outletRef = document.getElementById(outletId);
const includeRef = document.getElementById(includeId);
if (!outletRef) {
console.error(`Outlet element with id '${outletId}' not found`);
return null;
}
if (!includeRef) {
console.error(`Include element with id '${includeId}' not found`);
return null;
}
return new Router(outletRef, includeRef, routes);
}
export class Router {
constructor(outletRef, includeRef, routes) {
this.outletRef = outletRef;
this.includeRef = includeRef;
this.routes = routes;
this.templateCache = new Map();
outletRef.innerHTML = "Loading...";
includeRef.innerHTML = "";
navigation.addEventListener("navigate", this.handleNavigate.bind(this));
}
findMatchingRoute(path) {
const routeMatch = this.routes
.asEnumerable()
.select((route) => route.match(path))
.where((match) => match !== null)
.orderByDescending((match) => match.segmentCount)
.firstOrDefault();
return routeMatch;
}
async handleNavigate(event) {
const routeMatch = this.findMatchingRoute(event.destination.url);
if (routeMatch) {
event.preventDefault();
const template = await this.getCachedTemplate(routeMatch.route);
const controller = this.createComponentInstance(
routeMatch.route.componentClass,
routeMatch.params,
);
this.destroyCurrent();
this.activeController = controller;
this.activeTemplate = template;
this.insertIncludes(routeMatch.route);
this._boundUpdateHandler = this.handleUpdateRequest.bind(this);
this.activeController.addEventListener(
"requestUpdate",
this._boundUpdateHandler,
);
this.renderActiveComponent();
history.pushState(null, "", routeMatch.path);
}
}
destroyCurrent() {
if (this.activeController) {
this.activeController.removeEventListener(
"requestUpdate",
this._boundUpdateHandler,
);
this.activeController.onDestroy();
this.activeController = null;
}
}
handleUpdateRequest(args) {
if (this._rendering) {
this._pendingUpdate = true;
return;
} else {
this.renderActiveComponent();
}
}
insertIncludes(route) {
if (Array.isArray(route.ComponentDefinition.stylesPath)) {
route.ComponentDefinition.stylesPath.forEach((path) => {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = path;
this.includeRef.appendChild(link);
});
} else if (route.ComponentDefinition.stylesPath) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = route.ComponentDefinition.stylesPath;
this.includeRef.appendChild(link);
}
}
renderActiveComponent() {
this._rendering = true;
this._pendingUpdate = false;
this.activeController.onBeforeRender();
const renderedTemplate = this.activeTemplate.render(this.activeController);
this.outletRef.innerHTML = renderedTemplate;
this.wireEvents(this.activeController);
this.wireViewChildren(this.activeController);
this.activeController.onAfterRender();
this._rendering = false;
if (this._pendingUpdate) {
this.renderActiveComponent();
}
}
wireViewChildren(controller) {
const viewChildProps = Object.entries(controller)
.filter(([_, value]) => value instanceof ViewChild)
.forEach(([key, viewChild]) => {
if (viewChild._id) {
const element = this.outletRef.querySelector(`#${viewChild._id}`);
if (element) viewChild._setValue(element);
} else if (viewChild._selector) {
const element = this.outletRef.querySelector(viewChild._selector);
if (element) viewChild._setValue(element);
} else {
console.warn(`ViewChild ${key} has no selector or id defined`);
}
});
}
wireEvents(controller) {
const allElements = this.outletRef.querySelectorAll("*");
allElements.forEach((element) => {
element.getAttributeNames().forEach((attr) => {
const match = attr.match(/^\((\w+)\)$/);
if (!match) return;
const eventName = match[1];
const attrValue = element.getAttribute(attr).trim();
const methodName = attrValue.endsWith("()")
? attrValue.slice(0, -2)
: attrValue;
let listener;
if (typeof controller[methodName] === "function") {
// Named method — wire directly
const handler = controller[methodName].bind(controller);
listener = new EventListener(eventName, element, handler);
} else {
const fn = new Function("event", attrValue).bind(controller);
listener = new EventListener(eventName, element, fn);
}
listener.attach();
controller._eventListeners.push(listener);
});
});
}
createComponentInstance(component, params) {
const instance = new component();
for (const key of Object.keys(instance)) {
const val = instance[key];
if (val instanceof ComponentInput) {
val._self._owner = instance;
}
}
instance.onInit();
for (const [paramKey, paramValue] of Object.entries(params)) {
if (instance[paramKey] instanceof ComponentInput) {
instance[paramKey].set(paramValue);
continue;
}
for (const key of Object.keys(instance)) {
const val = instance[key];
if (val instanceof ComponentInput && val.alias === paramKey) {
val.set(paramValue);
break;
}
}
}
return instance;
}
async getCachedTemplate(route) {
if (this.templateCache.has(route.id)) {
return this.templateCache.get(route.id);
}
let templateContent = route.componentClass.definition.template;
if (!templateContent && route.componentClass.definition.templatesPath) {
const response = await fetch(
route.componentClass.definition.templatesPath,
);
if (response.ok === false) {
return new Template(`
<div class="error">
<h1>Failed to load template</h1>
<p>${response.status} ${response.statusText}</p>
</div>
`);
}
templateContent = await response.text();
}
try {
const template = new Template(templateContent);
this.templateCache.set(route.id, template);
return template;
} catch (error) {
return new Template(`
<div class="error">
<h1>Failed to compile template</h1>
<p>${error.message}</p>
</div>
`);
}
}
}