Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add poll editing to the rich text editor (#43046)

Renato Atilio08dd9cdcd7c7
diff --git a/plugins/poll/assets/javascripts/discourse/components/modal/poll-ui-builder.gjs b/plugins/poll/assets/javascripts/discourse/components/modal/poll-ui-builder.gjs
index 3492685c220..9f50bbeaf42 100644
--- a/plugins/poll/assets/javascripts/discourse/components/modal/poll-ui-builder.gjs
+++ b/plugins/poll/assets/javascripts/discourse/components/modal/poll-ui-builder.gjs
@@ -6,11 +6,12 @@ import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { trackedObject } from "@ember/reactive/collections";
import { service } from "@ember/service";
+import { isBlank } from "@ember/utils";
import AdvancedModeToggle from "discourse/components/advanced-mode-toggle";
import withEventValue from "discourse/helpers/with-event-value";
import { removeValueFromArray } from "discourse/lib/array-tools";
import { AUTO_GROUPS } from "discourse/lib/constants";
-import { bind } from "discourse/lib/decorators";
+import { buildBBCodeAttrs } from "discourse/lib/text";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import ComboBox from "discourse/select-kit/components/combo-box";
import GroupChooser from "discourse/select-kit/components/group-chooser";
@@ -28,16 +29,26 @@ import { i18n } from "discourse-i18n";
import generateCurrentDateMarkup from "discourse/plugins/discourse-local-dates/lib/generate-current-date-markup" with {
discourseImport: "optional",
};
+import {
+ ALWAYS_POLL_RESULT,
+ BAR_CHART_TYPE,
+ MULTIPLE_POLL_TYPE,
+ NUMBER_POLL_TYPE,
+ PIE_CHART_TYPE,
+ pollAttrsFromSettings,
+ RANKED_CHOICE_POLL_TYPE,
+ REGULAR_POLL_TYPE,
+} from "discourse/plugins/poll/lib/poll-settings";
+
+export {
+ BAR_CHART_TYPE,
+ PIE_CHART_TYPE,
+ REGULAR_POLL_TYPE,
+ NUMBER_POLL_TYPE,
+ MULTIPLE_POLL_TYPE,
+ RANKED_CHOICE_POLL_TYPE,
+} from "discourse/plugins/poll/lib/poll-settings";
-export const BAR_CHART_TYPE = "bar";
-export const PIE_CHART_TYPE = "pie";
-
-export const REGULAR_POLL_TYPE = "regular";
-export const NUMBER_POLL_TYPE = "number";
-export const MULTIPLE_POLL_TYPE = "multiple";
-export const RANKED_CHOICE_POLL_TYPE = "ranked_choice";
-
-const ALWAYS_POLL_RESULT = "always";
const VOTE_POLL_RESULT = "on_vote";
const CLOSED_POLL_RESULT = "on_close";
const STAFF_POLL_RESULT = "staff_only";
@@ -62,6 +73,42 @@ export default class PollUiBuilderModal extends Component {
@tracked showAdvanced = false;
@autoTrackedArray pollOptions = [trackedObject({ value: "" })];
+ constructor() {
+ super(...arguments);
+
+ const poll = this.args.model.poll;
+ if (poll) {
+ this.pollType = poll.type || REGULAR_POLL_TYPE;
+ this.chartType = poll.chartType || BAR_CHART_TYPE;
+ this.dynamic = poll.dynamic === "true";
+ this.pollAutoClose = poll.close ? moment(poll.close) : null;
+ this.pollGroups = poll.groups?.split(",");
+ this.pollMin = Number(poll.min ?? 1);
+ this.pollMax = Number(
+ poll.max ??
+ (this.isNumber
+ ? this.siteSettings.poll_maximum_options
+ : poll.optionCount)
+ );
+ this.pollStep = Number(poll.step ?? 1);
+ this.pollResult = poll.results || ALWAYS_POLL_RESULT;
+ this.publicPoll = poll.public === "true";
+ this.showAdvanced = true;
+ }
+ }
+
+ get isEditing() {
+ return !!this.args.model.poll;
+ }
+
+ get showTitle() {
+ return this.showAdvanced && !this.isEditing;
+ }
+
+ get showOptions() {
+ return !this.isNumber && !this.isEditing;
+ }
+
get showNumber() {
return this.showAdvanced || this.isNumber;
}
@@ -125,8 +172,9 @@ export default class PollUiBuilderModal extends Component {
}
get pollOptionsCount() {
- return (this.pollOptions || []).filter((option) => option.value.length > 0)
- .length;
+ return this.isEditing
+ ? this.args.model.poll.optionCount
+ : this.pollOptions.filter((option) => option.value.trim()).length;
}
get siteGroups() {
@@ -134,79 +182,63 @@ export default class PollUiBuilderModal extends Component {
return this.site.groups.filter((g) => g.id !== AUTO_GROUPS.everyone.id);
}
+ get hasRange() {
+ return this.isMultiple || this.isNumber;
+ }
+
get isPie() {
return (
this.pollType !== NUMBER_POLL_TYPE && this.chartType === PIE_CHART_TYPE
);
}
- get pollOutput() {
- let pollHeader = "[poll";
- let output = "";
-
- const match = this.args.model.toolbarEvent
+ get #pollOutput() {
+ const pollAttrs = this.#pollAttrs;
+ const existingPolls = this.args.model.toolbarEvent
.getText()
.match(/\[poll(\s+name=[^\s\]]+)*.*\]/gim);
-
- if (match) {
- pollHeader += ` name=poll${match.length + 1}`;
+ if (existingPolls) {
+ pollAttrs.name = `poll${existingPolls.length + 1}`;
}
- let step = this.pollStep;
- if (step < 1) {
- step = 1;
- }
-
- if (this.pollType) {
- pollHeader += ` type=${this.pollType}`;
- }
- if (this.pollResult) {
- pollHeader += ` results=${this.pollResult}`;
- }
- if (this.pollMin && this.pollType !== REGULAR_POLL_TYPE) {
- pollHeader += ` min=${this.pollMin}`;
- }
- if (this.pollMax && this.pollType !== REGULAR_POLL_TYPE) {
- pollHeader += ` max=${this.pollMax}`;
- }
- if (this.pollType === NUMBER_POLL_TYPE) {
- pollHeader += ` step=${step}`;
- }
- pollHeader += ` public=${this.publicPoll ? "true" : "false"}`;
- if (this.chartType && this.pollType !== NUMBER_POLL_TYPE) {
- pollHeader += ` chartType=${this.chartType}`;
- }
- if (this.dynamic) {
- pollHeader += ` dynamic=true`;
- }
- if (this.pollGroups?.length > 0) {
- pollHeader += ` groups=${this.pollGroups}`;
- }
- if (this.pollAutoClose) {
- pollHeader += ` close=${this.pollAutoClose.toISOString()}`;
- }
-
- pollHeader += "]";
- output += `${pollHeader}\n`;
-
- if (this.pollTitle) {
- output += `# ${this.pollTitle.trim()}\n`;
- }
-
- if (this.pollOptions.length > 0 && this.pollType !== NUMBER_POLL_TYPE) {
- this.pollOptions.forEach((option) => {
- if (option.value.length > 0) {
- output += `* ${option.value.trim()}\n`;
- }
- });
- }
+ const attrs = buildBBCodeAttrs(pollAttrs);
+ const title = this.pollTitle ? `# ${this.pollTitle.trim()}\n` : "";
+ const options = this.isNumber
+ ? ""
+ : this.pollOptions
+ .map((option) => option.value.trim())
+ .filter(Boolean)
+ .map((option) => `* ${option}\n`)
+ .join("");
+
+ return `[poll${attrs ? ` ${attrs}` : ""}]\n${title}${options}[/poll]\n`;
+ }
- output += "[/poll]\n";
- return output;
+ get #pollAttrs() {
+ return pollAttrsFromSettings(
+ {
+ pollType: this.pollType,
+ chartType: this.chartType,
+ dynamic: this.dynamic,
+ pollAutoClose: this.pollAutoClose,
+ pollGroups: this.pollGroups,
+ pollMin: this.pollMin,
+ pollMax: this.pollMax,
+ pollStep: this.pollStep,
+ pollResult: this.pollResult,
+ publicPoll: this.publicPoll,
+ },
+ {
+ originalAttrs: this.args.model.poll,
+ optionCount: this.pollOptionsCount,
+ maximumOptions: this.siteSettings.poll_maximum_options,
+ }
+ );
}
get minNumOfOptionsValidation() {
- if (!this.isNumber) {
+ // Option counts are edited in the document, not in this settings modal.
+ if (!this.isNumber && !this.isEditing) {
if (this.pollOptionsCount < 1) {
return {
failed: true,
@@ -232,18 +264,26 @@ export default class PollUiBuilderModal extends Component {
}
get minMaxValueValidation() {
+ if (!this.hasRange) {
+ return { ok: true };
+ }
+
const pollMin = parseInt(this.pollMin, 10) || 0;
const pollMax = parseInt(this.pollMax, 10) || 0;
const pollStep = parseInt(this.pollStep, 10) || 0;
- if (pollMin < 0) {
+ if (isBlank(this.pollMin) || pollMin < 0) {
return {
failed: true,
reason: i18n("poll.ui_builder.help.invalid_min_value"),
};
}
- if (pollMax < 0 || (this.isMultiple && pollMax > this.pollOptionsCount)) {
+ if (
+ isBlank(this.pollMax) ||
+ pollMax < 0 ||
+ (this.isMultiple && pollMax > this.pollOptionsCount)
+ ) {
return {
failed: true,
reason: i18n("poll.ui_builder.help.invalid_max_value"),
@@ -291,52 +331,33 @@ export default class PollUiBuilderModal extends Component {
return !this.minMaxValueValidation.ok || !this.minNumOfOptionsValidation.ok;
}
- @bind
- enforceMinMaxValues() {
- if (this.isMultiple) {
- if (
- this.pollMin <= 0 ||
- this.pollMin >= this.pollMax ||
- this.pollMin >= this.pollOptionsCount
- ) {
- this.pollMin = this.pollOptionsCount > 0 ? 1 : 0;
- }
-
- if (
- this.pollMax <= 0 ||
- this.pollMin >= this.pollMax ||
- this.pollMax > this.pollOptionsCount
- ) {
- this.pollMax = this.pollOptionsCount;
- }
- } else if (this.isNumber) {
- this.pollMax = this.siteSettings.poll_maximum_options;
- }
- }
-
@action
onChangePollMin(event) {
this.pollMin = event.target.value;
- this.enforceMinMaxValues();
+ this.#enforceMinMaxValues();
}
@action
onChangePollMax(event) {
this.pollMax = event.target.value;
- this.enforceMinMaxValues();
+ this.#enforceMinMaxValues();
}
@action
- onOptionsTextChange(e) {
- this.pollOptions = e.target.value
+ onOptionsTextChange(event) {
+ this.pollOptions = event.target.value
.split("\n")
.map((value) => trackedObject({ value }));
- this.enforceMinMaxValues();
+ this.#enforceMinMaxValues();
}
@action
insertPoll() {
- this.args.model.toolbarEvent.addText(this.pollOutput);
+ if (this.args.model.onSave) {
+ this.args.model.onSave(this.#pollAttrs);
+ } else {
+ this.args.model.toolbarEvent.addText(this.#pollOutput);
+ }
this.args.closeModal();
}
@@ -351,7 +372,7 @@ export default class PollUiBuilderModal extends Component {
@action
updateValue(option, event) {
option.value = event.target.value;
- this.enforceMinMaxValues();
+ this.#enforceMinMaxValues();
}
@action
@@ -386,7 +407,7 @@ export default class PollUiBuilderModal extends Component {
const value = option.value || "";
option.value = value.slice(0, start) + markup + value.slice(end);
- this.enforceMinMaxValues();
+ this.#enforceMinMaxValues();
requestAnimationFrame(() => {
input.setSelectionRange(start + markup.length, start + markup.length);
@@ -402,20 +423,23 @@ export default class PollUiBuilderModal extends Component {
const option = trackedObject({ value: "" });
this.pollOptions.splice(atIndex, 0, option);
- this.enforceMinMaxValues();
+ this.#enforceMinMaxValues();
}
@action
removeOption(option) {
removeValueFromArray(this.pollOptions, option);
- this.enforceMinMaxValues();
+ this.#enforceMinMaxValues();
}
@action
updatePollType(pollType, event) {
event?.preventDefault();
+ if (pollType === NUMBER_POLL_TYPE && !this.isNumber) {
+ this.pollMax = this.siteSettings.poll_maximum_options;
+ }
this.pollType = pollType;
- this.enforceMinMaxValues();
+ this.#enforceMinMaxValues();
}
@action
@@ -423,6 +447,26 @@ export default class PollUiBuilderModal extends Component {
this.publicPoll = !this.publicPoll;
}
+ #enforceMinMaxValues() {
+ if (this.isMultiple) {
+ if (
+ this.pollMin <= 0 ||
+ this.pollMin >= this.pollMax ||
+ this.pollMin >= this.pollOptionsCount
+ ) {
+ this.pollMin = this.pollOptionsCount > 0 ? 1 : 0;
+ }
+
+ if (
+ this.pollMax <= 0 ||
+ this.pollMin >= this.pollMax ||
+ this.pollMax > this.pollOptionsCount
+ ) {
+ this.pollMax = this.pollOptionsCount;
+ }
+ }
+ }
+
_comboboxOptions(startIndex, endIndex) {
return [...Array(endIndex - startIndex).keys()].map((number) => ({
value: number + startIndex,
@@ -435,7 +479,9 @@ export default class PollUiBuilderModal extends Component {
class="poll-ui-builder"
@closeModal={{@closeModal}}
@inline={{@inline}}
- @title={{i18n "poll.ui_builder.title"}}
+ @title={{i18n
+ (if @model.poll "poll.ui_builder.edit" "poll.ui_builder.title")
+ }}
>
<:body>
<ul class="nav nav-pills poll-type">
@@ -489,7 +535,7 @@ export default class PollUiBuilderModal extends Component {
{{/if}}
</ul>
- {{#if this.showAdvanced}}
+ {{#if this.showTitle}}
<div class="input-group poll-title">
<label class="input-group-label">{{i18n
"poll.ui_builder.poll_title.label"
@@ -502,7 +548,7 @@ export default class PollUiBuilderModal extends Component {
</div>
{{/if}}
- {{#unless this.isNumber}}
+ {{#if this.showOptions}}
<div class="poll-options">
{{#if this.showAdvanced}}
<label class="input-group-label">{{i18n
@@ -554,7 +600,7 @@ export default class PollUiBuilderModal extends Component {
</div>
{{/if}}
</div>
- {{/unless}}
+ {{/if}}
{{#unless this.rankedChoiceOrRegular}}
<div class="options">
@@ -698,15 +744,17 @@ export default class PollUiBuilderModal extends Component {
@action={{this.insertPoll}}
@disabled={{this.disableInsert}}
@icon="chart-bar"
- @label="poll.ui_builder.insert"
+ @label={{if @model.poll "save" "poll.ui_builder.insert"}}
/>
<DButton class="btn-flat" @action={{@closeModal}} @label="cancel" />
- <AdvancedModeToggle
- @active={{this.showAdvanced}}
- @onToggle={{this.toggleAdvanced}}
- />
+ {{#unless this.isEditing}}
+ <AdvancedModeToggle
+ @active={{this.showAdvanced}}
+ @onToggle={{this.toggleAdvanced}}
+ />
+ {{/unless}}
</:footer>
</DModal>
diff --git a/plugins/poll/assets/javascripts/discourse/components/poll-node-view.gjs b/plugins/poll/assets/javascripts/discourse/components/poll-node-view.gjs
new file mode 100644
index 00000000000..960498ee936
--- /dev/null
+++ b/plugins/poll/assets/javascripts/discourse/components/poll-node-view.gjs
@@ -0,0 +1,190 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { buildBBCodeAttrs } from "discourse/lib/text";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+import pollBounds from "discourse/plugins/poll/lib/poll-bounds";
+import PollUiBuilder from "./modal/poll-ui-builder";
+import PollInfo from "./poll-info";
+
+export default class PollNodeView extends Component {
+ @service modal;
+
+ constructor() {
+ super(...arguments);
+ this.args.contentDOM.classList.add(
+ "poll-container",
+ "composer-poll-node__content"
+ );
+ this.args.dom.style.setProperty(
+ "--poll-title-placeholder",
+ JSON.stringify(i18n("poll.ui_builder.poll_title.placeholder"))
+ );
+ this.args.onSetup(this);
+ this.update(this.args.node);
+ }
+
+ get #optionCount() {
+ return this.#optionList(this.args.node)?.node.childCount ?? 0;
+ }
+
+ get #bounds() {
+ return pollBounds(this.args.node.attrs, this.#optionCount);
+ }
+
+ get pollInfo() {
+ const { attrs } = this.args.node;
+ const closesAt = attrs.close ? moment(attrs.close) : null;
+
+ return {
+ isMultiple: attrs.type === "multiple",
+ isPublic: attrs.public === "true",
+ isDynamic: attrs.dynamic === "true",
+ results: attrs.results,
+ min: this.#bounds.min,
+ max: this.#bounds.max,
+ closesAt,
+ isAutomaticallyClosed: !!closesAt?.isBefore(moment()),
+ // PollInfo uses only the length when describing selection limits.
+ options: new Array(this.#optionCount),
+ };
+ }
+
+ deselectNode() {
+ this.args.dom.classList.remove("ProseMirror-selectednode");
+ }
+
+ @action
+ editPoll() {
+ const { node } = this.args;
+
+ this.modal.show(PollUiBuilder, {
+ model: {
+ poll: { ...node.attrs, optionCount: this.#optionCount },
+ onSave: (attrs) => this.#savePoll(attrs),
+ },
+ });
+ }
+
+ ignoreMutation(mutation) {
+ return (
+ mutation.type !== "selection" &&
+ ((mutation.type === "attributes" &&
+ mutation.target === this.args.contentDOM) ||
+ !this.args.contentDOM.contains(mutation.target))
+ );
+ }
+
+ selectNode() {
+ this.args.dom.classList.add("ProseMirror-selectednode");
+ }
+
+ stopEvent(event) {
+ return !!event.target.closest(".composer-poll-node__edit");
+ }
+
+ update(node) {
+ const attrs = node.type.spec.toDOM(node)[1];
+ for (const [name, value] of Object.entries(attrs)) {
+ if (name === "class") {
+ this.args.dom.classList.add(value);
+ } else if (value === null) {
+ this.args.dom.removeAttribute(name);
+ } else {
+ this.args.dom.setAttribute(name, value);
+ }
+ }
+ // An empty editor block contains a trailing break, so :empty won't match.
+ this.args.dom.classList.toggle(
+ "--untitled",
+ node.firstChild?.type.name === "poll_title" &&
+ node.firstChild.content.size === 0
+ );
+
+ // Generated options are omitted from Markdown, so edits here would be lost.
+ const list = this.args.contentDOM.querySelector(":scope > ul");
+ if (list) {
+ if (node.attrs.type === "number") {
+ list.contentEditable = "false";
+ } else {
+ list.removeAttribute("contenteditable");
+ }
+ }
+ }
+
+ #optionList(node) {
+ const { bullet_list: bulletList } = this.args.pluginParams.schema.nodes;
+ let offset = 1;
+
+ for (let index = 0; index < node.childCount; index++) {
+ const child = node.child(index);
+ if (child.type === bulletList) {
+ return { node: child, offset };
+ }
+ offset += child.nodeSize;
+ }
+ }
+
+ #savePoll(attrs) {
+ const { getPos, view, pluginParams } = this.args;
+ const pos = getPos();
+ if (pos === undefined || view.isDestroyed) {
+ return;
+ }
+
+ const node = view.state.doc.nodeAt(pos);
+ if (node?.type !== this.args.node.type) {
+ return;
+ }
+
+ const tr = view.state.tr.setNodeMarkup(pos, null, attrs);
+
+ if (attrs.type === "number") {
+ const generatedPoll = pluginParams.utils.convertFromMarkdown(
+ `[poll ${buildBBCodeAttrs(attrs)}]\n[/poll]`
+ ).firstChild;
+ const generated = generatedPoll && this.#optionList(generatedPoll)?.node;
+ const list = this.#optionList(node);
+
+ if (list && generated?.type === list.node.type) {
+ const from = pos + list.offset;
+ tr.replaceWith(from, from + list.node.nodeSize, generated);
+ }
+ }
+
+ tr.setSelection(pluginParams.pmState.NodeSelection.create(tr.doc, pos));
+ view.dispatch(tr);
+ view.focus();
+ }
+
+ <template>
+ <div class="composer-poll-node__info" contenteditable="false">
+ {{#let this.pollInfo as |info|}}
+ <PollInfo
+ @closesAt={{info.closesAt}}
+ @isAutomaticallyClosed={{info.isAutomaticallyClosed}}
+ @isDynamic={{info.isDynamic}}
+ @isMultiple={{info.isMultiple}}
+ @isPublic={{info.isPublic}}
+ @max={{info.max}}
+ @min={{info.min}}
+ @options={{info.options}}
+ @results={{info.results}}
+ @voters={{0}}
+ />
+ {{/let}}
+ </div>
+ <div
+ class="poll-buttons composer-poll-node__actions"
+ contenteditable="false"
+ >
+ <DButton
+ class="btn-default composer-poll-node__edit"
+ @action={{this.editPoll}}
+ @icon="pencil"
+ @label="poll.ui_builder.edit"
+ />
+ </div>
+ </template>
+}
diff --git a/plugins/poll/assets/javascripts/discourse/components/poll.gjs b/plugins/poll/assets/javascripts/discourse/components/poll.gjs
index fa05cfa986c..df0dca8c03c 100644
--- a/plugins/poll/assets/javascripts/discourse/components/poll.gjs
+++ b/plugins/poll/assets/javascripts/discourse/components/poll.gjs
@@ -17,6 +17,7 @@ import { triggerBlobDownload } from "discourse/lib/download-blob";
import round from "discourse/lib/round";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
+import pollBounds from "discourse/plugins/poll/lib/poll-bounds";
import PollBreakdownModal from "../components/modal/poll-breakdown";
import {
MULTIPLE_POLL_TYPE,
@@ -283,22 +284,16 @@ export default class PollComponent extends Component {
return this.poll.ranked_choice_outcome || null;
}
- get min() {
- let min = parseInt(this.poll.min, 10);
- if (isNaN(min) || min < 0) {
- min = 1;
- }
+ get #bounds() {
+ return pollBounds(this.poll, this.poll.options?.length ?? 0);
+ }
- return min;
+ get min() {
+ return this.#bounds.min;
}
get max() {
- let max = parseInt(this.poll.max, 10);
- const numOptions = this.poll.options.length;
- if (isNaN(max) || max > numOptions) {
- max = numOptions;
- }
- return max;
+ return this.#bounds.max;
}
get closed() {
diff --git a/plugins/poll/assets/javascripts/lib/poll-bounds.js b/plugins/poll/assets/javascripts/lib/poll-bounds.js
new file mode 100644
index 00000000000..e8eb6a0a8cd
--- /dev/null
+++ b/plugins/poll/assets/javascripts/lib/poll-bounds.js
@@ -0,0 +1,18 @@
+/**
+ * How many options a poll accepts, given what its markup carries. Both bounds
+ * are optional there: no minimum means one, and no maximum, or one past the
+ * options that exist, means all of them.
+ *
+ * @param {{ min?: string|number, max?: string|number }} poll
+ * @param {number} optionCount
+ * @returns {{ min: number, max: number }}
+ */
+export default function pollBounds(poll, optionCount) {
+ const min = parseInt(poll.min, 10);
+ const max = parseInt(poll.max, 10);
+
+ return {
+ min: isNaN(min) || min < 0 ? 1 : min,
+ max: isNaN(max) || max > optionCount ? optionCount : max,
+ };
+}
diff --git a/plugins/poll/assets/javascripts/lib/poll-settings.js b/plugins/poll/assets/javascripts/lib/poll-settings.js
new file mode 100644
index 00000000000..3560d547587
--- /dev/null
+++ b/plugins/poll/assets/javascripts/lib/poll-settings.js
@@ -0,0 +1,73 @@
+import { isBlank } from "@ember/utils";
+
+export const BAR_CHART_TYPE = "bar";
+export const PIE_CHART_TYPE = "pie";
+
+export const REGULAR_POLL_TYPE = "regular";
+export const NUMBER_POLL_TYPE = "number";
+export const MULTIPLE_POLL_TYPE = "multiple";
+export const RANKED_CHOICE_POLL_TYPE = "ranked_choice";
+
+export const ALWAYS_POLL_RESULT = "always";
+
+export function pollAttrsFromSettings(
+ settings,
+ { originalAttrs, optionCount, maximumOptions }
+) {
+ const isNumber = settings.pollType === NUMBER_POLL_TYPE;
+ const hasRange = isNumber || settings.pollType === MULTIPLE_POLL_TYPE;
+ const originalClose = originalAttrs?.close;
+ let close = null;
+
+ if (settings.pollAutoClose) {
+ close =
+ originalClose && moment(originalClose).isSame(settings.pollAutoClose)
+ ? originalClose
+ : settings.pollAutoClose.toISOString();
+ }
+
+ const attrs = {
+ name: originalAttrs?.name ?? null,
+ type: settings.pollType || null,
+ results: settings.pollResult || null,
+ min: hasRange ? rangeAttr(settings.pollMin) : null,
+ max: hasRange ? rangeAttr(settings.pollMax) : null,
+ step: isNumber ? String(Math.max(Number(settings.pollStep) || 1, 1)) : null,
+ public: String(settings.publicPoll),
+ chartType: !isNumber && settings.chartType ? settings.chartType : null,
+ dynamic: settings.dynamic ? "true" : null,
+ groups: settings.pollGroups?.length ? settings.pollGroups.join(",") : null,
+ close,
+ status: originalAttrs?.status ?? null,
+ order: originalAttrs?.order ?? null,
+ };
+
+ if (originalAttrs) {
+ const impliedAttrs = {
+ type: REGULAR_POLL_TYPE,
+ results: ALWAYS_POLL_RESULT,
+ public: "false",
+ chartType: BAR_CHART_TYPE,
+ min: "1",
+ max: String(isNumber ? maximumOptions : optionCount),
+ step: "1",
+ };
+
+ // Preserve omitted defaults so bounds can still follow later option changes.
+ for (const [name, value] of Object.entries(impliedAttrs)) {
+ if (attrs[name] === value && !originalAttrs[name]) {
+ attrs[name] = null;
+ }
+ }
+ }
+
+ return attrs;
+}
+
+function rangeAttr(value) {
+ if (isBlank(value) || !Number.isFinite(Number(value))) {
+ return null;
+ }
+
+ return String(Number(value));
+}
diff --git a/plugins/poll/assets/javascripts/lib/rich-editor-extension.js b/plugins/poll/assets/javascripts/lib/rich-editor-extension.js
index bb5f2cacb27..acb37f6cf63 100644
--- a/plugins/poll/assets/javascripts/lib/rich-editor-extension.js
+++ b/plugins/poll/assets/javascripts/lib/rich-editor-extension.js
@@ -1,7 +1,11 @@
import { buildBBCodeAttrs } from "discourse/lib/text";
+import PollNodeView from "../discourse/components/poll-node-view";
/** @type {RichEditorExtension} */
const extension = {
+ nodeViews: {
+ poll: { component: PollNodeView, name: "poll", hasContent: true },
+ },
nodeSpec: {
poll: {
attrs: {
@@ -19,7 +23,7 @@ const extension = {
order: { default: null },
step: { default: null },
},
- content: "heading? bullet_list poll_info?",
+ content: "poll_title bullet_list poll_info?",
group: "block",
selectable: true,
isolating: true,
@@ -71,6 +75,11 @@ const extension = {
0,
],
},
+ poll_title: {
+ content: "inline*",
+ parseDOM: [{ tag: "div.poll-title" }],
+ toDOM: () => ["div", { class: "poll-title" }, 0],
+ },
poll_info: {
content: "inline*",
selectable: false,
@@ -90,7 +99,7 @@ const extension = {
}),
},
poll_container: { ignore: true },
- poll_title: { block: "heading" },
+ poll_title: { block: "poll_title" },
poll_info: { block: "poll_info" },
poll_info_counts: { ignore: true },
poll_info_counts_count: { ignore: true },
@@ -104,16 +113,39 @@ const extension = {
poll(state, node) {
const attrs = buildBBCodeAttrs(node.attrs);
state.write(`[poll${attrs ? ` ${attrs}` : ""}]\n`);
- if (node.attrs.type === "number") {
- // options are generated from the range, they are not authored content
- if (node.firstChild?.type.name === "heading") {
- state.render(node.firstChild, node, 0);
+
+ node.forEach((child, offset, index) => {
+ // the title node is always present, an untitled poll leaves it empty
+ if (child.type.name === "poll_title" && child.content.size === 0) {
+ return;
}
- } else {
- state.renderContent(node);
- }
+
+ // a number poll's options come from its range, not from authored items
+ if (child.type.name === "bullet_list" && node.attrs.type === "number") {
+ return;
+ }
+
+ state.render(child, node, index);
+ });
+
state.write("[/poll]\n\n");
},
+ poll_title(state, node) {
+ state.write("# ");
+
+ // a title is one line of markdown: a break written as a newline would
+ // end the title and leave the rest of the poll unreadable to the parser
+ const { hard_break: hardBreak } = state.nodes;
+ state.nodes.hard_break = (titleState) => titleState.write("<br>");
+
+ try {
+ state.renderInline(node, false);
+ } finally {
+ state.nodes.hard_break = hardBreak;
+ }
+
+ state.closeBlock(node);
+ },
poll_info() {},
},
};
diff --git a/plugins/poll/assets/stylesheets/common/poll.scss b/plugins/poll/assets/stylesheets/common/poll.scss
index 337eb1815e9..93896a31d15 100644
--- a/plugins/poll/assets/stylesheets/common/poll.scss
+++ b/plugins/poll/assets/stylesheets/common/poll.scss
@@ -5,7 +5,8 @@
--poll-bar-color--chosen: var(--tertiary);
}
-div.poll-outer {
+div.poll-outer,
+.ProseMirror {
div.poll {
margin: 1em 0;
border: 1px solid var(--content-border-color);
@@ -592,74 +593,115 @@ body.crawler {
}
}
-.ProseMirror {
- .poll {
- border: 1px solid var(--content-border-color);
- border-radius: var(--d-border-radius);
- padding: 1rem;
- margin-bottom: 1rem;
+// The cooked poll styles above also apply inside the editor, so the rules here
+// that carry a `.poll` or a media query are deliberately written to outrank a
+// specific one of them.
+.composer-poll-node {
+ &__content {
+ min-width: 0;
- ul {
- list-style-type: none;
- padding: 0;
- }
+ > ul {
+ margin: 0;
- li {
- p {
- display: inline;
+ > li {
+ position: relative;
+ padding: 0.5em 0;
+ padding-inline-start: 1.5em;
+ overflow-wrap: anywhere;
+
+ > p {
+ margin: 0;
+ }
+
+ &::before {
+ content: "";
+ position: absolute;
+ inset-inline-start: 0;
+ top: 0.75em;
+ width: 0.9em;
+ height: 0.9em;
+ box-sizing: border-box;
+ border: 2px solid var(--primary);
+ border-radius: 50%;
+ }
}
}
+ }
- li::before {
- position: relative;
- vertical-align: baseline;
- border: 2px solid var(--primary);
- border-radius: 50%;
- display: inline-block;
- margin-right: 0.5em;
- width: 12px;
- height: 12px;
- content: "";
+ &__info {
+ display: contents;
+ }
+
+ .ProseMirror &.poll {
+ grid-template-areas: "poll" "info" "buttons";
+
+ @include viewport.from(sm) {
+ // sized to its content, so a setting is not split across lines
+ grid-template-columns: 1fr max-content;
+ grid-template-areas: "poll info" "buttons buttons";
}
+ }
- &[data-poll-type="multiple"],
- &[data-poll-type="ranked_choice"] {
- display: flex;
- align-items: center;
+ @include viewport.from(sm) {
+ .ProseMirror &.poll &__info .poll-info {
+ max-width: 18em;
}
}
- &[data-poll-type="multiple"] {
- li::before {
- border-radius: 3px;
+ // the cooked column has a fixed width, so its lines share it by percentage;
+ // here the column follows the text, which then needs its natural width
+ .ProseMirror
+ &.poll
+ &__info
+ .poll-info_instructions
+ li:not(:first-child:last-child) {
+ .d-icon,
+ span {
+ width: auto;
}
}
- &[data-poll-type="ranked_choice"] {
- li {
- position: relative;
+ &.poll:not([data-poll-type="number"]) &__content > ul > li {
+ cursor: text;
+ }
- &::before {
- mask-image: svg-uri(
- '<svg width="0.75em" height="0.75em" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512">\3c !--!Font Awesome Free 6.6.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z"/></svg>'
- );
- z-index: 1;
- width: 0.75em;
- margin-right: 0.75em;
- left: 0.2em;
- background: var(--primary-high);
- border-radius: var(--d-button-border-radius);
- border: none;
- }
+ // a lone instruction is centred by the cooked styles, which lets the icon
+ // fall onto a line of its own here: centre the pair instead
+ @include viewport.from(sm) {
+ &.poll &__info .poll-info_instructions li:first-child:last-child {
+ display: flex;
+ justify-content: center;
+ }
+ }
- &::after {
- content: "";
- position: absolute;
- height: 1.125em;
- width: 1.125em;
- background: var(--primary-low);
- border-radius: var(--d-button-border-radius);
- }
+ &.--untitled &__content > .poll-title::before {
+ content: var(--poll-title-placeholder, "");
+ color: var(--primary-medium);
+ position: absolute;
+ pointer-events: none;
+ }
+
+ // the parsed info node is replaced by the one rendered below it
+ &.poll &__content > .poll-info {
+ display: none;
+ }
+
+ &[data-poll-type="multiple"] &__content > ul > li::before {
+ border-radius: 0.15em;
+ }
+
+ &[data-poll-type="ranked_choice"] &__content > ul {
+ counter-reset: poll-option;
+
+ > li::before {
+ counter-increment: poll-option;
+ content: counter(poll-option);
+ top: 0.5em;
+ width: 1em;
+ height: auto;
+ border: none;
+ border-radius: 0;
+ color: var(--primary-medium);
}
}
}
diff --git a/plugins/poll/config/locales/client.en.yml b/plugins/poll/config/locales/client.en.yml
index 9f382f545ce..68759fdfd4c 100644
--- a/plugins/poll/config/locales/client.en.yml
+++ b/plugins/poll/config/locales/client.en.yml
@@ -152,6 +152,7 @@ en:
error_while_exporting_results: "Sorry, there was an error exporting poll results."
ui_builder:
+ edit: Edit poll
title: Build poll
insert: Insert Poll
help:
@@ -189,6 +190,7 @@ en:
label: Allow options to be added or removed after posting
poll_title:
label: Title (optional)
+ placeholder: Poll title
poll_options:
label: Options (one per line)
add: Add option
diff --git a/plugins/poll/test/javascripts/acceptance/poll-builder-enabled-test.js b/plugins/poll/test/javascripts/acceptance/poll-builder-enabled-test.js
index 5a4559eb90f..2098989b351 100644
--- a/plugins/poll/test/javascripts/acceptance/poll-builder-enabled-test.js
+++ b/plugins/poll/test/javascripts/acceptance/poll-builder-enabled-test.js
@@ -1,8 +1,18 @@
-import { click } from "@ember/test-helpers";
+import {
+ click,
+ fillIn,
+ findAll,
+ settled,
+ triggerKeyEvent,
+ visit,
+ waitFor,
+} from "@ember/test-helpers";
import { test } from "qunit";
+import { resetRichEditorExtensions } from "discourse/lib/composer/rich-editor-extensions";
import { AUTO_GROUPS } from "discourse/lib/constants";
import {
acceptance,
+ metaModifier,
updateCurrentUser,
} from "discourse/tests/helpers/qunit-helpers";
import { i18n } from "discourse-i18n";
@@ -10,11 +20,287 @@ import { displayPollBuilderButton } from "discourse/plugins/poll/helpers/display
acceptance("Poll Builder - polls are enabled", function (needs) {
needs.user();
+ needs.hooks.beforeEach(() => resetRichEditorExtensions());
+ needs.hooks.afterEach(() => resetRichEditorExtensions());
needs.settings({
+ default_composer_category: 1,
poll_enabled: true,
poll_create_allowed_groups: AUTO_GROUPS.trust_level_1,
});
+ test("edits an existing rich editor poll's settings in place", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn(
+ ".d-editor-input",
+ "Before\n\n[poll]\n* First\n* Second\n[/poll]\n\nBetween\n\n[poll name=second type=multiple min=1 max=2 public=false chartType=pie results=on_vote dynamic=true status=closed order=asc]\n# **Question**\n* **Yes**\n* [No](https://example.com)\n[/poll]\n\nAfter"
+ );
+ await click(".composer-toggle-switch");
+ await waitFor(".ProseMirror");
+ await settled();
+ await click(findAll(".composer-poll-node__edit")[1]);
+
+ assert
+ .dom(".poll-ui-builder .d-modal__title")
+ .hasText("Edit poll", "opens the editing builder");
+ assert
+ .dom(".poll-type-value-multiple")
+ .hasClass("active", "restores the poll type");
+ assert
+ .dom(".poll-options")
+ .doesNotExist("options stay in the document, not in the builder");
+
+ await click(".poll-type-value-regular");
+ await click(".insert-poll");
+
+ const poll = '.ProseMirror .poll[data-poll-name="second"]';
+ assert
+ .dom(".ProseMirror .poll")
+ .exists({ count: 2 }, "replaces rather than appends a poll");
+ assert
+ .dom(poll)
+ .hasAttribute("data-poll-type", "regular", "applies the edited setting");
+ assert
+ .dom(`${poll} .poll-title`)
+ .hasText("Question", "leaves the title untouched");
+ assert
+ .dom(`${poll} .multiple-help-text`)
+ .doesNotExist("and the summary follows the edited setting");
+ assert
+ .dom(`${poll} .composer-poll-node__content li`)
+ .exists({ count: 2 }, "leaves the options untouched");
+ assert
+ .dom(poll)
+ .hasAttribute(
+ "data-poll-status",
+ "closed",
+ "does not reopen a closed poll"
+ );
+ assert
+ .dom(poll)
+ .hasAttribute(
+ "data-poll-results",
+ "on_vote",
+ "preserves results visibility"
+ );
+ assert
+ .dom(poll)
+ .hasAttribute("data-poll-public", "false", "preserves voter privacy");
+ assert
+ .dom(poll)
+ .hasAttribute("data-poll-dynamic", "true", "preserves dynamic voting");
+
+ await triggerKeyEvent(".ProseMirror", "keydown", "Z", metaModifier);
+ assert
+ .dom(poll)
+ .hasAttribute(
+ "data-poll-type",
+ "multiple",
+ "undo restores the original poll"
+ );
+ await triggerKeyEvent(".ProseMirror", "keydown", "Z", {
+ ...metaModifier,
+ shiftKey: true,
+ });
+ assert
+ .dom(poll)
+ .hasAttribute("data-poll-type", "regular", "redo reapplies the edit");
+
+ await click(".composer-toggle-switch");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "Before\n\n[poll]\n* First\n* Second\n\n[/poll]\n\nBetween\n\n[poll type=regular results=on_vote public=false name=second chartType=pie dynamic=true status=closed order=asc]\n# **Question**\n\n* **Yes**\n* [No](https://example.com)\n\n[/poll]\n\nAfter",
+ "preserves the other poll, the content and the surrounding text"
+ );
+ });
+
+ test("cancelling poll edits leaves the document unchanged", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn(".d-editor-input", "[poll]\n* First\n* Second\n[/poll]");
+ await click(".composer-toggle-switch");
+ await waitFor(".ProseMirror");
+ await settled();
+ await click(".composer-poll-node__edit");
+ await click(".poll-type-value-multiple");
+ await click(".poll-ui-builder .d-modal__footer .btn-flat");
+
+ assert
+ .dom(".ProseMirror .poll")
+ .doesNotHaveAttribute(
+ "data-poll-type",
+ "cancel does not apply the change"
+ );
+ await click(".composer-poll-node__edit");
+ await click(".insert-poll");
+ assert
+ .dom(".ProseMirror .poll")
+ .doesNotHaveAttribute(
+ "data-poll-name",
+ "saving preserves the unnamed poll's identity"
+ );
+ });
+
+ test("editing leaves structured poll content alone", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn(
+ ".d-editor-input",
+ "[poll close=2050-01-01]\n## Question\n* First paragraph\n\n Second paragraph\n* Simple\n[/poll]"
+ );
+ await click(".composer-toggle-switch");
+ await waitFor(".ProseMirror");
+ await settled();
+
+ assert
+ .dom(".composer-poll-node__content li:first-child p")
+ .exists({ count: 2 }, "loads both paragraphs in the first option");
+
+ await click(".composer-poll-node__edit");
+ await click(".insert-poll");
+
+ assert
+ .dom(".ProseMirror .poll .poll-title")
+ .hasText("Question", "preserves the poll title");
+ assert
+ .dom(".composer-poll-node__content li:first-child p")
+ .exists({ count: 2 }, "keeps both paragraphs attached to the option");
+ assert
+ .dom(".ProseMirror .poll")
+ .hasAttribute(
+ "data-poll-close",
+ "2050-01-01",
+ "preserves the original date-only close value"
+ );
+ });
+
+ test("a newly inserted rich editor poll can be edited", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await click(".composer-toggle-switch");
+ await waitFor(".ProseMirror");
+ await click(".toolbar-menu__options-trigger");
+ await click(`button[title='${i18n("poll.ui_builder.title")}']`);
+ await fillIn(".poll-option-value input", "First");
+ await click(".poll-option-add");
+ await fillIn(".poll-option-value:nth-of-type(2) input", "Second");
+ await click(".insert-poll");
+ await click(".composer-poll-node__edit");
+
+ assert
+ .dom(".poll-type-value-regular")
+ .hasClass("active", "loads the newly inserted poll");
+ await click(".poll-type-value-multiple");
+ await click(".insert-poll");
+
+ assert
+ .dom(".ProseMirror .poll")
+ .exists({ count: 1 }, "keeps a single poll");
+ assert
+ .dom(".ProseMirror .poll")
+ .hasAttribute("data-poll-type", "multiple", "applies the edited setting");
+ assert
+ .dom(".ProseMirror .composer-poll-node__content li")
+ .exists({ count: 2 }, "keeps the options it was inserted with");
+ });
+
+ test("edits a numeric poll's range and step", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn(
+ ".d-editor-input",
+ "[poll type=number min=0 max=10 step=2]\n[/poll]"
+ );
+ await click(".composer-toggle-switch");
+ await waitFor(".ProseMirror");
+ await settled();
+ assert
+ .dom(".composer-poll-node")
+ .hasClass("--untitled", "offers an empty title slot");
+ assert
+ .dom(".composer-poll-node__content")
+ .doesNotHaveAttribute(
+ "contenteditable",
+ "whose title is editable like any other content"
+ );
+ assert
+ .dom(".composer-poll-node__content > ul")
+ .hasAttribute(
+ "contenteditable",
+ "false",
+ "while its generated options are not"
+ );
+
+ await click(".composer-poll-node__edit");
+
+ assert.dom(".poll-options-min").hasValue("0", "restores the lower bound");
+ assert.dom(".poll-options-max").hasValue("10", "restores the upper bound");
+ assert.dom(".poll-options-step").hasValue("2", "restores the step");
+ await fillIn(".poll-options-max", "8");
+ await fillIn(".poll-options-step", "4");
+ await click(".insert-poll");
+
+ assert
+ .dom(".ProseMirror .composer-poll-node__content li")
+ .exists({ count: 3 }, "regenerates the numeric options");
+ assert
+ .dom(".ProseMirror .composer-poll-node__content li:last-child")
+ .hasText("8", "keeps the edited maximum");
+ await click(".composer-toggle-switch");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "[poll type=number max=8 min=0 step=4]\n[/poll]\n\n",
+ "serializes the numeric range without list items"
+ );
+ });
+
+ test("switching a poll to and from a numeric range", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn(".d-editor-input", "[poll]\n* First\n* Second\n[/poll]");
+ await click(".composer-toggle-switch");
+ await waitFor(".ProseMirror");
+ await settled();
+
+ await click(".composer-poll-node__edit");
+ await click(".poll-type-value-number");
+ await fillIn(".poll-options-min", "1");
+ await fillIn(".poll-options-max", "3");
+ await fillIn(".poll-options-step", "1");
+ await click(".insert-poll");
+
+ assert
+ .dom(".ProseMirror .composer-poll-node__content li")
+ .exists({ count: 3 }, "replaces the authored options with the range");
+ assert
+ .dom(".composer-poll-node__content > ul")
+ .hasAttribute(
+ "contenteditable",
+ "false",
+ "and stops them being typed in"
+ );
+
+ await click(".composer-poll-node__edit");
+ await click(".poll-type-value-regular");
+ await click(".insert-poll");
+
+ assert
+ .dom(".ProseMirror .poll")
+ .hasAttribute("data-poll-type", "regular", "switches back");
+ assert
+ .dom(".composer-poll-node__content > ul")
+ .doesNotHaveAttribute("contenteditable", "leaving them editable again");
+ await click(".composer-toggle-switch");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "[poll type=regular]\n* 1\n* 2\n* 3\n\n[/poll]\n\n",
+ "keeps the generated options as authored ones"
+ );
+ });
+
test("regular user - sufficient trust level", async function (assert) {
updateCurrentUser({
moderator: false,
diff --git a/plugins/poll/test/javascripts/component/poll-ui-builder-test.gjs b/plugins/poll/test/javascripts/component/poll-ui-builder-test.gjs
index 16bb182f6cf..1ad32eb886b 100644
--- a/plugins/poll/test/javascripts/component/poll-ui-builder-test.gjs
+++ b/plugins/poll/test/javascripts/component/poll-ui-builder-test.gjs
@@ -4,11 +4,13 @@ import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import selectKit from "discourse/tests/helpers/select-kit-helper";
import PollUiBuilder from "discourse/plugins/poll/discourse/components/modal/poll-ui-builder";
-async function setupBuilder() {
+async function setupBuilder(poll) {
const noop = () => {};
const results = [];
const model = {
toolbarEvent: { getText: () => "", addText: (t) => results.push(t) },
+ poll,
+ onSave: poll ? (attrs) => results.push(attrs) : undefined,
};
await render(
@@ -23,6 +25,174 @@ async function setupBuilder() {
module("Component | PollUiBuilder", function (hooks) {
setupRenderingTest(hooks);
+ test("editing keeps the settings the builder does not show", async function (assert) {
+ const results = await setupBuilder({
+ name: "existing",
+ type: "regular",
+ optionCount: 2,
+ public: "false",
+ groups: "custom_group",
+ close: "2050-01-01",
+ status: "closed",
+ order: "desc",
+ });
+
+ assert
+ .dom(".poll-options")
+ .doesNotExist("options are edited in the document, not in the builder");
+ assert.dom(".poll-title").doesNotExist("neither is the title");
+ assert
+ .dom(".advanced-mode-btn")
+ .doesNotExist(
+ "every remaining setting is shown, so there is no advanced mode"
+ );
+ assert.dom(".poll-date").exists("the close date is one of them");
+ await click(".insert-poll");
+
+ assert.deepEqual(
+ results[0],
+ {
+ name: "existing",
+ type: "regular",
+ results: null,
+ min: null,
+ max: null,
+ step: null,
+ public: "false",
+ chartType: null,
+ dynamic: null,
+ groups: "custom_group",
+ close: "2050-01-01",
+ status: "closed",
+ order: "desc",
+ },
+ "keeps what it carried and adds no default it lacked"
+ );
+ });
+
+ test("editing writes no attribute that matches its default", async function (assert) {
+ const results = await setupBuilder({ optionCount: 2 });
+
+ await click(".insert-poll");
+
+ assert.deepEqual(
+ results[0],
+ {
+ name: null,
+ type: null,
+ results: null,
+ min: null,
+ max: null,
+ step: null,
+ public: null,
+ chartType: null,
+ dynamic: null,
+ groups: null,
+ close: null,
+ status: null,
+ order: null,
+ },
+ "saving an untouched poll leaves its markdown alone"
+ );
+ });
+
+ test("editing leaves a range the poll did not carry to the options", async function (assert) {
+ const results = await setupBuilder({ type: "multiple", optionCount: 2 });
+
+ await click(".insert-poll");
+
+ assert.strictEqual(
+ results[0].min,
+ null,
+ "writes no minimum, so one option stays enough"
+ );
+ assert.strictEqual(
+ results[0].max,
+ null,
+ "and no maximum, so a later option is still selectable"
+ );
+ });
+
+ test("editing keeps a range the poll spelled out", async function (assert) {
+ const results = await setupBuilder({
+ type: "multiple",
+ optionCount: 3,
+ min: "1",
+ max: "2",
+ });
+
+ await click(".insert-poll");
+
+ assert.strictEqual(results[0].min, "1", "keeps the minimum it carried");
+ assert.strictEqual(results[0].max, "2", "and the maximum");
+ });
+
+ test("editing a number poll leaves its implied range out", async function (assert) {
+ const results = await setupBuilder({ type: "number" });
+
+ await click(".insert-poll");
+
+ assert.strictEqual(results[0].min, null, "writes no minimum");
+ assert.strictEqual(
+ results[0].max,
+ null,
+ "and no maximum, so the range still follows the setting"
+ );
+ assert.strictEqual(results[0].step, null, "nor a step of one");
+ });
+
+ test("editing keeps a number poll's own step", async function (assert) {
+ const results = await setupBuilder({ type: "number", step: "5" });
+
+ await click(".insert-poll");
+
+ assert.strictEqual(results[0].step, "5", "keeps the step it carried");
+ });
+
+ test("a range field cannot be dropped by emptying it", async function (assert) {
+ await setupBuilder({ type: "number", min: "1", max: "5", step: "1" });
+
+ assert.dom(".insert-poll").isEnabled("the poll starts out saveable");
+
+ await fillIn(".poll-options-max", "");
+ assert
+ .dom(".insert-poll")
+ .isDisabled("an empty maximum is refused, not read as having none");
+
+ await fillIn(".poll-options-max", "5");
+ await fillIn(".poll-options-min", "");
+ assert
+ .dom(".insert-poll")
+ .isDisabled("and an empty minimum is not read as zero");
+ });
+
+ test("editing a poll with more options than the site allows", async function (assert) {
+ const results = await setupBuilder({ type: "regular", optionCount: 25 });
+
+ assert
+ .dom(".insert-poll")
+ .isEnabled("the option count belongs to the document, not the builder");
+ await click(".insert-poll");
+
+ assert.strictEqual(results.length, 1, "so the settings still save");
+ });
+
+ test("editing a ranked choice poll leaves range attributes out", async function (assert) {
+ const results = await setupBuilder({
+ type: "ranked_choice",
+ optionCount: 2,
+ min: "3",
+ });
+
+ assert
+ .dom(".insert-poll")
+ .isNotDisabled("a stale range does not block saving a type without one");
+ await click(".insert-poll");
+
+ assert.strictEqual(results[0].min, null, "drops the stale minimum");
+ assert.strictEqual(results[0].max, null, "and writes no maximum");
+ });
+
test("Can switch poll type", async function (assert) {
await setupBuilder();
@@ -74,6 +244,11 @@ module("Component | PollUiBuilder", function (hooks) {
.dom(".insert-poll")
.isDisabled("Insert button disabled when no options specified");
+ await fillIn(".poll-option-value input", " ");
+ assert
+ .dom(".insert-poll")
+ .isDisabled("Insert button disabled for a whitespace-only option");
+
await fillIn(".poll-option-value input", "a");
assert
.dom(".insert-poll")
diff --git a/plugins/poll/test/javascripts/component/rich-editor-extension-test.js b/plugins/poll/test/javascripts/component/rich-editor-extension-test.js
index 70417680d20..810a2305d3c 100644
--- a/plugins/poll/test/javascripts/component/rich-editor-extension-test.js
+++ b/plugins/poll/test/javascripts/component/rich-editor-extension-test.js
@@ -4,7 +4,7 @@ import {
resetRichEditorExtensions,
} from "discourse/lib/composer/rich-editor-extensions";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import { testMarkdown } from "discourse/tests/helpers/rich-editor-helper";
+import { setupRichEditor } from "discourse/tests/helpers/rich-editor-helper";
import { ALLOWED_ATTRIBUTES } from "discourse/plugins/poll/lib/discourse-markdown/poll";
import richEditorExtension from "discourse/plugins/poll/lib/rich-editor-extension";
@@ -17,56 +17,258 @@ module(
await resetRichEditorExtensions();
registerRichEditorExtension(richEditorExtension);
});
-
- const voters =
- '<div class="poll-info" contenteditable="false">0 voters</div>';
+ hooks.afterEach(() => resetRichEditorExtensions());
Object.entries({
"regular poll": [
"[poll]\n* Option 1\n* Option 2\n[/poll]\n\n",
- `<div class="poll"><ul data-tight="true"><li><p>Option 1</p></li><li><p>Option 2</p></li></ul>${voters}</div>`,
+ {},
"[poll]\n* Option 1\n* Option 2\n\n[/poll]\n\n",
],
"multiple choice poll": [
"[poll type=multiple min=1 max=2]\n* Option 1\n* Option 2\n* Option 3\n[/poll]",
- `<div class="poll" data-poll-type="multiple" data-poll-max="2" data-poll-min="1"><ul data-tight="true"><li><p>Option 1</p></li><li><p>Option 2</p></li><li><p>Option 3</p></li></ul>${voters}</div>`,
+ { type: "multiple", max: "2", min: "1" },
"[poll type=multiple max=2 min=1]\n* Option 1\n* Option 2\n* Option 3\n\n[/poll]\n\n",
],
"public poll": [
"[poll public=true]\n* Option 1\n* Option 2\n[/poll]",
- `<div class="poll" data-poll-public="true"><ul data-tight="true"><li><p>Option 1</p></li><li><p>Option 2</p></li></ul>${voters}</div>`,
+ { public: "true" },
"[poll public=true]\n* Option 1\n* Option 2\n\n[/poll]\n\n",
],
"poll with name, results, close date, groups": [
"[poll name=PollName chartType=pie results=always anonymous=true close=2021-01-01 groups=group1,group2]\n* Option 1\n* Option 2\n[/poll]",
- `<div class="poll" data-poll-results="always" data-poll-name="PollName" data-poll-charttype="pie" data-poll-close="2021-01-01" data-poll-groups="group1,group2"><ul data-tight="true"><li><p>Option 1</p></li><li><p>Option 2</p></li></ul>${voters}</div>`,
+ {
+ results: "always",
+ name: "PollName",
+ charttype: "pie",
+ close: "2021-01-01",
+ groups: "group1,group2",
+ },
"[poll results=always name=PollName chartType=pie close=2021-01-01 groups=group1,group2]\n* Option 1\n* Option 2\n\n[/poll]\n\n",
],
"poll with bar chart type": [
"[poll chartType=bar]\n* Option 1\n* Option 2\n[/poll]",
- `<div class="poll" data-poll-charttype="bar"><ul data-tight="true"><li><p>Option 1</p></li><li><p>Option 2</p></li></ul>${voters}</div>`,
+ { charttype: "bar" },
"[poll chartType=bar]\n* Option 1\n* Option 2\n\n[/poll]\n\n",
],
- "closed poll with a set option order": [
- "[poll status=closed order=asc]\n* Option 1\n* Option 2\n[/poll]",
- `<div class="poll" data-poll-status="closed" data-poll-order="asc"><ul data-tight="true"><li><p>Option 1</p></li><li><p>Option 2</p></li></ul>${voters}</div>`,
- "[poll status=closed order=asc]\n* Option 1\n* Option 2\n\n[/poll]\n\n",
- ],
- "number poll": [
- "[poll type=number min=0 max=4 step=2]\n[/poll]",
- `<div class="poll" data-poll-type="number" data-poll-max="4" data-poll-min="0" data-poll-step="2"><ul data-tight="true"><li><p>0</p></li><li><p>2</p></li><li><p>4</p></li></ul>${voters}</div>`,
- "[poll type=number max=4 min=0 step=2]\n[/poll]\n\n",
- ],
- "number poll with a title": [
- "[poll type=number min=1 max=2]\n# How many?\n[/poll]",
- `<div class="poll" data-poll-type="number" data-poll-max="2" data-poll-min="1"><h1>How many?</h1><ul data-tight="true"><li><p>1</p></li><li><p>2</p></li></ul>${voters}</div>`,
- "[poll type=number max=2 min=1]\n# How many?\n\n[/poll]\n\n",
- ],
- }).forEach(([name, [markdown, html, expectedMarkdown]]) => {
+ }).forEach(([name, [markdown, attrs, expectedMarkdown]]) => {
test(name, async function (assert) {
- await testMarkdown(assert, markdown, html, expectedMarkdown);
+ const [editor] = await setupRichEditor(assert, markdown);
+
+ assert
+ .dom(".composer-poll-node__content li")
+ .exists(
+ { count: attrs.type === "multiple" ? 3 : 2 },
+ "renders the options"
+ );
+ assert
+ .dom(".composer-poll-node__content li:first-child")
+ .hasText("Option 1", "renders option text");
+ assert
+ .dom(".composer-poll-node__info .poll-info_counts")
+ .hasText("0 voters", "renders the voter count");
+ assert
+ .dom(".composer-poll-node__edit")
+ .hasText("Edit poll", "offers poll editing");
+ for (const [attr, value] of Object.entries(attrs)) {
+ assert
+ .dom(".poll")
+ .hasAttribute(`data-poll-${attr}`, value, `preserves ${attr}`);
+ }
+ assert.strictEqual(
+ editor.value,
+ expectedMarkdown,
+ "serializes the poll without its edit control"
+ );
});
});
+
+ test("numeric polls preserve their range without serializing generated options", async function (assert) {
+ const markdown = "[poll type=number max=10 min=0 step=2]\n[/poll]\n\n";
+ const [editor] = await setupRichEditor(assert, markdown, {
+ multiToggle: true,
+ });
+
+ assert
+ .dom(".composer-poll-node__content li")
+ .exists({ count: 6 }, "generates all six numeric options");
+ assert
+ .dom(".composer-poll-node__content li:first-child")
+ .hasText("0", "includes zero as the lower bound");
+ assert
+ .dom(".composer-poll-node__content li:last-child")
+ .hasText("10", "includes the upper bound");
+ assert.strictEqual(
+ editor.value,
+ markdown,
+ "preserves the range and step across editor toggles"
+ );
+ });
+
+ test("numeric polls keep an authored title", async function (assert) {
+ const markdown =
+ "[poll type=number max=2 min=1]\n# How many?\n\n[/poll]\n\n";
+ const [editor] = await setupRichEditor(assert, markdown);
+
+ assert
+ .dom(".composer-poll-node__content .poll-title")
+ .hasText("How many?", "renders the title");
+ assert
+ .dom(".composer-poll-node__content li")
+ .exists({ count: 2 }, "generates the options");
+ assert.strictEqual(
+ editor.value,
+ markdown,
+ "keeps the title and drops the generated options"
+ );
+ });
+
+ test("the poll summary shows settings and a zero voter count", async function (assert) {
+ await setupRichEditor(
+ assert,
+ "[poll type=multiple min=1 max=2 results=on_vote close=2050-01-01 dynamic=true]\n* Option 1\n* Option 2\n\n[/poll]\n\n"
+ );
+
+ assert
+ .dom(".composer-poll-node__info .poll-info_counts")
+ .hasText("0 voters", "shows zero voters");
+ assert
+ .dom(".composer-poll-node__info .multiple-help-text")
+ .exists("shows the selection limit");
+ assert
+ .dom(".composer-poll-node__info .is-dynamic")
+ .exists("shows that options can change after posting");
+ assert
+ .dom(".composer-poll-node__info li[title]")
+ .exists("shows the close date");
+ assert
+ .dom(".composer-poll-node__info .poll-info_instructions li")
+ .exists(
+ { count: 3 },
+ "shows the dynamic-options, selection-limit, and close-date instructions"
+ );
+ assert
+ .dom(".poll")
+ .hasAttribute(
+ "data-poll-results",
+ "on_vote",
+ "preserves the results visibility attribute"
+ );
+ assert
+ .dom(".composer-poll-node__info .poll-info_counts-count")
+ .exists({ count: 1 }, "renders only the voter-count element");
+ });
+
+ test("a multiple choice poll without bounds still phrases its hint", async function (assert) {
+ await setupRichEditor(
+ assert,
+ "[poll type=multiple]\n* Option 1\n* Option 2\n\n[/poll]\n\n"
+ );
+
+ assert
+ .dom(".composer-poll-node__info .multiple-help-text")
+ .hasAnyText("no line is left as a bare icon");
+ });
+
+ test("a poll that has already closed does not say it will close", async function (assert) {
+ await setupRichEditor(
+ assert,
+ "[poll close=2021-01-01]\n* Option 1\n* Option 2\n\n[/poll]\n\n"
+ );
+
+ assert
+ .dom(".composer-poll-node__info .d-icon-lock")
+ .exists("shows the close date as past");
+ assert
+ .dom(".composer-poll-node__info .d-icon-far-clock")
+ .doesNotExist("rather than as a countdown");
+ });
+
+ test("a closed multiple choice poll claims no totals", async function (assert) {
+ await setupRichEditor(
+ assert,
+ "[poll type=multiple min=1 max=2 status=closed]\n* Option 1\n* Option 2\n\n[/poll]\n\n"
+ );
+
+ assert
+ .dom(".composer-poll-node__info .poll-info_counts-count")
+ .exists({ count: 1 }, "no total votes block");
+ });
+
+ test("a line break in a title survives as markup", async function (assert) {
+ const [editor] = await setupRichEditor(
+ assert,
+ "[poll]\n# First<br>Second\n* Option 1\n[/poll]"
+ );
+
+ assert
+ .dom(".composer-poll-node__content .poll-title br")
+ .exists("keeps the break in the document");
+ assert.strictEqual(
+ editor.value,
+ "[poll]\n# First<br>Second\n\n* Option 1\n\n[/poll]\n\n",
+ "and writes it as markup, which would otherwise end the title"
+ );
+ });
+
+ test("a title's line break does not leak into the rest of the document", async function (assert) {
+ const [editor] = await setupRichEditor(
+ assert,
+ "[poll]\n# A<br>B\n* Option 1\n[/poll]\n\nOne\nTwo"
+ );
+
+ assert.strictEqual(
+ editor.value,
+ "[poll]\n# A<br>B\n\n* Option 1\n\n[/poll]\n\nOne\nTwo",
+ "a break outside the title is still written as a newline"
+ );
+ });
+
+ test("a title keeps markdown that would start a block", async function (assert) {
+ const [editor] = await setupRichEditor(
+ assert,
+ "[poll]\n# - pick one\n* Option 1\n[/poll]"
+ );
+
+ assert
+ .dom(".composer-poll-node__content .poll-title")
+ .hasText("- pick one", "renders the title as written");
+ assert.strictEqual(
+ editor.value,
+ "[poll]\n# - pick one\n\n* Option 1\n\n[/poll]\n\n",
+ "and does not escape it on the way back"
+ );
+ });
+
+ test("an untitled poll carries an empty title to type into", async function (assert) {
+ const markdown = "[poll]\n* Option 1\n* Option 2\n\n[/poll]\n\n";
+ const [editor] = await setupRichEditor(assert, markdown);
+
+ assert
+ .dom(".composer-poll-node__content > .poll-title")
+ .exists("the title node is always present")
+ .hasText("", "and is empty when the poll has no title");
+ assert.strictEqual(
+ editor.value,
+ markdown,
+ "an empty title is left out of the markdown"
+ );
+ });
+
+ test("closed polls preserve status and option order", async function (assert) {
+ const markdown =
+ "[poll status=closed order=asc]\n* Option 1\n* Option 2\n\n[/poll]\n\n";
+ const [editor] = await setupRichEditor(assert, markdown);
+
+ assert
+ .dom(".poll")
+ .hasAttribute("data-poll-status", "closed", "keeps the poll closed");
+ assert.strictEqual(
+ editor.value,
+ markdown,
+ "preserves attributes not editable in the builder"
+ );
+ });
}
);
diff --git a/plugins/poll/test/javascripts/unit/lib/poll-bounds-test.js b/plugins/poll/test/javascripts/unit/lib/poll-bounds-test.js
new file mode 100644
index 00000000000..49a8bd2b5e9
--- /dev/null
+++ b/plugins/poll/test/javascripts/unit/lib/poll-bounds-test.js
@@ -0,0 +1,26 @@
+import { module, test } from "qunit";
+import pollBounds from "discourse/plugins/poll/lib/poll-bounds";
+
+module("Unit | Lib | poll-bounds", function () {
+ test("reads what the markup carries, and fills in what it does not", function (assert) {
+ const cases = [
+ [{}, 2, { min: 1, max: 2 }],
+ [{ min: "1", max: "2" }, 3, { min: 1, max: 2 }],
+ [{ min: "0" }, 2, { min: 0, max: 2 }],
+ [{ min: "-1" }, 2, { min: 1, max: 2 }],
+ [{ min: "abc", max: "abc" }, 2, { min: 1, max: 2 }],
+ [{ max: "9" }, 2, { min: 1, max: 2 }],
+ [{ max: "0" }, 2, { min: 1, max: 0 }],
+ [{ min: "2", max: "2" }, 5, { min: 2, max: 2 }],
+ [{ min: "1", max: "2" }, 0, { min: 1, max: 0 }],
+ ];
+
+ for (const [poll, optionCount, expected] of cases) {
+ assert.deepEqual(
+ pollBounds(poll, optionCount),
+ expected,
+ `${JSON.stringify(poll)} over ${optionCount} options`
+ );
+ }
+ });
+});