84 lines
2.6 KiB
C++
84 lines
2.6 KiB
C++
#include "RedirectPage.h"
|
|
#include "BoostLog.h"
|
|
#include <Wt/WAnchor.h>
|
|
#include <Wt/WTimer.h>
|
|
|
|
constexpr auto Template = R"(
|
|
<p>${message}</p>
|
|
<div>您将在${seconds}秒后${go}${anchor}。</div>
|
|
)";
|
|
|
|
RedirectPage::RedirectPage() : Wt::WTemplate(Template), m_history(this, "history") {
|
|
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();
|
|
bindEmpty("message");
|
|
bindEmpty("anchor");
|
|
bindString("go", "返回");
|
|
bindInt("seconds", m_time / 1000);
|
|
|
|
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()));
|
|
}
|
|
|
|
void RedirectPage::setRedirect(const std::string &path, const std::string &text) {
|
|
if (m_redirect != path) {
|
|
m_redirect = path;
|
|
}
|
|
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));
|
|
}
|
|
}
|
|
|
|
void RedirectPage::setMessage(const std::string &message) {
|
|
bindString("message", message);
|
|
}
|
|
|
|
void RedirectPage::redirect(const std::string &path) {
|
|
if (m_timer->isActive()) {
|
|
m_timer->stop();
|
|
}
|
|
auto app = Wt::WApplication::instance();
|
|
if (path.empty()) {
|
|
if (m_historySize > 2) {
|
|
doJavaScript("window.history.go(-1)");
|
|
} else {
|
|
app->redirect("/");
|
|
}
|
|
} else {
|
|
if (m_redirect.starts_with("/wt")) {
|
|
app->setInternalPath(m_redirect, true);
|
|
} else {
|
|
app->redirect(m_redirect);
|
|
}
|
|
}
|
|
}
|
|
|
|
void RedirectPage::onTimeout() {
|
|
m_time -= 1000;
|
|
if (m_time <= 0) {
|
|
redirect(m_redirect); // stop timer inside.
|
|
} else {
|
|
bindInt("seconds", m_time / 1000);
|
|
}
|
|
}
|