fix poll results on ajax topic and eliminate unnecessary allocs for resources that aren't used

This commit is contained in:
Azareal 2020-03-13 12:56:23 +10:00
parent aa32bd335c
commit 372508bf98
7 changed files with 133 additions and 60 deletions

View File

@ -101,6 +101,26 @@ func (h *Header) AddSheet(name string) {
h.Stylesheets = append(h.Stylesheets, name)
}
// ! Experimental
func (h *Header) AddXRes(names ...string) {
var o string
for i, name := range names {
if name[0] == '/' && name[1] == '/' {
} else {
file, ok := StaticFiles.Get("/s/" + name)
if ok {
name = file.OName
}
}
if i != 0 {
o += "," + name
} else {
o += name
}
}
h.Writer.Header().Set("X-Res", o)
}
func (h *Header) AddNotice(name string) {
h.NoticeList = append(h.NoticeList, p.GetNoticePhrase(name))
}

View File

@ -341,6 +341,12 @@ function runWebSockets(resume=false) {
}
}
// TODO: Surely, there's a prettier and more elegant way of doing this?
function getExt(name) {
if(!name.indexOf('.' > -1)) throw("This file doesn't have an extension");
return name.split('.').pop();
}
(() => {
addInitHook("pre_init", () => {
runInitHook("pre_global");
@ -813,35 +819,38 @@ function mainInit(){
if(ev.which == 39) this.querySelectorAll("#nextFloat a")[0].click();
};
//id="poll_results_{{.Poll.ID}}" class="poll_results auto_hide"
$(".poll_results_button").click(function(){
let pollID = $(this).attr("data-poll-id");
$("#poll_results_" + pollID).removeClass("auto_hide");
fetch("/poll/results/" + pollID, {
credentials: 'same-origin'
}).then(resp => resp.text()).catch(err => console.error("err",err)).then(rawData => {
// TODO: Make sure the received data is actually a list of integers
let data = JSON.parse(rawData);
let allZero = true;
for(let i = 0; i < data.length; i++) {
if(data[i] != "0") allZero = false;
function asyncGetSheet(src) {
return new Promise((resolve,reject) => {
let res = document.createElement('link');
res.async = true;
const onloadHandler = (e,isAbort) => {
if (isAbort || !res.readyState || /loaded|complete/.test(res.readyState)) {
res.onload = null;
res.onreadystatechange = null;
res = undefined;
isAbort ? reject(e) : resolve();
}
if(allZero) {
$("#poll_results_"+pollID+" .poll_no_results").removeClass("auto_hide");
console.log("all zero")
return;
}
$("#poll_results_"+pollID+" .user_content").html("<div id='poll_results_chart_"+pollID+"'></div>");
console.log("rawData",rawData);
console.log("series",data);
Chartist.Pie('#poll_results_chart_'+pollID, {
series: data,
}, {
height: '120px',
});
})
res.onerror = (e) => {
reject(e);
};
res.onload = onloadHandler;
res.onreadystatechange = onloadHandler;
res.href = src;
res.rel = "stylesheet";
res.type = "text/css";
const prior = document.getElementsByTagName('link')[0];
prior.parentNode.insertBefore(res,prior);
});
}
function stripQ(name) {
return name.split('?')[0];
}
$(".rowtopic a,a.rowtopic").click(function(ev) {
let base = this.getAttribute("href");
@ -849,6 +858,18 @@ function mainInit(){
fetch(href, {credentials:"same-origin"})
.then(resp => {
if(!resp.ok) throw(href+" failed to load");
let xRes = resp.headers.get("x-res")
for(let res of xRes.split(",")) {
let pro;
if(stripQ(getExt(res)) == "css") pro = asyncGetSheet("/s/"+res)
else pro = asyncGetScript("/s/"+res)
pro.then(() => console.log("Loaded " + res))
.catch(e => {
console.log("Unable to get res '"+res+"'");
console.log("e",e);
console.trace();
});
}
return resp.text();
}).then(data => {
document.querySelector("#back").outerHTML = data;
@ -1002,6 +1023,36 @@ function bindTopic() {
quoteItemCallback(src.innerHTML,item);
});
//id="poll_results_{{.Poll.ID}}" class="poll_results auto_hide"
$(".poll_results_button").click(function(){
let pollID = $(this).attr("data-poll-id");
$("#poll_results_" + pollID).removeClass("auto_hide");
fetch("/poll/results/" + pollID, {
credentials: 'same-origin'
}).then(resp => resp.text()).catch(err => console.error("err",err)).then(rawData => {
// TODO: Make sure the received data is actually a list of integers
let data = JSON.parse(rawData);
let allZero = true;
for(let i = 0; i < data.length; i++) {
if(data[i] != "0") allZero = false;
}
if(allZero) {
$("#poll_results_"+pollID+" .poll_no_results").removeClass("auto_hide");
console.log("all zero")
return;
}
$("#poll_results_"+pollID+" .user_content").html("<div id='poll_results_chart_"+pollID+"'></div>");
console.log("rawData",rawData);
console.log("series",data);
Chartist.Pie('#poll_results_chart_'+pollID, {
series: data,
}, {
height: '120px',
});
})
});
runHook("end_bind_topic");
}
@ -1012,5 +1063,6 @@ function unbindTopic() {
$(".edit_item").unbind("click");
$(".submit_edit").unbind("click");
$(".quote_item").unbind("click");
$(".poll_results_button").unbind("click");
runHook("end_unbind_topic");
}

View File

@ -14,12 +14,6 @@ var imageExts = ["png", "jpg", "jpe","jpeg","jif","jfi","jfif", "svg", "bmp", "g
document.body.removeChild(el);
}
// TODO: Surely, there's a prettier and more elegant way of doing this?
function getExt(name) {
if(!name.indexOf('.' > -1)) throw("This file doesn't have an extension");
return name.split('.').pop();
}
function uploadFileHandler(fileList, maxFiles = 5, step1 = () => {}, step2 = () => {}) {
let files = [];
for(var i = 0; i < fileList.length && i < 5; i++) files[i] = fileList[i];

View File

@ -119,7 +119,9 @@ func FootHeaders(w http.ResponseWriter, header *c.Header) {
func renderTemplate3(tmplName, hookName string, w http.ResponseWriter, r *http.Request, h *c.Header, pi interface{}) error {
s := h.Stylesheets
h.Stylesheets = nil
if r.FormValue("i") != "1" {
c.PrepResources(&h.CurrentUser, h, h.Theme)
}
for _, ss := range s {
h.Stylesheets = append(h.Stylesheets, ss)
}

View File

@ -115,8 +115,6 @@ func ViewTopic(w http.ResponseWriter, r *http.Request, user c.User, header *c.He
return c.InternalError(err, w, r)
}
poll = pPoll.Copy()
header.AddSheet("chartist/chartist.min.css")
header.AddScript("chartist/chartist.min.js")
}
if topic.LikeCount > 0 && user.Liked > 0 {
@ -166,6 +164,9 @@ func ViewTopic(w http.ResponseWriter, r *http.Request, user c.User, header *c.He
var rerr c.RouteError
tmpl := forum.Tmpl
if r.FormValue("i") == "1" {
if tpage.Poll.ID != 0 {
header.AddXRes("chartist/chartist.min.css", "chartist/chartist.min.js")
}
if tmpl == "" {
rerr = renderTemplate("topic_mini", w, r, header, tpage)
} else {
@ -176,6 +177,10 @@ func ViewTopic(w http.ResponseWriter, r *http.Request, user c.User, header *c.He
}
}
} else {
if tpage.Poll.ID != 0 {
header.AddSheet("chartist/chartist.min.css")
header.AddScript("chartist/chartist.min.js")
}
if tmpl == "" {
rerr = renderTemplate("topic", w, r, header, tpage)
} else {

View File

@ -6,7 +6,7 @@
<link href="/s/{{.}}"rel="stylesheet"type="text/css">{{end}}
{{range .Header.PreScriptsAsync}}
<script async src="/s/{{.}}"></script>{{end}}
<meta property="x-loggedin" content="{{.CurrentUser.Loggedin}}"/>
<meta property="x-loggedin"content="{{.CurrentUser.Loggedin}}">
<script src="/s/init.js?i=10"></script>
{{range .Header.ScriptsAsync}}
<script async src="/s/{{.}}"></script>{{end}}