Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63ee71a19b |
No files matched your search
@@ -16,7 +16,7 @@ namespace OnlyPrompt.Backend.Controllers
|
||||
[Route("api/v1/auth")]
|
||||
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 ITokenService _jwtService;
|
||||
private readonly ILogger<AuthController> _logger;
|
||||
@@ -103,7 +103,18 @@ namespace OnlyPrompt.Backend.Controllers
|
||||
public RedirectHttpResult Logout()
|
||||
{
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,7 @@ var rewrite = new RewriteOptions()
|
||||
.AddRewrite(@"^(?!scalar\/?|api\/?)([^.]+)$", "$1.html", skipRemainingRules: true);
|
||||
|
||||
app.UseRewriter(rewrite);
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
@@ -97,6 +98,13 @@ else
|
||||
}
|
||||
|
||||
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");
|
||||
using var scope = app.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<OnlyPromptContext>();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"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": {
|
||||
"Issuer": "https://onlyprompts.com",
|
||||
|
||||
@@ -108,7 +108,7 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
fetch('../html/sidebar.html')
|
||||
fetch('/sidebar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => {
|
||||
document.getElementById('sidebar-container').innerHTML = data;
|
||||
@@ -121,7 +121,7 @@
|
||||
if (chatsLink) chatsLink.classList.add('active');
|
||||
});
|
||||
|
||||
fetch('../html/topbar.html')
|
||||
fetch('/topbar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => document.getElementById('topbar-container').innerHTML = data);
|
||||
</script>
|
||||
|
||||
@@ -140,7 +140,7 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
fetch('../html/sidebar.html')
|
||||
fetch('/sidebar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => {
|
||||
document.getElementById('sidebar-container').innerHTML = data;
|
||||
@@ -153,7 +153,7 @@
|
||||
if (thirdLink) thirdLink.classList.add('active');
|
||||
});
|
||||
|
||||
fetch('../html/topbar.html')
|
||||
fetch('/topbar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => document.getElementById('topbar-container').innerHTML = data);
|
||||
</script>
|
||||
|
||||
@@ -160,7 +160,7 @@
|
||||
});
|
||||
|
||||
// Fetch sidebar and topbar
|
||||
fetch('../html/sidebar.html')
|
||||
fetch('/sidebar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => {
|
||||
document.getElementById('sidebar-container').innerHTML = data;
|
||||
@@ -173,7 +173,7 @@
|
||||
if (createLink) createLink.classList.add('active');
|
||||
});
|
||||
|
||||
fetch('../html/topbar.html')
|
||||
fetch('/topbar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => document.getElementById('topbar-container').innerHTML = data);
|
||||
</script>
|
||||
|
||||
@@ -100,13 +100,22 @@
|
||||
padding-top: 16px;
|
||||
}
|
||||
|
||||
.sidebar-bottom form {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.sidebar-logout {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
padding: 12px 16px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
color: #64748b;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
transition: background 0.2s ease;
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
fetch('../html/sidebar.html')
|
||||
fetch('/sidebar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => {
|
||||
document.getElementById('sidebar-container').innerHTML = data;
|
||||
@@ -158,7 +158,7 @@
|
||||
if (firstLink) firstLink.classList.add('active');
|
||||
});
|
||||
|
||||
fetch('../html/topbar.html')
|
||||
fetch('/topbar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => document.getElementById('topbar-container').innerHTML = data);
|
||||
</script>
|
||||
|
||||
+126
-116
@@ -1,140 +1,150 @@
|
||||
// LINQ-like Enumerable class wrapping lazy generator chains
|
||||
|
||||
class Enumerable {
|
||||
constructor(iteratorFn) {
|
||||
this._iteratorFn = iteratorFn;
|
||||
}
|
||||
constructor(iteratorFn) {
|
||||
this._iteratorFn = iteratorFn;
|
||||
}
|
||||
|
||||
[Symbol.iterator]() {
|
||||
return this._iteratorFn();
|
||||
}
|
||||
[Symbol.iterator]() {
|
||||
return this._iteratorFn();
|
||||
}
|
||||
|
||||
_chain(generatorFn) {
|
||||
const source = this;
|
||||
return new Enumerable(function* () {
|
||||
yield* generatorFn(source);
|
||||
});
|
||||
}
|
||||
_chain(generatorFn) {
|
||||
const source = this;
|
||||
return new Enumerable(function* () {
|
||||
yield* generatorFn(source);
|
||||
});
|
||||
}
|
||||
|
||||
where(predicate) {
|
||||
return this._chain(function* (source) {
|
||||
for (const item of source)
|
||||
if (predicate(item))
|
||||
yield item;
|
||||
});
|
||||
}
|
||||
where(predicate) {
|
||||
return this._chain(function* (source) {
|
||||
for (const item of source) if (predicate(item)) yield item;
|
||||
});
|
||||
}
|
||||
|
||||
select(selector) {
|
||||
return this._chain(function* (source) {
|
||||
for (const item of source)
|
||||
yield selector(item);
|
||||
});
|
||||
}
|
||||
select(selector) {
|
||||
return this._chain(function* (source) {
|
||||
for (const item of source) yield selector(item);
|
||||
});
|
||||
}
|
||||
|
||||
take(count) {
|
||||
count = Math.max(0, count);
|
||||
return this._chain(function* (source) {
|
||||
for (const item of source) {
|
||||
if (count-- <= 0) break;
|
||||
yield item;
|
||||
}
|
||||
});
|
||||
}
|
||||
take(count) {
|
||||
count = Math.max(0, count);
|
||||
return this._chain(function* (source) {
|
||||
for (const item of source) {
|
||||
if (count-- <= 0) break;
|
||||
yield item;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
skip(count) {
|
||||
count = Math.max(0, count);
|
||||
return this._chain(function* (source) {
|
||||
for (const item of source) {
|
||||
if (count-- > 0) continue;
|
||||
yield item;
|
||||
}
|
||||
});
|
||||
}
|
||||
skip(count) {
|
||||
count = Math.max(0, count);
|
||||
return this._chain(function* (source) {
|
||||
for (const item of source) {
|
||||
if (count-- > 0) continue;
|
||||
yield item;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
isLast() {
|
||||
return this._chain(function* (source) {
|
||||
const iter = source[Symbol.iterator]();
|
||||
let current = iter.next();
|
||||
let index = 0;
|
||||
while (!current.done) {
|
||||
const next = iter.next();
|
||||
yield [current.value, next.done, index];
|
||||
current = next;
|
||||
index++;
|
||||
}
|
||||
});
|
||||
}
|
||||
isLast() {
|
||||
return this._chain(function* (source) {
|
||||
const iter = source[Symbol.iterator]();
|
||||
let current = iter.next();
|
||||
let index = 0;
|
||||
while (!current.done) {
|
||||
const next = iter.next();
|
||||
yield [current.value, next.done, index];
|
||||
current = next;
|
||||
index++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
forEach(action) {
|
||||
for (const item of this) {
|
||||
if (Array.isArray(item)) {
|
||||
action(...item);
|
||||
} else {
|
||||
action(item);
|
||||
}
|
||||
}
|
||||
forEach(action) {
|
||||
for (const item of this) {
|
||||
if (Array.isArray(item)) {
|
||||
action(...item);
|
||||
} else {
|
||||
action(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toArray() {
|
||||
return Array.from(this);
|
||||
}
|
||||
toArray() {
|
||||
return Array.from(this);
|
||||
}
|
||||
|
||||
firstOrDefault(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
for (const item of source) return item;
|
||||
return undefined;
|
||||
}
|
||||
orderByDescending(keySelector) {
|
||||
return this._chain(function* (source) {
|
||||
const items = Array.from(source);
|
||||
items.sort((a, b) => keySelector(b) - keySelector(a));
|
||||
yield* items;
|
||||
});
|
||||
}
|
||||
|
||||
first(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
for (const item of source) return item;
|
||||
throw new Error("No elements in sequence.");
|
||||
}
|
||||
orderBy(keySelector) {
|
||||
return this._chain(function* (source) {
|
||||
const items = Array.from(source);
|
||||
items.sort((a, b) => keySelector(a) - keySelector(b));
|
||||
yield* items;
|
||||
});
|
||||
}
|
||||
|
||||
lastOrDefault(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
let lastValue = undefined;
|
||||
for (const item of source) lastValue = item;
|
||||
return lastValue;
|
||||
}
|
||||
firstOrDefault(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
for (const item of source) return item;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
last(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
let lastValue = undefined;
|
||||
let found = false;
|
||||
for (const item of source) {
|
||||
lastValue = item;
|
||||
found = true;
|
||||
}
|
||||
if (!found) throw new Error("No elements in sequence.");
|
||||
return lastValue;
|
||||
}
|
||||
first(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
for (const item of source) return item;
|
||||
throw new Error("No elements in sequence.");
|
||||
}
|
||||
|
||||
any(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
for (const _ of source) return true;
|
||||
return false;
|
||||
}
|
||||
lastOrDefault(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
let lastValue = undefined;
|
||||
for (const item of source) lastValue = item;
|
||||
return lastValue;
|
||||
}
|
||||
|
||||
all(predicate) {
|
||||
for (const item of this)
|
||||
if (!predicate(item))
|
||||
return false;
|
||||
return true;
|
||||
last(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
let lastValue = undefined;
|
||||
let found = false;
|
||||
for (const item of source) {
|
||||
lastValue = item;
|
||||
found = true;
|
||||
}
|
||||
if (!found) throw new Error("No elements in sequence.");
|
||||
return lastValue;
|
||||
}
|
||||
|
||||
count(predicate) {
|
||||
let count = 0;
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
for (const _ of source) count++;
|
||||
return count;
|
||||
}
|
||||
any(predicate) {
|
||||
const source = predicate ? this.where(predicate) : this;
|
||||
for (const _ of source) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
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 () {
|
||||
const arr = this;
|
||||
return new Enumerable(function* () {
|
||||
for (const item of arr)
|
||||
yield item;
|
||||
});
|
||||
}
|
||||
const arr = this;
|
||||
return new Enumerable(function* () {
|
||||
for (const item of arr) yield item;
|
||||
});
|
||||
};
|
||||
@@ -1,5 +1,16 @@
|
||||
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() {
|
||||
const passwordInput = document.getElementById('password');
|
||||
const newInputType = passwordInput.type === 'password' ? 'text' : 'password';
|
||||
@@ -19,3 +30,5 @@ loginForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault(); // Prevent the default form submission
|
||||
await submitLoginForm();
|
||||
});
|
||||
|
||||
await redirectIfAlreadySignedIn();
|
||||
@@ -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
@@ -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]);
|
||||
@@ -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
@@ -1,455 +1,476 @@
|
||||
import './linq.js'
|
||||
import "./linq.js";
|
||||
|
||||
function selectPath(data, expression) {
|
||||
if (!expression) return data;
|
||||
try {
|
||||
return new Function('$data', `with($data) { return (${expression}); }`)(data);
|
||||
} catch {
|
||||
console.error(`Error evaluating Template expression: ${expression}`);
|
||||
return undefined;
|
||||
}
|
||||
if (!expression) return data;
|
||||
try {
|
||||
return new Function("$data", `with($data) { return (${expression}); }`)(
|
||||
data,
|
||||
);
|
||||
} catch {
|
||||
console.error(`Error evaluating Template expression: ${expression}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
class ScopeDict {
|
||||
constructor(initial = {}) {
|
||||
this._entries = { ...initial };
|
||||
}
|
||||
constructor(initial = {}) {
|
||||
this._entries = { ...initial };
|
||||
}
|
||||
|
||||
set(name, value) {
|
||||
if (name.startsWith('$')) {
|
||||
throw new Error(`Cannot declare '${name}' with @let. Variables starting with '$' are reserved.`);
|
||||
}
|
||||
this._entries[name] = value;
|
||||
set(name, value) {
|
||||
if (name.startsWith("$")) {
|
||||
throw new Error(
|
||||
`Cannot declare '${name}' with @let. Variables starting with '$' are reserved.`,
|
||||
);
|
||||
}
|
||||
this._entries[name] = value;
|
||||
}
|
||||
|
||||
setBuiltin(name, value) {
|
||||
this._entries[name] = value;
|
||||
}
|
||||
setBuiltin(name, value) {
|
||||
this._entries[name] = value;
|
||||
}
|
||||
|
||||
has(name) {
|
||||
return name in this._entries;
|
||||
}
|
||||
has(name) {
|
||||
return name in this._entries;
|
||||
}
|
||||
|
||||
get(name) {
|
||||
return this._entries[name];
|
||||
}
|
||||
get(name) {
|
||||
return this._entries[name];
|
||||
}
|
||||
|
||||
clone() {
|
||||
return new ScopeDict(this._entries);
|
||||
}
|
||||
clone() {
|
||||
return new ScopeDict(this._entries);
|
||||
}
|
||||
}
|
||||
|
||||
function createScopeProxy(data, scope) {
|
||||
if (data === null || data === undefined || typeof data !== 'object') {
|
||||
scope.setBuiltin('$this', data);
|
||||
return new Proxy({}, {
|
||||
get(_target, prop) {
|
||||
if (prop === '$this') return data;
|
||||
if (scope.has(prop)) return scope.get(prop);
|
||||
return undefined;
|
||||
},
|
||||
has(_target, prop) {
|
||||
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];
|
||||
if (data === null || data === undefined || typeof data !== "object") {
|
||||
scope.setBuiltin("$this", data);
|
||||
return new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_target, prop) {
|
||||
if (prop === "$this") return data;
|
||||
if (scope.has(prop)) return scope.get(prop);
|
||||
return undefined;
|
||||
},
|
||||
has(target, prop) {
|
||||
return prop === '$this' || scope.has(prop) || prop in target;
|
||||
}
|
||||
});
|
||||
has(_target, prop) {
|
||||
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) {
|
||||
const quote = str[i];
|
||||
const quote = str[i];
|
||||
i++;
|
||||
while (i < str.length && str[i] !== quote) {
|
||||
if (str[i] === "\\") i++;
|
||||
i++;
|
||||
while (i < str.length && str[i] !== quote) {
|
||||
if (str[i] === '\\') i++;
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
function findClosingParen(str, openPos) {
|
||||
let depth = 1;
|
||||
let i = openPos + 1;
|
||||
while (i < str.length && depth > 0) {
|
||||
if (str[i] === "'" || str[i] === '"' || str[i] === '`') {
|
||||
i = skipString(str, i) + 1;
|
||||
continue;
|
||||
}
|
||||
if (str[i] === '(') depth++;
|
||||
else if (str[i] === ')') depth--;
|
||||
if (depth > 0) i++;
|
||||
let depth = 1;
|
||||
let i = openPos + 1;
|
||||
while (i < str.length && depth > 0) {
|
||||
if (str[i] === "'" || str[i] === '"' || str[i] === "`") {
|
||||
i = skipString(str, i) + 1;
|
||||
continue;
|
||||
}
|
||||
if (depth !== 0) throw new Error('Unclosed ( in template');
|
||||
return i;
|
||||
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 findClosingBrace(str, openPos) {
|
||||
let depth = 1;
|
||||
let i = openPos + 1;
|
||||
while (i < str.length && depth > 0) {
|
||||
if (str[i] === "'" || str[i] === '"' || str[i] === '`') {
|
||||
i = skipString(str, i) + 1;
|
||||
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++;
|
||||
let depth = 1;
|
||||
let i = openPos + 1;
|
||||
while (i < str.length && depth > 0) {
|
||||
if (str[i] === "'" || str[i] === '"' || str[i] === "`") {
|
||||
i = skipString(str, i) + 1;
|
||||
continue;
|
||||
}
|
||||
if (depth !== 0) throw new Error('Unclosed { in template');
|
||||
return i;
|
||||
}
|
||||
|
||||
function findTopLevelComma(str) {
|
||||
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;
|
||||
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;
|
||||
}
|
||||
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) {
|
||||
const hasThousands = spec.includes(',');
|
||||
const dotIdx = spec.indexOf('.');
|
||||
const hasThousands = spec.includes(",");
|
||||
const dotIdx = spec.indexOf(".");
|
||||
|
||||
let decimals = 0;
|
||||
if (dotIdx !== -1) {
|
||||
decimals = spec.length - dotIdx - 1;
|
||||
let decimals = 0;
|
||||
if (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);
|
||||
|
||||
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;
|
||||
return result;
|
||||
}
|
||||
|
||||
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 = {
|
||||
'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),
|
||||
};
|
||||
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 [token, value] of Object.entries(tokens).sort((a, b) => b[0].length - a[0].length)) {
|
||||
result = result.replaceAll(token, String(value));
|
||||
}
|
||||
let result = spec;
|
||||
for (const [token, value] of Object.entries(tokens).sort(
|
||||
(a, b) => b[0].length - a[0].length,
|
||||
)) {
|
||||
result = result.replaceAll(token, String(value));
|
||||
}
|
||||
|
||||
return result;
|
||||
return result;
|
||||
}
|
||||
|
||||
function createFormatter(formatSpec) {
|
||||
return (value) => {
|
||||
if (value == null) return '';
|
||||
if (value instanceof Date) return formatDate(value, formatSpec);
|
||||
if (typeof value === 'number') return formatNumber(value, formatSpec);
|
||||
return String(value);
|
||||
};
|
||||
return (value) => {
|
||||
if (value == null) return "";
|
||||
if (value instanceof Date) return formatDate(value, formatSpec);
|
||||
if (typeof value === "number") return formatNumber(value, formatSpec);
|
||||
return String(value);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
class StaticTemplatePart {
|
||||
constructor(text) {
|
||||
this.text = text;
|
||||
}
|
||||
constructor(text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
render(_data) {
|
||||
return this.text;
|
||||
}
|
||||
render(_data) {
|
||||
return this.text;
|
||||
}
|
||||
}
|
||||
|
||||
class VariableTemplatePart {
|
||||
constructor(contextPath, formatter) {
|
||||
this.contextPath = contextPath;
|
||||
this.formatter = formatter || (x => x);
|
||||
}
|
||||
constructor(contextPath, formatter) {
|
||||
this.contextPath = contextPath;
|
||||
this.formatter = formatter || ((x) => x);
|
||||
}
|
||||
|
||||
render(data) {
|
||||
return this.formatter(selectPath(data, this.contextPath));
|
||||
}
|
||||
render(data) {
|
||||
return this.formatter(selectPath(data, this.contextPath));
|
||||
}
|
||||
}
|
||||
|
||||
class LetTemplatePart {
|
||||
constructor(name, expression) {
|
||||
this.name = name;
|
||||
this.expression = expression;
|
||||
}
|
||||
constructor(name, expression) {
|
||||
this.name = name;
|
||||
this.expression = expression;
|
||||
}
|
||||
|
||||
declareScoped(scope, data) {
|
||||
scope.set(this.name, selectPath(data, this.expression));
|
||||
}
|
||||
declareScoped(scope, data) {
|
||||
scope.set(this.name, selectPath(data, this.expression));
|
||||
}
|
||||
|
||||
render(_data) {
|
||||
return '';
|
||||
}
|
||||
render(_data) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
class ListTemplatePart {
|
||||
constructor(varNames, contextPath, innerTemplate, emptyTemplate, formatter) {
|
||||
this.varNames = varNames;
|
||||
this.contextPath = contextPath;
|
||||
this.formatter = formatter || (x => x);
|
||||
this.innerTemplate = innerTemplate;
|
||||
this.emptyTemplate = emptyTemplate;
|
||||
constructor(varNames, contextPath, innerTemplate, emptyTemplate, formatter) {
|
||||
this.varNames = varNames;
|
||||
this.contextPath = contextPath;
|
||||
this.formatter = formatter || ((x) => x);
|
||||
this.innerTemplate = innerTemplate;
|
||||
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) {
|
||||
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) : '';
|
||||
let result = "";
|
||||
const count = arr.length;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const scope = new ScopeDict();
|
||||
const item = arr[index];
|
||||
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 = '';
|
||||
const count = arr.length;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const scope = new ScopeDict();
|
||||
const item = arr[index];
|
||||
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]);
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
class ConditionalTemplatePart {
|
||||
constructor(contextPath, condition, trueTemplate, falseTemplate, formatter) {
|
||||
this.contextPath = contextPath;
|
||||
this.formatter = formatter || (x => x);
|
||||
this.condition = condition;
|
||||
this.trueTemplate = trueTemplate;
|
||||
this.falseTemplate = falseTemplate;
|
||||
}
|
||||
constructor(contextPath, condition, trueTemplate, falseTemplate, formatter) {
|
||||
this.contextPath = contextPath;
|
||||
this.formatter = formatter || ((x) => x);
|
||||
this.condition = condition;
|
||||
this.trueTemplate = trueTemplate;
|
||||
this.falseTemplate = falseTemplate;
|
||||
}
|
||||
|
||||
render(data) {
|
||||
const selectedData = this.formatter(selectPath(data, this.contextPath));
|
||||
if (this.condition(selectedData)) {
|
||||
return this.trueTemplate ? this.trueTemplate.render(data) : '';
|
||||
} else {
|
||||
return this.falseTemplate ? this.falseTemplate.render(data) : '';
|
||||
}
|
||||
render(data) {
|
||||
const selectedData = this.formatter(selectPath(data, this.contextPath));
|
||||
if (this.condition(selectedData)) {
|
||||
return this.trueTemplate ? this.trueTemplate.render(data) : "";
|
||||
} else {
|
||||
return this.falseTemplate ? this.falseTemplate.render(data) : "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class Template {
|
||||
constructor(templateString) {
|
||||
if (templateString != null) {
|
||||
this.parts = this._parseBlock(templateString);
|
||||
}
|
||||
constructor(templateString) {
|
||||
if (templateString != null) {
|
||||
this.parts = this._parseBlock(templateString);
|
||||
}
|
||||
}
|
||||
|
||||
_parseBlock(str) {
|
||||
const parts = [];
|
||||
let i = 0;
|
||||
_parseBlock(str) {
|
||||
const parts = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < str.length) {
|
||||
// {{ expression }} or {{ expression:format }}
|
||||
if (str[i] === '{' && str[i + 1] === '{') {
|
||||
const end = str.indexOf('}}', i + 2);
|
||||
if (end === -1) throw new Error('Unclosed {{ }}');
|
||||
const content = str.substring(i + 2, end).trim();
|
||||
while (i < str.length) {
|
||||
// {{ expression }} or {{ expression:format }}
|
||||
if (str[i] === "{" && str[i + 1] === "{") {
|
||||
const end = str.indexOf("}}", i + 2);
|
||||
if (end === -1) throw new Error("Unclosed {{ }}");
|
||||
const content = str.substring(i + 2, end).trim();
|
||||
|
||||
let expression, formatter = null;
|
||||
const colonIdx = content.lastIndexOf(':');
|
||||
if (colonIdx > 0) {
|
||||
const possibleFormat = content.substring(colonIdx + 1).trim();
|
||||
if (/^[0#.,yMdHhmsafzZ\-\/: ]+$/.test(possibleFormat)) {
|
||||
expression = content.substring(0, colonIdx).trim();
|
||||
formatter = createFormatter(possibleFormat);
|
||||
} 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;
|
||||
}
|
||||
let expression,
|
||||
formatter = null;
|
||||
const colonIdx = content.lastIndexOf(":");
|
||||
if (colonIdx > 0) {
|
||||
const possibleFormat = content.substring(colonIdx + 1).trim();
|
||||
if (/^[0#.,yMdHhmsafzZ\-\/: ]+$/.test(possibleFormat)) {
|
||||
expression = content.substring(0, colonIdx).trim();
|
||||
formatter = createFormatter(possibleFormat);
|
||||
} else {
|
||||
expression = content;
|
||||
}
|
||||
} else {
|
||||
expression = content;
|
||||
}
|
||||
|
||||
return parts;
|
||||
}
|
||||
parts.push(new VariableTemplatePart(expression, formatter));
|
||||
i = end + 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
render(data, parentScope = new ScopeDict()) {
|
||||
const scope = parentScope.clone();
|
||||
const proxy = createScopeProxy(data, scope);
|
||||
// @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();
|
||||
|
||||
let result = '';
|
||||
for (const part of this.parts) {
|
||||
part.declareScoped?.(scope, proxy);
|
||||
result += part.render(proxy);
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
@@ -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");
|
||||
@@ -216,7 +216,7 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
fetch('../html/sidebar.html')
|
||||
fetch('/sidebar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => {
|
||||
document.getElementById('sidebar-container').innerHTML = data;
|
||||
@@ -229,7 +229,7 @@
|
||||
if (secondLink) secondLink.classList.add('active');
|
||||
});
|
||||
|
||||
fetch('../html/topbar.html')
|
||||
fetch('/topbar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => document.getElementById('topbar-container').innerHTML = data);
|
||||
</script>
|
||||
|
||||
@@ -93,7 +93,7 @@
|
||||
|
||||
<script>
|
||||
// Fetch sidebar and topbar
|
||||
fetch('../html/sidebar.html')
|
||||
fetch('/sidebar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => {
|
||||
document.getElementById('sidebar-container').innerHTML = data;
|
||||
@@ -106,7 +106,7 @@
|
||||
if (marketplaceLink) marketplaceLink.classList.add('active');
|
||||
});
|
||||
|
||||
fetch('../html/topbar.html')
|
||||
fetch('/topbar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => document.getElementById('topbar-container').innerHTML = data);
|
||||
</script>
|
||||
|
||||
@@ -90,7 +90,7 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
fetch('../html/sidebar.html')
|
||||
fetch('/sidebar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => {
|
||||
document.getElementById('sidebar-container').innerHTML = data;
|
||||
@@ -103,7 +103,7 @@
|
||||
if (profileLink) profileLink.classList.add('active');
|
||||
});
|
||||
|
||||
fetch('../html/topbar.html')
|
||||
fetch('/topbar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => document.getElementById('topbar-container').innerHTML = data);
|
||||
</script>
|
||||
|
||||
@@ -179,7 +179,7 @@
|
||||
});
|
||||
|
||||
// Fetch sidebar and topbar
|
||||
fetch('../html/sidebar.html')
|
||||
fetch('/sidebar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => {
|
||||
document.getElementById('sidebar-container').innerHTML = data;
|
||||
@@ -189,7 +189,7 @@
|
||||
const settingsLink = document.querySelector('#sidebar-container a[href="settings.html"]');
|
||||
if (settingsLink) settingsLink.classList.add('active');
|
||||
});
|
||||
fetch('../html/topbar.html')
|
||||
fetch('/topbar.html')
|
||||
.then(r => r.text())
|
||||
.then(data => document.getElementById('topbar-container').innerHTML = data);
|
||||
</script>
|
||||
|
||||
@@ -67,12 +67,14 @@
|
||||
|
||||
<!-- Logout 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">
|
||||
<i class="bi bi-box-arrow-right"></i>
|
||||
<span class="nav-text">Logout</span>
|
||||
</div>
|
||||
<i class="bi bi-chevron-right logout-arrow"></i>
|
||||
</a>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@@ -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>
|
||||
Reference in new issue
Block a user