discourse/plugins/poll/assets/javascripts/initializers/extend-for-poll.js.es6

118 lines
2.8 KiB
Plaintext
Raw Normal View History

2018-06-16 00:42:20 +08:00
import { withPluginApi } from "discourse/lib/plugin-api";
2016-06-07 18:55:01 +08:00
import { observes } from "ember-addons/ember-computed-decorators";
2018-06-16 00:42:20 +08:00
import { getRegister } from "discourse-common/lib/get-owner";
import WidgetGlue from "discourse/widgets/glue";
function initializePolls(api) {
const register = getRegister(api);
2018-06-16 00:42:20 +08:00
api.modifyClass("controller:topic", {
subscribe() {
this._super(...arguments);
this.messageBus.subscribe("/polls/" + this.get("model.id"), msg => {
2018-06-16 00:42:20 +08:00
const post = this.get("model.postStream").findLoadedPost(msg.post_id);
if (post) {
2018-06-16 00:42:20 +08:00
post.set("polls", msg.polls);
}
});
},
2018-06-16 00:42:20 +08:00
unsubscribe() {
this.messageBus.unsubscribe("/polls/*");
this._super(...arguments);
}
});
let _glued = [];
let _interval = null;
function rerender() {
_glued.forEach(g => g.queueRerender());
}
2018-06-16 00:42:20 +08:00
api.modifyClass("model:post", {
_polls: null,
pollsObject: null,
// we need a proper ember object so it is bindable
2016-06-07 18:55:01 +08:00
@observes("polls")
pollsChanged() {
const polls = this.polls;
if (polls) {
this._polls = this._polls || {};
polls.forEach(p => {
const existing = this._polls[p.name];
if (existing) {
this._polls[p.name].setProperties(p);
} else {
2019-01-12 00:54:23 +08:00
this._polls[p.name] = Ember.Object.create(p);
}
});
this.set("pollsObject", this._polls);
rerender();
}
2016-06-07 18:55:01 +08:00
}
});
function attachPolls($elem, helper) {
2018-06-16 00:42:20 +08:00
const $polls = $(".poll", $elem);
if (!$polls.length) {
return;
}
if (!helper) {
return;
}
const post = helper.getModel();
api.preventCloak(post.id);
2018-06-16 00:42:20 +08:00
const votes = post.get("polls_votes") || {};
post.pollsChanged();
const polls = post.get("pollsObject");
2018-06-16 00:42:20 +08:00
if (!polls) {
return;
}
_interval = _interval || setInterval(rerender, 30000);
$polls.each((idx, pollElem) => {
const $poll = $(pollElem);
const pollName = $poll.data("poll-name");
const poll = polls[pollName];
if (poll) {
2018-06-16 00:42:20 +08:00
const glue = new WidgetGlue("discourse-poll", register, {
id: `${pollName}-${post.id}`,
post,
poll,
vote: votes[pollName] || []
});
glue.appendTo(pollElem);
_glued.push(glue);
}
});
}
function cleanUpPolls() {
if (_interval) {
clearInterval(_interval);
_interval = null;
}
_glued.forEach(g => g.cleanUp());
_glued = [];
}
api.includePostAttributes("polls", "polls_votes");
api.decorateCooked(attachPolls, { onlyStream: true, id: "discourse-poll" });
api.cleanupStream(cleanUpPolls);
}
export default {
name: "extend-for-poll",
initialize() {
2018-06-16 00:42:20 +08:00
withPluginApi("0.8.7", initializePolls);
}
2015-05-01 00:25:38 +08:00
};