2021-01-26 16:36:53 +01:00
|
|
|
// Copyright 2020 The Gitea Authors. All rights reserved.
|
2022-11-27 19:20:29 +01:00
|
|
|
// SPDX-License-Identifier: MIT
|
2021-01-26 16:36:53 +01:00
|
|
|
|
2021-01-30 09:55:53 +01:00
|
|
|
package middleware
|
2021-01-26 16:36:53 +01:00
|
|
|
|
2024-02-14 22:48:45 +01:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"html/template"
|
|
|
|
"net/url"
|
|
|
|
)
|
2021-01-26 16:36:53 +01:00
|
|
|
|
|
|
|
// Flash represents a one time data transfer between two requests.
|
|
|
|
type Flash struct {
|
2023-05-04 08:36:34 +02:00
|
|
|
DataStore ContextDataStore
|
2021-01-26 16:36:53 +01:00
|
|
|
url.Values
|
|
|
|
ErrorMsg, WarningMsg, InfoMsg, SuccessMsg string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *Flash) set(name, msg string, current ...bool) {
|
2021-01-27 14:33:32 +01:00
|
|
|
if f.Values == nil {
|
|
|
|
f.Values = make(map[string][]string)
|
|
|
|
}
|
2023-07-15 10:52:03 +02:00
|
|
|
showInCurrentPage := len(current) > 0 && current[0]
|
|
|
|
if showInCurrentPage {
|
|
|
|
// assign it to the context data, then the template can use ".Flash.XxxMsg" to render the message
|
2023-05-04 08:36:34 +02:00
|
|
|
f.DataStore.GetData()["Flash"] = f
|
2021-01-26 16:36:53 +01:00
|
|
|
} else {
|
2023-07-15 10:52:03 +02:00
|
|
|
// the message map will be saved into the cookie and be shown in next response (a new page response which decodes the cookie)
|
2021-01-26 16:36:53 +01:00
|
|
|
f.Set(name, msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-14 22:48:45 +01:00
|
|
|
func flashMsgStringOrHTML(msg any) string {
|
|
|
|
switch v := msg.(type) {
|
|
|
|
case string:
|
|
|
|
return v
|
|
|
|
case template.HTML:
|
|
|
|
return string(v)
|
|
|
|
}
|
|
|
|
panic(fmt.Sprintf("unknown type: %T", msg))
|
|
|
|
}
|
|
|
|
|
2021-01-26 16:36:53 +01:00
|
|
|
// Error sets error message
|
2024-02-14 22:48:45 +01:00
|
|
|
func (f *Flash) Error(msg any, current ...bool) {
|
|
|
|
f.ErrorMsg = flashMsgStringOrHTML(msg)
|
|
|
|
f.set("error", f.ErrorMsg, current...)
|
2021-01-26 16:36:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Warning sets warning message
|
2024-02-14 22:48:45 +01:00
|
|
|
func (f *Flash) Warning(msg any, current ...bool) {
|
|
|
|
f.WarningMsg = flashMsgStringOrHTML(msg)
|
|
|
|
f.set("warning", f.WarningMsg, current...)
|
2021-01-26 16:36:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Info sets info message
|
2024-02-14 22:48:45 +01:00
|
|
|
func (f *Flash) Info(msg any, current ...bool) {
|
|
|
|
f.InfoMsg = flashMsgStringOrHTML(msg)
|
|
|
|
f.set("info", f.InfoMsg, current...)
|
2021-01-26 16:36:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Success sets success message
|
2024-02-14 22:48:45 +01:00
|
|
|
func (f *Flash) Success(msg any, current ...bool) {
|
|
|
|
f.SuccessMsg = flashMsgStringOrHTML(msg)
|
|
|
|
f.set("success", f.SuccessMsg, current...)
|
2021-01-26 16:36:53 +01:00
|
|
|
}
|