DEV: apply coding standards to plugins (#10594)

This commit is contained in:
Joffrey JAFFEUX
2020-09-04 13:51:53 +02:00
committed by GitHub
parent 034a59a69d
commit bf88410126
27 changed files with 269 additions and 277 deletions

View File

@ -2,15 +2,15 @@ import I18n from "I18n";
import { withPluginApi } from "discourse/lib/plugin-api"; import { withPluginApi } from "discourse/lib/plugin-api";
function initializeDetails(api) { function initializeDetails(api) {
api.decorateCooked($elem => $("details", $elem), { api.decorateCooked(($elem) => $("details", $elem), {
id: "discourse-details" id: "discourse-details",
}); });
api.addToolbarPopupMenuOptionsCallback(() => { api.addToolbarPopupMenuOptionsCallback(() => {
return { return {
action: "insertDetails", action: "insertDetails",
icon: "caret-right", icon: "caret-right",
label: "details.title" label: "details.title",
}; };
}); });
@ -23,8 +23,8 @@ function initializeDetails(api) {
"details_text", "details_text",
{ multiline: false } { multiline: false }
); );
} },
} },
}); });
} }
@ -33,5 +33,5 @@ export default {
initialize() { initialize() {
withPluginApi("0.8.7", initializeDetails); withPluginApi("0.8.7", initializeDetails);
} },
}; };

View File

@ -13,7 +13,7 @@ const rule = {
after: function (state) { after: function (state) {
state.push("bbcode_close", "details", -1); state.push("bbcode_close", "details", -1);
} },
}; };
export function setup(helper) { export function setup(helper) {
@ -22,10 +22,10 @@ export function setup(helper) {
"summary[title]", "summary[title]",
"details", "details",
"details[open]", "details[open]",
"details.elided" "details.elided",
]); ]);
helper.registerPlugin(md => { helper.registerPlugin((md) => {
md.block.bbcode.ruler.push("details", rule); md.block.bbcode.ruler.push("details", rule);
}); });
} }

View File

