{"version":3,"file":"poll.js","names":["define","_exports","_component","_helper","_modifier","_object","_service","_string","_template","_truthHelpers","_dModal","_concatClass","_ajax","_ajaxError","_decorators","_loadScript","_discourseI18n","_comboBox","_pollBreakdownChart","_pollBreakdownOption","_templateFactory","Object","defineProperty","value","default","PollBreakdownModal","static","dt7948","g","this","prototype","service","dialog","i","siteSettings","model","charts","groupedBy","highlightedOption","displayMode","init","set","groupableUserFields","id","then","fetchGroupedPollData","super","arguments","title","pollTitle","topicTitle","htmlSafe","n","poll_groupable_user_fields","split","filter","Boolean","map","field","transformed","length","classify","label","join","totalVotes","options","reduce","sum","option","votes","ajax","data","post_id","post","poll_name","poll","name","user_field_name","catch","error","popupAjaxError","alert","i18n","result","isDestroying","isDestroyed","grouped_results","setGrouping","action","onSelectPanel","panel","setComponentTemplate","createTemplateFactory","block","moduleName","scope","eq","on","fn","get","isStrictMode","_computed","_object2","_dButton","_dToggleSwitch","_dateTimeInput","_inputTip","_radioButton","_dIcon","_autoFocus","_groupChooser","REGULAR_POLL_TYPE","RANKED_CHOICE_POLL_TYPE","PIE_CHART_TYPE","NUMBER_POLL_TYPE","MULTIPLE_POLL_TYPE","BAR_CHART_TYPE","ALWAYS_POLL_RESULT","PollUiBuilderModal","showAdvanced","pollType","pollOptions","create","pollOptionsText","pollMin","pollMax","pollStep","pollGroups","pollAutoClose","pollResult","chartType","publicPoll","poll_default_public","or","showNumber","showRankedChoice","gt","canRemoveOption","rankedChoiceOrRegular","rankedChoiceOrNumber","pollResults","staff","push","isRegular","isNumber","isMultiple","isRankedChoice","pollOptionsCount","siteGroups","groups","isPie","_setPollMinMax","poll_maximum_options","observes","pollOutput","pollHeader","output","match","toolbarEvent","getText","step","toISOString","trim","forEach","minNumOfOptionsValidation","failed","reason","count","ok","showMinNumOfOptionsValidation","minMaxValueValidation","parseInt","optionsCount","disableInsert","_comboboxOptions","startIndex","endIndex","Array","keys","number","onOptionsTextChange","e","target","insertPoll","addText","closeModal","toggleAdvanced","toggleProperty","x","updateValue","event","onInputKeydown","index","key","preventDefault","stopPropagation","addOption","atIndex","insertAt","removeOption","removeObject","updatePollType","togglePublic","Input","Textarea","and","not","_runloop","_component2","_chartColors","_pollUiBuilder","PollBreakdownChart","c","group","setHighlightedOption","mapBy","_optionToSlice","_previousHighlightedSliceIndex","_previousDisplayMode","willDestroy","_chart","destroy","didInsertElement","canvas","element","querySelector","window","Chart","getContext","chartConfig","didReceiveAttrs","_updateDisplayMode","_updateHighlight","colorStyle","optionColors","transformedData","counter","colors","getColors","color","type","plugins","ChartDataLabels","datasets","backgroundColor","hoverBorderColor","tooltip","datalabels","borderRadius","font","family","getComputedStyle","document","body","fontFamily","size","padding","top","right","bottom","left","formatter","toNumber","precision","responsive","aspectRatio","animation","duration","onHover","activeElements","next","sliceIndex","optionIndex","find","Number","config","update","undefined","datasetIndex","setActiveElements","classNames","_computed2","PollBreakdownOption","onMouseOver","onMouseOut","propertyEqual","highlighted","equal","showPercentage","percent","total","colorBackgroundStyle","colorPreviewStyle","helpers","getHoverColor","tagName","_dropdownMenu","_dMenu","buttonOptionsMap","exportResults","className","icon","showBreakdown","openPoll","closePoll","showTally","PollButtonsDropdownComponent","currentUser","constructor","getDropdownButtonState","dropDownClick","dropDownAction","args","getDropdownContent","contents","isAdmin","admin","dataExplorerEnabled","data_explorer_enabled","exportQueryID","poll_export_ranked_choice_data_explorer_query_id","poll_export_data_explorer_query_id","closed","voters","isStaff","isMe","topicArchived","isAutomaticallyClosed","availableDisplayMode","showDropdown","showDropdownAsButton","_formatter","STAFF_ONLY","PollInfoComponent","multipleHelpText","min","max","votersLabel","showTotalVotes","showResults","o","totalVotesLabel","automaticCloseAgeLabel","age","automaticCloseClosesInLabel","timeLeft","showMultipleHelpText","closeTitle","closeDate","moment","utc","close","isValid","format","relativeAge","toDate","addAgo","to","resultsOnVote","results","hasVoted","postUserId","resultsOnVoteTitle","resultsOnClose","resultsOnCloseTitle","resultsStaffOnly","resultsStaffOnlyTitle","publicTitle","isPublic","publicTitleLabel","showInstructionsSection","PollOptionsDropdownComponent","onRegisterApi","api","dMenu","selectRank","rank","sendRank","rankLabel","_routeAction","_pollOptionRankedChoiceDropdown","PollOptionsComponent","_pollOptionRankedChoice","isChosen","includes","sendClick","sendOptionSelect","rankedChoiceDropdownContent","priority","toString","_didInsert","_emberModifier","PollResultsPieComponent","htmlLegendPlugin","afterUpdate","chart","ul","getElementById","containerID","innerHTML","legend","labels","generateLabels","item","li","createElement","classList","add","onclick","toggleDataVisibility","boxSpan","style","background","fillStyle","textContainer","fontColor","text","getDataVisibility","opacity","appendChild","stripHtml","html","DOMParser","parseFromString","textContent","pieChartConfig","_this","opts","strippedLabels","l","display","htmlLegend","legendContainerId","registerLegendElement","modifier","legendElement","registerCanvasElement","canvasElement","canvasId","legendId","drawPie","el","PollResultsRankedChoiceComponent","rankedChoiceWinnerText","rankedChoiceOutcome","round_activity","winner","winning_candidate","rankedChoiceTiedText","_evenRound","_pollVoters","PollResultsStandardComponent","orderOptions","sort","a","b","getPercentages","ordered","votersCount","fill","roundPercentages","percentages","Math","floor","enrichOptions","rounded","idx","per","chosen","vote","percentage","loading","orderedOptions","roundedPercentages","concat","_tracking","_pollResultsRankedChoice","_pollResultsStandard","TabsComponent","tracked","activeTab","tabOne","tabTwo","tabs","selectTab","tab","_boundAvatarTemplate","PollVotersComponent","groupVotersByRank","voter","rankedChoiceVoters","groupedByRank","_conditionalLoadingSpinner","_pollVotersRankedChoice","showMore","_didUpdate","_round","_pollBreakdown","_pollButtonsDropdown","_pollInfo","_pollOptions","_pollResultsPie","_pollResultsTabs","RANKED_CHOICE","ON_CLOSE","CLOSED_STATUS","PollComponent","router","appEvents","modal","polls_votes","defaultPreloadedVoters","preloadedVoters","voterListExpanded","hasSavedVote","staffOnly","checkUserGroups","user","toLowerCase","userGroups","some","areRanksValid","arr","ranks","Set","hasNonZeroDuplicate","allZeros","obj","has","_toggleOption","chosenIdx","indexOf","splice","candidate","findIndex","object","digest","public","preloaded_voters","titleHTML","user_id","status","castVotes","canCastVotes","assign","trigger","enrichedOptions","ranked_choice_outcome","isNaN","numOptions","hideResultsDisabled","toggleOption","removeVote","toggleResults","selectedOptionCount","notInVotingGroup","showCastVotesButton","castVotesButtonClass","castVotesButtonIcon","castVotesDisabled","showHideResultsButton","showShowResultsButton","showRemoveVoteButton","isCheckbox","resultsWidgetTypeClass","chart_type","resultsPie","averageRating","totalScore","average","updatedVoters","fetchVoters","optionId","option_id","page","limit","newVoters","votersSet","username","otherOptionId","finally","_ref","toggleStatus","yesNoConfirm","message","didConfirm","refresh","show","queryID","params","JSON","stringify","explain","download","csvContent","downloadLink","blob","Blob","href","URL","createObjectURL","setAttribute","click","remove","toggleDisplayMode","_pluginApi","_richEditorExtension","initializePollUIBuilder","addComposerToolbarPopupMenuOption","container","lookup","condition","composer","getCurrentUser","poll_enabled","topic","pm_with_non_human_user","can_create_poll","registerRichEditorExtension","initialize","withPluginApi","_trackedBuiltIns","_poll","_templateOnly","attachPolls","elem","helper","pollNodes","querySelectorAll","node","parentNode","getModel","polls","pollsObject","pollNode","pollName","dataset","pollPost","quotedId","closest","postId","quoted","TrackedObject","p","outerHTML","newPollNode","replaceWith","renderGlimmer","initializePolls","modifyClass","Superclass","subscribe","messageBus","_onPollMessage","unsubscribe","msg","findLoadedPost","bind","_polls","_refreshPollsObject","rawPoll","decorateCookedElement","onlyStream","addSearchSuggestion","palette","gradient","currentGradientValue","previousGradientIndex","gradientKeys","colorIndex","baseGradientKeyIndex","y","differenceMultiplier","k","round","setup","allowList","registerOptions","features","pollMaximumOptions","registerPlugin","md","bbcode","ruler","rule","DATA_PREFIX","DEFAULT_POLL","ALLOWED_ATTRIBUTES","tag","before","state","attrs","tokens","t","poll_attrs","after","openToken","openTokenIndex","pollTokens","slice","titleTokens","discourse","Token","token","content","String","addNumberListItems","endsWith","listItemCloseIndex","j","hash","md5","addPollContainer","addPollInfo","md5cycle","d","ff","gg","hh","ii","add32","cmn","q","s","md5blk","md5blks","charCodeAt","hex_chr","rhex","hex","unescape","encodeURI","substring","tail","md51","sumsUpTo100","decimals","sumOfDecimals","ceil","greatest","extension","nodeSpec","draggable","selectable","isolating","defining","parseDOM","getAttrs","dom","getAttribute","toDOM","class","poll_info","contentEditable","parse","poll_container","ignore","poll_title","poll_info_counts","poll_info_counts_count","poll_info_number","poll_info_label_open","poll_info_label_close","serializeNode","entries","write","renderContent"],"sources":["discourse/plugins/poll/discourse/components/modal/poll-breakdown.js","discourse/plugins/poll/discourse/components/modal/poll-ui-builder.js","discourse/plugins/poll/discourse/components/poll-breakdown-chart.js","discourse/plugins/poll/discourse/components/poll-breakdown-option.js","discourse/plugins/poll/discourse/components/poll-buttons-dropdown.js","discourse/plugins/poll/discourse/components/poll-info.js","discourse/plugins/poll/discourse/components/poll-option-ranked-choice-dropdown.js","discourse/plugins/poll/discourse/components/poll-option-ranked-choice.js","discourse/plugins/poll/discourse/components/poll-options.js","discourse/plugins/poll/discourse/components/poll-results-pie.js","discourse/plugins/poll/discourse/components/poll-results-ranked-choice.js","discourse/plugins/poll/discourse/components/poll-results-standard.js","discourse/plugins/poll/discourse/components/poll-results-tabs.js","discourse/plugins/poll/discourse/components/poll-voters-ranked-choice.js","discourse/plugins/poll/discourse/components/poll-voters.js","discourse/plugins/poll/discourse/components/poll.js","discourse/plugins/poll/discourse/initializers/add-poll-ui-builder.js","discourse/plugins/poll/discourse/initializers/extend-for-poll.js","discourse/plugins/poll/lib/chart-colors.js","discourse/plugins/poll/lib/discourse-markdown/poll.js","discourse/plugins/poll/lib/even-round.js","discourse/plugins/poll/lib/rich-editor-extension.js"],"sourcesContent":["define(\"discourse/plugins/poll/discourse/components/modal/poll-breakdown\", [\"exports\", \"@ember/component\", \"@ember/helper\", \"@ember/modifier\", \"@ember/object\", \"@ember/service\", \"@ember/string\", \"@ember/template\", \"truth-helpers\", \"discourse/components/d-modal\", \"discourse/helpers/concat-class\", \"discourse/lib/ajax\", \"discourse/lib/ajax-error\", \"discourse/lib/decorators\", \"discourse/lib/load-script\", \"discourse-i18n\", \"select-kit/components/combo-box\", \"discourse/plugins/poll/discourse/components/poll-breakdown-chart\", \"discourse/plugins/poll/discourse/components/poll-breakdown-option\", \"@ember/template-factory\"], function (_exports, _component, _helper, _modifier, _object, _service, _string, _template, _truthHelpers, _dModal, _concatClass, _ajax, _ajaxError, _decorators, _loadScript, _discourseI18n, _comboBox, _pollBreakdownChart, _pollBreakdownOption, _templateFactory) {\n \"use strict\";\n\n Object.defineProperty(_exports, \"__esModule\", {\n value: true\n });\n _exports.default = void 0;\n class PollBreakdownModal extends _component.default {\n static #_ = (() => dt7948.g(this.prototype, \"dialog\", [_service.service]))();\n #dialog = (() => (dt7948.i(this, \"dialog\"), void 0))();\n static #_2 = (() => dt7948.g(this.prototype, \"siteSettings\", [_service.service]))();\n #siteSettings = (() => (dt7948.i(this, \"siteSettings\"), void 0))();\n model = null;\n charts = null;\n groupedBy = null;\n highlightedOption = null;\n displayMode = \"percentage\";\n init() {\n this.set(\"groupedBy\", this.groupableUserFields[0]?.id);\n (0, _loadScript.default)(\"/javascripts/Chart.min.js\").then(() => (0, _loadScript.default)(\"/javascripts/chartjs-plugin-datalabels.min.js\")).then(() => {\n this.fetchGroupedPollData();\n });\n super.init(...arguments);\n }\n title(pollTitle, topicTitle) {\n return pollTitle ? (0, _template.htmlSafe)(pollTitle) : topicTitle;\n }\n static #_3 = (() => dt7948.n(this.prototype, \"title\", [(0, _decorators.default)(\"model.poll.title\", \"model.post.topic.title\")]))();\n get groupableUserFields() {\n return this.siteSettings.poll_groupable_user_fields.split(\"|\").filter(Boolean).map(field => {\n const transformed = field.split(\"_\").filter(Boolean);\n if (transformed.length > 1) {\n transformed[0] = (0, _string.classify)(transformed[0]);\n }\n return {\n id: field,\n label: transformed.join(\" \")\n };\n });\n }\n totalVotes(options) {\n return options.reduce((sum, option) => sum + option.votes, 0);\n }\n static #_4 = (() => dt7948.n(this.prototype, \"totalVotes\", [(0, _decorators.default)(\"model.poll.options\")]))();\n fetchGroupedPollData() {\n return (0, _ajax.ajax)(\"/polls/grouped_poll_results.json\", {\n data: {\n post_id: this.model.post.id,\n poll_name: this.model.poll.name,\n user_field_name: this.groupedBy\n }\n }).catch(error => {\n if (error) {\n (0, _ajaxError.popupAjaxError)(error);\n } else {\n this.dialog.alert((0, _discourseI18n.i18n)(\"poll.error_while_fetching_voters\"));\n }\n }).then(result => {\n if (this.isDestroying || this.isDestroyed) {\n return;\n }\n this.set(\"charts\", result.grouped_results);\n });\n }\n setGrouping(value) {\n this.set(\"groupedBy\", value);\n this.fetchGroupedPollData();\n }\n static #_5 = (() => dt7948.n(this.prototype, \"setGrouping\", [_object.action]))();\n onSelectPanel(panel) {\n this.set(\"displayMode\", panel.id);\n }\n static #_6 = (() => dt7948.n(this.prototype, \"onSelectPanel\", [_object.action]))();\n static #_7 = (() => (0, _component.setComponentTemplate)((0, _templateFactory.createTemplateFactory)(\n /*\n \n {{! template-lint-disable no-invalid-interactive }}\n \n
\n \n <:body>\n \n \n \n
\n \n {{#if this.showAdvanced}}\n
| {{i18n \"poll.ranked_choice.round\"}} | \n{{i18n \"poll.ranked_choice.majority\"}} | \n{{i18n \"poll.ranked_choice.eliminated\"}} | \n
|---|---|---|
| {{round.round}} | \n{{htmlSafe round.majority.html}} | \n{{i18n \"poll.ranked_choice.none\"}} | \n
| {{round.round}} | \n{{i18n \"poll.ranked_choice.none\"}} | \n\n {{#each round.eliminated as |eliminated|}}\n {{htmlSafe eliminated.html}}\n {{/each}}\n | \n
\n {{#unless @isRankedChoice}}\n {{#if @showTally}}\n {{i18n\n \"poll.votes\"\n count=option.votes\n }}\n {{else}}\n {{i18n\n \"number.percent\"\n count=option.percentage\n }}\n {{/if}}\n {{/unless}}\n {{htmlSafe option.html}}\n
\n {{#unless @isRankedChoice}}\n \n {{/unless}}\n {{#if @isPublic}}\n