Controllers+Views+Routes: Add ScriptAfterLoad functionality

This commit is contained in:
Riyyi
2024-11-22 21:32:49 +01:00
parent 7f1e78fa08
commit f0cb958ea2
8 changed files with 88 additions and 14 deletions
+1 -1
View File
@@ -59,7 +59,7 @@ struct MainLayout<Body: HTML>: HTMLDocument {
}
// Placeholder for all toast messages
ToastView()
ToastComponent()
}
// ---------------------------------
@@ -0,0 +1,35 @@
import Elementary
struct ScriptAfterLoad: HTML {
var initial: Bool = false
var js: String = ""
init(initial: Bool = false, js: () -> String) {
self.initial = initial
self.js = js()
}
// -------------------------------------
var content: some HTML {
if initial {
script {
"""
document.addEventListener("DOMContentLoaded", function() {
\(js)
});
"""
}
} else {
script {
"""
web.afterLoad(function () {
\(js)
});
"""
}
}
}
}
-53
View File
@@ -1,53 +0,0 @@
import Elementary
import ElementaryHTMX
// Usage:
//
// let state = try getState(request: req)
// state.toast = ToastState(message: "", title: "", level: ToastState.Level.error)
// throw Abort(.badRequest, headers: ["HX-Trigger": "toast"])
//
// The header "HX-Trigger" will make the part refresh and show the toast message
struct ToastView: HTML {
var state: ToastState = ToastState()
// -------------------------------------
var content: some HTML {
div(
.class("toast-container"), .id("cdiv_toast"),
.hx.get("/toast"),
.hx.trigger(HTMLAttributeValue.HTMX.EventTrigger(rawValue: "toast from:body")),
.hx.swap(.outerHTML)
) {
div(.class("toast"), .id("toast")) {
div(.class("toast-header bg-\(state.level.rawValue) text-white")) {
strong(.class("me-auto")) { state.title }
button(
.class("btn-close btn-close-white"), .type(.button),
.data("bs-dismiss", value: "toast")
) {}
}
div(.class("toast-body")) { state.message }
}
if !state.message.isEmpty {
script {
"""
runOnceAfterSettle(function () {
const element = document.getElementById("toast");
const toast = new bootstrap.Toast(element, { autohide: true, delay: 5000 });
toast.show();
element.addEventListener("hidden.bs.toast", function () {
element.remove();
});
});
"""
}
}
}
}
}