A platform for community discussion. Free, open, simple.
FEATURE: Poll breakdown 2.0 (#10345)
Jarek Radoszcd4f2518914b
diff --git a/app/assets/javascripts/discourse/app/components/modal-tab.js b/app/assets/javascripts/discourse/app/components/modal-tab.jsindex 3211fbbdd25..a798e22d6d9 100644--- a/app/assets/javascripts/discourse/app/components/modal-tab.js+++ b/app/assets/javascripts/discourse/app/components/modal-tab.js@@ -20,6 +20,10 @@ export default Component.extend({},click() {- this.onSelectPanel(this.panel);+ this.set("selectedPanel", this.panel);++ if (this.onSelectPanel) {+ this.onSelectPanel(this.panel);+ }}});diff --git a/app/assets/javascripts/discourse/app/lib/show-modal.js b/app/assets/javascripts/discourse/app/lib/show-modal.jsindex 37c6b8efe3f..6a6fb17a71b 100644--- a/app/assets/javascripts/discourse/app/lib/show-modal.js+++ b/app/assets/javascripts/discourse/app/lib/show-modal.js@@ -50,7 +50,10 @@ export default function(name, opts) {});if (controller.actions.onSelectPanel) {- modalController.set("onSelectPanel", controller.actions.onSelectPanel);+ modalController.set(+ "onSelectPanel",+ controller.actions.onSelectPanel.bind(controller)+ );}modalController.set(diff --git a/app/assets/javascripts/discourse/app/mixins/modal-functionality.js b/app/assets/javascripts/discourse/app/mixins/modal-functionality.jsindex 70b5bd010c0..ac40b161b56 100644--- a/app/assets/javascripts/discourse/app/mixins/modal-functionality.js+++ b/app/assets/javascripts/discourse/app/mixins/modal-functionality.js@@ -18,10 +18,6 @@ export default Mixin.create({closeModal() {this.modal.send("closeModal");this.set("panels", []);- },-- onSelectPanel(panel) {- this.set("selectedPanel", panel);}}});diff --git a/app/assets/stylesheets/common/base/modal.scss b/app/assets/stylesheets/common/base/modal.scssindex 178be0a01d2..fc09f8990d1 100644--- a/app/assets/stylesheets/common/base/modal.scss+++ b/app/assets/stylesheets/common/base/modal.scss@@ -148,7 +148,7 @@}&:not(.history-modal) {- .modal-body:not(.reorder-categories):not(.poll-ui-builder) {+ .modal-body:not(.reorder-categories):not(.poll-ui-builder):not(.poll-breakdown) {max-height: 80vh !important;@media screen and (max-height: 500px) {max-height: 65vh !important;diff --git a/lib/tasks/javascript.rake b/lib/tasks/javascript.rakeindex c7c745242a9..25392df9035 100644--- a/lib/tasks/javascript.rake+++ b/lib/tasks/javascript.rake@@ -69,6 +69,9 @@ task 'javascript:update' do}, {source: 'chart.js/dist/Chart.min.js',public: true+ }, {+ source: 'chartjs-plugin-datalabels/dist/chartjs-plugin-datalabels.min.js',+ public: true}, {source: 'magnific-popup/dist/jquery.magnific-popup.min.js',public: truediff --git a/package.json b/package.jsonindex 9ce74d66f80..e73fee2fbc8 100644--- a/package.json+++ b/package.json@@ -13,6 +13,7 @@"bootbox": "3.2.0","bootstrap": "v3.4.1","chart.js": "2.9.3",+ "chartjs-plugin-datalabels": "^0.7.0","eslint-plugin-lodash": "^6.0.0","favcount": "https://github.com/chrishunt/favcount","handlebars": "^4.7.0",diff --git a/plugins/poll/assets/javascripts/components/poll-breakdown-chart.js.es6 b/plugins/poll/assets/javascripts/components/poll-breakdown-chart.js.es6new file mode 100644index 00000000000..ea9a34559dc--- /dev/null+++ b/plugins/poll/assets/javascripts/components/poll-breakdown-chart.js.es6@@ -0,0 +1,182 @@+import I18n from "I18n";+import Component from "@ember/component";+import { mapBy } from "@ember/object/computed";+import { htmlSafe } from "@ember/template";+import { PIE_CHART_TYPE } from "discourse/plugins/poll/controllers/poll-ui-builder";+import { getColors } from "discourse/plugins/poll/lib/chart-colors";+import discourseComputed from "discourse-common/utils/decorators";++export default Component.extend({+ // Arguments:+ group: null,+ options: null,+ displayMode: null,+ highlightedOption: null,+ setHighlightedOption: null,++ classNames: "poll-breakdown-chart-container",++ _optionToSlice: null,+ _previousHighlightedSliceIndex: null,+ _previousDisplayMode: null,++ data: mapBy("options", "votes"),++ init() {+ this._super(...arguments);+ this._optionToSlice = {};+ },++ didInsertElement() {+ this._super(...arguments);++ const canvas = this.element.querySelector("canvas");+ this._chart = new window.Chart(canvas.getContext("2d"), this.chartConfig);+ },++ didReceiveAttrs() {+ this._super(...arguments);++ if (this._chart) {+ this._updateDisplayMode();+ this._updateHighlight();+ }+ },++ willDestroy() {+ this._super(...arguments);++ if (this._chart) {+ this._chart.destroy();+ }+ },++ @discourseComputed("optionColors", "index")+ colorStyle(optionColors, index) {+ return htmlSafe(`background: ${optionColors[index]};`);+ },++ @discourseComputed("data", "displayMode")+ chartConfig(data, displayMode) {+ const transformedData = [];+ let counter = 0;++ this._optionToSlice = {};++ data.forEach((votes, index) => {+ if (votes > 0) {+ transformedData.push(votes);+ this._optionToSlice[index] = counter++;+ }+ });++ const totalVotes = transformedData.reduce((sum, votes) => sum + votes, 0);+ const colors = getColors(data.length).filter(+ (color, index) => data[index] > 0+ );++ return {+ type: PIE_CHART_TYPE,+ plugins: [window.ChartDataLabels],+ data: {+ datasets: [+ {+ data: transformedData,+ backgroundColor: colors,+ // TODO: It's a workaround for Chart.js' terrible hover styling.+ // It will break on non-white backgrounds.+ // Should be updated after #10341 lands+ hoverBorderColor: "#fff"+ }+ ]+ },+ options: {+ plugins: {+ datalabels: {+ color: "#333",+ backgroundColor: "rgba(255, 255, 255, 0.5)",+ borderRadius: 2,+ font: {+ family: getComputedStyle(document.body).fontFamily,+ size: 16+ },+ padding: {+ top: 2,+ right: 6,+ bottom: 2,+ left: 6+ },+ formatter(votes) {+ if (displayMode !== "percentage") {+ return votes;+ }++ const percent = I18n.toNumber((votes / totalVotes) * 100.0, {+ precision: 1+ });++ return `${percent}%`;+ }+ }+ },+ responsive: true,+ aspectRatio: 1.1,+ animation: { duration: 0 },+ tooltips: false,+ onHover: (event, activeElements) => {+ if (!activeElements.length) {+ this.setHighlightedOption(null);+ return;+ }++ const sliceIndex = activeElements[0]._index;+ const optionIndex = Object.keys(this._optionToSlice).find(+ option => this._optionToSlice[option] === sliceIndex+ );++ // Clear the array to avoid issues in Chart.js+ activeElements.length = 0;++ this.setHighlightedOption(Number(optionIndex));+ }+ }+ };+ },++ _updateDisplayMode() {+ if (this.displayMode !== this._previousDisplayMode) {+ const config = this.chartConfig;+ this._chart.data.datasets = config.data.datasets;+ this._chart.options = config.options;++ this._chart.update();+ this._previousDisplayMode = this.displayMode;+ }+ },++ _updateHighlight() {+ const meta = this._chart.getDatasetMeta(0);++ if (this._previousHighlightedSliceIndex !== null) {+ const slice = meta.data[this._previousHighlightedSliceIndex];+ meta.controller.removeHoverStyle(slice);+ this._chart.draw();+ }++ if (this.highlightedOption === null) {+ this._previousHighlightedSliceIndex = null;+ return;+ }++ const sliceIndex = this._optionToSlice[this.highlightedOption];+ if (typeof sliceIndex === "undefined") {+ this._previousHighlightedSliceIndex = null;+ return;+ }++ const slice = meta.data[sliceIndex];+ this._previousHighlightedSliceIndex = sliceIndex;+ meta.controller.setHoverStyle(slice);+ this._chart.draw();+ }+});diff --git a/plugins/poll/assets/javascripts/components/poll-breakdown-option.js.es6 b/plugins/poll/assets/javascripts/components/poll-breakdown-option.js.es6new file mode 100644index 00000000000..f1816b13f95--- /dev/null+++ b/plugins/poll/assets/javascripts/components/poll-breakdown-option.js.es6@@ -0,0 +1,61 @@+import I18n from "I18n";+import Component from "@ember/component";+import { action } from "@ember/object";+import { equal } from "@ember/object/computed";+import { htmlSafe } from "@ember/template";+import { propertyEqual } from "discourse/lib/computed";+import discourseComputed from "discourse-common/utils/decorators";+import { getColors } from "discourse/plugins/poll/lib/chart-colors";++export default Component.extend({+ // Arguments:+ option: null,+ index: null,+ totalVotes: null,+ optionsCount: null,+ displayMode: null,+ highlightedOption: null,+ onMouseOver: null,+ onMouseOut: null,++ tagName: "",++ highlighted: propertyEqual("highlightedOption", "index"),+ showPercentage: equal("displayMode", "percentage"),++ @discourseComputed("option.votes", "totalVotes")+ percent(votes, total) {+ return I18n.toNumber((votes / total) * 100.0, { precision: 1 });+ },++ @discourseComputed("optionsCount")+ optionColors(optionsCount) {+ return getColors(optionsCount);+ },++ @discourseComputed("highlighted")+ colorBackgroundStyle(highlighted) {+ if (highlighted) {+ // TODO: Use CSS variables (#10341)+ return htmlSafe("background: rgba(0, 0, 0, 0.1);");+ }+ },++ @discourseComputed("highlighted", "optionColors", "index")+ colorPreviewStyle(highlighted, optionColors, index) {+ const color = highlighted+ ? window.Chart.helpers.getHoverColor(optionColors[index])+ : optionColors[index];++ return htmlSafe(`background: ${color};`);+ },++ @action+ onHover(active) {+ if (active) {+ this.onMouseOver();+ } else {+ this.onMouseOut();+ }+ }+});diff --git a/plugins/poll/assets/javascripts/controllers/poll-breakdown.js.es6 b/plugins/poll/assets/javascripts/controllers/poll-breakdown.js.es6new file mode 100644index 00000000000..f5cb61bcba4--- /dev/null+++ b/plugins/poll/assets/javascripts/controllers/poll-breakdown.js.es6@@ -0,0 +1,83 @@+import I18n from "I18n";+import Controller from "@ember/controller";+import { action } from "@ember/object";+import { classify } from "@ember/string";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import loadScript from "discourse/lib/load-script";+import ModalFunctionality from "discourse/mixins/modal-functionality";+import discourseComputed from "discourse-common/utils/decorators";++export default Controller.extend(ModalFunctionality, {+ model: null,+ charts: null,+ groupedBy: null,+ highlightedOption: null,+ displayMode: "percentage",++ @discourseComputed("model.groupableUserFields")+ groupableUserFields(fields) {+ return fields.map(field => {+ const transformed = field.split("_").filter(Boolean);++ if (transformed.length > 1) {+ transformed[0] = classify(transformed[0]);+ }++ return { id: field, label: transformed.join(" ") };+ });+ },++ @discourseComputed("model.poll.options")+ totalVotes(options) {+ return options.reduce((sum, option) => sum + option.votes, 0);+ },++ onShow() {+ this.set("charts", null);+ this.set("displayMode", "percentage");+ this.set("groupedBy", this.model.groupableUserFields[0]);++ loadScript("/javascripts/Chart.min.js")+ .then(() => loadScript("/javascripts/chartjs-plugin-datalabels.min.js"))+ .then(() => {+ window.Chart.plugins.unregister(window.ChartDataLabels);+ this.fetchGroupedPollData();+ });+ },++ fetchGroupedPollData() {+ return ajax("/polls/grouped_poll_results.json", {+ data: {+ post_id: this.model.post.id,+ poll_name: this.model.poll.name,+ user_field_name: this.groupedBy+ }+ })+ .catch(error => {+ if (error) {+ popupAjaxError(error);+ } else {+ bootbox.alert(I18n.t("poll.error_while_fetching_voters"));+ }+ })+ .then(result => {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ this.set("charts", result.grouped_results);+ });+ },++ @action+ setGrouping(value) {+ this.set("groupedBy", value);+ this.fetchGroupedPollData();+ },++ @action+ onSelectPanel(panel) {+ this.set("displayMode", panel.id);+ }+});diff --git a/plugins/poll/assets/javascripts/controllers/poll-ui-builder.js.es6 b/plugins/poll/assets/javascripts/controllers/poll-ui-builder.js.es6index 0dc7325150f..2c0c4ff36e0 100644--- a/plugins/poll/assets/javascripts/controllers/poll-ui-builder.js.es6+++ b/plugins/poll/assets/javascripts/controllers/poll-ui-builder.js.es6@@ -1,7 +1,7 @@import I18n from "I18n";import Controller from "@ember/controller";-import discourseComputed, { observes } from "discourse-common/utils/decorators";import EmberObject from "@ember/object";+import discourseComputed, { observes } from "discourse-common/utils/decorators";export const BAR_CHART_TYPE = "bar";export const PIE_CHART_TYPE = "pie";diff --git a/plugins/poll/assets/javascripts/discourse/templates/components/poll-breakdown-chart.hbs b/plugins/poll/assets/javascripts/discourse/templates/components/poll-breakdown-chart.hbsnew file mode 100644index 00000000000..9e91bc41e7a--- /dev/null+++ b/plugins/poll/assets/javascripts/discourse/templates/components/poll-breakdown-chart.hbs@@ -0,0 +1,2 @@+<label class="poll-breakdown-chart-label">{{@group}}</label>+<canvas class="poll-breakdown-chart-chart"></canvas>diff --git a/plugins/poll/assets/javascripts/discourse/templates/components/poll-breakdown-option.hbs b/plugins/poll/assets/javascripts/discourse/templates/components/poll-breakdown-option.hbsnew file mode 100644index 00000000000..b56106982e3--- /dev/null+++ b/plugins/poll/assets/javascripts/discourse/templates/components/poll-breakdown-option.hbs@@ -0,0 +1,17 @@+<li+ class="poll-breakdown-option"+ style={{this.colorBackgroundStyle}}+ {{on "mouseover" @onMouseOver}}+ {{on "mouseout" @onMouseOut}}+>+ <span class="poll-breakdown-option-color" style={{this.colorPreviewStyle}}></span>++ <span class="poll-breakdown-option-count">+ {{#if showPercentage}}+ {{this.percent}}%+ {{else}}+ {{@option.votes}}+ {{/if}}+ </span>+ <span class="poll-breakdown-option-text">{{{@option.html}}}</span>+</li>diff --git a/plugins/poll/assets/javascripts/discourse/templates/modal/poll-breakdown.hbs b/plugins/poll/assets/javascripts/discourse/templates/modal/poll-breakdown.hbsnew file mode 100644index 00000000000..0cb26c08d5f--- /dev/null+++ b/plugins/poll/assets/javascripts/discourse/templates/modal/poll-breakdown.hbs@@ -0,0 +1,49 @@+{{#d-modal-body title="poll.breakdown.title"}}+ <div class="poll-breakdown-sidebar">+ {{!-- TODO: replace with the (optional) poll title --}}+ <p class="poll-breakdown-title">{{this.model.post.topic.title}}</p>++ <div class="poll-breakdown-total-votes">{{i18n "poll.breakdown.votes" count=this.model.poll.voters}}</div>++ <ul class="poll-breakdown-options">+ {{#each this.model.poll.options as |option index|}}+ {{poll-breakdown-option+ option=option+ index=index+ totalVotes=this.totalVotes+ optionsCount=this.model.poll.options.length+ displayMode=this.displayMode+ highlightedOption=this.highlightedOption+ onMouseOver=(fn (mut this.highlightedOption) index)+ onMouseOut=(fn (mut this.highlightedOption) null)+ }}+ {{/each}}+ </ul>+ </div>++ <div class="poll-breakdown-body">+ <div class="poll-breakdown-body-header">+ <label class="poll-breakdown-body-header-label">{{i18n "poll.breakdown.breakdown"}}</label>++ {{combo-box+ content=this.groupableUserFields+ value=this.groupedBy+ nameProperty="label"+ class="poll-breakdown-dropdown"+ onChange=(action this.setGrouping)+ }}+ </div>++ <div class="poll-breakdown-charts">+ {{#each this.charts as |chart|}}+ {{poll-breakdown-chart+ group=(get chart "group")+ options=(get chart "options")+ displayMode=this.displayMode+ highlightedOption=this.highlightedOption+ setHighlightedOption=(fn (mut this.highlightedOption))+ }}+ {{/each}}+ </div>+ </div>+{{/d-modal-body}}diff --git a/plugins/poll/assets/javascripts/initializers/add-poll-ui-builder.js.es6 b/plugins/poll/assets/javascripts/initializers/add-poll-ui-builder.js.es6index d9da92d2526..eae72fff0b0 100644--- a/plugins/poll/assets/javascripts/initializers/add-poll-ui-builder.js.es6+++ b/plugins/poll/assets/javascripts/initializers/add-poll-ui-builder.js.es6@@ -1,6 +1,6 @@import { withPluginApi } from "discourse/lib/plugin-api";-import discourseComputed from "discourse-common/utils/decorators";import showModal from "discourse/lib/show-modal";+import discourseComputed from "discourse-common/utils/decorators";function initializePollUIBuilder(api) {api.modifyClass("controller:composer", {diff --git a/plugins/poll/assets/javascripts/initializers/extend-for-poll.js.es6 b/plugins/poll/assets/javascripts/initializers/extend-for-poll.js.es6index 13b209dd50e..897d37eee56 100644--- a/plugins/poll/assets/javascripts/initializers/extend-for-poll.js.es6+++ b/plugins/poll/assets/javascripts/initializers/extend-for-poll.js.es6@@ -1,8 +1,8 @@import EmberObject from "@ember/object";import { withPluginApi } from "discourse/lib/plugin-api";-import { observes } from "discourse-common/utils/decorators";-import { getRegister } from "discourse-common/lib/get-owner";import WidgetGlue from "discourse/widgets/glue";+import { getRegister } from "discourse-common/lib/get-owner";+import { observes } from "discourse-common/utils/decorators";function initializePolls(api) {const register = getRegister(api);diff --git a/plugins/poll/assets/javascripts/widgets/discourse-poll.js.es6 b/plugins/poll/assets/javascripts/widgets/discourse-poll.js.es6index 96f6f32003d..acff44d2463 100644--- a/plugins/poll/assets/javascripts/widgets/discourse-poll.js.es6+++ b/plugins/poll/assets/javascripts/widgets/discourse-poll.js.es6@@ -1,18 +1,18 @@import I18n from "I18n";-import { createWidget } from "discourse/widgets/widget";import { h } from "virtual-dom";-import { iconNode } from "discourse-common/lib/icon-library";-import RawHtml from "discourse/widgets/raw-html";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";-import evenRound from "discourse/plugins/poll/lib/even-round";-import { avatarFor } from "discourse/widgets/post";-import round from "discourse/lib/round";import { relativeAge } from "discourse/lib/formatter";import loadScript from "discourse/lib/load-script";-import { getColors } from "../lib/chart-colors";-import { classify } from "@ember/string";-import { PIE_CHART_TYPE } from "../controllers/poll-ui-builder";+import round from "discourse/lib/round";+import showModal from "discourse/lib/show-modal";+import { avatarFor } from "discourse/widgets/post";+import RawHtml from "discourse/widgets/raw-html";+import { createWidget } from "discourse/widgets/widget";+import { iconNode } from "discourse-common/lib/icon-library";+import { PIE_CHART_TYPE } from "discourse/plugins/poll/controllers/poll-ui-builder";+import { getColors } from "discourse/plugins/poll/lib/chart-colors";+import evenRound from "discourse/plugins/poll/lib/even-round";function optionHtml(option) {const $node = $(`<span>${option.html}</span>`);@@ -453,120 +453,6 @@ createWidget("discourse-poll-info", {}});-function transformUserFieldToLabel(fieldName) {- let transformed = fieldName.split("_").filter(Boolean);- if (transformed.length > 1) {- transformed[0] = classify(transformed[0]);- }- return transformed.join(" ");-}--createWidget("discourse-poll-grouped-pies", {- tagName: "div.poll-grouped-pies",- buildAttributes(attrs) {- return {- id: `poll-results-grouped-pie-charts-${attrs.id}`- };- },-- html(attrs) {- const fields = Object.assign({}, attrs.groupableUserFields);- const fieldSelectId = `field-select-${attrs.id}`;- attrs.groupedBy = attrs.groupedBy || fields[0];-- let contents = [];-- const btn = this.attach("button", {- className: "btn-default poll-group-by-toggle",- label: "poll.ungroup-results.label",- title: "poll.ungroup-results.title",- icon: "far-eye-slash",- action: "toggleGroupedPieCharts"- });- const select = h(- `select#${fieldSelectId}.poll-group-by-selector`,- { value: attrs.groupBy },- attrs.groupableUserFields.map(field => {- return h("option", { value: field }, transformUserFieldToLabel(field));- })- );- contents.push(h("div.poll-grouped-pies-controls", [btn, select]));-- ajax("/polls/grouped_poll_results.json", {- data: {- post_id: attrs.post.id,- poll_name: attrs.poll.name,- user_field_name: attrs.groupedBy- }- })- .catch(error => {- if (error) {- popupAjaxError(error);- } else {- bootbox.alert(I18n.t("poll.error_while_fetching_voters"));- }- })- .then(result => {- let groupBySelect = document.getElementById(fieldSelectId);- if (!groupBySelect) return;-- groupBySelect.value = attrs.groupedBy;- const parent = document.getElementById(- `poll-results-grouped-pie-charts-${attrs.id}`- );-- for (- let chartIdx = 0;- chartIdx < result.grouped_results.length;- chartIdx++- ) {- const data = result.grouped_results[chartIdx].options.mapBy("votes");- const labels = result.grouped_results[chartIdx].options.mapBy("html");- const chartConfig = pieChartConfig(data, labels, {- aspectRatio: 1.2- });- const canvasId = `pie-${attrs.id}-${chartIdx}`;- let el = document.querySelector(`#${canvasId}`);- if (!el) {- const container = document.createElement("div");- container.classList.add("poll-grouped-pie-container");-- const label = document.createElement("label");- label.classList.add("poll-pie-label");- label.textContent = result.grouped_results[chartIdx].group;-- const canvas = document.createElement("canvas");- canvas.classList.add(`poll-grouped-pie-${attrs.id}`);- canvas.id = canvasId;-- container.appendChild(label);- container.appendChild(canvas);- parent.appendChild(container);- // eslint-disable-next-line- new Chart(canvas.getContext("2d"), chartConfig);- } else {- // eslint-disable-next-line- Chart.helpers.each(Chart.instances, function(instance) {- if (instance.chart.canvas.id === canvasId && el.$chartjs) {- instance.destroy();- // eslint-disable-next-line- new Chart(el.getContext("2d"), chartConfig);- }- });- }- }- });- return contents;- },-- click(e) {- let select = $(e.target).closest("select");- if (select.length) {- this.sendWidgetAction("refreshCharts", select[0].value);- }- }-});-function clearPieChart(id) {let el = document.querySelector(`#poll-results-chart-${id}`);el && el.parentNode.removeChild(el);@@ -607,27 +493,23 @@ createWidget("discourse-poll-pie-chart", {return contents;}- let btn;- let chart;- if (attrs.groupResults && attrs.groupableUserFields.length > 0) {- chart = this.attach("discourse-poll-grouped-pies", attrs);- clearPieChart(attrs.id);- } else {- if (attrs.groupableUserFields.length) {- btn = this.attach("button", {- className: "btn-default poll-group-by-toggle",- label: "poll.group-results.label",- title: "poll.group-results.title",- icon: "far-eye",- action: "toggleGroupedPieCharts"- });- }+ if (attrs.groupableUserFields.length) {+ const button = this.attach("button", {+ className: "btn-default poll-show-breakdown",+ label: "poll.group-results.label",+ title: "poll.group-results.title",+ icon: "far-eye",+ action: "showBreakdown"+ });- chart = this.attach("discourse-poll-pie-canvas", attrs);+ contents.push(button);}- contents.push(btn);++ const chart = this.attach("discourse-poll-pie-canvas", attrs);contents.push(chart);+contents.push(h(`div#poll-results-legend-${attrs.id}.pie-chart-legends`));+return contents;}});@@ -1072,19 +954,13 @@ export default createWidget("discourse-poll", {});},- toggleGroupedPieCharts() {- this.attrs.groupResults = !this.attrs.groupResults;- },-- refreshCharts(newGroupedByValue) {- let el = document.getElementById(- `poll-results-grouped-pie-charts-${this.attrs.id}`- );- Array.from(el.getElementsByClassName("poll-grouped-pie-container")).forEach(- container => {- el.removeChild(container);- }- );- this.attrs.groupedBy = newGroupedByValue;+ showBreakdown() {+ showModal("poll-breakdown", {+ model: this.attrs,+ panels: [+ { id: "percentage", title: "poll.breakdown.percentage" },+ { id: "count", title: "poll.breakdown.count" }+ ]+ });}});diff --git a/plugins/poll/assets/stylesheets/common/poll-breakdown.scss b/plugins/poll/assets/stylesheets/common/poll-breakdown.scssnew file mode 100644index 00000000000..c178c7bd386--- /dev/null+++ b/plugins/poll/assets/stylesheets/common/poll-breakdown.scss@@ -0,0 +1,116 @@+.poll-breakdown-modal {+ .modal-inner-container {+ max-width: unset;+ width: 90vw;+ }++ .modal-tabs {+ justify-content: flex-end;+ }++ .modal-body {+ display: grid;+ height: 80vh;+ grid: auto-flow / 1fr 2fr;+ padding: 0;+ }+}++.poll-breakdown-sidebar {+ background: var(--primary-very-low);+ box-sizing: border-box;+ padding: 1rem;+}++.poll-breakdown-title {+ font-weight: 600;+ margin: 0;+ text-align: center;+}++.poll-breakdown-total-votes {+ font-size: 1.2rem;+ font-weight: 600;+ margin-top: 0.5rem;+ text-align: center;+}++.poll-breakdown-options {+ display: grid;+ list-style: none;+ margin: 1.5rem 0 0 0;+}++.poll-breakdown-option {+ align-items: center;+ border-radius: 5px;+ column-gap: 0.66rem;+ cursor: default;+ display: grid;+ grid-template-columns: 2.5rem 1fr;+ row-gap: 0.1rem;+ justify-content: start;+ padding: 0.5rem 1rem;+}++.poll-breakdown-option-color {+ align-self: end;+ border: 1px solid rgba(0, 0, 0, 0.15);+ grid-column: 1;+ height: 0.6rem;+ justify-self: center;+ width: 1.2rem;+}++.poll-breakdown-option-count {+ align-self: start;+ font-size: 0.9rem;+ grid-column: 1;+ justify-self: center;+}++.poll-breakdown-option-text {+ grid-column: 2;+ grid-row: 1/3;+}++.poll-breakdown-body {+ box-sizing: border-box;+ padding: 1rem 2rem;+}++.poll-breakdown-body-header {+ align-items: center;+ border-bottom: 1px solid var(--primary-low);+ display: flex;+ flex: 0 0 auto;+ padding-bottom: 0.5rem;+}++.poll-breakdown-body-header-label {+ font-size: 1.2rem;+ font-weight: 600;+ margin: 0;+}++.poll-breakdown-dropdown {+ margin-left: 1rem;+}++.poll-breakdown-charts {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(33.3%, 0.33fr));+}++.poll-breakdown-chart-container {+ display: flex;+ flex-direction: column;+ justify-content: flex-end;+ margin-top: 1rem;+ position: relative;+}++.poll-breakdown-chart-label {+ display: block;+ text-align: center;+}diff --git a/plugins/poll/assets/stylesheets/common/poll.scss b/plugins/poll/assets/stylesheets/common/poll.scssindex e99f0c4e2f8..a40bb789173 100644--- a/plugins/poll/assets/stylesheets/common/poll.scss+++ b/plugins/poll/assets/stylesheets/common/poll.scss@@ -149,41 +149,22 @@ div.poll {}.poll-results-chart {- height: 310px;+ height: 320px;overflow-y: auto;overflow-x: hidden;}- .poll-group-by-toggle {+ .poll-show-breakdown {margin-bottom: 10px;}-- .poll-group-by-selector {- height: 30px;- }-- .poll-grouped-pie-container {- display: inline-block;- position: relative;- padding: 15px 0;-- .poll-pie-label {- display: block;- text-align: center;- }- }}div.poll.pie {.poll-container {display: inline-block;- height: 310px;- max-height: 310px;+ height: 320px;+ max-height: 320px;overflow-y: auto;-- .poll-grouped-pie-container {- width: 50%;- }}.poll-info {display: inline-block;diff --git a/plugins/poll/assets/stylesheets/desktop/poll.scss b/plugins/poll/assets/stylesheets/desktop/poll.scssindex 436dc952bf4..bbfffda2691 100644--- a/plugins/poll/assets/stylesheets/desktop/poll.scss+++ b/plugins/poll/assets/stylesheets/desktop/poll.scss@@ -49,11 +49,8 @@ div.poll {div.poll.pie {.poll-container {width: calc(100% - 190px);-- .poll-grouped-pie-container {- width: 50%;- }}+.poll-info {display: inline-block;width: 150px;diff --git a/plugins/poll/assets/stylesheets/mobile/poll.scss b/plugins/poll/assets/stylesheets/mobile/poll.scssindex 596c036d8ed..037dfb7584f 100644--- a/plugins/poll/assets/stylesheets/mobile/poll.scss+++ b/plugins/poll/assets/stylesheets/mobile/poll.scss@@ -28,15 +28,15 @@ div.poll {margin-left: 0.25em;}}++ .poll-show-breakdown {+ display: none;+ }}div.poll.pie {.poll-container {width: calc(100% - 30px);border-bottom: 1px solid var(--primary-low);-- .poll-grouped-pie-container {- width: 100%;- }}}diff --git a/plugins/poll/config/locales/client.en.yml b/plugins/poll/config/locales/client.en.ymlindex 03a736e69d7..856009b5046 100644--- a/plugins/poll/config/locales/client.en.yml+++ b/plugins/poll/config/locales/client.en.yml@@ -52,10 +52,6 @@ en:title: "Group votes by user field"label: "Show breakdown"- ungroup-results:- title: "Combine all votes"- label: "Hide breakdown"-export-results:title: "Export the poll results"label: "Export"@@ -74,6 +70,13 @@ en:closes_in: "Closes in <strong>%{timeLeft}</strong>."age: "Closed <strong>%{age}</strong>"+ breakdown:+ title: "Poll results"+ votes: "%{count} votes"+ breakdown: "Breakdown"+ percentage: "Percentage"+ count: "Count"+error_while_toggling_status: "Sorry, there was an error toggling the status of this poll."error_while_casting_votes: "Sorry, there was an error casting your votes."error_while_fetching_voters: "Sorry, there was an error displaying the voters."diff --git a/plugins/poll/plugin.rb b/plugins/poll/plugin.rbindex 8331b8fca63..1dee522602c 100644--- a/plugins/poll/plugin.rb+++ b/plugins/poll/plugin.rb@@ -8,6 +8,7 @@register_asset "stylesheets/common/poll.scss"register_asset "stylesheets/common/poll-ui-builder.scss"+register_asset "stylesheets/common/poll-breakdown.scss"register_asset "stylesheets/desktop/poll.scss", :desktopregister_asset "stylesheets/mobile/poll.scss", :mobileregister_asset "stylesheets/mobile/poll-ui-builder.scss", :mobilediff --git a/plugins/poll/test/javascripts/acceptance/poll-breakdown-test.js.es6 b/plugins/poll/test/javascripts/acceptance/poll-breakdown-test.js.es6new file mode 100644index 00000000000..4b76ad90c73--- /dev/null+++ b/plugins/poll/test/javascripts/acceptance/poll-breakdown-test.js.es6@@ -0,0 +1,119 @@+import { acceptance } from "helpers/qunit-helpers";+import { clearPopupMenuOptionsCallback } from "discourse/controllers/composer";+import { Promise } from "rsvp";++acceptance("Poll breakdown", {+ loggedIn: true,+ settings: { poll_enabled: true, poll_groupable_user_fields: "something" },+ beforeEach() {+ clearPopupMenuOptionsCallback();+ },+ pretend(server, helper) {+ server.get("/polls/grouped_poll_results.json", () => {+ return new Promise(resolve => {+ resolve(+ helper.response({+ grouped_results: [+ {+ group: "Engineering",+ options: [+ {+ digest: "687a1ccf3c6a260f9aeeb7f68a1d463c",+ html: "This Is",+ votes: 1+ },+ {+ digest: "9377906763a1221d31d656ea0c4a4495",+ html: "A test for sure",+ votes: 1+ },+ {+ digest: "ecf47c65a85a0bb20029072b1b721977",+ html: "Why not give it some more",+ votes: 1+ }+ ]+ },+ {+ group: "Marketing",+ options: [+ {+ digest: "687a1ccf3c6a260f9aeeb7f68a1d463c",+ html: "This Is",+ votes: 1+ },+ {+ digest: "9377906763a1221d31d656ea0c4a4495",+ html: "A test for sure",+ votes: 1+ },+ {+ digest: "ecf47c65a85a0bb20029072b1b721977",+ html: "Why not give it some more",+ votes: 1+ }+ ]+ }+ ]+ })+ );+ });+ });+ }+});++test("Displaying the poll breakdown modal", async assert => {+ await visit("/t/-/topic_with_pie_chart_poll");++ assert.equal(+ find(".poll-show-breakdown").text(),+ "Show breakdown",+ "shows the breakdown button when poll_groupable_user_fields is non-empty"+ );++ await click(".poll-show-breakdown:first");++ assert.equal(+ find(".poll-breakdown-total-votes")[0].textContent.trim(),+ "2 votes",+ "display the correct total vote count"+ );++ assert.equal(+ find(".poll-breakdown-chart-container").length,+ 2,+ "renders a chart for each of the groups in group_results response"+ );++ assert.ok(+ find(".poll-breakdown-chart-container > canvas")[0].$chartjs,+ "$chartjs is defined on the pie charts"+ );+});++test("Changing the display mode from percentage to count", async assert => {+ await visit("/t/-/topic_with_pie_chart_poll");+ await click(".poll-show-breakdown:first");++ assert.equal(+ find(".poll-breakdown-option-count:first")[0].textContent.trim(),+ "40.0%",+ "displays the correct vote percentage"+ );++ await click(".modal-tabs .count");++ assert.equal(+ find(".poll-breakdown-option-count:first")[0].textContent.trim(),+ "2",+ "displays the correct vote count"+ );++ await click(".modal-tabs .percentage");++ assert.equal(+ find(".poll-breakdown-option-count:last")[0].textContent.trim(),+ "20.0%",+ "displays the percentage again"+ );+});diff --git a/plugins/poll/test/javascripts/acceptance/poll-pie-chart-test.js.es6 b/plugins/poll/test/javascripts/acceptance/poll-pie-chart-test.js.es6index 379a9554adb..02696d2035f 100644--- a/plugins/poll/test/javascripts/acceptance/poll-pie-chart-test.js.es6+++ b/plugins/poll/test/javascripts/acceptance/poll-pie-chart-test.js.es6@@ -1,68 +1,11 @@import { acceptance } from "helpers/qunit-helpers";-import { clearPopupMenuOptionsCallback } from "discourse/controllers/composer";-import { Promise } from "rsvp";acceptance("Rendering polls with pie charts - desktop", {loggedIn: true,- settings: { poll_enabled: true, poll_groupable_user_fields: "something" },- beforeEach() {- clearPopupMenuOptionsCallback();- },- pretend(server, helper) {- server.get("/polls/grouped_poll_results.json", () => {- return new Promise(resolve => {- resolve(- helper.response({- grouped_results: [- {- group: "Engineering",- options: [- {- digest: "687a1ccf3c6a260f9aeeb7f68a1d463c",- html: "This Is",- votes: 1- },- {- digest: "9377906763a1221d31d656ea0c4a4495",- html: "A test for sure",- votes: 1- },- {- digest: "ecf47c65a85a0bb20029072b1b721977",- html: "Why not give it some more",- votes: 1- }- ]- },- {- group: "Marketing",- options: [- {- digest: "687a1ccf3c6a260f9aeeb7f68a1d463c",- html: "This Is",- votes: 1- },- {- digest: "9377906763a1221d31d656ea0c4a4495",- html: "A test for sure",- votes: 1- },- {- digest: "ecf47c65a85a0bb20029072b1b721977",- html: "Why not give it some more",- votes: 1- }- ]- }- ]- })- );- });- });- }+ settings: { poll_enabled: true, poll_groupable_user_fields: "something" }});-test("Polls", async assert => {+test("Displays the pie chart", async assert => {await visit("/t/-/topic_with_pie_chart_poll");const poll = find(".poll")[0];@@ -90,39 +33,4 @@ test("Polls", async assert => {1,"Renders the chart div instead of bar container");-- assert.equal(- find(".poll-group-by-toggle").text(),- "Show breakdown",- "Shows the breakdown button when poll_groupable_user_fields is non-empty"- );-- await click(".poll-group-by-toggle:first");-- assert.equal(- find(".poll-group-by-toggle").text(),- "Hide breakdown",- "Shows the combine breakdown button after toggle is clicked"- );-- // Double click to make sure the state toggles back to combined view- await click(".toggle-results:first");- await click(".toggle-results:first");-- assert.equal(- find(".poll-group-by-toggle").text(),- "Hide breakdown",- "Returns to the grouped view, after toggling results shown"- );-- assert.equal(- find(".poll-grouped-pie-container").length,- 2,- "Renders a chart for each of the groups in group_results response"- );-- assert.ok(- find(".poll-grouped-pie-container > canvas")[0].$chartjs,- "$chartjs is defined on the pie charts"- );});diff --git a/public/javascripts/chartjs-plugin-datalabels.min.js b/public/javascripts/chartjs-plugin-datalabels.min.jsnew file mode 100644index 00000000000..75eb4203362--- /dev/null+++ b/public/javascripts/chartjs-plugin-datalabels.min.js@@ -0,0 +1,7 @@+/*!+ * chartjs-plugin-datalabels v0.7.0+ * https://chartjs-plugin-datalabels.netlify.com+ * (c) 2019 Chart.js Contributors+ * Released under the MIT license+ */+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("chart.js")):"function"==typeof define&&define.amd?define(["chart.js"],e):(t=t||self).ChartDataLabels=e(t.Chart)}(this,function(t){"use strict";var e=(t=t&&t.hasOwnProperty("default")?t.default:t).helpers,r=function(){if("undefined"!=typeof window){if(window.devicePixelRatio)return window.devicePixelRatio;var t=window.screen;if(t)return(t.deviceXDPI||1)/(t.logicalXDPI||1)}return 1}(),n={toTextLines:function(t){var r,n=[];for(t=[].concat(t);t.length;)"string"==typeof(r=t.pop())?n.unshift.apply(n,r.split("\n")):Array.isArray(r)?t.push.apply(t,r):e.isNullOrUndef(t)||n.unshift(""+r);return n},toFontString:function(t){return!t||e.isNullOrUndef(t.size)||e.isNullOrUndef(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family},textSize:function(t,e,r){var n,i=[].concat(e),o=i.length,a=t.font,l=0;for(t.font=r.string,n=0;n<o;++n)l=Math.max(t.measureText(i[n]).width,l);return t.font=a,{height:o*r.lineHeight,width:l}},parseFont:function(r){var i=t.defaults.global,o=e.valueOrDefault(r.size,i.defaultFontSize),a={family:e.valueOrDefault(r.family,i.defaultFontFamily),lineHeight:e.options.toLineHeight(r.lineHeight,o),size:o,style:e.valueOrDefault(r.style,i.defaultFontStyle),weight:e.valueOrDefault(r.weight,null),string:""};return a.string=n.toFontString(a),a},bound:function(t,e,r){return Math.max(t,Math.min(e,r))},arrayDiff:function(t,e){var r,n,i,o,a=t.slice(),l=[];for(r=0,i=e.length;r<i;++r)o=e[r],-1===(n=a.indexOf(o))?l.push([o,1]):a.splice(n,1);for(r=0,i=a.length;r<i;++r)l.push([a[r],-1]);return l},rasterize:function(t){return Math.round(t*r)/r}};function i(t,e){var r=e.x,n=e.y;if(null===r)return{x:0,y:-1};if(null===n)return{x:1,y:0};var i=t.x-r,o=t.y-n,a=Math.sqrt(i*i+o*o);return{x:a?i/a:0,y:a?o/a:-1}}var o=0,a=1,l=2,s=4,u=8;function f(t,e,r){var n=o;return t<r.left?n|=a:t>r.right&&(n|=l),e<r.top?n|=u:e>r.bottom&&(n|=s),n}function d(t,e){var r,n,i=e.anchor,o=t;return e.clamp&&(o=function(t,e){for(var r,n,i,o=t.x0,d=t.y0,c=t.x1,h=t.y1,x=f(o,d,e),y=f(c,h,e);x|y&&!(x&y);)(r=x||y)&u?(n=o+(c-o)*(e.top-d)/(h-d),i=e.top):r&s?(n=o+(c-o)*(e.bottom-d)/(h-d),i=e.bottom):r&l?(i=d+(h-d)*(e.right-o)/(c-o),n=e.right):r&a&&(i=d+(h-d)*(e.left-o)/(c-o),n=e.left),r===x?x=f(o=n,d=i,e):y=f(c=n,h=i,e);return{x0:o,x1:c,y0:d,y1:h}}(o,e.area)),"start"===i?(r=o.x0,n=o.y0):"end"===i?(r=o.x1,n=o.y1):(r=(o.x0+o.x1)/2,n=(o.y0+o.y1)/2),function(t,e,r,n,i){switch(i){case"center":r=n=0;break;case"bottom":r=0,n=1;break;case"right":r=1,n=0;break;case"left":r=-1,n=0;break;case"top":r=0,n=-1;break;case"start":r=-r,n=-n;break;case"end":break;default:i*=Math.PI/180,r=Math.cos(i),n=Math.sin(i)}return{x:t,y:e,vx:r,vy:n}}(r,n,t.vx,t.vy,e.align)}var c={arc:function(t,e){var r=(t.startAngle+t.endAngle)/2,n=Math.cos(r),i=Math.sin(r),o=t.innerRadius,a=t.outerRadius;return d({x0:t.x+n*o,y0:t.y+i*o,x1:t.x+n*a,y1:t.y+i*a,vx:n,vy:i},e)},point:function(t,e){var r=i(t,e.origin),n=r.x*t.radius,o=r.y*t.radius;return d({x0:t.x-n,y0:t.y-o,x1:t.x+n,y1:t.y+o,vx:r.x,vy:r.y},e)},rect:function(t,e){var r=i(t,e.origin),n=t.x,o=t.y,a=0,l=0;return t.horizontal?(n=Math.min(t.x,t.base),a=Math.abs(t.base-t.x)):(o=Math.min(t.y,t.base),l=Math.abs(t.base-t.y)),d({x0:n,y0:o+l,x1:n+a,y1:o,vx:r.x,vy:r.y},e)},fallback:function(t,e){var r=i(t,e.origin);return d({x0:t.x,y0:t.y,x1:t.x,y1:t.y,vx:r.x,vy:r.y},e)}},h=t.helpers,x=n.rasterize;function y(t){var e=t._model.horizontal,r=t._scale||e&&t._xScale||t._yScale;if(!r)return null;if(void 0!==r.xCenter&&void 0!==r.yCenter)return{x:r.xCenter,y:r.yCenter};var n=r.getBasePixel();return e?{x:n,y:null}:{x:null,y:n}}function v(t,e,r){var n=t.shadowBlur,i=r.stroked,o=x(r.x),a=x(r.y),l=x(r.w);i&&t.strokeText(e,o,a,l),r.filled&&(n&&i&&(t.shadowBlur=0),t.fillText(e,o,a,l),n&&i&&(t.shadowBlur=n))}var _=function(t,e,r,n){var i=this;i._config=t,i._index=n,i._model=null,i._rects=null,i._ctx=e,i._el=r};h.extend(_.prototype,{_modelize:function(e,r,i,o){var a,l=this._index,s=h.options.resolve,u=n.parseFont(s([i.font,{}],o,l)),f=s([i.color,t.defaults.global.defaultFontColor],o,l);return{align:s([i.align,"center"],o,l),anchor:s([i.anchor,"center"],o,l),area:o.chart.chartArea,backgroundColor:s([i.backgroundColor,null],o,l),borderColor:s([i.borderColor,null],o,l),borderRadius:s([i.borderRadius,0],o,l),borderWidth:s([i.borderWidth,0],o,l),clamp:s([i.clamp,!1],o,l),clip:s([i.clip,!1],o,l),color:f,display:e,font:u,lines:r,offset:s([i.offset,0],o,l),opacity:s([i.opacity,1],o,l),origin:y(this._el),padding:h.options.toPadding(s([i.padding,0],o,l)),positioner:(a=this._el,a instanceof t.elements.Arc?c.arc:a instanceof t.elements.Point?c.point:a instanceof t.elements.Rectangle?c.rect:c.fallback),rotation:s([i.rotation,0],o,l)*(Math.PI/180),size:n.textSize(this._ctx,r,u),textAlign:s([i.textAlign,"start"],o,l),textShadowBlur:s([i.textShadowBlur,0],o,l),textShadowColor:s([i.textShadowColor,f],o,l),textStrokeColor:s([i.textStrokeColor,f],o,l),textStrokeWidth:s([i.textStrokeWidth,0],o,l)}},update:function(t){var e,r,i,o=this,a=null,l=null,s=o._index,u=o._config,f=h.options.resolve([u.display,!0],t,s);f&&(e=t.dataset.data[s],r=h.valueOrDefault(h.callback(u.formatter,[e,t]),e),(i=h.isNullOrUndef(r)?[]:n.toTextLines(r)).length&&(l=function(t){var e=t.borderWidth||0,r=t.padding,n=t.size.height,i=t.size.width,o=-i/2,a=-n/2;return{frame:{x:o-r.left-e,y:a-r.top-e,w:i+r.width+2*e,h:n+r.height+2*e},text:{x:o,y:a,w:i,h:n}}}(a=o._modelize(f,i,u,t)))),o._model=a,o._rects=l},geometry:function(){return this._rects?this._rects.frame:{}},rotation:function(){return this._model?this._model.rotation:0},visible:function(){return this._model&&this._model.opacity},model:function(){return this._model},draw:function(t,e){var r,i=t.ctx,o=this._model,a=this._rects;this.visible()&&(i.save(),o.clip&&(r=o.area,i.beginPath(),i.rect(r.left,r.top,r.right-r.left,r.bottom-r.top),i.clip()),i.globalAlpha=n.bound(0,o.opacity,1),i.translate(x(e.x),x(e.y)),i.rotate(o.rotation),function(t,e,r){var n=r.backgroundColor,i=r.borderColor,o=r.borderWidth;(n||i&&o)&&(t.beginPath(),h.canvas.roundedRect(t,x(e.x)+o/2,x(e.y)+o/2,x(e.w)-o,x(e.h)-o,r.borderRadius),t.closePath(),n&&(t.fillStyle=n,t.fill()),i&&o&&(t.strokeStyle=i,t.lineWidth=o,t.lineJoin="miter",t.stroke()))}(i,a.frame,o),function(t,e,r,n){var i,o=n.textAlign,a=n.color,l=!!a,s=n.font,u=e.length,f=n.textStrokeColor,d=n.textStrokeWidth,c=f&&d;if(u&&(l||c))for(r=function(t,e,r){var n=r.lineHeight,i=t.w,o=t.x;return"center"===e?o+=i/2:"end"!==e&&"right"!==e||(o+=i),{h:n,w:i,x:o,y:t.y+n/2}}(r,o,s),t.font=s.string,t.textAlign=o,t.textBaseline="middle",t.shadowBlur=n.textShadowBlur,t.shadowColor=n.textShadowColor,l&&(t.fillStyle=a),c&&(t.lineJoin="round",t.lineWidth=d,t.strokeStyle=f),i=0,u=e.length;i<u;++i)v(t,e[i],{stroked:c,filled:l,w:r.w,x:r.x,y:r.y+r.h*i})}(i,o.lines,a.text,o),i.restore())}});var b=t.helpers,p=Number.MIN_SAFE_INTEGER||-9007199254740991,g=Number.MAX_SAFE_INTEGER||9007199254740991;function m(t,e,r){var n=Math.cos(r),i=Math.sin(r),o=e.x,a=e.y;return{x:o+n*(t.x-o)-i*(t.y-a),y:a+i*(t.x-o)+n*(t.y-a)}}function w(t,e){var r,n,i,o,a,l=g,s=p,u=e.origin;for(r=0;r<t.length;++r)i=(n=t[r]).x-u.x,o=n.y-u.y,a=e.vx*i+e.vy*o,l=Math.min(l,a),s=Math.max(s,a);return{min:l,max:s}}function k(t,e){var r=e.x-t.x,n=e.y-t.y,i=Math.sqrt(r*r+n*n);return{vx:(e.x-t.x)/i,vy:(e.y-t.y)/i,origin:t,ln:i}}var M=function(){this._rotation=0,this._rect={x:0,y:0,w:0,h:0}};function S(t,e,r){var n=e.positioner(t,e),i=n.vx,o=n.vy;if(!i&&!o)return{x:n.x,y:n.y};var a=r.w,l=r.h,s=e.rotation,u=Math.abs(a/2*Math.cos(s))+Math.abs(l/2*Math.sin(s)),f=Math.abs(a/2*Math.sin(s))+Math.abs(l/2*Math.cos(s)),d=1/Math.max(Math.abs(i),Math.abs(o));return u*=i*d,f*=o*d,u+=e.offset*i,f+=e.offset*o,{x:n.x+u,y:n.y+f}}b.extend(M.prototype,{center:function(){var t=this._rect;return{x:t.x+t.w/2,y:t.y+t.h/2}},update:function(t,e,r){this._rotation=r,this._rect={x:e.x+t.x,y:e.y+t.y,w:e.w,h:e.h}},contains:function(t){var e=this._rect;return!((t=m(t,this.center(),-this._rotation)).x<e.x-1||t.y<e.y-1||t.x>e.x+e.w+2||t.y>e.y+e.h+2)},intersects:function(t){var e,r,n,i=this._points(),o=t._points(),a=[k(i[0],i[1]),k(i[0],i[3])];for(this._rotation!==t._rotation&&a.push(k(o[0],o[1]),k(o[0],o[3])),e=0;e<a.length;++e)if(r=w(i,a[e]),n=w(o,a[e]),r.max<n.min||n.max<r.min)return!1;return!0},_points:function(){var t=this._rect,e=this._rotation,r=this.center();return[m({x:t.x,y:t.y},r,e),m({x:t.x+t.w,y:t.y},r,e),m({x:t.x+t.w,y:t.y+t.h},r,e),m({x:t.x,y:t.y+t.h},r,e)]}});var C={prepare:function(t){var e,r,n,i,o,a=[];for(e=0,n=t.length;e<n;++e)for(r=0,i=t[e].length;r<i;++r)o=t[e][r],a.push(o),o.$layout={_box:new M,_hidable:!1,_visible:!0,_set:e,_idx:r};return a.sort(function(t,e){var r=t.$layout,n=e.$layout;return r._idx===n._idx?n._set-r._set:n._idx-r._idx}),this.update(a),a},update:function(t){var e,r,n,i,o,a=!1;for(e=0,r=t.length;e<r;++e)i=(n=t[e]).model(),(o=n.$layout)._hidable=i&&"auto"===i.display,o._visible=n.visible(),a|=o._hidable;a&&function(t){var e,r,n,i,o,a;for(e=0,r=t.length;e<r;++e)(i=(n=t[e]).$layout)._visible&&(o=n.geometry(),a=S(n._el._model,n.model(),o),i._box.update(a,o,n.rotation()));(function(t,e){var r,n,i,o;for(r=t.length-1;r>=0;--r)for(i=t[r].$layout,n=r-1;n>=0&&i._visible;--n)(o=t[n].$layout)._visible&&i._box.intersects(o._box)&&e(i,o)})(t,function(t,e){var r=t._hidable,n=e._hidable;r&&n||n?e._visible=!1:r&&(t._visible=!1)})}(t)},lookup:function(t,e){var r,n;for(r=t.length-1;r>=0;--r)if((n=t[r].$layout)&&n._visible&&n._box.contains(e))return t[r];return null},draw:function(t,e){var r,n,i,o,a,l;for(r=0,n=e.length;r<n;++r)(o=(i=e[r]).$layout)._visible&&(a=i.geometry(),l=S(i._el._view,i.model(),a),o._box.update(l,a,i.rotation()),i.draw(t,l))}},z=t.helpers,$={align:"center",anchor:"center",backgroundColor:null,borderColor:null,borderRadius:0,borderWidth:0,clamp:!1,clip:!1,color:void 0,display:!0,font:{family:void 0,lineHeight:1.2,size:void 0,style:void 0,weight:null},formatter:function(t){if(z.isNullOrUndef(t))return null;var e,r,n,i=t;if(z.isObject(t))if(z.isNullOrUndef(t.label))if(z.isNullOrUndef(t.r))for(i="",n=0,r=(e=Object.keys(t)).length;n<r;++n)i+=(0!==n?", ":"")+e[n]+": "+t[e[n]];else i=t.r;else i=t.label;return""+i},labels:void 0,listeners:{},offset:4,opacity:1,padding:{top:4,right:4,bottom:4,left:4},rotation:0,textAlign:"start",textStrokeColor:void 0,textStrokeWidth:0,textShadowBlur:0,textShadowColor:void 0},O=t.helpers,A="$datalabels",D="$default";function P(t,e,r){if(e){var n,i=r.$context,o=r.$groups;e[o._set]&&(n=e[o._set][o._key])&&!0===O.callback(n,[i])&&(t[A]._dirty=!0,r.update(i))}}function N(t,e){var r,n,i=t[A],o=i._listeners;if(o.enter||o.leave){if("mousemove"===e.type)n=C.lookup(i._labels,e);else if("mouseout"!==e.type)return;r=i._hovered,i._hovered=n,function(t,e,r,n){var i,o;(r||n)&&(r?n?r!==n&&(o=i=!0):o=!0:i=!0,o&&P(t,e.leave,r),i&&P(t,e.enter,n))}(t,o,r,n)}}t.defaults.global.plugins.datalabels=$;var R={id:"datalabels",beforeInit:function(t){t[A]={_actives:[]}},beforeUpdate:function(t){var e=t[A];e._listened=!1,e._listeners={},e._datasets=[],e._labels=[]},afterDatasetUpdate:function(t,e,r){var n,i,o,a,l,s,u,f,d=e.index,c=t[A],h=c._datasets[d]=[],x=t.isDatasetVisible(d),y=t.data.datasets[d],v=function(t,e){var r,n,i,o=t.datalabels,a=[];return!1===o?null:(!0===o&&(o={}),e=O.merge({},[e,o]),n=e.labels||{},i=Object.keys(n),delete e.labels,i.length?i.forEach(function(t){n[t]&&a.push(O.merge({},[e,n[t],{_key:t}]))}):a.push(e),r=a.reduce(function(t,e){return O.each(e.listeners||{},function(r,n){t[n]=t[n]||{},t[n][e._key||D]=r}),delete e.listeners,t},{}),{labels:a,listeners:r})}(y,r),b=e.meta.data||[],p=t.ctx;for(p.save(),n=0,o=b.length;n<o;++n)if((u=b[n])[A]=[],x&&u&&!u.hidden&&!u._model.skip)for(i=0,a=v.labels.length;i<a;++i)s=(l=v.labels[i])._key,(f=new _(l,p,u,n)).$groups={_set:d,_key:s||D},f.$context={active:!1,chart:t,dataIndex:n,dataset:y,datasetIndex:d},f.update(f.$context),u[A].push(f),h.push(f);p.restore(),O.merge(c._listeners,v.listeners,{merger:function(t,r,n){r[t]=r[t]||{},r[t][e.index]=n[t],c._listened=!0}})},afterUpdate:function(t,e){t[A]._labels=C.prepare(t[A]._datasets,e)},afterDatasetsDraw:function(t){C.draw(t,t[A]._labels)},beforeEvent:function(t,e){if(t[A]._listened)switch(e.type){case"mousemove":case"mouseout":N(t,e);break;case"click":!function(t,e){var r=t[A],n=r._listeners.click,i=n&&C.lookup(r._labels,e);i&&P(t,n,i)}(t,e)}},afterEvent:function(e){var r,i,o,a,l,s,u,f=e[A],d=f._actives,c=f._actives=e.lastActive||[],h=n.arrayDiff(d,c);for(r=0,i=h.length;r<i;++r)if((l=h[r])[1])for(o=0,a=(u=l[0][A]||[]).length;o<a;++o)(s=u[o]).$context.active=1===l[1],s.update(s.$context);(f._dirty||h.length)&&(C.update(f._labels),function(e){if(!e.animating){for(var r=t.animationService.animations,n=0,i=r.length;n<i;++n)if(r[n].chart===e)return;e.render({duration:1,lazy:!0})}}(e)),delete f._dirty}};return t.plugins.register(R),R});diff --git a/yarn.lock b/yarn.lockindex 578c46a4861..9a4b87cccc4 100644--- a/yarn.lock+++ b/yarn.lock@@ -623,6 +623,11 @@ chartjs-color@^2.1.0:chartjs-color-string "^0.6.0"color-convert "^1.9.3"+chartjs-plugin-datalabels@^0.7.0:+ version "0.7.0"+ resolved "https://registry.yarnpkg.com/chartjs-plugin-datalabels/-/chartjs-plugin-datalabels-0.7.0.tgz#f72e44edb2db45ef68913e9320bcc50398a205e6"+ integrity sha512-PKVUX14nYhH0wcdCpgOoC39Gbzvn6cZ7O9n+bwc02yKD9FTnJ7/TSrBcfebmolFZp1Rcicr9xbT0a5HUbigS7g==+chrome-launcher@^0.12.0:version "0.12.0"resolved "https://registry.yarnpkg.com/chrome-launcher/-/chrome-launcher-0.12.0.tgz#08db81ef0f7b283c331df2c350e780c38bd0ce3a"