error modals are so on
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -8,6 +8,7 @@ tmp/
|
||||
static/css/output.css
|
||||
internal/view/**/*_templ.go
|
||||
internal/view/**/*_templ.txt
|
||||
oslstats
|
||||
|
||||
# Database backups (compressed)
|
||||
backups/*.sql.gz
|
||||
|
||||
@@ -35,7 +35,8 @@ func setupHttpServer(
|
||||
ignoredPaths := []string{
|
||||
"/static/css/output.css",
|
||||
"/static/favicon.ico",
|
||||
"/static/js/popups.js",
|
||||
"/static/js/toasts.js",
|
||||
"/static/js/copytoclipboard.js",
|
||||
"/static/js/theme.js",
|
||||
"/static/vendored/htmx@2.0.8.min.js",
|
||||
"/static/vendored/htmx-ext-ws.min.js",
|
||||
|
||||
@@ -7,25 +7,6 @@ import (
|
||||
"git.haelnorr.com/h/oslstats/internal/view/page"
|
||||
)
|
||||
|
||||
// func ErrorPage(
|
||||
// error hws.HWSError,
|
||||
// ) (hws.ErrorPage, error) {
|
||||
// messages := map[int]string{
|
||||
// 400: "The request you made was malformed or unexpected.",
|
||||
// 401: "You need to login to view this page.",
|
||||
// 403: "You do not have permission to view this page.",
|
||||
// 404: "The page or resource you have requested does not exist.",
|
||||
// 500: `An error occured on the server. Please try again, and if this
|
||||
// continues to happen contact an administrator.`,
|
||||
// 503: "The server is currently down for maintenance and should be back soon. =)",
|
||||
// }
|
||||
// msg, exists := messages[error.StatusCode]
|
||||
// if !exists {
|
||||
// return nil, errors.New("No valid message for the given code")
|
||||
// }
|
||||
// return page.Error(error.StatusCode, http.StatusText(error.StatusCode), msg), nil
|
||||
// }
|
||||
|
||||
func ErrorPage(hwsError hws.HWSError) (hws.ErrorPage, error) {
|
||||
// Determine if this status code should show technical details
|
||||
showDetails := shouldShowDetails(hwsError.StatusCode)
|
||||
@@ -40,7 +21,7 @@ func ErrorPage(hwsError hws.HWSError) (hws.ErrorPage, error) {
|
||||
// Get technical details if applicable
|
||||
var details string
|
||||
if showDetails && hwsError.Error != nil {
|
||||
details = hwsError.Error.Error()
|
||||
details = formatErrorDetails(hwsError.Error)
|
||||
}
|
||||
|
||||
// Render appropriate template
|
||||
@@ -63,7 +44,7 @@ func ErrorPage(hwsError hws.HWSError) (hws.ErrorPage, error) {
|
||||
// shouldShowDetails determines if a status code should display technical details
|
||||
func shouldShowDetails(statusCode int) bool {
|
||||
switch statusCode {
|
||||
case 400, 500, 503: // Bad Request, Internal Server Error, Service Unavailable
|
||||
case 400, 418, 500, 503: // Bad Request, Internal Server Error, Service Unavailable
|
||||
return true
|
||||
case 401, 403, 404: // Unauthorized, Forbidden, Not Found
|
||||
return false
|
||||
@@ -80,6 +61,7 @@ func getDefaultMessage(statusCode int) string {
|
||||
401: "You need to login to view this page.",
|
||||
403: "You do not have permission to view this page.",
|
||||
404: "The page or resource you have requested does not exist.",
|
||||
418: "I'm a teapot!",
|
||||
500: `An error occurred on the server. Please try again, and if this
|
||||
continues to happen contact an administrator.`,
|
||||
503: "The server is currently down for maintenance and should be back soon. =)",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
@@ -107,3 +108,50 @@ func throwNotFound(
|
||||
err := errors.New("Resource not found")
|
||||
throwError(s, w, r, http.StatusNotFound, msg, err, "debug")
|
||||
}
|
||||
|
||||
// ErrorDetails contains structured error information for WebSocket error modals
|
||||
type ErrorDetails struct {
|
||||
Code int `json:"code"`
|
||||
Stacktrace string `json:"stacktrace"`
|
||||
}
|
||||
|
||||
// formatErrorDetails extracts and formats error details from wrapped errors
|
||||
func formatErrorDetails(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
// Use %+v format to get stack trace from github.com/pkg/errors
|
||||
return fmt.Sprintf("%+v", err)
|
||||
}
|
||||
|
||||
// SerializeErrorDetails creates a JSON string with code and stacktrace
|
||||
// This is exported so it can be used when creating error notifications
|
||||
func SerializeErrorDetails(code int, err error) string {
|
||||
details := ErrorDetails{
|
||||
Code: code,
|
||||
Stacktrace: formatErrorDetails(err),
|
||||
}
|
||||
jsonData, jsonErr := json.Marshal(details)
|
||||
if jsonErr != nil {
|
||||
// Fallback if JSON encoding fails
|
||||
return fmt.Sprintf(`{"code":%d,"stacktrace":"Failed to serialize error"}`, code)
|
||||
}
|
||||
return string(jsonData)
|
||||
}
|
||||
|
||||
// parseErrorDetails extracts code and stacktrace from JSON Details field
|
||||
// Returns (code, stacktrace). If parsing fails, returns (500, original details string)
|
||||
func parseErrorDetails(details string) (int, string) {
|
||||
if details == "" {
|
||||
return 500, ""
|
||||
}
|
||||
|
||||
var errDetails ErrorDetails
|
||||
err := json.Unmarshal([]byte(details), &errDetails)
|
||||
if err != nil {
|
||||
// Not JSON or malformed - treat as plain stacktrace with default code
|
||||
return 500, details
|
||||
}
|
||||
|
||||
return errDetails.Code, errDetails.Stacktrace
|
||||
}
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
)
|
||||
|
||||
// NotificationType defines the type of notification
|
||||
type NotificationType string
|
||||
|
||||
const (
|
||||
NotificationSuccess NotificationType = "success"
|
||||
NotificationWarning NotificationType = "warning"
|
||||
NotificationInfo NotificationType = "info"
|
||||
)
|
||||
|
||||
// Notification represents a toast notification (success, warning, info)
|
||||
type Notification struct {
|
||||
Type NotificationType `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// ErrorModal represents a full-screen error modal (500, 503)
|
||||
type ErrorModal struct {
|
||||
Code int `json:"code"`
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message"`
|
||||
Details string `json:"details"`
|
||||
}
|
||||
|
||||
// setHXTrigger sets the HX-Trigger header with JSON-encoded data
|
||||
func setHXTrigger(w http.ResponseWriter, event string, data any) {
|
||||
payload := map[string]any{
|
||||
event: data,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
// Fallback if JSON encoding fails
|
||||
w.Header().Set("HX-Trigger", event)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("HX-Trigger", string(jsonData))
|
||||
}
|
||||
|
||||
// formatErrorDetails extracts and formats error details from wrapped errors
|
||||
func formatErrorDetails(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Use %+v format to get stack trace from github.com/pkg/errors
|
||||
return fmt.Sprintf("%+v", err)
|
||||
}
|
||||
|
||||
// notifyToast sends a toast notification via HX-Trigger header
|
||||
func notifyToast(
|
||||
w http.ResponseWriter,
|
||||
notifType NotificationType,
|
||||
title string,
|
||||
message string,
|
||||
) {
|
||||
notification := Notification{
|
||||
Type: notifType,
|
||||
Title: title,
|
||||
Message: message,
|
||||
}
|
||||
|
||||
setHXTrigger(w, "showNotification", notification)
|
||||
}
|
||||
|
||||
// notifyErrorModal sends a full-screen error modal via HX-Trigger header
|
||||
func notifyErrorModal(
|
||||
s *hws.Server,
|
||||
w http.ResponseWriter,
|
||||
statusCode int,
|
||||
title string,
|
||||
message string,
|
||||
err error,
|
||||
) {
|
||||
modal := ErrorModal{
|
||||
Code: statusCode,
|
||||
Title: title,
|
||||
Message: message,
|
||||
Details: formatErrorDetails(err),
|
||||
}
|
||||
|
||||
// Log the error
|
||||
s.LogError(hws.HWSError{
|
||||
StatusCode: statusCode,
|
||||
Message: message,
|
||||
Error: err,
|
||||
Level: hws.ErrorERROR,
|
||||
})
|
||||
|
||||
// Set response status
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
// Send notification via HX-Trigger
|
||||
setHXTrigger(w, "showErrorModal", modal)
|
||||
}
|
||||
|
||||
// notifySuccess sends a success toast notification
|
||||
func notifySuccess(w http.ResponseWriter, title string, message string) {
|
||||
notifyToast(w, NotificationSuccess, title, message)
|
||||
}
|
||||
|
||||
// notifyWarning sends a warning toast notification
|
||||
func notifyWarning(w http.ResponseWriter, title string, message string) {
|
||||
notifyToast(w, NotificationWarning, title, message)
|
||||
}
|
||||
|
||||
// notifyInfo sends an info toast notification
|
||||
func notifyInfo(w http.ResponseWriter, title string, message string) {
|
||||
notifyToast(w, NotificationInfo, title, message)
|
||||
}
|
||||
|
||||
// notifyInternalServiceError sends a 500 error modal
|
||||
func notifyInternalServiceError(
|
||||
s *hws.Server,
|
||||
w http.ResponseWriter,
|
||||
message string,
|
||||
err error,
|
||||
) {
|
||||
notifyErrorModal(s, w, 500, "Internal Server Error", message, err)
|
||||
}
|
||||
|
||||
// notifyServiceUnavailable sends a 503 error modal
|
||||
func notifyServiceUnavailable(
|
||||
s *hws.Server,
|
||||
w http.ResponseWriter,
|
||||
message string,
|
||||
err error,
|
||||
) {
|
||||
notifyErrorModal(s, w, 503, "Service Unavailable", message, err)
|
||||
}
|
||||
@@ -104,7 +104,9 @@ func notifyLoop(ctx context.Context, c *hws.Client, ws *websocket.Conn) error {
|
||||
case notify.LevelWarn:
|
||||
err = popup.Toast(nt, count, 10000).Render(ctx, w)
|
||||
case notify.LevelError:
|
||||
// do error modal
|
||||
// Parse error code and stacktrace from Details field
|
||||
code, stacktrace := parseErrorDetails(nt.Details)
|
||||
err = popup.ErrorModalWS(code, stacktrace, nt, count).Render(ctx, w)
|
||||
default:
|
||||
err = popup.Toast(nt, count, 6000).Render(ctx, w)
|
||||
}
|
||||
|
||||
@@ -3,11 +3,11 @@ package handlers
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.haelnorr.com/h/oslstats/internal/view/page"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"git.haelnorr.com/h/golib/hws"
|
||||
"git.haelnorr.com/h/golib/notify"
|
||||
"git.haelnorr.com/h/oslstats/internal/view/page"
|
||||
)
|
||||
|
||||
// Handles responses to the / path. Also serves a 404 Page for paths that
|
||||
@@ -15,7 +15,14 @@ import (
|
||||
func NotifyTester(server *hws.Server) http.Handler {
|
||||
return http.HandlerFunc(
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
testErr := errors.New("This is a stack trace. No really i swear. Just pretend ok? Thanks")
|
||||
if r.Method == "GET" {
|
||||
// page, _ := ErrorPage(hws.HWSError{
|
||||
// StatusCode: http.StatusTeapot,
|
||||
// Message: "This error has been rendered as a test",
|
||||
// Error: testErr,
|
||||
// })
|
||||
// page.Render(r.Context(), w)
|
||||
page.Test().Render(r.Context(), w)
|
||||
} else {
|
||||
r.ParseForm()
|
||||
@@ -27,16 +34,20 @@ func NotifyTester(server *hws.Server) http.Handler {
|
||||
"warn": notify.LevelWarn,
|
||||
"error": notify.LevelError,
|
||||
}[r.Form.Get("type")]
|
||||
error := errors.New("This is a stack trace. No really i swear. Just pretend ok? Thanks")
|
||||
message := r.Form.Get("message")
|
||||
nt := notify.Notification{
|
||||
Target: notify.Target(target),
|
||||
Title: title,
|
||||
Message: message,
|
||||
Level: level,
|
||||
Details: error.Error(),
|
||||
}
|
||||
if target == "" {
|
||||
|
||||
// For error level, serialize error details with code
|
||||
if level == notify.LevelError {
|
||||
nt.Details = SerializeErrorDetails(500, testErr)
|
||||
}
|
||||
|
||||
if target == "all" {
|
||||
server.NotifyAll(nt)
|
||||
} else {
|
||||
server.NotifySub(nt)
|
||||
@@ -45,7 +56,3 @@ func NotifyTester(server *hws.Server) http.Handler {
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func notifyInfoWS() {
|
||||
|
||||
}
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
package popup
|
||||
|
||||
// ErrorModal displays a full-screen modal for critical errors (500, 503)
|
||||
templ ErrorModal() {
|
||||
<div
|
||||
x-show="errorModal.show"
|
||||
x-cloak
|
||||
class="fixed inset-0 z-50 flex items-center justify-center p-4"
|
||||
x-transition:enter="transition ease-out duration-300"
|
||||
x-transition:enter-start="opacity-0"
|
||||
x-transition:enter-end="opacity-100"
|
||||
x-transition:leave="transition ease-in duration-200"
|
||||
x-transition:leave-start="opacity-100"
|
||||
x-transition:leave-end="opacity-0"
|
||||
>
|
||||
<!-- Backdrop (not clickable) -->
|
||||
<div class="absolute inset-0 bg-crust/80"></div>
|
||||
<!-- Modal Card -->
|
||||
<div
|
||||
class="relative bg-surface0 border-2 border-dark-red rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto"
|
||||
x-transition:enter="transition ease-out duration-300 delay-100"
|
||||
x-transition:enter-start="opacity-0 translate-y-4"
|
||||
x-transition:enter-end="opacity-100 translate-y-0"
|
||||
x-transition:leave="transition ease-in duration-200"
|
||||
x-transition:leave-start="opacity-100 translate-y-0"
|
||||
x-transition:leave-end="opacity-0 translate-y-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="error-modal-title"
|
||||
>
|
||||
<!-- Header -->
|
||||
<div class="flex items-start justify-between p-6 border-b border-dark-red">
|
||||
<div class="flex items-center gap-3">
|
||||
<!-- Warning Icon -->
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
class="size-8 text-red flex-shrink-0"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z"
|
||||
clip-rule="evenodd"
|
||||
></path>
|
||||
</svg>
|
||||
<!-- Title -->
|
||||
<h2
|
||||
id="error-modal-title"
|
||||
class="text-2xl font-bold text-red"
|
||||
x-text="`${errorModal.code} - ${errorModal.title}`"
|
||||
></h2>
|
||||
</div>
|
||||
<!-- Close Button -->
|
||||
<button
|
||||
@click="closeErrorModal()"
|
||||
class="text-subtext0 hover:text-text transition"
|
||||
aria-label="Close modal"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.5"
|
||||
stroke="currentColor"
|
||||
class="size-6"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<!-- Body -->
|
||||
<div class="p-6">
|
||||
<!-- User Message -->
|
||||
<p class="text-lg text-subtext0" x-text="errorModal.message"></p>
|
||||
<!-- Details Dropdown -->
|
||||
<div class="mt-6">
|
||||
<details class="bg-mantle rounded-lg p-4">
|
||||
<summary class="cursor-pointer text-subtext1 font-semibold select-none hover:text-text transition">
|
||||
Details
|
||||
<span class="text-xs text-subtext0 ml-2">(click to expand)</span>
|
||||
</summary>
|
||||
<div class="mt-4 relative">
|
||||
<pre
|
||||
id="error-modal-details"
|
||||
class="text-xs text-subtext0 font-mono whitespace-pre-wrap break-all bg-surface0 p-4 rounded overflow-x-auto max-h-96"
|
||||
x-text="errorModal.details"
|
||||
></pre>
|
||||
</div>
|
||||
<button
|
||||
onclick="copyToClipboard('error-modal-details', this)"
|
||||
class="mt-2 bg-mauve text-crust px-3 py-1 rounded text-xs hover:bg-mauve/75 transition"
|
||||
title="Copy to clipboard"
|
||||
>
|
||||
Copy
|
||||
</button>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Copy to Clipboard Script -->
|
||||
<script>
|
||||
function copyToClipboard(elementId, button) {
|
||||
const element = document.getElementById(elementId);
|
||||
const text = element.innerText;
|
||||
|
||||
navigator.clipboard.writeText(text)
|
||||
.then(() => {
|
||||
const originalText = button.innerText;
|
||||
button.innerText = 'Copied!';
|
||||
setTimeout(() => {
|
||||
button.innerText = originalText;
|
||||
}, 2000);
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Failed to copy:', err);
|
||||
button.innerText = 'Failed';
|
||||
});
|
||||
}
|
||||
</script>
|
||||
}
|
||||
6
internal/view/component/popup/errorModalContainer.templ
Normal file
6
internal/view/component/popup/errorModalContainer.templ
Normal file
@@ -0,0 +1,6 @@
|
||||
package popup
|
||||
|
||||
// ErrorModalContainer provides the target div for WebSocket error modal OOB swaps
|
||||
templ ErrorModalContainer() {
|
||||
<div id="error-modal-ws-container"></div>
|
||||
}
|
||||
65
internal/view/component/popup/errorModalWS.templ
Normal file
65
internal/view/component/popup/errorModalWS.templ
Normal file
@@ -0,0 +1,65 @@
|
||||
package popup
|
||||
|
||||
import "strconv"
|
||||
import "fmt"
|
||||
import "git.haelnorr.com/h/golib/notify"
|
||||
|
||||
// ErrorModalWS displays a WebSocket-triggered error modal
|
||||
// Matches design of error page (page.ErrorWithDetails)
|
||||
templ ErrorModalWS(code int, stacktrace string, nt notify.Notification, id int) {
|
||||
<div
|
||||
id="error-modal-ws-container"
|
||||
hx-swap-oob="morph:#error-modal-ws-container"
|
||||
>
|
||||
<!-- Fullscreen backdrop overlay -->
|
||||
<div class="fixed inset-0 z-50 bg-crust/80 flex items-center justify-center p-4">
|
||||
<!-- Modal card -->
|
||||
<div class="bg-base rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto p-8 text-center">
|
||||
<!-- Error code -->
|
||||
<h1 class="text-9xl text-text">{ strconv.Itoa(code) }</h1>
|
||||
<!-- Error title -->
|
||||
<p class="text-2xl font-bold tracking-tight text-subtext1 sm:text-4xl">
|
||||
{ nt.Title }
|
||||
</p>
|
||||
<!-- User message -->
|
||||
<p class="mt-4 text-subtext0">{ nt.Message }</p>
|
||||
<!-- Details dropdown -->
|
||||
if stacktrace != "" {
|
||||
<div class="mt-8 text-left">
|
||||
<details class="bg-surface0 rounded-lg p-4 text-right">
|
||||
<summary class="text-left cursor-pointer text-subtext1 font-semibold select-none hover:text-text">
|
||||
Details
|
||||
<span class="text-xs text-subtext0 ml-2">(click to expand)</span>
|
||||
</summary>
|
||||
<div class="text-left mt-4 relative">
|
||||
<pre
|
||||
id={ fmt.Sprintf("error-modal-ws-details-%d", id) }
|
||||
class="text-xs text-subtext0 font-mono whitespace-pre-wrap break-all bg-mantle p-4 rounded overflow-x-auto max-h-96"
|
||||
>{ stacktrace }</pre>
|
||||
</div>
|
||||
<button
|
||||
onclick={ templ.JSFuncCall("copyToClipboard", fmt.Sprintf("error-modal-ws-details-%v", id), "copyButton") }
|
||||
id="copyButton"
|
||||
class="mt-2 bg-mauve text-crust px-3 py-1 rounded text-xs hover:bg-mauve/75 transition"
|
||||
title="Copy to clipboard"
|
||||
>
|
||||
Copy
|
||||
</button>
|
||||
</details>
|
||||
</div>
|
||||
}
|
||||
<!-- Close button -->
|
||||
<div class="mt-6">
|
||||
<button
|
||||
onclick="document.getElementById('error-modal-ws-container').innerHTML = ''"
|
||||
class="inline-block rounded-lg bg-mauve px-5 py-3 text-sm text-crust transition hover:bg-mauve/75"
|
||||
>
|
||||
Close Modal
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/static/js/copytoclipboard.js"></script>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package popup
|
||||
|
||||
templ ErrorPopup() {
|
||||
<div
|
||||
x-cloak
|
||||
x-show="showError500"
|
||||
class="absolute w-82 left-0 right-0 mt-20 mr-5 ml-auto"
|
||||
x-transition:enter="transform translate-x-[100%] opacity-0 duration-200"
|
||||
x-transition:enter-start="opacity-0 translate-x-[100%]"
|
||||
x-transition:enter-end="opacity-100 translate-x-0"
|
||||
x-transition:leave="opacity-0 duration-200"
|
||||
x-transition:leave-start="opacity-100 translate-x-0"
|
||||
x-transition:leave-end="opacity-0 translate-x-[100%]"
|
||||
>
|
||||
<div
|
||||
role="alert"
|
||||
class="rounded-sm bg-dark-red p-4"
|
||||
>
|
||||
<div class="flex justify-between">
|
||||
<div class="flex items-center gap-2 text-red w-fit">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
class="size-5"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355
|
||||
12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309
|
||||
0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75
|
||||
0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0
|
||||
01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z"
|
||||
clip-rule="evenodd"
|
||||
></path>
|
||||
</svg>
|
||||
<strong class="block font-medium">Something went wrong </strong>
|
||||
</div>
|
||||
<div class="flex">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.5"
|
||||
stroke="currentColor"
|
||||
class="size-6 text-subtext0 hover:cursor-pointer"
|
||||
@click="showError500=false"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mt-2 text-sm text-red">
|
||||
An error occured on the server. Please try again later,
|
||||
or contact an administrator
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -8,16 +8,22 @@ import "git.haelnorr.com/h/golib/hws"
|
||||
// Backend should pass: notifType ("success"|"warning"|"info"), title, message
|
||||
templ Toast(nt notify.Notification, id, duration int) {
|
||||
{{
|
||||
// Determine classes server-side based on notifType
|
||||
color := map[notify.Level]string{
|
||||
notify.LevelSuccess: "green",
|
||||
notify.LevelWarn: "yellow",
|
||||
notify.LevelInfo: "blue",
|
||||
hws.LevelShutdown: "yellow",
|
||||
type style struct {
|
||||
bg string
|
||||
fg string
|
||||
border string
|
||||
bgdark string
|
||||
}
|
||||
// Determine classes server-side based on notifType
|
||||
var colors style
|
||||
switch nt.Level {
|
||||
case notify.LevelSuccess:
|
||||
colors = style{bg: "bg-green", fg: "text-green", border: "border-green", bgdark: "bg-dark-green"}
|
||||
case notify.LevelWarn, hws.LevelShutdown:
|
||||
colors = style{bg: "bg-yellow", fg: "text-yellow", border: "border-yellow", bgdark: "bg-dark-yellow"}
|
||||
case notify.LevelInfo:
|
||||
colors = style{bg: "bg-blue", fg: "text-blue", border: "border-blue", bgdark: "bg-dark-blue"}
|
||||
}
|
||||
containerClass := fmt.Sprintf("bg-dark-%s border-2 border-%s", color[nt.Level], color[nt.Level])
|
||||
textClass := fmt.Sprintf("text-%s", color[nt.Level])
|
||||
progressClass := fmt.Sprintf("bg-%s", color[nt.Level])
|
||||
}}
|
||||
<div
|
||||
id="toast-ws-container"
|
||||
@@ -25,23 +31,23 @@ templ Toast(nt notify.Notification, id, duration int) {
|
||||
>
|
||||
<div
|
||||
id={ fmt.Sprintf("ws-toast-%d", id) }
|
||||
class={ fmt.Sprintf("pointer-events-auto rounded-lg shadow-lg overflow-hidden w-full mb-2 %s", containerClass) }
|
||||
class={ fmt.Sprintf("pointer-events-auto rounded-lg shadow-lg overflow-hidden w-full mb-2 border-2 %s %s", colors.bgdark, colors.border) }
|
||||
role="alert"
|
||||
x-data={ templ.JSFuncCall("progressBar", fmt.Sprintf("ws-toast-%d", id), duration).CallInline }
|
||||
@mouseenter="paused = true"
|
||||
@mouseleave="paused = false"
|
||||
>
|
||||
<!-- @mouseleave="paused = false" -->
|
||||
<!-- Toast Content -->
|
||||
<div class="p-4 max-w-80">
|
||||
<div class="flex justify-between items-start gap-3">
|
||||
<!-- Icon + Content -->
|
||||
<div class="flex items-start gap-3 flex-1">
|
||||
<!-- Icon (rendered server-side based on notifType) -->
|
||||
<!-- Icon -->
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
class={ fmt.Sprintf("size-5 shrink-0 %s", textClass) }
|
||||
class={ fmt.Sprintf("size-5 shrink-0 %s", colors.fg) }
|
||||
>
|
||||
switch nt.Level {
|
||||
case notify.LevelSuccess:
|
||||
@@ -64,9 +70,9 @@ templ Toast(nt notify.Notification, id, duration int) {
|
||||
></path>
|
||||
}
|
||||
</svg>
|
||||
<!-- Text Content (rendered server-side) -->
|
||||
<!-- Text Content -->
|
||||
<div class="flex-1 min-w-0 max-w-48 text-wrap">
|
||||
<p class={ fmt.Sprintf("font-semibold %s", textClass) }>
|
||||
<p class={ fmt.Sprintf("font-semibold %s", colors.fg) }>
|
||||
{ nt.Title }
|
||||
</p>
|
||||
<p class="text-sm text-subtext0 mt-1 text-wrap">
|
||||
@@ -97,11 +103,11 @@ templ Toast(nt notify.Notification, id, duration int) {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Progress Bar (vanilla JS manages width) -->
|
||||
<div class="h-1 bg-surface0">
|
||||
<!-- Progress Bar -->
|
||||
<div class="h-1">
|
||||
<div
|
||||
id={ fmt.Sprintf("ws-toast-%d-progress", id) }
|
||||
class={ fmt.Sprintf("h-full %s", progressClass) }
|
||||
class={ fmt.Sprintf("h-full %s", colors.bg) }
|
||||
style="width: 0"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@ package popup
|
||||
// ToastContainer displays stacked toast notifications (success, warning, info)
|
||||
// Supports both regular toasts (AlpineJS) and WebSocket toasts (HTMX OOB swaps)
|
||||
templ ToastContainer() {
|
||||
<script src="/static/js/toasts.js" defer></script>
|
||||
<div class="fixed top-20 right-5 z-40 flex flex-col gap-3 max-w-sm pointer-events-none">
|
||||
<div id="toast-ws-container"></div>
|
||||
</div>
|
||||
|
||||
@@ -26,7 +26,6 @@ templ Global(title string) {
|
||||
<link href="/static/css/output.css" rel="stylesheet"/>
|
||||
<script src="/static/vendored/htmx@2.0.8.min.js"></script>
|
||||
<script src="/static/vendored/htmx-ext-ws.min.js"></script>
|
||||
<script src="/static/js/toasts.js" defer></script>
|
||||
<script src="/static/vendored/alpinejs@3.15.4.min.js" defer></script>
|
||||
if devInfo.HTMXLog {
|
||||
<script>
|
||||
@@ -39,7 +38,7 @@ templ Global(title string) {
|
||||
hx-ext="ws"
|
||||
ws-connect={ devInfo.WebsocketBase + "/ws/notifications" }
|
||||
>
|
||||
<!-- @popup.ErrorModal() -->
|
||||
@popup.ErrorModalContainer()
|
||||
@popup.ToastContainer()
|
||||
<div
|
||||
id="main-content"
|
||||
|
||||
@@ -29,7 +29,7 @@ templ ErrorWithDetails(code int, err string, message string, details string) {
|
||||
<pre id="details" class="text-xs text-subtext0 font-mono whitespace-pre-wrap break-all bg-mantle p-4 rounded overflow-x-auto">{ details }</pre>
|
||||
</div>
|
||||
<button
|
||||
onclick="copyToClipboard('details')"
|
||||
onclick="copyToClipboard('details', 'copyButton')"
|
||||
id="copyButton"
|
||||
class="mt-2 bg-mauve text-crust px-3 py-1 rounded text-xs hover:bg-mauve/75 transition hover:cursor-pointer"
|
||||
title="Copy to clipboard"
|
||||
@@ -45,24 +45,7 @@ templ ErrorWithDetails(code int, err string, message string, details string) {
|
||||
</div>
|
||||
</div>
|
||||
if details != "" {
|
||||
<script>
|
||||
function copyToClipboard(id) {
|
||||
var details = document.getElementById(id).innerText;
|
||||
var button = document.getElementById("copyButton");
|
||||
navigator.clipboard
|
||||
.writeText(details)
|
||||
.then(function () {
|
||||
button.innerText = "Copied!";
|
||||
setTimeout(function () {
|
||||
button.innerText = "Copy";
|
||||
}, 2000);
|
||||
})
|
||||
.catch(function (err) {
|
||||
console.error("Failed to copy:", err);
|
||||
button.innerText = "Failed";
|
||||
});
|
||||
}
|
||||
</script>
|
||||
<script src="/static/js/copytoclipboard.js"></script>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ templ Test() {
|
||||
</h1>
|
||||
<!-- Form Card -->
|
||||
<div class="bg-surface0 rounded-lg shadow-lg p-6 border border-overlay0">
|
||||
<form hx-post="/test" hx-swap="none" class="flex flex-col gap-4">
|
||||
<form hx-post="/notification-tester" hx-swap="none" class="flex flex-col gap-4">
|
||||
<!-- Notification Type -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="type" class="text-sm font-semibold text-subtext1">
|
||||
@@ -27,15 +27,16 @@ templ Test() {
|
||||
<option value="success">Success Toast</option>
|
||||
<option value="info">Info Toast</option>
|
||||
<option value="warn">Warning Toast</option>
|
||||
<!-- <option value="error">Error Modal</option> -->
|
||||
<option value="error">Error Modal</option>
|
||||
</select>
|
||||
</div>
|
||||
<!-- Target Input -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="target" class="text-sm font-semibold text-subtext1">
|
||||
Title
|
||||
Target
|
||||
</label>
|
||||
<input
|
||||
required
|
||||
type="text"
|
||||
name="target"
|
||||
id="target"
|
||||
|
||||
@@ -292,9 +292,6 @@
|
||||
.left-0 {
|
||||
left: calc(var(--spacing) * 0);
|
||||
}
|
||||
.z-3 {
|
||||
z-index: 3;
|
||||
}
|
||||
.z-10 {
|
||||
z-index: 10;
|
||||
}
|
||||
@@ -484,9 +481,6 @@
|
||||
.flex-shrink {
|
||||
flex-shrink: 1;
|
||||
}
|
||||
.flex-shrink-0 {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.shrink-0 {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@@ -503,14 +497,6 @@
|
||||
--tw-translate-x: calc(var(--spacing) * 0);
|
||||
translate: var(--tw-translate-x) var(--tw-translate-y);
|
||||
}
|
||||
.translate-x-\[100\%\] {
|
||||
--tw-translate-x: 100%;
|
||||
translate: var(--tw-translate-x) var(--tw-translate-y);
|
||||
}
|
||||
.translate-x-full {
|
||||
--tw-translate-x: 100%;
|
||||
translate: var(--tw-translate-x) var(--tw-translate-y);
|
||||
}
|
||||
.translate-y-0 {
|
||||
--tw-translate-y: calc(var(--spacing) * 0);
|
||||
translate: var(--tw-translate-x) var(--tw-translate-y);
|
||||
@@ -719,12 +705,12 @@
|
||||
.p-4 {
|
||||
padding: calc(var(--spacing) * 4);
|
||||
}
|
||||
.p-5 {
|
||||
padding: calc(var(--spacing) * 5);
|
||||
}
|
||||
.p-6 {
|
||||
padding: calc(var(--spacing) * 6);
|
||||
}
|
||||
.p-8 {
|
||||
padding: calc(var(--spacing) * 8);
|
||||
}
|
||||
.px-2 {
|
||||
padding-inline: calc(var(--spacing) * 2);
|
||||
}
|
||||
@@ -897,11 +883,6 @@
|
||||
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
|
||||
transition-duration: var(--tw-duration, var(--default-transition-duration));
|
||||
}
|
||||
.transition-all {
|
||||
transition-property: all;
|
||||
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
|
||||
transition-duration: var(--tw-duration, var(--default-transition-duration));
|
||||
}
|
||||
.delay-100 {
|
||||
transition-delay: 100ms;
|
||||
}
|
||||
|
||||
17
pkg/embedfs/files/js/copytoclipboard.js
Normal file
17
pkg/embedfs/files/js/copytoclipboard.js
Normal file
@@ -0,0 +1,17 @@
|
||||
function copyToClipboard(elementId, buttonId) {
|
||||
const element = document.getElementById(elementId);
|
||||
const button = document.getElementById(buttonId);
|
||||
|
||||
navigator.clipboard.writeText(element.innerText)
|
||||
.then(() => {
|
||||
const originalText = button.innerText;
|
||||
button.innerText = 'Copied!';
|
||||
setTimeout(() => {
|
||||
button.innerText = originalText;
|
||||
}, 2000);
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Failed to copy:', err);
|
||||
button.innerText = 'Failed';
|
||||
});
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
const popupData = {
|
||||
// Error modal (blocking, full-screen) - for 500/503 errors
|
||||
errorModal: {
|
||||
show: false,
|
||||
code: 0,
|
||||
title: "",
|
||||
message: "",
|
||||
details: "",
|
||||
},
|
||||
|
||||
// Toast notifications (non-blocking, stacked) - for success/warning/info
|
||||
toasts: [],
|
||||
toastIdCounter: 0,
|
||||
|
||||
// Handle HTMX beforeSwap event - intercept both errors and successes
|
||||
handleBeforeSwap(event) {
|
||||
const xhr = event.detail.xhr;
|
||||
if (!xhr) return;
|
||||
|
||||
const status = xhr.status;
|
||||
const trigger = xhr.getResponseHeader("HX-Trigger");
|
||||
if (!trigger) return;
|
||||
|
||||
try {
|
||||
const data = JSON.parse(trigger);
|
||||
|
||||
// Handle 500/503 error modals
|
||||
if ((status === 500 || status === 503) && data.showErrorModal) {
|
||||
this.errorModal = {
|
||||
show: true,
|
||||
code: data.showErrorModal.code,
|
||||
title: data.showErrorModal.title,
|
||||
message: data.showErrorModal.message,
|
||||
details: data.showErrorModal.details,
|
||||
};
|
||||
// Prevent swap but allow error logging
|
||||
event.detail.shouldSwap = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle success/warning/info toasts (200-299)
|
||||
if (status >= 200 && status < 300 && data.showNotification) {
|
||||
this.addToast(data.showNotification);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to parse HX-Trigger:", e);
|
||||
}
|
||||
},
|
||||
|
||||
// Add toast to stack
|
||||
addToast(notification) {
|
||||
const toast = {
|
||||
id: ++this.toastIdCounter,
|
||||
type: notification.type,
|
||||
title: notification.title,
|
||||
message: notification.message,
|
||||
paused: false,
|
||||
progress: 0,
|
||||
};
|
||||
|
||||
this.toasts.push(toast);
|
||||
|
||||
// Determine timeout based on type
|
||||
const timeout = notification.type === "warning" ? 5000 : 3000;
|
||||
|
||||
// Start progress animation
|
||||
this.animateToastProgress(toast.id, timeout);
|
||||
},
|
||||
|
||||
// Animate toast progress bar and auto-dismiss
|
||||
animateToastProgress(toastId, duration) {
|
||||
const toast = this.toasts.find((t) => t.id === toastId);
|
||||
if (!toast) return;
|
||||
|
||||
const startTime = performance.now();
|
||||
let totalPausedTime = 0;
|
||||
let pauseStartTime = null;
|
||||
|
||||
const animate = (currentTime) => {
|
||||
const toast = this.toasts.find((t) => t.id === toastId);
|
||||
if (!toast) return; // Toast was manually removed
|
||||
|
||||
if (toast.paused) {
|
||||
// Track when pause started
|
||||
if (pauseStartTime === null) {
|
||||
pauseStartTime = currentTime;
|
||||
}
|
||||
// Keep animating while paused
|
||||
requestAnimationFrame(animate);
|
||||
return;
|
||||
} else {
|
||||
// If we were paused, accumulate the paused time
|
||||
if (pauseStartTime !== null) {
|
||||
totalPausedTime += currentTime - pauseStartTime;
|
||||
pauseStartTime = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate actual elapsed time (excluding paused time)
|
||||
const elapsed = currentTime - startTime - totalPausedTime;
|
||||
toast.progress = Math.min((elapsed / duration) * 100, 100);
|
||||
|
||||
if (elapsed >= duration) {
|
||||
this.removeToast(toastId);
|
||||
} else {
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
};
|
||||
|
||||
requestAnimationFrame(animate);
|
||||
},
|
||||
|
||||
// Remove toast from stack
|
||||
removeToast(id) {
|
||||
this.toasts = this.toasts.filter((t) => t.id !== id);
|
||||
},
|
||||
|
||||
// Close error modal
|
||||
closeErrorModal() {
|
||||
this.errorModal.show = false;
|
||||
},
|
||||
};
|
||||
|
||||
// Global function for WebSocket toasts to animate progress and auto-dismiss
|
||||
// Pure vanilla JavaScript - no Alpine.js dependency
|
||||
// Called via inline script in ToastNotificationWS template
|
||||
function animateToastProgress(toastId, duration) {
|
||||
const toastEl = document.getElementById(toastId);
|
||||
const progressEl = document.getElementById(toastId + "-progress");
|
||||
|
||||
if (!toastEl || !progressEl) {
|
||||
console.error("animateToastProgress: elements not found", toastId);
|
||||
return;
|
||||
}
|
||||
|
||||
const startTime = performance.now();
|
||||
let totalPausedTime = 0;
|
||||
let pauseStartTime = null;
|
||||
|
||||
const animate = (currentTime) => {
|
||||
const el = document.getElementById(toastId);
|
||||
const progEl = document.getElementById(toastId + "-progress");
|
||||
|
||||
if (!el || !progEl) return; // Toast was manually removed
|
||||
|
||||
// Check if paused (set via onmouseenter/onmouseleave)
|
||||
const isPaused = el.dataset.paused === "true";
|
||||
|
||||
if (isPaused) {
|
||||
// Track when pause started
|
||||
if (pauseStartTime === null) {
|
||||
pauseStartTime = currentTime;
|
||||
}
|
||||
// Keep animating while paused
|
||||
requestAnimationFrame(animate);
|
||||
return;
|
||||
} else {
|
||||
// If we were paused, accumulate the paused time
|
||||
if (pauseStartTime !== null) {
|
||||
totalPausedTime += currentTime - pauseStartTime;
|
||||
pauseStartTime = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate actual elapsed time (excluding paused time)
|
||||
const elapsed = currentTime - startTime - totalPausedTime;
|
||||
// Progress bar goes from 100% to 0%
|
||||
const progress = Math.max(100 - (elapsed / duration) * 100, 0);
|
||||
progEl.style.width = progress + "%";
|
||||
|
||||
if (elapsed >= duration) {
|
||||
// Remove the toast element
|
||||
el.remove();
|
||||
} else {
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
};
|
||||
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
Reference in New Issue
Block a user