@ -40,16 +40,16 @@ export default Component.extend({
timezones: [], timezones: [],
formats: (this.siteSettings.discourse_local_dates_default_formats || "") formats: (this.siteSettings.discourse_local_dates_default_formats || "")
.split("|") .split("|")
.filter(f => f), .filter((f) => f),
timezone: moment.tz.guess(), timezone: moment.tz.guess(),
date: moment().format(this.dateFormat) date: moment().format(this.dateFormat),
}); });
}, },
didInsertElement() { didInsertElement() {
this._super(...arguments); this._super(...arguments);
this._setupPicker().then(picker => { this._setupPicker().then((picker) => {
this._picker = picker; this._picker = picker;
this.send("focusFrom"); this.send("focusFrom");
}); });
@ -60,7 +60,7 @@ export default Component.extend({
const markup = this.markup; const markup = this.markup;
if (markup) { if (markup) {
cookAsync(markup).then(result => { cookAsync(markup).then((result) => {
this.set("currentPreview", result); this.set("currentPreview", result);
schedule("afterRender", () => schedule("afterRender", () =>
this.$(".preview .discourse-local-date").applyLocalDates() this.$(".preview .discourse-local-date").applyLocalDates()
@ -121,7 +121,7 @@ export default Component.extend({
time, time,
dateTime, dateTime,
format, format,
range: isRange ? "start" : false range: isRange ? "start" : false,
}); });
}, },
@ -154,7 +154,7 @@ export default Component.extend({
time, time,
dateTime, dateTime,
format, format,
range: isRange ? "end" : false range: isRange ? "end" : false,
}); });
}, },
@ -164,7 +164,7 @@ export default Component.extend({
recurring, recurring,
timezones, timezones,
timezone, timezone,
format format,
}); });
}, },
@ -177,7 +177,7 @@ export default Component.extend({
return EmberObject.create({ return EmberObject.create({
from: fromConfig, from: fromConfig,
to: toConfig, to: toConfig,
options options,
}); });
}, },
@ -198,18 +198,15 @@ export default Component.extend({
@computed("currentUserTimezone") @computed("currentUserTimezone")
formatedCurrentUserTimezone(timezone) { formatedCurrentUserTimezone(timezone) {
return timezone return timezone.replace("_", " ").replace("Etc/", "").split("/");
.replace("_", " ")
.replace("Etc/", "")
.split("/");
}, },
@computed("formats") @computed("formats")
previewedFormats(formats) { previewedFormats(formats) {
return formats.map(format => { return formats.map((format) => {
return { return {
format: format, format: format,
preview: moment().format(format) preview: moment().format(format),
}; };
}); });
}, },
@ -221,36 +218,36 @@ export default Component.extend({
return [ return [
{ {
name: I18n.t(`${key}.every_day`), name: I18n.t(`${key}.every_day`),
id: "1.days" id: "1.days",
}, },
{ {
name: I18n.t(`${key}.every_week`), name: I18n.t(`${key}.every_week`),
id: "1.weeks" id: "1.weeks",
}, },
{ {
name: I18n.t(`${key}.every_two_weeks`), name: I18n.t(`${key}.every_two_weeks`),
id: "2.weeks" id: "2.weeks",
}, },
{ {
name: I18n.t(`${key}.every_month`), name: I18n.t(`${key}.every_month`),
id: "1.months" id: "1.months",
}, },
{ {
name: I18n.t(`${key}.every_two_months`), name: I18n.t(`${key}.every_two_months`),
id: "2.months" id: "2.months",
}, },
{ {
name: I18n.t(`${key}.every_three_months`), name: I18n.t(`${key}.every_three_months`),
id: "3.months" id: "3.months",
}, },
{ {
name: I18n.t(`${key}.every_six_months`), name: I18n.t(`${key}.every_six_months`),
id: "6.months" id: "6.months",
}, },
{ {
name: I18n.t(`${key}.every_year`), name: I18n.t(`${key}.every_year`),
id: "1.years" id: "1.years",
} },
]; ];
}, },
@ -360,7 +357,7 @@ export default Component.extend({
cancel() { cancel() {
this._closeModal(); this._closeModal();
} },
}, },
_setTimeIfValid(time, key) { _setTimeIfValid(time, key) {
@ -375,7 +372,7 @@ export default Component.extend({
}, },
_setupPicker() { _setupPicker() {
return new Promise(resolve => { return new Promise((resolve) => {
loadScript("/javascripts/pikaday.js").then(() => { loadScript("/javascripts/pikaday.js").then(() => {
const options = { const options = {
field: this.$(`.fake-input`)[0], field: this.$(`.fake-input`)[0],
@ -391,9 +388,9 @@ export default Component.extend({
nextMonth: I18n.t("dates.next_month"), nextMonth: I18n.t("dates.next_month"),
months: moment.months(), months: moment.months(),
weekdays: moment.weekdays(), weekdays: moment.weekdays(),
weekdaysShort: moment.weekdaysMin() weekdaysShort: moment.weekdaysMin(),
}, },
onSelect: date => { onSelect: (date) => {
const formattedDate = moment(date).format("YYYY-MM-DD"); const formattedDate = moment(date).format("YYYY-MM-DD");
if (this.fromSelected) { if (this.fromSelected) {
@ -403,7 +400,7 @@ export default Component.extend({
if (this.toSelected) { if (this.toSelected) {
this.set("toDate", formattedDate); this.set("toDate", formattedDate);
} }
} },
}; };
resolve(new Pikaday(options)); resolve(new Pikaday(options));
@ -434,5 +431,5 @@ export default Component.extend({
_closeModal() { _closeModal() {
const composer = Discourse.__container__.lookup("controller:composer"); const composer = Discourse.__container__.lookup("controller:composer");
composer.send("closeModal"); composer.send("closeModal");
} },
}); });

View File

@ -17,5 +17,5 @@ export default Controller.extend(ModalFunctionality, {
); );
localDatesBtn && localDatesBtn.focus(); localDatesBtn && localDatesBtn.focus();
}); });
} },
}); });

View File

@ -13,18 +13,18 @@ const DATE_TEMPLATE = `
function initializeDiscourseLocalDates(api) { function initializeDiscourseLocalDates(api) {
api.decorateCooked( api.decorateCooked(
$elem => $(".discourse-local-date", $elem).applyLocalDates(), ($elem) => $(".discourse-local-date", $elem).applyLocalDates(),
{ id: "discourse-local-date" } { id: "discourse-local-date" }
); );
api.onToolbarCreate(toolbar => { api.onToolbarCreate((toolbar) => {
toolbar.addButton({ toolbar.addButton({
title: "discourse_local_dates.title", title: "discourse_local_dates.title",
id: "local-dates", id: "local-dates",
group: "extras", group: "extras",
icon: "calendar-alt", icon: "calendar-alt",
sendAction: event => sendAction: (event) =>
toolbar.context.send("insertDiscourseLocalDate", event) toolbar.context.send("insertDiscourseLocalDate", event),
}); });
}); });
@ -32,10 +32,10 @@ function initializeDiscourseLocalDates(api) {
actions: { actions: {
insertDiscourseLocalDate(toolbarEvent) { insertDiscourseLocalDate(toolbarEvent) {
showModal("discourse-local-dates-create-modal").setProperties({ showModal("discourse-local-dates-create-modal").setProperties({
toolbarEvent toolbarEvent,
}); });
} },
} },
}); });
} }
@ -70,7 +70,7 @@ export default {
moment.tz.guess() moment.tz.guess()
).build(); ).build();
const htmlPreviews = localDateBuilder.previews.map(preview => { const htmlPreviews = localDateBuilder.previews.map((preview) => {
const previewNode = document.createElement("div"); const previewNode = document.createElement("div");
previewNode.classList.add("preview"); previewNode.classList.add("preview");
if (preview.current) { if (preview.current) {
@ -92,7 +92,7 @@ export default {
const previewsNode = document.createElement("div"); const previewsNode = document.createElement("div");
previewsNode.classList.add("locale-dates-previews"); previewsNode.classList.add("locale-dates-previews");
htmlPreviews.forEach(htmlPreview => htmlPreviews.forEach((htmlPreview) =>
previewsNode.appendChild(htmlPreview) previewsNode.appendChild(htmlPreview)
); );
@ -110,5 +110,5 @@ export default {
withPluginApi("0.8.8", initializeDiscourseLocalDates); withPluginApi("0.8.8", initializeDiscourseLocalDates);
} }
} },
}; };

View File

@ -25,7 +25,7 @@ export default class DateWithZoneHelper {
"day", "day",
"hour", "hour",
"minute", "minute",
"second" "second",
]), ]),
this.timezone this.timezone
); );
@ -79,7 +79,7 @@ export default class DateWithZoneHelper {
minute: datetime.minute(), minute: datetime.minute(),
second: datetime.second(), second: datetime.second(),
timezone, timezone,
localTimezone localTimezone,
}); });
} }

View File

@ -10,7 +10,7 @@ function addLocalDate(buffer, matches, state) {
format: null, format: null,
timezones: null, timezones: null,
displayedTimezone: null, displayedTimezone: null,
countdown: null countdown: null,
}; };
const matchString = matches[1].replace(/„|“/g, '"'); const matchString = matches[1].replace(/„|“/g, '"');
@ -64,14 +64,14 @@ function addLocalDate(buffer, matches, state) {
if (config.countdown) { if (config.countdown) {
token.attrs.push([ token.attrs.push([
"data-countdown", "data-countdown",
state.md.utils.escapeHtml(config.countdown) state.md.utils.escapeHtml(config.countdown),
]); ]);
} }
if (config.calendar) { if (config.calendar) {
token.attrs.push([ token.attrs.push([
"data-calendar", "data-calendar",
state.md.utils.escapeHtml(config.calendar) state.md.utils.escapeHtml(config.calendar),
]); ]);
} }
@ -81,25 +81,25 @@ function addLocalDate(buffer, matches, state) {
) { ) {
token.attrs.push([ token.attrs.push([
"data-displayed-timezone", "data-displayed-timezone",
state.md.utils.escapeHtml(config.displayedTimezone) state.md.utils.escapeHtml(config.displayedTimezone),
]); ]);
} }
if (config.timezones) { if (config.timezones) {
const timezones = config.timezones.split("|").filter(timezone => { const timezones = config.timezones.split("|").filter((timezone) => {
return moment.tz.names().includes(timezone); return moment.tz.names().includes(timezone);
}); });
token.attrs.push([ token.attrs.push([
"data-timezones", "data-timezones",
state.md.utils.escapeHtml(timezones.join("|")) state.md.utils.escapeHtml(timezones.join("|")),
]); ]);
} }
if (config.timezone && moment.tz.names().includes(config.timezone)) { if (config.timezone && moment.tz.names().includes(config.timezone)) {
token.attrs.push([ token.attrs.push([
"data-timezone", "data-timezone",
state.md.utils.escapeHtml(config.timezone) state.md.utils.escapeHtml(config.timezone),
]); ]);
dateTime = moment.tz(dateTime, config.timezone); dateTime = moment.tz(dateTime, config.timezone);
} else { } else {
@ -109,7 +109,7 @@ function addLocalDate(buffer, matches, state) {
if (config.recurring) { if (config.recurring) {
token.attrs.push([ token.attrs.push([
"data-recurring", "data-recurring",
state.md.utils.escapeHtml(config.recurring) state.md.utils.escapeHtml(config.recurring),
]); ]);
} }
@ -141,7 +141,7 @@ export function setup(helper) {
helper.whiteList([ helper.whiteList([
"span.discourse-local-date", "span.discourse-local-date",
"span[data-*]", "span[data-*]",
"span[aria-label]" "span[aria-label]",
]); ]);
helper.registerOptions((opts, siteSettings) => { helper.registerOptions((opts, siteSettings) => {
@ -152,10 +152,10 @@ export function setup(helper) {
] = !!siteSettings.discourse_local_dates_enabled; ] = !!siteSettings.discourse_local_dates_enabled;
}); });
helper.registerPlugin(md => { helper.registerPlugin((md) => {
const rule = { const rule = {
matcher: /\[date(=.+?)\]/, matcher: /\[date(=.+?)\]/,
onMatch: addLocalDate onMatch: addLocalDate,
}; };
md.core.textPostProcess.ruler.push("discourse-local-dates", rule); md.core.textPostProcess.ruler.push("discourse-local-dates", rule);

View File

@ -23,10 +23,10 @@ export default class LocalDateBuilder {
} }
build() { build() {
const [year, month, day] = this.date.split("-").map(x => parseInt(x, 10)); const [year, month, day] = this.date.split("-").map((x) => parseInt(x, 10));
const [hour, minute, second] = (this.time || "") const [hour, minute, second] = (this.time || "")
.split(":") .split(":")
.map(x => (x ? parseInt(x, 10) : undefined)); .map((x) => (x ? parseInt(x, 10) : undefined));
let displayedTimezone; let displayedTimezone;
if (this.time) { if (this.time) {
@ -44,7 +44,7 @@ export default class LocalDateBuilder {
minute, minute,
second, second,
timezone: this.timezone, timezone: this.timezone,
localTimezone: this.localTimezone localTimezone: this.localTimezone,
}); });
if (this.recurring) { if (this.recurring) {
@ -66,13 +66,13 @@ export default class LocalDateBuilder {
moment.tz(this.localTimezone).isAfter(localDate.datetime), moment.tz(this.localTimezone).isAfter(localDate.datetime),
formated: this._applyFormatting(localDate, displayedTimezone), formated: this._applyFormatting(localDate, displayedTimezone),
previews, previews,
textPreview: this._generateTextPreviews(previews) textPreview: this._generateTextPreviews(previews),
}; };
} }
_generateTextPreviews(previews) { _generateTextPreviews(previews) {
return previews return previews
.map(preview => { .map((preview) => {
const formatedZone = this._zoneWithoutPrefix(preview.timezone); const formatedZone = this._zoneWithoutPrefix(preview.timezone);
return `${formatedZone} ${preview.formated}`; return `${formatedZone} ${preview.formated}`;
}) })
@ -83,7 +83,7 @@ export default class LocalDateBuilder {
const previewedTimezones = []; const previewedTimezones = [];
const timezones = this.timezones.filter( const timezones = this.timezones.filter(
timezone => !this._isEqualZones(timezone, this.localTimezone) (timezone) => !this._isEqualZones(timezone, this.localTimezone)
); );
previewedTimezones.push({ previewedTimezones.push({
@ -96,7 +96,7 @@ export default class LocalDateBuilder {
this.localTimezone this.localTimezone
), ),
this.time this.time
) ),
}); });
if ( if (
@ -104,12 +104,12 @@ export default class LocalDateBuilder {
displayedTimezone === this.localTimezone && displayedTimezone === this.localTimezone &&
this.timezone !== displayedTimezone && this.timezone !== displayedTimezone &&
!this._isEqualZones(displayedTimezone, this.timezone) && !this._isEqualZones(displayedTimezone, this.timezone) &&
!this.timezones.any(t => this._isEqualZones(t, this.timezone)) !this.timezones.any((t) => this._isEqualZones(t, this.timezone))
) { ) {
timezones.unshift(this.timezone); timezones.unshift(this.timezone);
} }
timezones.forEach(timezone => { timezones.forEach((timezone) => {
if (this._isEqualZones(timezone, displayedTimezone)) { if (this._isEqualZones(timezone, displayedTimezone)) {
return; return;
} }
@ -127,7 +127,7 @@ export default class LocalDateBuilder {
timezone timezone
), ),
this.time this.time
) ),
}); });
}); });
@ -158,7 +158,7 @@ export default class LocalDateBuilder {
return [ return [
startRange.format("LLLL"), startRange.format("LLLL"),
RANGE_SEPARATOR, RANGE_SEPARATOR,
endRange.format("LLLL") endRange.format("LLLL"),
].join(" "); ].join(" ");
} }
} }
@ -209,19 +209,19 @@ export default class LocalDateBuilder {
sameDay: this._translateCalendarKey(time, "today"), sameDay: this._translateCalendarKey(time, "today"),
nextDay: this._translateCalendarKey(time, "tomorrow"), nextDay: this._translateCalendarKey(time, "tomorrow"),
lastDay: this._translateCalendarKey(time, "yesterday"), lastDay: this._translateCalendarKey(time, "yesterday"),
sameElse: "L" sameElse: "L",
}; };
} }
_translateCalendarKey(time, key) { _translateCalendarKey(time, key) {
const translated = I18n.t(`discourse_local_dates.relative_dates.${key}`, { const translated = I18n.t(`discourse_local_dates.relative_dates.${key}`, {
time: "LT" time: "LT",
}); });
if (time) { if (time) {
return translated return translated
.split("LT") .split("LT")
.map(w => `[${w}]`) .map((w) => `[${w}]`)
.join("LT"); .join("LT");
} else { } else {
return `[${translated.replace(" LT", "")}]`; return `[${translated.replace(" LT", "")}]`;
@ -229,10 +229,7 @@ export default class LocalDateBuilder {
} }
_formatTimezone(timezone) { _formatTimezone(timezone) {
return timezone return timezone.replace("_", " ").replace("Etc/", "").split("/");
.replace("_", " ")
.replace("Etc/", "")
.split("/");
} }
_zoneWithoutPrefix(timezone) { _zoneWithoutPrefix(timezone) {

View File

@ -10,7 +10,7 @@ function initialize(api) {
didInsertElement() { didInsertElement() {
this._super(...arguments); this._super(...arguments);
this.dispatch("header:search-context-trigger", "header"); this.dispatch("header:search-context-trigger", "header");
} },
}); });
api.modifyClass("model:post", { api.modifyClass("model:post", {
@ -22,18 +22,18 @@ function initialize(api) {
if (this.user_id === discobotUserId && !this.bookmarked) { if (this.user_id === discobotUserId && !this.bookmarked) {
return ajax("/bookmarks", { return ajax("/bookmarks", {
type: "POST", type: "POST",
data: { post_id: this.id } data: { post_id: this.id },
}).then(response => { }).then((response) => {
this.setProperties({ this.setProperties({
"topic.bookmarked": true, "topic.bookmarked": true,
bookmarked: true, bookmarked: true,
bookmark_id: response.id bookmark_id: response.id,
}); });
this.appEvents.trigger("post-stream:refresh", { id: this.id }); this.appEvents.trigger("post-stream:refresh", { id: this.id });
}); });
} }
return this._super(); return this._super();
} },
}); });
api.attachWidgetAction("header", "headerSearchContextTrigger", function () { api.attachWidgetAction("header", "headerSearchContextTrigger", function () {
@ -59,5 +59,5 @@ export default {
const siteSettings = container.lookup("site-settings:main"); const siteSettings = container.lookup("site-settings:main");
if (siteSettings.discourse_narrative_bot_enabled) if (siteSettings.discourse_narrative_bot_enabled)
withPluginApi("0.8.7", initialize); withPluginApi("0.8.7", initialize);
} },
}; };

View File

@ -4,14 +4,14 @@ import { equal, gt } from "@ember/object/computed";
import { inject as service } from "@ember/service"; import { inject as service } from "@ember/service";
import discourseComputed, { import discourseComputed, {
observes, observes,
on on,
} from "discourse-common/utils/decorators"; } from "discourse-common/utils/decorators";
import { import {
REPLYING, REPLYING,
CLOSED, CLOSED,
EDITING, EDITING,
COMPOSER_TYPE, COMPOSER_TYPE,
KEEP_ALIVE_DURATION_SECONDS KEEP_ALIVE_DURATION_SECONDS,
} from "discourse/plugins/discourse-presence/discourse/lib/presence"; } from "discourse/plugins/discourse-presence/discourse/lib/presence";
import { REPLY, EDIT } from "discourse/models/composer"; import { REPLY, EDIT } from "discourse/models/composer";
@ -74,7 +74,7 @@ export default Component.extend({
state: action === EDIT ? EDITING : REPLYING, state: action === EDIT ? EDITING : REPLYING,
whisper: this.get("model.whisper"), whisper: this.get("model.whisper"),
postId: this.get("model.post.id"), postId: this.get("model.post.id"),
presenceStaffOnly: this.get("model._presenceStaffOnly") presenceStaffOnly: this.get("model._presenceStaffOnly"),
}; };
this._prevPublishData = data; this._prevPublishData = data;
@ -118,5 +118,5 @@ export default Component.extend({
cancel(this._throttle); cancel(this._throttle);
this._throttle = null; this._throttle = null;
} }
} },
}); });

View File

@ -23,5 +23,5 @@ export default Component.extend({
@on("willDestroyElement") @on("willDestroyElement")
_destroyed() { _destroyed() {
this.presenceManager.unsubscribe(this.get("topic.id"), TOPIC_TYPE); this.presenceManager.unsubscribe(this.get("topic.id"), TOPIC_TYPE);
} },
}); });

View File

@ -44,7 +44,7 @@ const Presence = EmberObject.extend({
this.setProperties({ this.setProperties({
users: [], users: [],
editingUsers: [], editingUsers: [],
subscribers: new Set() subscribers: new Set(),
}); });
}, },
@ -52,7 +52,7 @@ const Presence = EmberObject.extend({
if (this.subscribers.size === 0) { if (this.subscribers.size === 0) {
this.messageBus.subscribe( this.messageBus.subscribe(
this.channel, this.channel,
message => { (message) => {
const { user, state } = message; const { user, state } = message;
if (this.get("currentUser.id") === user.id) return; if (this.get("currentUser.id") === user.id) return;
@ -62,7 +62,7 @@ const Presence = EmberObject.extend({
break; break;
case EDITING: case EDITING:
this._appendUser(this.editingUsers, user, { this._appendUser(this.editingUsers, user, {
post_id: parseInt(message.post_id, 10) post_id: parseInt(message.post_id, 10),
}); });
break; break;
case CLOSED: case CLOSED:
@ -87,7 +87,7 @@ const Presence = EmberObject.extend({
this.setProperties({ this.setProperties({
users: [], users: [],
editingUsers: [] editingUsers: [],
}); });
} }
@ -104,7 +104,7 @@ const Presence = EmberObject.extend({
const data = { const data = {
state, state,
topic_id: this.topicId topic_id: this.topicId,
}; };
if (whisper) { if (whisper) {
@ -121,22 +121,22 @@ const Presence = EmberObject.extend({
return ajax("/presence/publish", { return ajax("/presence/publish", {
type: "POST", type: "POST",
data data,
}); });
}, },
_removeUser(user) { _removeUser(user) {
[this.users, this.editingUsers].forEach(users => { [this.users, this.editingUsers].forEach((users) => {
const existingUser = users.findBy("id", user.id); const existingUser = users.findBy("id", user.id);
if (existingUser) users.removeObject(existingUser); if (existingUser) users.removeObject(existingUser);
}); });
}, },
_cleanUpUsers() { _cleanUpUsers() {
[this.users, this.editingUsers].forEach(users => { [this.users, this.editingUsers].forEach((users) => {
const staleUsers = []; const staleUsers = [];
users.forEach(user => { users.forEach((user) => {
if (user.last_seen <= Date.now() - BUFFER_DURATION_SECONDS * 1000) { if (user.last_seen <= Date.now() - BUFFER_DURATION_SECONDS * 1000) {
staleUsers.push(user); staleUsers.push(user);
} }
@ -152,7 +152,7 @@ const Presence = EmberObject.extend({
let existingUser; let existingUser;
let usersLength = 0; let usersLength = 0;
users.forEach(u => { users.forEach((u) => {
if (u.id === user.id) { if (u.id === user.id) {
existingUser = u; existingUser = u;
} }
@ -204,7 +204,7 @@ const Presence = EmberObject.extend({
if (!this._timer) { if (!this._timer) {
this.set("_timer", this._scheduleTimer(callback)); this.set("_timer", this._scheduleTimer(callback));
} }
} },
}); });
export default Presence; export default Presence;

View File

@ -1,6 +1,6 @@
import Service from "@ember/service"; import Service from "@ember/service";
import Presence, { import Presence, {
CLOSED CLOSED,
} from "discourse/plugins/discourse-presence/discourse/lib/presence"; } from "discourse/plugins/discourse-presence/discourse/lib/presence";
const PresenceManager = Service.extend({ const PresenceManager = Service.extend({
@ -10,7 +10,7 @@ const PresenceManager = Service.extend({
this._super(...arguments); this._super(...arguments);
this.setProperties({ this.setProperties({
presences: {} presences: {},
}); });
}, },
@ -49,7 +49,7 @@ const PresenceManager = Service.extend({
}, },
cleanUpPresence(type) { cleanUpPresence(type) {
Object.keys(this.presences).forEach(key => { Object.keys(this.presences).forEach((key) => {
this.publish(key, CLOSED); this.publish(key, CLOSED);
this.unsubscribe(key, type); this.unsubscribe(key, type);
}); });
@ -61,12 +61,12 @@ const PresenceManager = Service.extend({
messageBus: this.messageBus, messageBus: this.messageBus,
siteSettings: this.siteSettings, siteSettings: this.siteSettings,
currentUser: this.currentUser, currentUser: this.currentUser,
topicId topicId,
}); });
} }
return this.presences[topicId]; return this.presences[topicId];
} },
}); });
export default PresenceManager; export default PresenceManager;

View File

@ -1,5 +1,5 @@
export default { export default {
shouldRender(_, component) { shouldRender(_, component) {
return component.siteSettings.presence_enabled; return component.siteSettings.presence_enabled;
} },
}; };

View File

@ -1,5 +1,5 @@
export default { export default {
shouldRender(_, component) { shouldRender(_, component) {
return component.siteSettings.presence_enabled; return component.siteSettings.presence_enabled;
} },
}; };

View File

@ -3,9 +3,9 @@ import { withPluginApi } from "discourse/lib/plugin-api";
export default { export default {
name: "apply-lazyYT", name: "apply-lazyYT",
initialize() { initialize() {
withPluginApi("0.1", api => { withPluginApi("0.1", (api) => {
api.decorateCooked( api.decorateCooked(
$elem => { ($elem) => {
const iframes = $(".lazyYT", $elem); const iframes = $(".lazyYT", $elem);
if (iframes.length === 0) { if (iframes.length === 0) {
return; return;
@ -21,11 +21,11 @@ export default {
if (postId) { if (postId) {
api.preventCloak(postId); api.preventCloak(postId);
} }
} },
}); });
}, },
{ id: "discourse-lazyyt" } { id: "discourse-lazyyt" }
); );
}); });
} },
}; };

View File

@ -91,7 +91,7 @@
$el $el
.css({ .css({
"padding-bottom": padding_bottom "padding-bottom": padding_bottom,
}) })
.html(innerHtml.join("")); .html(innerHtml.join(""));
@ -123,7 +123,7 @@
id, id,
"/", "/",
thumb_img, thumb_img,
'">' '">',
].join("") ].join("")
) )
); );
@ -160,7 +160,7 @@
var defaultSettings = { var defaultSettings = {
default_ratio: "16:9", default_ratio: "16:9",
callback: null, // ToDO execute callback if given callback: null, // ToDO execute callback if given
container_class: "lazyYT-container" container_class: "lazyYT-container",
}; };
var settings = $.extend(defaultSettings, newSettings); var settings = $.extend(defaultSettings, newSettings);

View File

@ -86,9 +86,9 @@ export default Component.extend({
// TODO: It's a workaround for Chart.js' terrible hover styling. // TODO: It's a workaround for Chart.js' terrible hover styling.
// It will break on non-white backgrounds. // It will break on non-white backgrounds.
// Should be updated after #10341 lands // Should be updated after #10341 lands
hoverBorderColor: "#fff" hoverBorderColor: "#fff",
} },
] ],
}, },
options: { options: {
plugins: { plugins: {
@ -98,13 +98,13 @@ export default Component.extend({
borderRadius: 2, borderRadius: 2,
font: { font: {
family: getComputedStyle(document.body).fontFamily, family: getComputedStyle(document.body).fontFamily,
size: 16 size: 16,
}, },
padding: { padding: {
top: 2, top: 2,
right: 6, right: 6,
bottom: 2, bottom: 2,
left: 6 left: 6,
}, },
formatter(votes) { formatter(votes) {
if (displayMode !== "percentage") { if (displayMode !== "percentage") {
@ -112,12 +112,12 @@ export default Component.extend({
} }
const percent = I18n.toNumber((votes / totalVotes) * 100.0, { const percent = I18n.toNumber((votes / totalVotes) * 100.0, {
precision: 1 precision: 1,
}); });
return `${percent}%`; return `${percent}%`;
} },
} },
}, },
responsive: true, responsive: true,
aspectRatio: 1.1, aspectRatio: 1.1,
@ -131,15 +131,15 @@ export default Component.extend({
const sliceIndex = activeElements[0]._index; const sliceIndex = activeElements[0]._index;
const optionIndex = Object.keys(this._optionToSlice).find( const optionIndex = Object.keys(this._optionToSlice).find(
option => this._optionToSlice[option] === sliceIndex (option) => this._optionToSlice[option] === sliceIndex
); );
// Clear the array to avoid issues in Chart.js // Clear the array to avoid issues in Chart.js
activeElements.length = 0; activeElements.length = 0;
this.setHighlightedOption(Number(optionIndex)); this.setHighlightedOption(Number(optionIndex));
} },
} },
}; };
}, },
@ -178,5 +178,5 @@ export default Component.extend({
this._previousHighlightedSliceIndex = sliceIndex; this._previousHighlightedSliceIndex = sliceIndex;
meta.controller.setHoverStyle(slice); meta.controller.setHoverStyle(slice);
this._chart.draw(); this._chart.draw();
} },
}); });

View File

@ -57,5 +57,5 @@ export default Component.extend({
} else { } else {
this.onMouseOut(); this.onMouseOut();
} }
} },
}); });

View File

@ -17,7 +17,7 @@ export default Controller.extend(ModalFunctionality, {
@discourseComputed("model.groupableUserFields") @discourseComputed("model.groupableUserFields")
groupableUserFields(fields) { groupableUserFields(fields) {
return fields.map(field => { return fields.map((field) => {
const transformed = field.split("_").filter(Boolean); const transformed = field.split("_").filter(Boolean);
if (transformed.length > 1) { if (transformed.length > 1) {
@ -51,17 +51,17 @@ export default Controller.extend(ModalFunctionality, {
data: { data: {
post_id: this.model.post.id, post_id: this.model.post.id,
poll_name: this.model.poll.name, poll_name: this.model.poll.name,
user_field_name: this.groupedBy user_field_name: this.groupedBy,
} },
}) })
.catch(error => { .catch((error) => {
if (error) { if (error) {
popupAjaxError(error); popupAjaxError(error);
} else { } else {
bootbox.alert(I18n.t("poll.error_while_fetching_voters")); bootbox.alert(I18n.t("poll.error_while_fetching_voters"));
} }
}) })
.then(result => { .then((result) => {
if (this.isDestroying || this.isDestroyed) { if (this.isDestroying || this.isDestroyed) {
return; return;
} }
@ -79,5 +79,5 @@ export default Controller.extend(ModalFunctionality, {
@action @action
onSelectPanel(panel) { onSelectPanel(panel) {
this.set("displayMode", panel.id); this.set("displayMode", panel.id);
} },
}); });

View File

@ -18,12 +18,12 @@ export default Controller.extend({
pollChartTypes: [ pollChartTypes: [
{ {
name: I18n.t("poll.ui_builder.poll_chart_type.bar"), name: I18n.t("poll.ui_builder.poll_chart_type.bar"),
value: BAR_CHART_TYPE value: BAR_CHART_TYPE,
}, },
{ {
name: I18n.t("poll.ui_builder.poll_chart_type.pie"), name: I18n.t("poll.ui_builder.poll_chart_type.pie"),
value: PIE_CHART_TYPE value: PIE_CHART_TYPE,
} },
], ],
pollType: null, pollType: null,
@ -39,16 +39,16 @@ export default Controller.extend({
return [ return [
{ {
name: I18n.t("poll.ui_builder.poll_type.regular"), name: I18n.t("poll.ui_builder.poll_type.regular"),
value: regularPollType value: regularPollType,
}, },
{ {
name: I18n.t("poll.ui_builder.poll_type.number"), name: I18n.t("poll.ui_builder.poll_type.number"),
value: numberPollType value: numberPollType,
}, },
{ {
name: I18n.t("poll.ui_builder.poll_type.multiple"), name: I18n.t("poll.ui_builder.poll_type.multiple"),
value: multiplePollType value: multiplePollType,
} },
]; ];
}, },
@ -72,21 +72,21 @@ export default Controller.extend({
let options = [ let options = [
{ {
name: I18n.t("poll.ui_builder.poll_result.always"), name: I18n.t("poll.ui_builder.poll_result.always"),
value: alwaysPollResult value: alwaysPollResult,
}, },
{ {
name: I18n.t("poll.ui_builder.poll_result.vote"), name: I18n.t("poll.ui_builder.poll_result.vote"),
value: votePollResult value: votePollResult,
}, },
{ {
name: I18n.t("poll.ui_builder.poll_result.closed"), name: I18n.t("poll.ui_builder.poll_result.closed"),
value: closedPollResult value: closedPollResult,
} },
]; ];
if (this.get("currentUser.staff")) { if (this.get("currentUser.staff")) {
options.push({ options.push({
name: I18n.t("poll.ui_builder.poll_result.staff"), name: I18n.t("poll.ui_builder.poll_result.staff"),
value: staffPollResult value: staffPollResult,
}); });
} }
return options; return options;
@ -95,7 +95,7 @@ export default Controller.extend({
@discourseComputed("site.groups") @discourseComputed("site.groups")
siteGroups(groups) { siteGroups(groups) {
return groups return groups
.map(g => { .map((g) => {
// prevents group "everyone" to be listed // prevents group "everyone" to be listed
if (g.id !== 0) { if (g.id !== 0) {
return { name: g.name }; return { name: g.name };
@ -130,7 +130,7 @@ export default Controller.extend({
let length = 0; let length = 0;
pollOptions.split("\n").forEach(option => { pollOptions.split("\n").forEach((option) => {
if (option.length !== 0) length += 1; if (option.length !== 0) length += 1;
}); });
@ -267,7 +267,7 @@ export default Controller.extend({
output += `${pollHeader}\n`; output += `${pollHeader}\n`;
if (pollOptions.length > 0 && !isNumber) { if (pollOptions.length > 0 && !isNumber) {
pollOptions.split("\n").forEach(option => { pollOptions.split("\n").forEach((option) => {
if (option.length !== 0) output += `* ${option}\n`; if (option.length !== 0) output += `* ${option}\n`;
}); });
} }
@ -299,7 +299,7 @@ export default Controller.extend({
if (pollMin >= pollMax) { if (pollMin >= pollMax) {
options = { options = {
failed: true, failed: true,
reason: I18n.t("poll.ui_builder.help.invalid_values") reason: I18n.t("poll.ui_builder.help.invalid_values"),
}; };
} }
@ -313,7 +313,7 @@ export default Controller.extend({
if (pollStep < 1) { if (pollStep < 1) {
options = { options = {
failed: true, failed: true,
reason: I18n.t("poll.ui_builder.help.min_step_value") reason: I18n.t("poll.ui_builder.help.min_step_value"),
}; };
} }
@ -327,7 +327,7 @@ export default Controller.extend({
if (disableInsert) { if (disableInsert) {
options = { options = {
failed: true, failed: true,
reason: I18n.t("poll.ui_builder.help.options_count") reason: I18n.t("poll.ui_builder.help.options_count"),
}; };
} }
@ -335,9 +335,9 @@ export default Controller.extend({
}, },
_comboboxOptions(startIndex, endIndex) { _comboboxOptions(startIndex, endIndex) {
return [...Array(endIndex - startIndex).keys()].map(number => ({ return [...Array(endIndex - startIndex).keys()].map((number) => ({
value: number + startIndex, value: number + startIndex,
name: number + startIndex name: number + startIndex,
})); }));
}, },
@ -353,12 +353,8 @@ export default Controller.extend({
chartType: BAR_CHART_TYPE, chartType: BAR_CHART_TYPE,
pollResult: this.alwaysPollResult, pollResult: this.alwaysPollResult,
pollGroups: null, pollGroups: null,
date: moment() date: moment().add(1, "day").format("YYYY-MM-DD"),
.add(1, "day") time: moment().add(1, "hour").format("HH:mm"),
.format("YYYY-MM-DD"),
time: moment()
.add(1, "hour")
.format("HH:mm")
}); });
}, },
@ -367,6 +363,6 @@ export default Controller.extend({
this.toolbarEvent.addText(this.pollOutput); this.toolbarEvent.addText(this.pollOutput);
this.send("closeModal"); this.send("closeModal");
this._setupPoll(); this._setupPoll();
} },
} },
}); });

View File

@ -22,8 +22,8 @@ function initializePollUIBuilder(api) {
actions: { actions: {
showPollBuilder() { showPollBuilder() {
showModal("poll-ui-builder").set("toolbarEvent", this.toolbarEvent); showModal("poll-ui-builder").set("toolbarEvent", this.toolbarEvent);
} },
} },
}); });
api.addToolbarPopupMenuOptionsCallback(() => { api.addToolbarPopupMenuOptionsCallback(() => {
@ -31,7 +31,7 @@ function initializePollUIBuilder(api) {
action: "showPollBuilder", action: "showPollBuilder",
icon: "chart-bar", icon: "chart-bar",
label: "poll.ui_builder.title", label: "poll.ui_builder.title",
condition: "canBuildPoll" condition: "canBuildPoll",
}; };
}); });
} }
@ -41,5 +41,5 @@ export default {
initialize() { initialize() {
withPluginApi("0.8.7", initializePollUIBuilder); withPluginApi("0.8.7", initializePollUIBuilder);
} },
}; };

View File

@ -10,7 +10,7 @@ function initializePolls(api) {
api.modifyClass("controller:topic", { api.modifyClass("controller:topic", {
subscribe() { subscribe() {
this._super(...arguments); this._super(...arguments);
this.messageBus.subscribe("/polls/" + this.get("model.id"), msg => { this.messageBus.subscribe("/polls/" + this.get("model.id"), (msg) => {
const post = this.get("model.postStream").findLoadedPost(msg.post_id); const post = this.get("model.postStream").findLoadedPost(msg.post_id);
if (post) { if (post) {
post.set("polls", msg.polls); post.set("polls", msg.polls);
@ -20,14 +20,14 @@ function initializePolls(api) {
unsubscribe() { unsubscribe() {
this.messageBus.unsubscribe("/polls/*"); this.messageBus.unsubscribe("/polls/*");
this._super(...arguments); this._super(...arguments);
} },
}); });
let _glued = []; let _glued = [];
let _interval = null; let _interval = null;
function rerender() { function rerender() {
_glued.forEach(g => g.queueRerender()); _glued.forEach((g) => g.queueRerender());
} }
api.modifyClass("model:post", { api.modifyClass("model:post", {
@ -40,7 +40,7 @@ function initializePolls(api) {
const polls = this.polls; const polls = this.polls;
if (polls) { if (polls) {
this._polls = this._polls || {}; this._polls = this._polls || {};
polls.forEach(p => { polls.forEach((p) => {
const existing = this._polls[p.name]; const existing = this._polls[p.name];
if (existing) { if (existing) {
this._polls[p.name].setProperties(p); this._polls[p.name].setProperties(p);
@ -51,7 +51,7 @@ function initializePolls(api) {
this.set("pollsObject", this._polls); this.set("pollsObject", this._polls);
rerender(); rerender();
} }
} },
}); });
function attachPolls($elem, helper) { function attachPolls($elem, helper) {
@ -81,7 +81,7 @@ function initializePolls(api) {
pollPost = post.quoted[quotedId]; pollPost = post.quoted[quotedId];
pollPost = EmberObject.create(pollPost); pollPost = EmberObject.create(pollPost);
poll = EmberObject.create( poll = EmberObject.create(
pollPost.polls.find(p => p.name === pollName) pollPost.polls.find((p) => p.name === pollName)
); );
vote = pollPost.polls_votes || {}; vote = pollPost.polls_votes || {};
vote = vote[pollName] || []; vote = vote[pollName] || [];
@ -98,7 +98,7 @@ function initializePolls(api) {
.poll_groupable_user_fields || "" .poll_groupable_user_fields || ""
) )
.split("|") .split("|")
.filter(Boolean) .filter(Boolean),
}; };
const glue = new WidgetGlue("discourse-poll", register, attrs); const glue = new WidgetGlue("discourse-poll", register, attrs);
glue.appendTo(pollElem); glue.appendTo(pollElem);
@ -113,7 +113,7 @@ function initializePolls(api) {
_interval = null; _interval = null;
} }
_glued.forEach(g => g.cleanUp()); _glued.forEach((g) => g.cleanUp());
_glued = []; _glued = [];
} }
@ -127,5 +127,5 @@ export default {
initialize() { initialize() {
withPluginApi("0.8.7", initializePolls); withPluginApi("0.8.7", initializePolls);
} },
}; };

View File

@ -9,7 +9,7 @@ export function getColors(count, palette) {
25: [220, 237, 200], 25: [220, 237, 200],
50: [66, 179, 213], 50: [66, 179, 213],
75: [26, 39, 62], 75: [26, 39, 62],
100: [0, 0, 0] 100: [0, 0, 0],
}; };
break; break;
case "warm": case "warm":
@ -18,7 +18,7 @@ export function getColors(count, palette) {
25: [254, 235, 101], 25: [254, 235, 101],
50: [228, 82, 27], 50: [228, 82, 27],
75: [77, 52, 47], 75: [77, 52, 47],
100: [0, 0, 0] 100: [0, 0, 0],
}; };
break; break;
} }

View File

@ -15,7 +15,7 @@ const WHITELISTED_ATTRIBUTES = [
"groups", "groups",
"status", "status",
"step", "step",
"type" "type",
]; ];
function replaceToken(tokens, target, list) { function replaceToken(tokens, target, list) {
@ -106,7 +106,7 @@ const rule = {
attributes.push([DATA_PREFIX + "status", "open"]); attributes.push([DATA_PREFIX + "status", "open"]);
} }
WHITELISTED_ATTRIBUTES.forEach(name => { WHITELISTED_ATTRIBUTES.forEach((name) => {
if (attrs[name]) { if (attrs[name]) {
attributes.push([DATA_PREFIX + name, attrs[name]]); attributes.push([DATA_PREFIX + name, attrs[name]]);
} }
@ -221,7 +221,7 @@ const rule = {
state.push("poll_close", "div", -1); state.push("poll_close", "div", -1);
state.push("poll_close", "div", -1); state.push("poll_close", "div", -1);
state.push("poll_close", "div", -1); state.push("poll_close", "div", -1);
} },
}; };
function newApiInit(helper) { function newApiInit(helper) {
@ -230,7 +230,7 @@ function newApiInit(helper) {
opts.pollMaximumOptions = siteSettings.poll_maximum_options; opts.pollMaximumOptions = siteSettings.poll_maximum_options;
}); });
helper.registerPlugin(md => { helper.registerPlugin((md) => {
md.block.bbcode.ruler.push("poll", rule); md.block.bbcode.ruler.push("poll", rule);
}); });
} }
@ -247,7 +247,7 @@ export function setup(helper) {
"span.info-label", "span.info-label",
"a.button.cast-votes", "a.button.cast-votes",
"a.button.toggle-results", "a.button.toggle-results",
"li[data-*]" "li[data-*]",
]); ]);
newApiInit(helper); newApiInit(helper);

View File

@ -1,10 +1,10 @@
// works as described on http://stackoverflow.com/a/13483710 // works as described on http://stackoverflow.com/a/13483710
function sumsUpTo100(percentages) { function sumsUpTo100(percentages) {
return percentages.map(p => Math.floor(p)).reduce((a, b) => a + b) === 100; return percentages.map((p) => Math.floor(p)).reduce((a, b) => a + b) === 100;
} }
export default function (percentages) { export default function (percentages) {
var decimals = percentages.map(a => a % 1); var decimals = percentages.map((a) => a % 1);
const sumOfDecimals = Math.ceil(decimals.reduce((a, b) => a + b)); const sumOfDecimals = Math.ceil(decimals.reduce((a, b) => a + b));
// compensate error by adding 1 to n items with the greatest decimal part // compensate error by adding 1 to n items with the greatest decimal part
for (let i = 0, max = decimals.length; i < sumOfDecimals && i < max; i++) { for (let i = 0, max = decimals.length; i < sumOfDecimals && i < max; i++) {
@ -24,5 +24,5 @@ export default function(percentages) {
if (sumsUpTo100(percentages)) break; if (sumsUpTo100(percentages)) break;
} }
return percentages.map(p => Math.floor(p)); return percentages.map((p) => Math.floor(p));
} }

View File

@ -26,12 +26,12 @@ function optionHtml(option) {
function infoTextHtml(text) { function infoTextHtml(text) {
return new RawHtml({ return new RawHtml({
html: `<span class="info-text">${text}</span>` html: `<span class="info-text">${text}</span>`,
}); });
} }
function _fetchVoters(data) { function _fetchVoters(data) {
return ajax("/polls/voters.json", { data }).catch(error => { return ajax("/polls/voters.json", { data }).catch((error) => {
if (error) { if (error) {
popupAjaxError(error); popupAjaxError(error);
} else { } else {
@ -42,16 +42,16 @@ function _fetchVoters(data) {
function checkUserGroups(user, poll) { function checkUserGroups(user, poll) {
const pollGroups = const pollGroups =
poll && poll.groups && poll.groups.split(",").map(g => g.toLowerCase()); poll && poll.groups && poll.groups.split(",").map((g) => g.toLowerCase());
if (!pollGroups) { if (!pollGroups) {
return true; return true;
} }
const userGroups = const userGroups =
user && user.groups && user.groups.map(g => g.name.toLowerCase()); user && user.groups && user.groups.map((g) => g.name.toLowerCase());
return userGroups && pollGroups.some(g => userGroups.includes(g)); return userGroups && pollGroups.some((g) => userGroups.includes(g));
} }
createWidget("discourse-poll-option", { createWidget("discourse-poll-option", {
@ -82,12 +82,12 @@ createWidget("discourse-poll-option", {
if ($(e.target).closest("a").length === 0) { if ($(e.target).closest("a").length === 0) {
this.sendWidgetAction("toggleOption", this.attrs.option); this.sendWidgetAction("toggleOption", this.attrs.option);
} }
} },
}); });
createWidget("discourse-poll-load-more", { createWidget("discourse-poll-load-more", {
tagName: "div.poll-voters-toggle-expand", tagName: "div.poll-voters-toggle-expand",
buildKey: attrs => `load-more-${attrs.optionId}`, buildKey: (attrs) => `load-more-${attrs.optionId}`,
defaultState() { defaultState() {
return { loading: false }; return { loading: false };
@ -108,18 +108,18 @@ createWidget("discourse-poll-load-more", {
return this.sendWidgetAction("loadMore").finally( return this.sendWidgetAction("loadMore").finally(
() => (state.loading = false) () => (state.loading = false)
); );
} },
}); });
createWidget("discourse-poll-voters", { createWidget("discourse-poll-voters", {
tagName: "ul.poll-voters-list", tagName: "ul.poll-voters-list",
buildKey: attrs => `poll-voters-${attrs.optionId}`, buildKey: (attrs) => `poll-voters-${attrs.optionId}`,
defaultState() { defaultState() {
return { return {
loaded: "new", loaded: "new",
voters: [], voters: [],
page: 1 page: 1,
}; };
}, },
@ -133,8 +133,8 @@ createWidget("discourse-poll-voters", {
post_id: attrs.postId, post_id: attrs.postId,
poll_name: attrs.pollName, poll_name: attrs.pollName,
option_id: attrs.optionId, option_id: attrs.optionId,
page: state.page page: state.page,
}).then(result => { }).then((result) => {
state.loaded = "loaded"; state.loaded = "loaded";
state.page += 1; state.page += 1;
@ -143,9 +143,11 @@ createWidget("discourse-poll-voters", {
? result.voters ? result.voters
: result.voters[attrs.optionId]; : result.voters[attrs.optionId];
const existingVoters = new Set(state.voters.map(voter => voter.username)); const existingVoters = new Set(
state.voters.map((voter) => voter.username)
);
newVoters.forEach(voter => { newVoters.forEach((voter) => {
if (!existingVoters.has(voter.username)) { if (!existingVoters.has(voter.username)) {
existingVoters.add(voter.username); existingVoters.add(voter.username);
state.voters.push(voter); state.voters.push(voter);
@ -165,13 +167,13 @@ createWidget("discourse-poll-voters", {
state.voters = attrs.voters; state.voters = attrs.voters;
} }
const contents = state.voters.map(user => { const contents = state.voters.map((user) => {
return h("li", [ return h("li", [
avatarFor("tiny", { avatarFor("tiny", {
username: user.username, username: user.username,
template: user.avatar_template template: user.avatar_template,
}), }),
" " " ",
]); ]);
}); });
@ -180,12 +182,12 @@ createWidget("discourse-poll-voters", {
} }
return h("div.poll-voters", contents); return h("div.poll-voters", contents);
} },
}); });
createWidget("discourse-poll-standard-results", { createWidget("discourse-poll-standard-results", {
tagName: "ul.results", tagName: "ul.results",
buildKey: attrs => `poll-standard-results-${attrs.id}`, buildKey: (attrs) => `poll-standard-results-${attrs.id}`,
defaultState() { defaultState() {
return { loaded: false }; return { loaded: false };
@ -196,8 +198,8 @@ createWidget("discourse-poll-standard-results", {
return _fetchVoters({ return _fetchVoters({
post_id: attrs.post.id, post_id: attrs.post.id,
poll_name: attrs.poll.get("name") poll_name: attrs.poll.get("name"),
}).then(result => { }).then((result) => {
state.voters = result.voters; state.voters = result.voters;
this.scheduleRerender(); this.scheduleRerender();
}); });
@ -233,7 +235,7 @@ createWidget("discourse-poll-standard-results", {
const percentages = const percentages =
voters === 0 voters === 0
? Array(ordered.length).fill(0) ? Array(ordered.length).fill(0)
: ordered.map(o => (100 * o.votes) / voters); : ordered.map((o) => (100 * o.votes) / voters);
const rounded = attrs.isMultiple const rounded = attrs.isMultiple
? percentages.map(Math.floor) ? percentages.map(Math.floor)
@ -265,7 +267,7 @@ createWidget("discourse-poll-standard-results", {
optionId: option.id, optionId: option.id,
pollName: poll.get("name"), pollName: poll.get("name"),
totalVotes: option.votes, totalVotes: option.votes,
voters: (state.voters && state.voters[option.id]) || [] voters: (state.voters && state.voters[option.id]) || [],
}) })
); );
} }
@ -273,11 +275,11 @@ createWidget("discourse-poll-standard-results", {
return h("li", { className: `${chosen ? "chosen" : ""}` }, contents); return h("li", { className: `${chosen ? "chosen" : ""}` }, contents);
}); });
} }
} },
}); });
createWidget("discourse-poll-number-results", { createWidget("discourse-poll-number-results", {
buildKey: attrs => `poll-number-results-${attrs.id}`, buildKey: (attrs) => `poll-number-results-${attrs.id}`,
defaultState() { defaultState() {
return { loaded: false }; return { loaded: false };
@ -288,8 +290,8 @@ createWidget("discourse-poll-number-results", {
return _fetchVoters({ return _fetchVoters({
post_id: attrs.post.id, post_id: attrs.post.id,
poll_name: attrs.poll.get("name") poll_name: attrs.poll.get("name"),
}).then(result => { }).then((result) => {
state.voters = result.voters; state.voters = result.voters;
this.scheduleRerender(); this.scheduleRerender();
}); });
@ -309,7 +311,7 @@ createWidget("discourse-poll-number-results", {
h( h(
"div.poll-results-number-rating", "div.poll-results-number-rating",
new RawHtml({ html: `<span>${averageRating}</span>` }) new RawHtml({ html: `<span>${averageRating}</span>` })
) ),
]; ];
if (poll.get("public")) { if (poll.get("public")) {
@ -324,13 +326,13 @@ createWidget("discourse-poll-number-results", {
voters: state.voters || [], voters: state.voters || [],
postId: attrs.post.id, postId: attrs.post.id,
pollName: poll.get("name"), pollName: poll.get("name"),
pollType: poll.get("type") pollType: poll.get("type"),
}) })
); );
} }
return contents; return contents;
} },
}); });
createWidget("discourse-poll-container", { createWidget("discourse-poll-container", {
@ -362,11 +364,11 @@ createWidget("discourse-poll-container", {
contents.push( contents.push(
h( h(
"ul", "ul",
options.map(option => { options.map((option) => {
return this.attach("discourse-poll-option", { return this.attach("discourse-poll-option", {
option, option,
isMultiple: attrs.isMultiple, isMultiple: attrs.isMultiple,
vote: attrs.vote vote: attrs.vote,
}); });
}) })
) )
@ -374,7 +376,7 @@ createWidget("discourse-poll-container", {
return contents; return contents;
} }
} },
}); });
createWidget("discourse-poll-info", { createWidget("discourse-poll-info", {
@ -390,11 +392,11 @@ createWidget("discourse-poll-info", {
if (max < options) { if (max < options) {
return I18n.t("poll.multiple.help.between_min_and_max_options", { return I18n.t("poll.multiple.help.between_min_and_max_options", {
min, min,
max max,
}); });
} else { } else {
return I18n.t("poll.multiple.help.at_least_min_options", { return I18n.t("poll.multiple.help.at_least_min_options", {
count: min count: min,
}); });
} }
} else if (max <= options) { } else if (max <= options) {
@ -409,8 +411,8 @@ createWidget("discourse-poll-info", {
const contents = [ const contents = [
h("p", [ h("p", [
h("span.info-number", count.toString()), h("span.info-number", count.toString()),
h("span.info-label", I18n.t("poll.voters", { count })) h("span.info-label", I18n.t("poll.voters", { count })),
]) ]),
]; ];
if (attrs.isMultiple) { if (attrs.isMultiple) {
@ -425,7 +427,7 @@ createWidget("discourse-poll-info", {
h( h(
"span.info-label", "span.info-label",
I18n.t("poll.total_votes", { count: totalVotes }) I18n.t("poll.total_votes", { count: totalVotes })
) ),
]) ])
); );
} else { } else {
@ -450,7 +452,7 @@ createWidget("discourse-poll-info", {
} }
return contents; return contents;
} },
}); });
function clearPieChart(id) { function clearPieChart(id) {
@ -478,9 +480,9 @@ createWidget("discourse-poll-pie-canvas", {
buildAttributes(attrs) { buildAttributes(attrs) {
return { return {
id: `poll-results-chart-${attrs.id}` id: `poll-results-chart-${attrs.id}`,
}; };
} },
}); });
createWidget("discourse-poll-pie-chart", { createWidget("discourse-poll-pie-chart", {
@ -499,7 +501,7 @@ createWidget("discourse-poll-pie-chart", {
label: "poll.group-results.label", label: "poll.group-results.label",
title: "poll.group-results.title", title: "poll.group-results.title",
icon: "far-eye", icon: "far-eye",
action: "showBreakdown" action: "showBreakdown",
}); });
contents.push(button); contents.push(button);
@ -511,22 +513,22 @@ createWidget("discourse-poll-pie-chart", {
contents.push(h(`div#poll-results-legend-${attrs.id}.pie-chart-legends`)); contents.push(h(`div#poll-results-legend-${attrs.id}.pie-chart-legends`));
return contents; return contents;
} },
}); });
function pieChartConfig(data, labels, opts = {}) { function pieChartConfig(data, labels, opts = {}) {
const aspectRatio = "aspectRatio" in opts ? opts.aspectRatio : 2.2; const aspectRatio = "aspectRatio" in opts ? opts.aspectRatio : 2.2;
const strippedLabels = labels.map(l => stripHtml(l)); const strippedLabels = labels.map((l) => stripHtml(l));
return { return {
type: PIE_CHART_TYPE, type: PIE_CHART_TYPE,
data: { data: {
datasets: [ datasets: [
{ {
data, data,
backgroundColor: getColors(data.length) backgroundColor: getColors(data.length),
} },
], ],
labels: strippedLabels labels: strippedLabels,
}, },
options: { options: {
responsive: true, responsive: true,
@ -540,8 +542,8 @@ function pieChartConfig(data, labels, opts = {}) {
${chart.data.datasets[0].backgroundColor[i]}"></span>${labels[i]}</div>`; ${chart.data.datasets[0].backgroundColor[i]}"></span>${labels[i]}</div>`;
} }
return legends; return legends;
} },
} },
}; };
} }
@ -576,7 +578,7 @@ createWidget("discourse-poll-buttons", {
label: "poll.cast-votes.label", label: "poll.cast-votes.label",
title: "poll.cast-votes.title", title: "poll.cast-votes.title",
disabled: castVotesDisabled, disabled: castVotesDisabled,
action: "castVotes" action: "castVotes",
}) })
); );
contents.push(" "); contents.push(" ");
@ -590,7 +592,7 @@ createWidget("discourse-poll-buttons", {
title: "poll.hide-results.title", title: "poll.hide-results.title",
icon: "far-eye-slash", icon: "far-eye-slash",
disabled: hideResultsDisabled, disabled: hideResultsDisabled,
action: "toggleResults" action: "toggleResults",
}) })
); );
} else { } else {
@ -608,7 +610,7 @@ createWidget("discourse-poll-buttons", {
title: "poll.show-results.title", title: "poll.show-results.title",
icon: "far-eye", icon: "far-eye",
disabled: poll.get("voters") === 0, disabled: poll.get("voters") === 0,
action: "toggleResults" action: "toggleResults",
}) })
); );
} }
@ -622,7 +624,7 @@ createWidget("discourse-poll-buttons", {
title: "poll.export-results.title", title: "poll.export-results.title",
icon: "download", icon: "download",
disabled: poll.voters === 0, disabled: poll.voters === 0,
action: "exportResults" action: "exportResults",
}) })
); );
} }
@ -643,7 +645,7 @@ createWidget("discourse-poll-buttons", {
contents.push( contents.push(
new RawHtml({ new RawHtml({
html: `<span class="info-text" title="${title}">${label}</span>` html: `<span class="info-text" title="${title}">${label}</span>`,
}) })
); );
} }
@ -662,7 +664,7 @@ createWidget("discourse-poll-buttons", {
label: "poll.open.label", label: "poll.open.label",
title: "poll.open.title", title: "poll.open.title",
icon: "unlock-alt", icon: "unlock-alt",
action: "toggleStatus" action: "toggleStatus",
}) })
); );
} }
@ -673,19 +675,19 @@ createWidget("discourse-poll-buttons", {
label: "poll.close.label", label: "poll.close.label",
title: "poll.close.title", title: "poll.close.title",
icon: "lock", icon: "lock",
action: "toggleStatus" action: "toggleStatus",
}) })
); );
} }
} }
return contents; return contents;
} },
}); });
export default createWidget("discourse-poll", { export default createWidget("discourse-poll", {
tagName: "div", tagName: "div",
buildKey: attrs => `poll-${attrs.id}`, buildKey: (attrs) => `poll-${attrs.id}`,
buildAttributes(attrs) { buildAttributes(attrs) {
let cssClasses = "poll"; let cssClasses = "poll";
@ -693,7 +695,7 @@ export default createWidget("discourse-poll", {
return { return {
class: cssClasses, class: cssClasses,
"data-poll-name": attrs.poll.get("name"), "data-poll-name": attrs.poll.get("name"),
"data-poll-type": attrs.poll.get("type") "data-poll-type": attrs.poll.get("type"),
}; };
}, },
@ -724,13 +726,13 @@ export default createWidget("discourse-poll", {
isMultiple: this.isMultiple(), isMultiple: this.isMultiple(),
max: this.max(), max: this.max(),
min: this.min(), min: this.min(),
showResults showResults,
}); });
return h("div", [ return h("div", [
this.attach("discourse-poll-container", newAttrs), this.attach("discourse-poll-container", newAttrs),
this.attach("discourse-poll-info", newAttrs), this.attach("discourse-poll-info", newAttrs),
this.attach("discourse-poll-buttons", newAttrs) this.attach("discourse-poll-buttons", newAttrs),
]); ]);
}, },
@ -801,7 +803,7 @@ export default createWidget("discourse-poll", {
I18n.t(this.isClosed() ? "poll.open.confirm" : "poll.close.confirm"), I18n.t(this.isClosed() ? "poll.open.confirm" : "poll.close.confirm"),
I18n.t("no_value"), I18n.t("no_value"),
I18n.t("yes_value"), I18n.t("yes_value"),
confirmed => { (confirmed) => {
if (confirmed) { if (confirmed) {
state.loading = true; state.loading = true;
const status = this.isClosed() ? "open" : "closed"; const status = this.isClosed() ? "open" : "closed";
@ -811,8 +813,8 @@ export default createWidget("discourse-poll", {
data: { data: {
post_id: post.get("id"), post_id: post.get("id"),
poll_name: poll.get("name"), poll_name: poll.get("name"),
status status,
} },
}) })
.then(() => { .then(() => {
poll.set("status", status); poll.set("status", status);
@ -821,7 +823,7 @@ export default createWidget("discourse-poll", {
} }
this.scheduleRerender(); this.scheduleRerender();
}) })
.catch(error => { .catch((error) => {
if (error) { if (error) {
popupAjaxError(error); popupAjaxError(error);
} else { } else {
@ -852,17 +854,17 @@ export default createWidget("discourse-poll", {
// needed for data-explorer route compatibility // needed for data-explorer route compatibility
params: JSON.stringify({ params: JSON.stringify({
poll_name: attrs.poll.name, poll_name: attrs.poll.name,
post_id: attrs.post.id.toString() // needed for data-explorer route compatibility post_id: attrs.post.id.toString(), // needed for data-explorer route compatibility
}), }),
explain: false, explain: false,
limit: 1000000, limit: 1000000,
download: 1 download: 1,
} },
}) })
.then(csvContent => { .then((csvContent) => {
const downloadLink = document.createElement("a"); const downloadLink = document.createElement("a");
const blob = new Blob([csvContent], { const blob = new Blob([csvContent], {
type: "text/csv;charset=utf-8;" type: "text/csv;charset=utf-8;",
}); });
downloadLink.href = URL.createObjectURL(blob); downloadLink.href = URL.createObjectURL(blob);
downloadLink.setAttribute( downloadLink.setAttribute(
@ -872,7 +874,7 @@ export default createWidget("discourse-poll", {
downloadLink.click(); downloadLink.click();
downloadLink.remove(); downloadLink.remove();
}) })
.catch(error => { .catch((error) => {
if (error) { if (error) {
popupAjaxError(error); popupAjaxError(error);
} else { } else {
@ -926,8 +928,8 @@ export default createWidget("discourse-poll", {
data: { data: {
post_id: attrs.post.id, post_id: attrs.post.id,
poll_name: attrs.poll.get("name"), poll_name: attrs.poll.get("name"),
options: attrs.vote options: attrs.vote,
} },
}) })
.then(({ poll }) => { .then(({ poll }) => {
attrs.poll.setProperties(poll); attrs.poll.setProperties(poll);
@ -942,7 +944,7 @@ export default createWidget("discourse-poll", {
} }
} }
}) })
.catch(error => { .catch((error) => {
if (error) { if (error) {
popupAjaxError(error); popupAjaxError(error);
} else { } else {
@ -959,8 +961,8 @@ export default createWidget("discourse-poll", {
model: this.attrs, model: this.attrs,
panels: [ panels: [
{ id: "percentage", title: "poll.breakdown.percentage" }, { id: "percentage", title: "poll.breakdown.percentage" },
{ id: "count", title: "poll.breakdown.count" } { id: "count", title: "poll.breakdown.count" },
] ],
}); });
} },
}); });