Add ability to display notifications other than HTTP errors

This commit is contained in:
Jason Streifling 2025-03-08 10:24:25 +01:00
parent 7da98fb2ab
commit dd689e0dfd
4 changed files with 39 additions and 4 deletions

View File

@ -88,6 +88,6 @@ func UploadDocx(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFunc {
return
}
w.WriteHeader(http.StatusOK)
notifyClient(w, "Hochladen erfolgreich!", http.StatusOK)
}
}

View File

@ -0,0 +1,20 @@
package frontend
import (
"fmt"
"html/template"
"net/http"
)
func notifyClient(w http.ResponseWriter, message string, status int) {
h := w.Header()
h.Del("Content-Length")
h.Set("Content-Type", "text/html; charset=utf-8")
if status >= 400 {
h.Set("X-Content-Type-Options", "nosniff")
}
w.WriteHeader(status)
safeMsg := template.HTMLEscapeString(message)
fmt.Fprintf(w, `<span id="notification-content" hx-swap-oob="true">%s</span>`, safeMsg)
}

View File

@ -54,6 +54,6 @@ func UploadPDF(c *b.Config, s map[string]*Session) http.HandlerFunc {
return
}
w.WriteHeader(http.StatusOK)
notifyClient(w, "Hochladen erfolgreich!", http.StatusOK)
}
}

View File

@ -29,7 +29,8 @@
<main class="mx-4">
<div class="hidden bg-slate-950 dark:bg-slate-50 fixed font-bold p-4 right-8 rounded-lg shadow-lg text-slate-100 dark:text-slate-900 top-8 z-50"
id="notification">
id="notification" hx-swap="innerHTML">
<span id="notification-content"></span>
</div>
<div id="page-content">
@ -74,12 +75,26 @@
</script>
<script>
htmx.on('htmx:afterSwap', function (event) {
var notificationContent = document.getElementById('notification-content');
if (notificationContent.textContent.trim() !== "") {
var notification = document.getElementById('notification');
notification.classList.remove('hidden');
setTimeout(function () {
notification.classList.add('hidden');
notificationContent.textContent = "";
}, 5000);
}
});
htmx.on('htmx:responseError', function (event) {
var notificationContent = document.getElementById('notification-content');
var notification = document.getElementById('notification');
notification.innerText = event.detail.xhr.responseText;
notificationContent.textContent = event.detail.xhr.responseText;
notification.classList.remove('hidden');
setTimeout(function () {
notification.classList.add('hidden');
notificationContent.textContent = "";
}, 5000);
});
</script>