Older/WebApplication/RedirectPage.cpp

84 lines
2.6 KiB
C++
Raw Normal View History

2025-01-05 00:33:19 +08:00
#include "RedirectPage.h"
#include "BoostLog.h"
2025-01-05 14:23:02 +08:00
#include <Wt/WAnchor.h>
2025-01-05 00:33:19 +08:00
#include <Wt/WTimer.h>
constexpr auto Template = R"(
<p>${message}</p>
2025-01-05 14:23:02 +08:00
<div>${seconds}${go}${anchor}</div>
2025-01-05 00:33:19 +08:00
)";
2025-01-05 14:23:02 +08:00
RedirectPage::RedirectPage() : Wt::WTemplate(Template), m_history(this, "history") {
2025-01-05 00:33:19 +08:00
m_timer = addChild(std::make_unique<Wt::WTimer>());
m_timer->setInterval(std::chrono::milliseconds(1000));
m_timer->timeout().connect(this, &RedirectPage::onTimeout);
m_timer->start();
2025-01-05 14:23:02 +08:00
bindEmpty("message");
bindEmpty("anchor");
bindString("go", "返回");
2025-01-05 00:33:19 +08:00
bindInt("seconds", m_time / 1000);
2025-01-05 14:23:02 +08:00
m_history.connect(this, [this](int history) {
LOG(info) << "history: " << history;
m_historySize = history;
m_anchor = bindWidget("anchor", std::make_unique<Wt::WAnchor>());
if (m_redirect.empty()) {
m_anchor->setText(history > 2 ? "上一页" : "首页");
bindString("go", history > 2 ? "返回" : "前往");
m_anchor->clicked().connect(this, [this]() { redirect(m_redirect); });
} else {
bindString("go", "前往");
m_anchor->setText(m_text.empty() ? m_redirect : m_text);
m_anchor->setLink(Wt::WLink(Wt::LinkType::Url, m_redirect));
}
});
doJavaScript(std::format("{}.emit({},'{}',window.history.length)", Wt::WApplication::instance()->javaScriptClass(), id(),
m_history.name()));
2025-01-05 00:33:19 +08:00
}
2025-01-05 14:23:02 +08:00
void RedirectPage::setRedirect(const std::string &path, const std::string &text) {
2025-01-05 00:33:19 +08:00
if (m_redirect != path) {
m_redirect = path;
}
2025-01-05 14:23:02 +08:00
if (m_text != text) {
m_text = text;
}
if (m_anchor != nullptr) {
m_anchor->setText(text.empty() ? path : text);
m_anchor->setLink(Wt::WLink(Wt::LinkType::Url, path));
}
2025-01-05 00:33:19 +08:00
}
2025-01-05 14:23:02 +08:00
void RedirectPage::setMessage(const std::string &message) {
bindString("message", message);
}
void RedirectPage::redirect(const std::string &path) {
if (m_timer->isActive()) {
2025-01-05 00:33:19 +08:00
m_timer->stop();
2025-01-05 14:23:02 +08:00
}
auto app = Wt::WApplication::instance();
if (path.empty()) {
if (m_historySize > 2) {
doJavaScript("window.history.go(-1)");
} else {
app->redirect("/");
}
} else {
2025-01-05 00:33:19 +08:00
if (m_redirect.starts_with("/wt")) {
app->setInternalPath(m_redirect, true);
} else {
app->redirect(m_redirect);
}
}
}
2025-01-05 14:23:02 +08:00
void RedirectPage::onTimeout() {
m_time -= 1000;
if (m_time <= 0) {
redirect(m_redirect); // stop timer inside.
} else {
bindInt("seconds", m_time / 1000);
}
}