1 Commits
Author SHA1 Message Date
GeNii96 63ee71a19b Initial commit 2026-05-27 12:47:16 +02:00
23 changed files with 2957 additions and 510 deletions

No files matched your search

@@ -16,7 +16,7 @@ namespace OnlyPrompt.Backend.Controllers
[Route("api/v1/auth")] [Route("api/v1/auth")]
public class AuthController : BaseController public class AuthController : BaseController
{ {
private static readonly CookieOptions AuthCookieOptions = new CookieOptions { Secure = true, HttpOnly = true, IsEssential = true }; private static readonly CookieOptions AuthCookieOptions = new CookieOptions { Secure = false, HttpOnly = true, IsEssential = true, SameSite = SameSiteMode.Lax };
private readonly IPasswordHasher<UserModel> _passwordHasher; private readonly IPasswordHasher<UserModel> _passwordHasher;
private readonly ITokenService _jwtService; private readonly ITokenService _jwtService;
private readonly ILogger<AuthController> _logger; private readonly ILogger<AuthController> _logger;
@@ -103,7 +103,18 @@ namespace OnlyPrompt.Backend.Controllers
public RedirectHttpResult Logout() public RedirectHttpResult Logout()
{ {
this.Response.Cookies.Delete("jwt", AuthCookieOptions); this.Response.Cookies.Delete("jwt", AuthCookieOptions);
return TypedResults.Redirect("login"); return TypedResults.Redirect("/login");
}
[Authorize]
[HttpGet("me")]
public async Task<Results<Ok<ApiUser>, NotFound<string>>> GetCurrentUserAsync()
{
var user = await GetUserAsync();
if (user is null)
return TypedResults.NotFound("User not found");
return TypedResults.Ok(_mapper.Map<ApiUser>(user));
} }
} }
} }
+8
View File
@@ -80,6 +80,7 @@ var rewrite = new RewriteOptions()
.AddRewrite(@"^(?!scalar\/?|api\/?)([^.]+)$", "$1.html", skipRemainingRules: true); .AddRewrite(@"^(?!scalar\/?|api\/?)([^.]+)$", "$1.html", skipRemainingRules: true);
app.UseRewriter(rewrite); app.UseRewriter(rewrite);
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
@@ -97,6 +98,13 @@ else
} }
app.MapControllers(); app.MapControllers();
app.MapGet("/", async (HttpContext context) =>
{
var authResult = await context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
return authResult.Succeeded
? Results.Redirect("/dashboard")
: Results.Redirect("/login");
});
app.MapFallbackToFile("/login.html"); app.MapFallbackToFile("/login.html");
using var scope = app.Services.CreateScope(); using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OnlyPromptContext>(); var db = scope.ServiceProvider.GetRequiredService<OnlyPromptContext>();
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Include Error Detail=true;User ID=onlyprompt;Password=onlyprompt;Host=localhost;Port=1803;Database=onlyprompt;Pooling=true;MinPoolSize=0;MaxPoolSize=100;Connection Lifetime=0;" "DefaultConnection": "Include Error Detail=true;User ID=onlyprompt;Password=onlyprompt;Host=localhost;Port=2803;Database=onlyprompt;Pooling=true;MinPoolSize=0;MaxPoolSize=100;Connection Lifetime=0;"
}, },
"Jwt": { "Jwt": {
"Issuer": "https://onlyprompts.com", "Issuer": "https://onlyprompts.com",
+2 -2
View File
@@ -108,7 +108,7 @@
</div> </div>
<script> <script>
fetch('../html/sidebar.html') fetch('/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -121,7 +121,7 @@
if (chatsLink) chatsLink.classList.add('active'); if (chatsLink) chatsLink.classList.add('active');
}); });
fetch('../html/topbar.html') fetch('/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
</script> </script>
+2 -2
View File
@@ -140,7 +140,7 @@
</div> </div>
<script> <script>
fetch('../html/sidebar.html') fetch('/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -153,7 +153,7 @@
if (thirdLink) thirdLink.classList.add('active'); if (thirdLink) thirdLink.classList.add('active');
}); });
fetch('../html/topbar.html') fetch('/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
</script> </script>
+2 -2
View File
@@ -160,7 +160,7 @@
}); });
// Fetch sidebar and topbar // Fetch sidebar and topbar
fetch('../html/sidebar.html') fetch('/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -173,7 +173,7 @@
if (createLink) createLink.classList.add('active'); if (createLink) createLink.classList.add('active');
}); });
fetch('../html/topbar.html') fetch('/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
</script> </script>
+9
View File
@@ -100,13 +100,22 @@
padding-top: 16px; padding-top: 16px;
} }
.sidebar-bottom form {
margin: 0;
}
.sidebar-logout { .sidebar-logout {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
width: 100%;
padding: 12px 16px; padding: 12px 16px;
border: 0;
background: transparent;
cursor: pointer;
text-decoration: none; text-decoration: none;
color: #64748b; color: #64748b;
font: inherit;
font-weight: 600; font-weight: 600;
transition: background 0.2s ease; transition: background 0.2s ease;
} }
+2 -2
View File
@@ -145,7 +145,7 @@
</div> </div>
<script> <script>
fetch('../html/sidebar.html') fetch('/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -158,7 +158,7 @@
if (firstLink) firstLink.classList.add('active'); if (firstLink) firstLink.classList.add('active');
}); });
fetch('../html/topbar.html') fetch('/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
</script> </script>
+126 -116
View File
@@ -1,140 +1,150 @@
// LINQ-like Enumerable class wrapping lazy generator chains // LINQ-like Enumerable class wrapping lazy generator chains
class Enumerable { class Enumerable {
constructor(iteratorFn) { constructor(iteratorFn) {
this._iteratorFn = iteratorFn; this._iteratorFn = iteratorFn;
} }
[Symbol.iterator]() { [Symbol.iterator]() {
return this._iteratorFn(); return this._iteratorFn();
} }
_chain(generatorFn) { _chain(generatorFn) {
const source = this; const source = this;
return new Enumerable(function* () { return new Enumerable(function* () {
yield* generatorFn(source); yield* generatorFn(source);
}); });
} }
where(predicate) { where(predicate) {
return this._chain(function* (source) { return this._chain(function* (source) {
for (const item of source) for (const item of source) if (predicate(item)) yield item;
if (predicate(item)) });
yield item; }
});
}
select(selector) { select(selector) {
return this._chain(function* (source) { return this._chain(function* (source) {
for (const item of source) for (const item of source) yield selector(item);
yield selector(item); });
}); }
}
take(count) { take(count) {
count = Math.max(0, count); count = Math.max(0, count);
return this._chain(function* (source) { return this._chain(function* (source) {
for (const item of source) { for (const item of source) {
if (count-- <= 0) break; if (count-- <= 0) break;
yield item; yield item;
} }
}); });
} }
skip(count) { skip(count) {
count = Math.max(0, count); count = Math.max(0, count);
return this._chain(function* (source) { return this._chain(function* (source) {
for (const item of source) { for (const item of source) {
if (count-- > 0) continue; if (count-- > 0) continue;
yield item; yield item;
} }
}); });
} }
isLast() { isLast() {
return this._chain(function* (source) { return this._chain(function* (source) {
const iter = source[Symbol.iterator](); const iter = source[Symbol.iterator]();
let current = iter.next(); let current = iter.next();
let index = 0; let index = 0;
while (!current.done) { while (!current.done) {
const next = iter.next(); const next = iter.next();
yield [current.value, next.done, index]; yield [current.value, next.done, index];
current = next; current = next;
index++; index++;
} }
}); });
} }
forEach(action) { forEach(action) {
for (const item of this) { for (const item of this) {
if (Array.isArray(item)) { if (Array.isArray(item)) {
action(...item); action(...item);
} else { } else {
action(item); action(item);
} }
}
} }
}
toArray() { toArray() {
return Array.from(this); return Array.from(this);
} }
firstOrDefault(predicate) { orderByDescending(keySelector) {
const source = predicate ? this.where(predicate) : this; return this._chain(function* (source) {
for (const item of source) return item; const items = Array.from(source);
return undefined; items.sort((a, b) => keySelector(b) - keySelector(a));
} yield* items;
});
}
first(predicate) { orderBy(keySelector) {
const source = predicate ? this.where(predicate) : this; return this._chain(function* (source) {
for (const item of source) return item; const items = Array.from(source);
throw new Error("No elements in sequence."); items.sort((a, b) => keySelector(a) - keySelector(b));
} yield* items;
});
}
lastOrDefault(predicate) { firstOrDefault(predicate) {
const source = predicate ? this.where(predicate) : this; const source = predicate ? this.where(predicate) : this;
let lastValue = undefined; for (const item of source) return item;
for (const item of source) lastValue = item; return undefined;
return lastValue; }
}
last(predicate) { first(predicate) {
const source = predicate ? this.where(predicate) : this; const source = predicate ? this.where(predicate) : this;
let lastValue = undefined; for (const item of source) return item;
let found = false; throw new Error("No elements in sequence.");
for (const item of source) { }
lastValue = item;
found = true;
}
if (!found) throw new Error("No elements in sequence.");
return lastValue;
}
any(predicate) { lastOrDefault(predicate) {
const source = predicate ? this.where(predicate) : this; const source = predicate ? this.where(predicate) : this;
for (const _ of source) return true; let lastValue = undefined;
return false; for (const item of source) lastValue = item;
} return lastValue;
}
all(predicate) { last(predicate) {
for (const item of this) const source = predicate ? this.where(predicate) : this;
if (!predicate(item)) let lastValue = undefined;
return false; let found = false;
return true; for (const item of source) {
lastValue = item;
found = true;
} }
if (!found) throw new Error("No elements in sequence.");
return lastValue;
}
count(predicate) { any(predicate) {
let count = 0; const source = predicate ? this.where(predicate) : this;
const source = predicate ? this.where(predicate) : this; for (const _ of source) return true;
for (const _ of source) count++; return false;
return count; }
}
all(predicate) {
for (const item of this) if (!predicate(item)) return false;
return true;
}
count(predicate) {
let count = 0;
const source = predicate ? this.where(predicate) : this;
for (const _ of source) count++;
return count;
}
} }
Array.prototype.asEnumerable = function () { Array.prototype.asEnumerable = function () {
const arr = this; const arr = this;
return new Enumerable(function* () { return new Enumerable(function* () {
for (const item of arr) for (const item of arr) yield item;
yield item; });
}); };
}
+13
View File
@@ -1,5 +1,16 @@
import { sendFormAsync } from "./shared.js"; import { sendFormAsync } from "./shared.js";
async function redirectIfAlreadySignedIn() {
const response = await fetch('/api/v1/auth/me', {
method: 'GET',
credentials: 'same-origin'
});
if (response.ok) {
window.location.replace('/dashboard');
}
}
function togglePassword() { function togglePassword() {
const passwordInput = document.getElementById('password'); const passwordInput = document.getElementById('password');
const newInputType = passwordInput.type === 'password' ? 'text' : 'password'; const newInputType = passwordInput.type === 'password' ? 'text' : 'password';
@@ -19,3 +30,5 @@ loginForm.addEventListener('submit', async (event) => {
event.preventDefault(); // Prevent the default form submission event.preventDefault(); // Prevent the default form submission
await submitLoginForm(); await submitLoginForm();
}); });
await redirectIfAlreadySignedIn();
+556
View File
@@ -0,0 +1,556 @@
import "./linq.js";
import { NodeTemplate } from "./node-template.js";
// ─── Route matching ───
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("/");
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);
}
}
// ─── ComponentInput (signal-like) ───
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;
}
}
// ─── ViewChild ───
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;
}
}
// ─── ComponentDefinition ───
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.style = options.style;
this.scriptsPath = options.scriptsPath;
}
}
// ─── EventListener ───
class EventBinding {
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);
}
}
// ─── Component ───
export class Component extends EventTarget {
constructor() {
super();
this._eventBindings = [];
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"));
}
static get definition() {
throw new Error("Component definition is not defined");
}
onInit() { }
onBeforeRender() { }
onAfterRender() { }
onDestroy() {
this._eventBindings.forEach((b) => b.detach());
}
}
// ─── Router init ───
export function initRouter(outletId, routes) {
const outletRef = document.getElementById(outletId);
if (!outletRef) {
console.error(`Outlet element with id '${outletId}' not found`);
return null;
}
return new Router(outletRef, routes);
}
// ─── Router ───
export class Router {
constructor(outletRef, routes) {
this.outletRef = outletRef;
this.shadowRoot = outletRef.attachShadow({ mode: "open" });
this.routes = routes;
this.templateCache = new Map();
this.activeController = null;
this.activeRenderResult = null;
this._boundUpdateHandler = null;
this._rendering = false;
this._pendingUpdate = false;
this.shadowRoot.textContent = "Loading...";
navigation.addEventListener("navigate", this.handleNavigate.bind(this));
}
findMatchingRoute(path) {
return this.routes
.asEnumerable()
.select((route) => route.match(path))
.where((match) => match !== null)
.orderByDescending((match) => match.segmentCount)
.firstOrDefault();
}
async handleNavigate(event) {
if (event.navigationType === 'replace' && event.destination.url === this.activeRoute) return;
const routeMatch = this.findMatchingRoute(event.destination.url);
if (!routeMatch) return;
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.activeRoute = event.destination.url;
this.insertIncludes(routeMatch.route);
this._boundUpdateHandler = this.handleUpdateRequest.bind(this);
this.activeController.addEventListener(
"requestUpdate",
this._boundUpdateHandler,
);
this.renderActiveComponent();
history.replaceState({}, "", event.destination.url);
}
destroyCurrent() {
if (this.activeController) {
this.activeController.removeEventListener(
"requestUpdate",
this._boundUpdateHandler,
);
this.activeController.onDestroy();
this.activeController = null;
}
if (this.activeRenderResult) {
this.activeRenderResult.destroy();
this.activeRenderResult = null;
}
}
handleUpdateRequest() {
if (this._rendering) {
this._pendingUpdate = true;
return;
}
this.updateActiveComponent();
}
insertIncludes(route) {
// Remove previous component styles from shadow root
this.shadowRoot
.querySelectorAll("link[data-component-style], style[data-component-style]")
.forEach((l) => l.remove());
if (route.componentDefinition.style) {
const styleEl = document.createElement("style");
styleEl.textContent = route.componentDefinition.style;
styleEl.setAttribute("data-component-style", "");
this.shadowRoot.appendChild(styleEl);
}
const paths = route.componentDefinition.stylesPath;
if (!paths) return;
const list = Array.isArray(paths) ? paths : [paths];
for (const p of list) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = p;
link.setAttribute("data-component-style", "");
this.shadowRoot.appendChild(link);
}
}
// ─── First render: build DOM from scratch ───
renderActiveComponent() {
this._rendering = true;
this._pendingUpdate = false;
this.activeController.onBeforeRender();
const result = this.activeTemplate.render(this.activeController);
this.activeRenderResult = result;
// Clear shadow root content (keep style links), append fragment
for (const child of Array.from(this.shadowRoot.childNodes)) {
if (
child.nodeType !== Node.ELEMENT_NODE ||
!child.hasAttribute("data-component-style")
) {
child.remove();
}
}
this.shadowRoot.appendChild(result.fragment);
// Wire events + two-way bindings on the live shadow DOM
this.wireEvents(this.activeController, this.shadowRoot);
this.wireViewChildren(this.activeController, this.shadowRoot);
this.activeController.onAfterRender();
this._rendering = false;
if (this._pendingUpdate) {
this.updateActiveComponent();
}
}
// ─── Subsequent updates: patch bindings only ───
updateActiveComponent() {
this._rendering = true;
this._pendingUpdate = false;
this.activeController.onBeforeRender();
this.activeRenderResult.update(this.activeController);
this.activeController.onAfterRender();
this._rendering = false;
if (this._pendingUpdate) {
this.updateActiveComponent();
}
}
// ─── ViewChild wiring ───
wireViewChildren(controller, root) {
Object.entries(controller)
.filter(([_, value]) => value instanceof ViewChild)
.forEach(([key, viewChild]) => {
if (viewChild._id) {
const el = root.querySelector(`#${viewChild._id}`);
if (el) viewChild._setValue(el);
} else if (viewChild._selector) {
const el = root.querySelector(viewChild._selector);
if (el) viewChild._setValue(el);
} else {
console.warn(`ViewChild ${key}: no selector or id`);
}
});
}
// ─── Event wiring ───
// Supports:
// (click)="methodName()" — event binding
// [(value)]="propName" — two-way binding (banana-in-a-box)
wireEvents(controller, root) {
const allElements = root.querySelectorAll("*");
allElements.forEach((element) => {
// ─── Two-way bindings from __templateMeta ───
if (element.__templateMeta) {
for (const meta of element.__templateMeta) {
if (meta.bracket === "[()]" && meta.expression) {
const domProp = meta.name.replace(/^\(|\)$/g, ""); // strip parens
this._bindTwoWay(controller, element, domProp, meta.expression);
}
}
}
// ─── Event bindings from DOM attributes ───
for (const attr of Array.from(element.attributes)) {
const name = attr.name;
const eventMatch = name.match(/^\((\w+)\)$/);
if (eventMatch) {
const eventName = eventMatch[1];
const attrValue = attr.value.trim();
const methodName = attrValue.endsWith("()")
? attrValue.slice(0, -2)
: attrValue;
let binding;
if (typeof controller[methodName] === "function") {
const handler = controller[methodName].bind(controller);
binding = new EventBinding(eventName, element, handler);
} else {
const fn = new Function("event", attrValue).bind(controller);
binding = new EventBinding(eventName, element, fn);
}
binding.attach();
controller._eventBindings.push(binding);
}
}
});
}
// ─── Two-way bind: DOM property ↔ controller field ───
// Sets DOM prop from controller on each update.
// Listens for input/change events to write back to controller.
_bindTwoWay(controller, element, domProp, field) {
// Controller → DOM: set initial value
const getValue = () => {
const v = controller[field];
return typeof v === "function" ? v() : v;
};
element[domProp] = getValue() ?? "";
// DOM → Controller: on input (for text) + change (for select/checkbox)
const writeBack = () => {
const domValue = element[domProp];
if (controller[field] instanceof ComponentInput) {
controller[field].set(domValue);
} else {
controller[field] = domValue;
}
};
const inputBinding = new EventBinding("input", element, writeBack);
const changeBinding = new EventBinding("change", element, writeBack);
inputBinding.attach();
changeBinding.attach();
controller._eventBindings.push(inputBinding, changeBinding);
// Controller → DOM: patch on every update via RenderResult hook
// We piggyback on requestUpdate listener — the attr binding in
// node-template handles {{expr}} attrs, but for [(prop)] we need
// to sync the DOM *property* (not attribute) on update.
const updateBinding = new EventBinding("requestUpdate", controller, () => {
const val = getValue() ?? "";
if (element[domProp] !== val) element[domProp] = val;
});
updateBinding.attach();
controller._eventBindings.push(updateBinding);
}
// ─── Component instance creation ───
createComponentInstance(component, params) {
const instance = new component();
// Wire _owner for ComponentInput reactivity
for (const key of Object.keys(instance)) {
const val = instance[key];
if (val instanceof ComponentInput) {
val._self._owner = instance;
}
}
instance.onInit();
// Bind route/query params → ComponentInputs (by name or alias)
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;
}
// ─── Template caching ───
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) {
return new NodeTemplate(
`<div class="error"><h1>Failed to load template</h1><p>${response.status} ${response.statusText}</p></div>`,
);
}
templateContent = await response.text();
}
try {
const template = new NodeTemplate(templateContent);
this.templateCache.set(route.id, template);
return template;
} catch (error) {
return new NodeTemplate(
`<div class="error"><h1>Failed to compile template</h1><p>${error.message}</p></div>`,
);
}
}
}
File diff suppressed because it is too large. Load diff
+65
View File
@@ -0,0 +1,65 @@
import { initRouter, Route, ViewChild, Component, ComponentInput, ComponentDefinition } from "./node-pwa.js";
import { IntInput } from "./utils.js";
class TestComponent extends Component {
static get definition() {
return new ComponentDefinition({
name: "test-component",
template: `<div>
<h1>Test Component</h1>
<p>This is a test component.</p>
<button
id="test-button"
[class.red-button]="count() % 2 === 0"
[class.green-button]="count() % 2 !== 0"
class="counter-button"
(click)="incrementCount()"
>Count: {{count()}}</button>
<input type="text" [(value)]="name" placeholder="Enter your name" />
<p>Hello, {{name()}}! Counter is {{count()}}</p>
</div>`,
style: `
.red-button {
background-color: red;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.green-button {
background-color: green;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.counter-button {
border-radius: 10px;
margin: 15px 30px;
font-size: 18px;
transition: opacity 0.3s ease;
}
.counter-button:hover {
opacity: 0.8;
}
`
});
}
count = new ComponentInput(0, IntInput);
name = new ComponentInput("World");
incrementCount() {
const currentCount = this.count();
this.count.set(currentCount + 1);
}
}
const route1 = new Route("/counter", TestComponent);
const route2 = new Route("/counter/:count", TestComponent);
initRouter("routerOutlet", [route1, route2]);
+432
View File
@@ -0,0 +1,432 @@
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>
`);
}
}
}
+394 -373
View File
@@ -1,455 +1,476 @@
import './linq.js' import "./linq.js";
function selectPath(data, expression) { function selectPath(data, expression) {
if (!expression) return data; if (!expression) return data;
try { try {
return new Function('$data', `with($data) { return (${expression}); }`)(data); return new Function("$data", `with($data) { return (${expression}); }`)(
} catch { data,
console.error(`Error evaluating Template expression: ${expression}`); );
return undefined; } catch {
} console.error(`Error evaluating Template expression: ${expression}`);
return undefined;
}
} }
class ScopeDict { class ScopeDict {
constructor(initial = {}) { constructor(initial = {}) {
this._entries = { ...initial }; this._entries = { ...initial };
} }
set(name, value) { set(name, value) {
if (name.startsWith('$')) { if (name.startsWith("$")) {
throw new Error(`Cannot declare '${name}' with @let. Variables starting with '$' are reserved.`); throw new Error(
} `Cannot declare '${name}' with @let. Variables starting with '$' are reserved.`,
this._entries[name] = value; );
} }
this._entries[name] = value;
}
setBuiltin(name, value) { setBuiltin(name, value) {
this._entries[name] = value; this._entries[name] = value;
} }
has(name) { has(name) {
return name in this._entries; return name in this._entries;
} }
get(name) { get(name) {
return this._entries[name]; return this._entries[name];
} }
clone() { clone() {
return new ScopeDict(this._entries); return new ScopeDict(this._entries);
} }
} }
function createScopeProxy(data, scope) { function createScopeProxy(data, scope) {
if (data === null || data === undefined || typeof data !== 'object') { if (data === null || data === undefined || typeof data !== "object") {
scope.setBuiltin('$this', data); scope.setBuiltin("$this", data);
return new Proxy({}, { return new Proxy(
get(_target, prop) { {},
if (prop === '$this') return data; {
if (scope.has(prop)) return scope.get(prop); get(_target, prop) {
return undefined; if (prop === "$this") return data;
}, if (scope.has(prop)) return scope.get(prop);
has(_target, prop) { return undefined;
return prop === '$this' || scope.has(prop);
}
});
}
scope.setBuiltin('$this', data);
return new Proxy(data, {
get(target, prop) {
if (prop === '$this') return data;
if (scope.has(prop)) return scope.get(prop);
return target[prop];
}, },
has(target, prop) { has(_target, prop) {
return prop === '$this' || scope.has(prop) || prop in target; return prop === "$this" || scope.has(prop);
} },
}); },
);
}
scope.setBuiltin("$this", data);
return new Proxy(data, {
get(target, prop) {
if (prop === "$this") return data;
if (scope.has(prop)) return scope.get(prop);
return target[prop];
},
has(target, prop) {
return prop === "$this" || scope.has(prop) || prop in target;
},
});
} }
function skipString(str, i) { function skipString(str, i) {
const quote = str[i]; const quote = str[i];
i++;
while (i < str.length && str[i] !== quote) {
if (str[i] === "\\") i++;
i++; i++;
while (i < str.length && str[i] !== quote) { }
if (str[i] === '\\') i++; return i;
i++;
}
return i;
} }
function findClosingParen(str, openPos) { function findClosingParen(str, openPos) {
let depth = 1; let depth = 1;
let i = openPos + 1; let i = openPos + 1;
while (i < str.length && depth > 0) { while (i < str.length && depth > 0) {
if (str[i] === "'" || str[i] === '"' || str[i] === '`') { if (str[i] === "'" || str[i] === '"' || str[i] === "`") {
i = skipString(str, i) + 1; i = skipString(str, i) + 1;
continue; continue;
}
if (str[i] === '(') depth++;
else if (str[i] === ')') depth--;
if (depth > 0) i++;
} }
if (depth !== 0) throw new Error('Unclosed ( in template'); if (str[i] === "(") depth++;
return i; else if (str[i] === ")") depth--;
if (depth > 0) i++;
}
if (depth !== 0) throw new Error("Unclosed ( in template");
return i;
} }
function findClosingBrace(str, openPos) { function findClosingBrace(str, openPos) {
let depth = 1; let depth = 1;
let i = openPos + 1; let i = openPos + 1;
while (i < str.length && depth > 0) { while (i < str.length && depth > 0) {
if (str[i] === "'" || str[i] === '"' || str[i] === '`') { if (str[i] === "'" || str[i] === '"' || str[i] === "`") {
i = skipString(str, i) + 1; i = skipString(str, i) + 1;
continue; continue;
}
if (str[i] === '{' && str[i + 1] === '{') {
const end = str.indexOf('}}', i + 2);
if (end === -1) throw new Error('Unclosed {{ }} in template');
i = end + 2;
continue;
}
if (str[i] === '{') depth++;
else if (str[i] === '}') depth--;
if (depth > 0) i++;
} }
if (depth !== 0) throw new Error('Unclosed { in template'); if (str[i] === "{" && str[i + 1] === "{") {
return i; const end = str.indexOf("}}", i + 2);
} if (end === -1) throw new Error("Unclosed {{ }} in template");
i = end + 2;
function findTopLevelComma(str) { continue;
let depth = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === "'" || str[i] === '"' || str[i] === '`') {
i = skipString(str, i);
continue;
}
if (str[i] === '(') depth++;
else if (str[i] === ')') depth--;
else if (str[i] === ',' && depth === 0) return i;
} }
return -1; if (str[i] === "{") depth++;
else if (str[i] === "}") depth--;
if (depth > 0) i++;
}
if (depth !== 0) throw new Error("Unclosed { in template");
return i;
} }
function formatNumber(value, spec) { function formatNumber(value, spec) {
const hasThousands = spec.includes(','); const hasThousands = spec.includes(",");
const dotIdx = spec.indexOf('.'); const dotIdx = spec.indexOf(".");
let decimals = 0; let decimals = 0;
if (dotIdx !== -1) { if (dotIdx !== -1) {
decimals = spec.length - dotIdx - 1; decimals = spec.length - dotIdx - 1;
}
let result = value.toFixed(decimals);
if (hasThousands) {
const parts = result.split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
result = parts.join(".");
}
if (!spec.includes(".") && !hasThousands) {
const padLength = spec.replace(/[^0]/g, "").length;
if (padLength > 0) {
const isNeg = value < 0;
let abs = Math.abs(Math.round(value)).toString();
abs = abs.padStart(padLength, "0");
result = isNeg ? "-" + abs : abs;
} }
}
let result = value.toFixed(decimals); return result;
if (hasThousands) {
const parts = result.split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
result = parts.join('.');
}
if (!spec.includes('.') && !hasThousands) {
const padLength = spec.replace(/[^0]/g, '').length;
if (padLength > 0) {
const isNeg = value < 0;
let abs = Math.abs(Math.round(value)).toString();
abs = abs.padStart(padLength, '0');
result = isNeg ? '-' + abs : abs;
}
}
return result;
} }
function formatDate(date, spec) { function formatDate(date, spec) {
const pad = (n, len = 2) => String(n).padStart(len, '0'); const pad = (n, len = 2) => String(n).padStart(len, "0");
const tokens = { const tokens = {
'yyyy': date.getFullYear(), yyyy: date.getFullYear(),
'yy': String(date.getFullYear()).slice(-2), yy: String(date.getFullYear()).slice(-2),
'MM': pad(date.getMonth() + 1), MM: pad(date.getMonth() + 1),
'M': date.getMonth() + 1, M: date.getMonth() + 1,
'dd': pad(date.getDate()), dd: pad(date.getDate()),
'd': date.getDate(), d: date.getDate(),
'HH': pad(date.getHours()), HH: pad(date.getHours()),
'H': date.getHours(), H: date.getHours(),
'hh': pad(date.getHours() % 12 || 12), hh: pad(date.getHours() % 12 || 12),
'h': date.getHours() % 12 || 12, h: date.getHours() % 12 || 12,
'mm': pad(date.getMinutes()), mm: pad(date.getMinutes()),
'm': date.getMinutes(), m: date.getMinutes(),
'ss': pad(date.getSeconds()), ss: pad(date.getSeconds()),
's': date.getSeconds(), s: date.getSeconds(),
'fff': pad(date.getMilliseconds(), 3), fff: pad(date.getMilliseconds(), 3),
}; };
let result = spec; let result = spec;
for (const [token, value] of Object.entries(tokens).sort((a, b) => b[0].length - a[0].length)) { for (const [token, value] of Object.entries(tokens).sort(
result = result.replaceAll(token, String(value)); (a, b) => b[0].length - a[0].length,
} )) {
result = result.replaceAll(token, String(value));
}
return result; return result;
} }
function createFormatter(formatSpec) { function createFormatter(formatSpec) {
return (value) => { return (value) => {
if (value == null) return ''; if (value == null) return "";
if (value instanceof Date) return formatDate(value, formatSpec); if (value instanceof Date) return formatDate(value, formatSpec);
if (typeof value === 'number') return formatNumber(value, formatSpec); if (typeof value === "number") return formatNumber(value, formatSpec);
return String(value); return String(value);
}; };
} }
class StaticTemplatePart { class StaticTemplatePart {
constructor(text) { constructor(text) {
this.text = text; this.text = text;
} }
render(_data) { render(_data) {
return this.text; return this.text;
} }
} }
class VariableTemplatePart { class VariableTemplatePart {
constructor(contextPath, formatter) { constructor(contextPath, formatter) {
this.contextPath = contextPath; this.contextPath = contextPath;
this.formatter = formatter || (x => x); this.formatter = formatter || ((x) => x);
} }
render(data) { render(data) {
return this.formatter(selectPath(data, this.contextPath)); return this.formatter(selectPath(data, this.contextPath));
} }
} }
class LetTemplatePart { class LetTemplatePart {
constructor(name, expression) { constructor(name, expression) {
this.name = name; this.name = name;
this.expression = expression; this.expression = expression;
} }
declareScoped(scope, data) { declareScoped(scope, data) {
scope.set(this.name, selectPath(data, this.expression)); scope.set(this.name, selectPath(data, this.expression));
} }
render(_data) { render(_data) {
return ''; return "";
} }
} }
class ListTemplatePart { class ListTemplatePart {
constructor(varNames, contextPath, innerTemplate, emptyTemplate, formatter) { constructor(varNames, contextPath, innerTemplate, emptyTemplate, formatter) {
this.varNames = varNames; this.varNames = varNames;
this.contextPath = contextPath; this.contextPath = contextPath;
this.formatter = formatter || (x => x); this.formatter = formatter || ((x) => x);
this.innerTemplate = innerTemplate; this.innerTemplate = innerTemplate;
this.emptyTemplate = emptyTemplate; this.emptyTemplate = emptyTemplate;
}
render(data) {
const list = this.formatter(selectPath(data, this.contextPath));
const arr = Array.isArray(list) ? list : Array.from(list);
if (arr.length === 0) {
return this.emptyTemplate ? this.emptyTemplate.render(data) : "";
} }
render(data) { let result = "";
const list = this.formatter(selectPath(data, this.contextPath)); const count = arr.length;
const arr = Array.isArray(list) ? list : Array.from(list); for (let index = 0; index < count; index++) {
const scope = new ScopeDict();
if (arr.length === 0) { const item = arr[index];
return this.emptyTemplate ? this.emptyTemplate.render(data) : ''; if (this.varNames.length === 1) {
scope.setBuiltin(this.varNames[0], item);
} else {
for (let v = 0; v < this.varNames.length; v++) {
scope.setBuiltin(this.varNames[v], item[v]);
} }
}
let result = ''; scope.setBuiltin("$index", index);
const count = arr.length; scope.setBuiltin("$first", index === 0);
for (let index = 0; index < count; index++) { scope.setBuiltin("$last", index === count - 1);
const scope = new ScopeDict(); scope.setBuiltin("$even", index % 2 === 0);
const item = arr[index]; scope.setBuiltin("$odd", index % 2 === 1);
if (this.varNames.length === 1) { scope.setBuiltin("$count", count);
scope.setBuiltin(this.varNames[0], item); result += this.innerTemplate.render(data, scope);
} else {
for (let v = 0; v < this.varNames.length; v++) {
scope.setBuiltin(this.varNames[v], item[v]);
}
}
scope.setBuiltin('$index', index);
scope.setBuiltin('$first', index === 0);
scope.setBuiltin('$last', index === count - 1);
scope.setBuiltin('$even', index % 2 === 0);
scope.setBuiltin('$odd', index % 2 === 1);
scope.setBuiltin('$count', count);
result += this.innerTemplate.render(data, scope);
}
return result;
} }
return result;
}
} }
class ConditionalTemplatePart { class ConditionalTemplatePart {
constructor(contextPath, condition, trueTemplate, falseTemplate, formatter) { constructor(contextPath, condition, trueTemplate, falseTemplate, formatter) {
this.contextPath = contextPath; this.contextPath = contextPath;
this.formatter = formatter || (x => x); this.formatter = formatter || ((x) => x);
this.condition = condition; this.condition = condition;
this.trueTemplate = trueTemplate; this.trueTemplate = trueTemplate;
this.falseTemplate = falseTemplate; this.falseTemplate = falseTemplate;
} }
render(data) { render(data) {
const selectedData = this.formatter(selectPath(data, this.contextPath)); const selectedData = this.formatter(selectPath(data, this.contextPath));
if (this.condition(selectedData)) { if (this.condition(selectedData)) {
return this.trueTemplate ? this.trueTemplate.render(data) : ''; return this.trueTemplate ? this.trueTemplate.render(data) : "";
} else { } else {
return this.falseTemplate ? this.falseTemplate.render(data) : ''; return this.falseTemplate ? this.falseTemplate.render(data) : "";
}
} }
}
} }
export class Template { export class Template {
constructor(templateString) { constructor(templateString) {
if (templateString != null) { if (templateString != null) {
this.parts = this._parseBlock(templateString); this.parts = this._parseBlock(templateString);
}
} }
}
_parseBlock(str) { _parseBlock(str) {
const parts = []; const parts = [];
let i = 0; let i = 0;
while (i < str.length) { while (i < str.length) {
// {{ expression }} or {{ expression:format }} // {{ expression }} or {{ expression:format }}
if (str[i] === '{' && str[i + 1] === '{') { if (str[i] === "{" && str[i + 1] === "{") {
const end = str.indexOf('}}', i + 2); const end = str.indexOf("}}", i + 2);
if (end === -1) throw new Error('Unclosed {{ }}'); if (end === -1) throw new Error("Unclosed {{ }}");
const content = str.substring(i + 2, end).trim(); const content = str.substring(i + 2, end).trim();
let expression, formatter = null; let expression,
const colonIdx = content.lastIndexOf(':'); formatter = null;
if (colonIdx > 0) { const colonIdx = content.lastIndexOf(":");
const possibleFormat = content.substring(colonIdx + 1).trim(); if (colonIdx > 0) {
if (/^[0#.,yMdHhmsafzZ\-\/: ]+$/.test(possibleFormat)) { const possibleFormat = content.substring(colonIdx + 1).trim();
expression = content.substring(0, colonIdx).trim(); if (/^[0#.,yMdHhmsafzZ\-\/: ]+$/.test(possibleFormat)) {
formatter = createFormatter(possibleFormat); expression = content.substring(0, colonIdx).trim();
} else { formatter = createFormatter(possibleFormat);
expression = content; } else {
} expression = content;
} else { }
expression = content; } else {
} expression = content;
parts.push(new VariableTemplatePart(expression, formatter));
i = end + 2;
continue;
}
// @for(item of expression){...} @empty{...}
if (str.startsWith('@for(', i)) {
const parenOpen = i + 4;
const parenClose = findClosingParen(str, parenOpen);
const forClause = str.substring(parenOpen + 1, parenClose).trim();
const ofIdx = forClause.indexOf(' of ');
if (ofIdx === -1) throw new Error('@for missing "of": @for(item of expression)');
const varNames = forClause.substring(0, ofIdx).split(',').map(v => v.trim());
const expression = forClause.substring(ofIdx + 4).trim();
const braceOpen = str.indexOf('{', parenClose + 1);
if (braceOpen === -1) throw new Error('@for missing block');
const braceClose = findClosingBrace(str, braceOpen);
const blockContent = str.substring(braceOpen + 1, braceClose);
const innerTemplate = new Template(null);
innerTemplate.parts = this._parseBlock(blockContent);
let emptyTemplate = null;
let afterBlock = braceClose + 1;
const remaining = str.substring(afterBlock);
const emptyMatch = remaining.match(/^\s*@empty\s*\{/);
if (emptyMatch) {
const emptyBraceOpen = afterBlock + emptyMatch[0].length - 1;
const emptyBraceClose = findClosingBrace(str, emptyBraceOpen);
const emptyContent = str.substring(emptyBraceOpen + 1, emptyBraceClose);
emptyTemplate = new Template(null);
emptyTemplate.parts = this._parseBlock(emptyContent);
afterBlock = emptyBraceClose + 1;
}
parts.push(new ListTemplatePart(varNames, expression, innerTemplate, emptyTemplate));
i = afterBlock;
continue;
}
// @if(expression){...}@else{...}
if (str.startsWith('@if(', i)) {
const parenOpen = i + 3;
const parenClose = findClosingParen(str, parenOpen);
const expression = str.substring(parenOpen + 1, parenClose).trim();
const trueBraceOpen = str.indexOf('{', parenClose + 1);
if (trueBraceOpen === -1) throw new Error('@if missing block');
const trueBraceClose = findClosingBrace(str, trueBraceOpen);
const trueContent = str.substring(trueBraceOpen + 1, trueBraceClose);
const trueTemplate = new Template(null);
trueTemplate.parts = this._parseBlock(trueContent);
let falseTemplate = null;
let afterBlock = trueBraceClose + 1;
const remaining = str.substring(afterBlock);
const elseMatch = remaining.match(/^\s*@else\s*\{/);
if (elseMatch) {
const falseBraceOpen = afterBlock + elseMatch[0].length - 1;
const falseBraceClose = findClosingBrace(str, falseBraceOpen);
const falseContent = str.substring(falseBraceOpen + 1, falseBraceClose);
falseTemplate = new Template(null);
falseTemplate.parts = this._parseBlock(falseContent);
afterBlock = falseBraceClose + 1;
}
parts.push(new ConditionalTemplatePart(expression, val => !!val, trueTemplate, falseTemplate));
i = afterBlock;
continue;
}
// @let name = expression (ends at newline or end of string)
if (str.startsWith('@let ', i)) {
const lineEnd = str.indexOf('\n', i);
const end = lineEnd === -1 ? str.length : lineEnd;
const declaration = str.substring(i + 5, end).trim();
const eqIdx = declaration.indexOf('=');
if (eqIdx === -1) throw new Error('Invalid @let: missing =');
const name = declaration.substring(0, eqIdx).trim();
const expression = declaration.substring(eqIdx + 1).trim();
parts.push(new LetTemplatePart(name, expression));
i = end + 1;
continue;
}
// Static text — collect until next special token
let end = i;
while (end < str.length) {
if (str[end] === '{' && str[end + 1] === '{') break;
if (str[end] === '@' && (
str.startsWith('@for(', end) ||
str.startsWith('@if(', end) ||
str.startsWith('@let ', end)
)) break;
end++;
}
if (end > i) {
parts.push(new StaticTemplatePart(str.substring(i, end)));
i = end;
}
} }
return parts; parts.push(new VariableTemplatePart(expression, formatter));
} i = end + 2;
continue;
}
render(data, parentScope = new ScopeDict()) { // @for(item of expression){...} @empty{...}
const scope = parentScope.clone(); if (str.startsWith("@for(", i)) {
const proxy = createScopeProxy(data, scope); const parenOpen = i + 4;
const parenClose = findClosingParen(str, parenOpen);
const forClause = str.substring(parenOpen + 1, parenClose).trim();
let result = ''; const ofIdx = forClause.indexOf(" of ");
for (const part of this.parts) { if (ofIdx === -1)
part.declareScoped?.(scope, proxy); throw new Error('@for missing "of": @for(item of expression)');
result += part.render(proxy); const varNames = forClause
.substring(0, ofIdx)
.split(",")
.map((v) => v.trim());
const expression = forClause.substring(ofIdx + 4).trim();
const braceOpen = str.indexOf("{", parenClose + 1);
if (braceOpen === -1) throw new Error("@for missing block");
const braceClose = findClosingBrace(str, braceOpen);
const blockContent = str.substring(braceOpen + 1, braceClose);
const innerTemplate = new Template(null);
innerTemplate.parts = this._parseBlock(blockContent);
let emptyTemplate = null;
let afterBlock = braceClose + 1;
const remaining = str.substring(afterBlock);
const emptyMatch = remaining.match(/^\s*@empty\s*\{/);
if (emptyMatch) {
const emptyBraceOpen = afterBlock + emptyMatch[0].length - 1;
const emptyBraceClose = findClosingBrace(str, emptyBraceOpen);
const emptyContent = str.substring(
emptyBraceOpen + 1,
emptyBraceClose,
);
emptyTemplate = new Template(null);
emptyTemplate.parts = this._parseBlock(emptyContent);
afterBlock = emptyBraceClose + 1;
} }
return result;
parts.push(
new ListTemplatePart(
varNames,
expression,
innerTemplate,
emptyTemplate,
),
);
i = afterBlock;
continue;
}
// @if(expression){...}@else{...}
if (str.startsWith("@if(", i)) {
const parenOpen = i + 3;
const parenClose = findClosingParen(str, parenOpen);
const expression = str.substring(parenOpen + 1, parenClose).trim();
const trueBraceOpen = str.indexOf("{", parenClose + 1);
if (trueBraceOpen === -1) throw new Error("@if missing block");
const trueBraceClose = findClosingBrace(str, trueBraceOpen);
const trueContent = str.substring(trueBraceOpen + 1, trueBraceClose);
const trueTemplate = new Template(null);
trueTemplate.parts = this._parseBlock(trueContent);
let falseTemplate = null;
let afterBlock = trueBraceClose + 1;
const remaining = str.substring(afterBlock);
const elseMatch = remaining.match(/^\s*@else\s*\{/);
if (elseMatch) {
const falseBraceOpen = afterBlock + elseMatch[0].length - 1;
const falseBraceClose = findClosingBrace(str, falseBraceOpen);
const falseContent = str.substring(
falseBraceOpen + 1,
falseBraceClose,
);
falseTemplate = new Template(null);
falseTemplate.parts = this._parseBlock(falseContent);
afterBlock = falseBraceClose + 1;
}
parts.push(
new ConditionalTemplatePart(
expression,
(val) => !!val,
trueTemplate,
falseTemplate,
),
);
i = afterBlock;
continue;
}
// @let name = expression (ends at newline or end of string)
if (str.startsWith("@let ", i)) {
const lineEnd = str.indexOf("\n", i);
const end = lineEnd === -1 ? str.length : lineEnd;
const declaration = str.substring(i + 5, end).trim();
const eqIdx = declaration.indexOf("=");
if (eqIdx === -1) throw new Error("Invalid @let: missing =");
const name = declaration.substring(0, eqIdx).trim();
const expression = declaration.substring(eqIdx + 1).trim();
parts.push(new LetTemplatePart(name, expression));
i = end + 1;
continue;
}
// Static text — collect until next special token
let end = i;
while (end < str.length) {
if (str[end] === "{" && str[end + 1] === "{") break;
if (
str[end] === "@" &&
(str.startsWith("@for(", end) ||
str.startsWith("@if(", end) ||
str.startsWith("@let ", end))
)
break;
end++;
}
if (end > i) {
parts.push(new StaticTemplatePart(str.substring(i, end)));
i = end;
}
} }
return parts;
}
render(data, parentScope = new ScopeDict()) {
const scope = parentScope.clone();
const proxy = createScopeProxy(data, scope);
let result = "";
for (const part of this.parts) {
part.declareScoped?.(scope, proxy);
result += part.render(proxy);
}
return result;
}
} }
+55
View File
@@ -0,0 +1,55 @@
import {
initRouter,
Route,
ViewChild,
Component,
ComponentInput,
ComponentDefinition,
} from "./pwa.js";
class TestComponent extends Component {
static get definition() {
return new ComponentDefinition({
name: "test-component",
template: `<div>
<h1>Test Component</h1>
<p>This is a test component.</p>
<button
id="test-button"
(click)="incrementCount()"
[class.green-button]="count % 2 !== 0"
[class.red-button]="count % 2 === 0"
>Count: {{count}}</button>
</div>`,
style: `
.red-button {
background-color: red;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.green-button {
background-color: green;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
`
});
}
count = new ComponentInput(0);
incrementCount() {
this.count++;
}
}
const route1 = new Route("/counter", TestComponent);
const route2 = new Route("/counter/:count", TestComponent);
initRouter("routerOutlet", "styleOutlet", [route1, route2]);
+204
View File
@@ -0,0 +1,204 @@
// ─── parseDate (C# DateTime.ParseExact style) ───
// Parses a date string using an exact format pattern.
// Supported tokens:
// yyyy — 4-digit year
// yy — 2-digit year (assumes 2000+)
// MM — 2-digit month (01–12)
// M — 1 or 2-digit month
// dd — 2-digit day (01–31)
// d — 1 or 2-digit day
// HH — 2-digit hour 24h (00–23)
// H — 1 or 2-digit hour 24h
// hh — 2-digit hour 12h (01–12)
// h — 1 or 2-digit hour 12h
// mm — 2-digit minute (00–59)
// m — 1 or 2-digit minute
// ss — 2-digit second (00–59)
// s — 1 or 2-digit second
// fff — 3-digit milliseconds
// ff — 2-digit (tenths + hundredths)
// f — 1-digit (tenths)
// tt — AM/PM
// t — A/P
// Z — literal 'Z' (UTC marker)
// K — timezone offset (+HH:mm, -HH:mm, or Z)
//
// All other characters are matched literally.
// Returns Date on success, null on failure.
const TOKEN_ORDER = [
"yyyy", "yy",
"MM", "M",
"dd", "d",
"HH", "H", "hh", "h",
"mm", "m",
"ss", "s",
"fff", "ff", "f",
"tt", "t",
"K", "Z",
];
const TOKEN_PATTERNS = {
yyyy: "(\\d{4})",
yy: "(\\d{2})",
MM: "(\\d{2})",
M: "(\\d{1,2})",
dd: "(\\d{2})",
d: "(\\d{1,2})",
HH: "(\\d{2})",
H: "(\\d{1,2})",
hh: "(\\d{2})",
h: "(\\d{1,2})",
mm: "(\\d{2})",
m: "(\\d{1,2})",
ss: "(\\d{2})",
s: "(\\d{1,2})",
fff: "(\\d{3})",
ff: "(\\d{2})",
f: "(\\d{1})",
tt: "(AM|PM|am|pm)",
t: "([AaPp])",
K: "(Z|[+-]\\d{2}:\\d{2})",
Z: "(Z)",
};
function buildFormatRegex(format) {
const groups = [];
let regexStr = "";
let i = 0;
while (i < format.length) {
let matched = false;
for (const token of TOKEN_ORDER) {
if (format.startsWith(token, i)) {
groups.push(token);
regexStr += TOKEN_PATTERNS[token];
i += token.length;
matched = true;
break;
}
}
if (!matched) {
// Escape literal character
regexStr += format[i].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
i++;
}
}
return { regex: new RegExp("^" + regexStr + "$"), groups };
}
export function parseDate(input, format) {
if (input == null || format == null) return null;
if (input instanceof Date) return input;
const str = String(input);
const { regex, groups } = buildFormatRegex(format);
const match = str.match(regex);
if (!match) return null;
let year = 0, month = 1, day = 1;
let hour = 0, minute = 0, second = 0, ms = 0;
let isPM = false, isAM = false;
let tzOffset = null; // minutes
for (let g = 0; g < groups.length; g++) {
const token = groups[g];
const val = match[g + 1];
switch (token) {
case "yyyy": year = parseInt(val, 10); break;
case "yy": year = 2000 + parseInt(val, 10); break;
case "MM":
case "M": month = parseInt(val, 10); break;
case "dd":
case "d": day = parseInt(val, 10); break;
case "HH":
case "H": hour = parseInt(val, 10); break;
case "hh":
case "h": hour = parseInt(val, 10); break;
case "mm":
case "m": minute = parseInt(val, 10); break;
case "ss":
case "s": second = parseInt(val, 10); break;
case "fff": ms = parseInt(val, 10); break;
case "ff": ms = parseInt(val, 10) * 10; break;
case "f": ms = parseInt(val, 10) * 100; break;
case "tt": isPM = val.toUpperCase() === "PM"; isAM = val.toUpperCase() === "AM"; break;
case "t": isPM = val.toUpperCase() === "P"; isAM = val.toUpperCase() === "A"; break;
case "Z": tzOffset = 0; break;
case "K":
if (val === "Z") {
tzOffset = 0;
} else {
const sign = val[0] === "+" ? 1 : -1;
const [h, m] = val.substring(1).split(":").map(Number);
tzOffset = sign * (h * 60 + m);
}
break;
}
}
// 12h → 24h conversion
if (isPM && hour < 12) hour += 12;
if (isAM && hour === 12) hour = 0;
if (tzOffset !== null) {
// Build UTC date, apply offset
const utcMs = Date.UTC(year, month - 1, day, hour, minute, second, ms);
return new Date(utcMs - tzOffset * 60000);
}
return new Date(year, month - 1, day, hour, minute, second, ms);
}
export function formatDate(date, spec) {
const pad = (n, l = 2) => String(n).padStart(l, "0");
const tokens = {
yyyy: date.getFullYear(),
yy: String(date.getFullYear()).slice(-2),
MM: pad(date.getMonth() + 1),
M: date.getMonth() + 1,
dd: pad(date.getDate()),
d: date.getDate(),
HH: pad(date.getHours()),
H: date.getHours(),
hh: pad(date.getHours() % 12 || 12),
h: date.getHours() % 12 || 12,
mm: pad(date.getMinutes()),
m: date.getMinutes(),
ss: pad(date.getSeconds()),
s: date.getSeconds(),
fff: pad(date.getMilliseconds(), 3),
};
let result = spec;
for (const [tok, val] of Object.entries(tokens).sort(
(a, b) => b[0].length - a[0].length,
)) {
result = result.replaceAll(tok, String(val));
}
return result;
}
// ─── Input transform presets ───
export const IntInput = { transform: parseInt };
export const FloatInput = { transform: parseFloat };
export const BoolInput = {
transform: (v) => {
if (typeof v === "boolean") return v;
if (typeof v === "string") {
if (v.toLowerCase() === "true") return true;
if (v.toLowerCase() === "false") return false;
}
return Boolean(v);
},
};
export function DateInput(format) {
return {
transform: (v) => parseDate(v, format),
};
}
export const IsoDateInput = DateInput("yyyy-MM-ddTHH:mm:ssK");
+2 -2
View File
@@ -216,7 +216,7 @@
</div> </div>
<script> <script>
fetch('../html/sidebar.html') fetch('/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -229,7 +229,7 @@
if (secondLink) secondLink.classList.add('active'); if (secondLink) secondLink.classList.add('active');
}); });
fetch('../html/topbar.html') fetch('/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
</script> </script>
+2 -2
View File
@@ -93,7 +93,7 @@
<script> <script>
// Fetch sidebar and topbar // Fetch sidebar and topbar
fetch('../html/sidebar.html') fetch('/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -106,7 +106,7 @@
if (marketplaceLink) marketplaceLink.classList.add('active'); if (marketplaceLink) marketplaceLink.classList.add('active');
}); });
fetch('../html/topbar.html') fetch('/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
</script> </script>
+2 -2
View File
@@ -90,7 +90,7 @@
</div> </div>
<script> <script>
fetch('../html/sidebar.html') fetch('/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -103,7 +103,7 @@
if (profileLink) profileLink.classList.add('active'); if (profileLink) profileLink.classList.add('active');
}); });
fetch('../html/topbar.html') fetch('/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
</script> </script>
+2 -2
View File
@@ -179,7 +179,7 @@
}); });
// Fetch sidebar and topbar // Fetch sidebar and topbar
fetch('../html/sidebar.html') fetch('/sidebar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => { .then(data => {
document.getElementById('sidebar-container').innerHTML = data; document.getElementById('sidebar-container').innerHTML = data;
@@ -189,7 +189,7 @@
const settingsLink = document.querySelector('#sidebar-container a[href="settings.html"]'); const settingsLink = document.querySelector('#sidebar-container a[href="settings.html"]');
if (settingsLink) settingsLink.classList.add('active'); if (settingsLink) settingsLink.classList.add('active');
}); });
fetch('../html/topbar.html') fetch('/topbar.html')
.then(r => r.text()) .then(r => r.text())
.then(data => document.getElementById('topbar-container').innerHTML = data); .then(data => document.getElementById('topbar-container').innerHTML = data);
</script> </script>
+4 -2
View File
@@ -67,12 +67,14 @@
<!-- Logout bottom --> <!-- Logout bottom -->
<div class="sidebar-bottom"> <div class="sidebar-bottom">
<a href="login.html" class="sidebar-logout"> <form action="/api/v1/auth/logout" method="post">
<button type="submit" class="sidebar-logout">
<div class="logout-left"> <div class="logout-left">
<i class="bi bi-box-arrow-right"></i> <i class="bi bi-box-arrow-right"></i>
<span class="nav-text">Logout</span> <span class="nav-text">Logout</span>
</div> </div>
<i class="bi bi-chevron-right logout-arrow"></i> <i class="bi bi-chevron-right logout-arrow"></i>
</a> </button>
</form>
</div> </div>
</div> </div>
+28
View File
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OnlyPrompt - Test</title>
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/base.css">
<div id="styleOutlet">
</div>
</head>
<body>
<div>
<h1>Test Site</h1>
<a href="/counter/1">Go to count 1</a>
<a href="/counter/2">Go to count 2</a>
<a href="/counter/3">Go to count 3</a>
<div id="routerOutlet">
Hello There
</div>
</div>
<script type="module" src="./js/node-test.js"></script>
</body>
</html>