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
@@ -9,7 +9,7 @@ import ElementaryHTMX
//
// The header "HX-Trigger" will make the part refresh and show the toast message
struct ToastView: HTML {
struct ToastComponent: HTML {
var state: ToastState = ToastState()
@@ -33,16 +33,14 @@ struct ToastView: HTML {
div(.class("toast-body")) { state.message }
}
if !state.message.isEmpty {
script {
ScriptAfterLoad(initial: false) {
"""
runOnceAfterSettle(function () {
const element = document.getElementById("toast");
const toast = new bootstrap.Toast(element, { autohide: true, delay: 5000 });
toast.show();
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();
});
element.addEventListener("hidden.bs.toast", function () {
element.remove();
});
"""
}
@@ -47,6 +47,8 @@ struct TodosTableComponent: HTML {
}
}
}
ScriptAfterLoad(initial: !refresh) { "web.tooltips();" };
}
}
+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)
});
"""
}
}
}
}