Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
feat(polls): add single answer polls (#17993)
moataz hjaijid9a7e2cf192c
diff --git a/config.js b/config.jsindex 019a3f37a5..2b8724f204 100644--- a/config.js+++ b/config.js@@ -145,6 +145,13 @@ var config = {// Disables polls feature.// disablePolls: false,+ // Shows/hides the "Allow only one answer" option when creating a poll. The option is sent with+ // lib-jitsi-meet's createPoll and enforced by the mod_polls_component prosody module, thus enable this+ // only when both support it. With visitors, enable it only once the main and all visitor prosodies run a+ // mod_polls_component with single answer support: an old visitor node shows checkboxes and keeps multi-answer+ // votes locally.+ // showPollSingleAnswerSetting: false,+// Disables chat feature entirely including notifications, sounds, and private messages.// disableChat: false,diff --git a/lang/main.json b/lang/main.jsonindex 4cfb6576e6..d4b7e71567 100644--- a/lang/main.json+++ b/lang/main.json@@ -1078,6 +1078,7 @@"answer": {"edit": "Edit","send": "Send",+ "singleAnswerHint": "Choose one answer","skip": "Skip","submit": "Submit"},@@ -1095,7 +1096,8 @@"pollQuestion": "Poll Question","questionPlaceholder": "Ask a question","removeOption": "Remove option",- "save": "Save"+ "save": "Save",+ "singleAnswer": "Allow only one answer"},"errors": {"notUniqueOption": "Options must be unique"diff --git a/react/features/base/config/configType.ts b/react/features/base/config/configType.tsindex 10d64b234c..53d4adde35 100644--- a/react/features/base/config/configType.ts+++ b/react/features/base/config/configType.ts@@ -715,6 +715,7 @@ export interface IConfig {sharedVideoAllowedURLDomains?: Array<string>;showBreakoutRoomJoinPermissionsModeratorSetting?: boolean;showChatPermissionsModeratorSetting?: boolean;+ showPollSingleAnswerSetting?: boolean;showSharedVideoPermissionsModeratorSetting?: boolean;sipInviteUrl?: string;speakerStats?: {diff --git a/react/features/base/ui/components/web/Checkbox.tsx b/react/features/base/ui/components/web/Checkbox.tsxindex 96b5327354..c4d35eb50e 100644--- a/react/features/base/ui/components/web/Checkbox.tsx+++ b/react/features/base/ui/components/web/Checkbox.tsx@@ -41,6 +41,12 @@ interface ICheckboxProps {* Change callback.*/onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;++ /**+ * The type of the input. A radio input looks the same, with a round box, and lets the user choose only one+ * of the inputs that share its name.+ */+ type?: 'checkbox' | 'radio';}const useStyles = makeStyles()(theme => {@@ -71,7 +77,7 @@ const useStyles = makeStyles()(theme => {position: 'relative',cursor: 'pointer',- '& input[type="checkbox"]': {+ '& input[type="checkbox"], & input[type="radio"]': {appearance: 'none',backgroundColor: 'transparent',margin: '3px',@@ -117,6 +123,10 @@ const useStyles = makeStyles()(theme => {}},+ '& input[type="radio"], & input[type="radio"]::before': {+ borderRadius: '50%'+ },+'& .checkmark': {position: 'absolute',left: '3px',@@ -129,7 +139,7 @@ const useStyles = makeStyles()(theme => {width: '40px',height: '40px',- '& input[type="checkbox"]': {+ '& input[type="checkbox"], & input[type="radio"]': {width: '24px',height: '24px',@@ -155,7 +165,8 @@ const Checkbox = ({id,label,name,- onChange+ onChange,+ type = 'checkbox'}: ICheckboxProps) => {const { classes: styles, cx, theme } = useStyles();const isMobile = isMobileBrowser();@@ -169,7 +180,7 @@ const Checkbox = ({id = { id }name = { name }onChange = { onChange }- type = 'checkbox' />+ type = { type } /><Iconaria-hidden = { true }className = 'checkmark'diff --git a/react/features/polls/components/AbstractPollAnswer.tsx b/react/features/polls/components/AbstractPollAnswer.tsxindex 33429c0fef..70ecb1aec1 100644--- a/react/features/polls/components/AbstractPollAnswer.tsx+++ b/react/features/polls/components/AbstractPollAnswer.tsx@@ -51,7 +51,7 @@ const AbstractPollAnswer = (Component: ComponentType<AbstractProps>) => (props:const poll: IPollData = useSelector(getPoll(pollId));- const { answers, lastVote, question, senderId } = poll;+ const { answers, lastVote, question, senderId, singleAnswer } = poll;const [ checkBoxStates, setCheckBoxState ] = useState(() => {if (lastVote !== null) {@@ -64,12 +64,15 @@ const AbstractPollAnswer = (Component: ComponentType<AbstractProps>) => (props:const participantName = useBoundSelector(getParticipantDisplayName, senderId);const setCheckbox = useCallback((index, state) => {- const newCheckBoxStates = [ ...checkBoxStates ];+ // Choosing an answer of a single answer poll clears the other answers.+ const newCheckBoxStates = singleAnswer && state+ ? new Array(checkBoxStates.length).fill(false)+ : [ ...checkBoxStates ];newCheckBoxStates[index] = state;setCheckBoxState(newCheckBoxStates);sendAnalytics(createPollEvent('vote.checked'));- }, [ checkBoxStates ]);+ }, [ checkBoxStates, singleAnswer ]);const dispatch = useDispatch();@@ -80,18 +83,18 @@ const AbstractPollAnswer = (Component: ComponentType<AbstractProps>) => (props:dispatch(registerVote(pollId, checkBoxStates));return false;- }, [ pollId, checkBoxStates, conference ]);+ }, [ conference, dispatch, pollId, checkBoxStates ]);const sendPoll = useCallback(() => {- conference?.getPolls().createPoll(pollId, question, answers);+ conference?.getPolls().createPoll(pollId, question, answers, { singleAnswer });dispatch(removePoll(poll));- }, [ conference, question, answers ]);+ }, [ conference, dispatch, poll, pollId, question, answers, singleAnswer ]);const skipAnswer = useCallback(() => {dispatch(registerVote(pollId, null));sendAnalytics(createPollEvent('vote.skipped'));- }, [ pollId ]);+ }, [ dispatch, pollId ]);const skipChangeVote = useCallback(() => {dispatch(setVoteChanging(pollId, false));diff --git a/react/features/polls/components/AbstractPollCreate.tsx b/react/features/polls/components/AbstractPollCreate.tsxindex 041dfbb421..439d89581c 100644--- a/react/features/polls/components/AbstractPollCreate.tsx+++ b/react/features/polls/components/AbstractPollCreate.tsx@@ -34,6 +34,9 @@ export type AbstractProps = InputProps & {removeAnswer: (index: number) => void;setAnswer: (index: number, value: IAnswerData) => void;setQuestion: (question: string) => void;+ setSingleAnswer: (singleAnswer: boolean) => void;+ showSingleAnswer: boolean;+ singleAnswer: boolean;t: Function;};@@ -86,6 +89,11 @@ const AbstractPollCreate = (Component: ComponentType<AbstractProps>) => (props:const [ answers, setAnswers ] = useState(answerResults);+ const [ singleAnswer, setSingleAnswer ] = useState(Boolean(editingPoll?.[1].singleAnswer));++ const showSingleAnswer = useSelector(+ (state: IReduxState) => Boolean(state['features/base/config'].showPollSingleAnswerSetting));+const setAnswer = useCallback((i: number, answer: IAnswerData) => {setAnswers(currentAnswers => {const newAnswers = [ ...currentAnswers ];@@ -144,6 +152,7 @@ const AbstractPollCreate = (Component: ComponentType<AbstractProps>) => (props:lastVote: null,question,answers: filteredAnswers,+ singleAnswer,saved: true,editing: false,pollId: editingPoll ? editingPoll[0] : pollId@@ -153,7 +162,7 @@ const AbstractPollCreate = (Component: ComponentType<AbstractProps>) => (props:setCreateMode(false);- }, [ conference, question, answers ]);+ }, [ conference, question, answers, singleAnswer ]);// Check if the poll create form can be submitted i.e. if the send button should be disabled.const isSubmitDisabled@@ -175,6 +184,9 @@ const AbstractPollCreate = (Component: ComponentType<AbstractProps>) => (props:setAnswer = { setAnswer }setCreateMode = { setCreateMode }setQuestion = { setQuestion }+ setSingleAnswer = { setSingleAnswer }+ showSingleAnswer = { showSingleAnswer }+ singleAnswer = { singleAnswer }t = { t } />);};diff --git a/react/features/polls/components/native/PollAnswer.tsx b/react/features/polls/components/native/PollAnswer.tsxindex 77fb413ac1..4cfd3f4769 100644--- a/react/features/polls/components/native/PollAnswer.tsx+++ b/react/features/polls/components/native/PollAnswer.tsx@@ -41,6 +41,11 @@ const PollAnswer = (props: AbstractProps) => {t('polls.by', { name: creatorName })}</Text>+ {+ poll.singleAnswer && <Text style = { dialogStyles.questionOwnerText as TextStyle }>+ { t('polls.answer.singleAnswerHint') }+ </Text>+ }</View>{pollSaved && <IconButtondiff --git a/react/features/polls/components/native/PollCreate.tsx b/react/features/polls/components/native/PollCreate.tsxindex 11b1ccdc4e..a2a3cd6cb0 100644--- a/react/features/polls/components/native/PollCreate.tsx+++ b/react/features/polls/components/native/PollCreate.tsx@@ -1,5 +1,5 @@import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { FlatList, Platform, SafeAreaView, TextInput, View, ViewStyle } from 'react-native';+import { FlatList, Platform, SafeAreaView, Text, TextInput, TextStyle, View, ViewStyle } from 'react-native';import { Divider } from 'react-native-paper';import { useDispatch } from 'react-redux';@@ -7,6 +7,7 @@ import { useKeyboardVisible } from '../../../base/modal/hooks.native';import BaseTheme from '../../../base/ui/components/BaseTheme.native';import Button from '../../../base/ui/components/native/Button';import Input from '../../../base/ui/components/native/Input';+import Switch from '../../../base/ui/components/native/Switch';import { BUTTON_TYPES } from '../../../base/ui/constants.native';import { editPoll } from '../../actions';import { ANSWERS_LIMIT, CHAR_LIMIT } from '../../constants';@@ -27,6 +28,9 @@ const PollCreate = (props: AbstractProps) => {setAnswer,setCreateMode,setQuestion,+ setSingleAnswer,+ showSingleAnswer,+ singleAnswer,t} = props;@@ -176,6 +180,15 @@ const PollCreate = (props: AbstractProps) => {pollsStyles.pollCreateButtonsContainer,keyboardVisible && { marginBottom: BaseTheme.spacing[8] }] as ViewStyle[] }>+ { showSingleAnswer && <View style = { pollsStyles.switchRow as ViewStyle }>+ <Switch+ checked = { singleAnswer }+ id = 'polls-single-answer'+ onChange = { state => setSingleAnswer(Boolean(state)) } />+ <Text style = { pollsStyles.switchLabel as TextStyle }>+ { t('polls.create.singleAnswer') }+ </Text>+ </View> }<ButtonaccessibilityLabel = 'polls.create.addOption'disabled = { answers.length >= ANSWERS_LIMIT }diff --git a/react/features/polls/components/web/PollAnswer.tsx b/react/features/polls/components/web/PollAnswer.tsxindex 094203ca71..05de904ac2 100644--- a/react/features/polls/components/web/PollAnswer.tsx+++ b/react/features/polls/components/web/PollAnswer.tsx@@ -95,6 +95,11 @@ const PollAnswer = ({<div className = { classes.creator }>{ t('polls.by', { name: creatorName }) }</div>+ {+ poll.singleAnswer && <div className = { classes.creator }>+ { t('polls.answer.singleAnswerHint') }+ </div>+ }</div><ul className = { classes.answerList }>{@@ -108,7 +113,9 @@ const PollAnswer = ({id = { `poll-answer-checkbox-${poll.pollId}-${index}` }key = { index }label = { answer.name }- onChange = { ev => setCheckbox(index, ev.target.checked) } />+ name = { `poll-answer-${poll.pollId}` }+ onChange = { ev => setCheckbox(index, ev.target.checked) }+ type = { poll.singleAnswer ? 'radio' : 'checkbox' } /></li>))}diff --git a/react/features/polls/components/web/PollCreate.tsx b/react/features/polls/components/web/PollCreate.tsxindex df0babc8dc..b1f6ab228a 100644--- a/react/features/polls/components/web/PollCreate.tsx+++ b/react/features/polls/components/web/PollCreate.tsx@@ -3,6 +3,7 @@ import { useDispatch } from 'react-redux';import { makeStyles } from 'tss-react/mui';import Button from '../../../base/ui/components/web/Button';+import Checkbox from '../../../base/ui/components/web/Checkbox';import Input from '../../../base/ui/components/web/Input';import { BUTTON_TYPES } from '../../../base/ui/constants.web';import { editPoll } from '../../actions';@@ -44,6 +45,9 @@ const useStyles = makeStyles()(theme => {border: 0,background: 'transparent'},+ singleAnswer: {+ marginBottom: '24px'+ },addButtonContainer: {display: 'flex'},@@ -74,6 +78,9 @@ const PollCreate = ({setAnswer,setCreateMode,setQuestion,+ setSingleAnswer,+ showSingleAnswer,+ singleAnswer,t}: AbstractProps) => {const { classes } = useStyles();@@ -243,6 +250,14 @@ const PollCreate = ({})}</ol>+ { showSingleAnswer && <div className = { classes.singleAnswer }>+ <Checkbox+ checked = { singleAnswer }+ id = 'polls-single-answer'+ label = { t('polls.create.singleAnswer') }+ name = 'polls-single-answer'+ onChange = { ev => setSingleAnswer(ev.target.checked) } />+ </div> }<div className = { classes.addButtonContainer }><ButtonaccessibilityLabel = { t('polls.create.addOption') }diff --git a/react/features/polls/middleware.ts b/react/features/polls/middleware.tsindex 2c95c1c878..d48068ee65 100644--- a/react/features/polls/middleware.ts+++ b/react/features/polls/middleware.ts@@ -102,7 +102,7 @@ function _handleReceivedPollsData(data: any, dispatch: IStore['dispatch'], getStreturn;}- const { pollId, answers, senderId, question, history } = data;+ const { pollId, answers, senderId, question, history, singleAnswer } = data;const poll = {changingVote: false,senderId,@@ -110,6 +110,7 @@ function _handleReceivedPollsData(data: any, dispatch: IStore['dispatch'], getStlastVote: null,question,answers: _sanitizeAnswers(answers),+ singleAnswer: singleAnswer === true,saved: false,editing: false,pollIddiff --git a/react/features/polls/types.ts b/react/features/polls/types.tsindex 27f9040623..c7602e61b0 100644--- a/react/features/polls/types.ts+++ b/react/features/polls/types.ts@@ -53,6 +53,11 @@ export interface IPoll {* ID of the sender of this poll.*/senderId: string | undefined;++ /**+ * Whether a voter can choose only one answer.+ */+ singleAnswer?: boolean;}/**diff --git a/resources/prosody-plugins/mod_polls_component.lua b/resources/prosody-plugins/mod_polls_component.luaindex 27494ddb6a..609a069919 100644--- a/resources/prosody-plugins/mod_polls_component.lua+++ b/resources/prosody-plugins/mod_polls_component.lua@@ -53,6 +53,10 @@ local function validate_polls(data)return false;end+ if data.singleAnswer ~= nil and type(data.singleAnswer) ~= 'boolean' then+ return false;+ end+for _, answer in ipairs(data.answers) doif type(answer) ~= "table" or type(answer.name) ~= "string" thenreturn false;@@ -235,7 +239,9 @@ endsenderId = poll_creator.occupant_id,senderName = poll_creator.occupant_name,question = data.question,- answers = answers+ answers = answers,+ -- a voter can choose only one answer of such a poll+ singleAnswer = data.singleAnswer == true or nil};room.polls.by_id[data.pollId] = poll@@ -250,7 +256,8 @@ endsenderId = poll_creator.occupant_id,senderName = poll_creator.occupant_name,question = data.question,- answers = compact_answers+ answers = compact_answers,+ singleAnswer = poll.singleAnswer}}@@ -258,6 +265,7 @@ end-- Only relay the sanitized answers (name only) so no unexpected-- fields from the sender's payload are forwarded to participants.data.answers = answers;+ data.singleAnswer = poll.singleAnswer;data.senderId = poll_creator.occupant_id;data.type = 'polls';local json_msg_str, error = json.encode(data);@@ -280,6 +288,32 @@ endreturn true;end+ if poll.singleAnswer then+ -- Keep only the first chosen answer instead of dropping the vote. The voter's+ -- client has already registered the vote and gets no error reply, so storing and+ -- broadcasting this one keeps every client, the voter's included, consistent with+ -- the server, also clients that do not know about singleAnswer.+ local kept = false;+ local dropped = false;+ local single = {};+ for idx, vote_flag in ipairs(data.answers) do+ if vote_flag and not kept then+ single[idx] = true;+ kept = true;+ else+ if vote_flag then+ dropped = true;+ end+ single[idx] = false;+ end+ end+ if dropped then+ module:log('debug', 'More than one answer for single answer poll %s, keeping the first. Sender: %s',+ data.pollId, stanza.attr.from);+ end+ data.answers = single;+ end+local voter = occupant_details;-- Capture the voter's current vote state so we can detect changes.@@ -468,7 +502,8 @@ local setup_muc_component = function(host_module, host)senderId = poll.senderId,senderName = poll.senderName,question = poll.question,- answers = poll.answers+ answers = poll.answers,+ singleAnswer = poll.singleAnswer};end@@ -542,6 +577,7 @@ local setup_muc_component = function(host_module, host)command = 'new-poll',pollId = new_poll.pollId,question = new_poll.question,+ singleAnswer = new_poll.singleAnswer,senderId = new_poll.senderId,roomJid = internal_room_jid_match_rewrite(room.jid),type = 'polls'diff --git a/resources/prosody-plugins/mod_visitors.lua b/resources/prosody-plugins/mod_visitors.luaindex e2d9888aed..b3d67283ac 100644--- a/resources/prosody-plugins/mod_visitors.lua+++ b/resources/prosody-plugins/mod_visitors.lua@@ -111,7 +111,8 @@ local function send_visitors_iq(conference_service, room, type)senderId = poll.senderId,senderName = poll.senderName,question = poll.question,- answers = poll.answers+ answers = poll.answers,+ singleAnswer = poll.singleAnswer};enddiff --git a/tests/prosody/mod_polls_component_spec.js b/tests/prosody/mod_polls_component_spec.jsindex e697b71c9f..07425a2926 100644--- a/tests/prosody/mod_polls_component_spec.js+++ b/tests/prosody/mod_polls_component_spec.js@@ -472,4 +472,152 @@ describe('mod_polls_component', () => {await assertNoPollBroadcast(nonOccupant);});});++ // ── Single answer polls ─────────────────────────────────────────────────++ describe('single answer polls', () => {++ /**+ * Creates a poll by sending a raw new-poll message, so that options can be set.+ *+ * @param {object} client+ * @param {string} pollId+ * @param {object} [extra] Extra fields of the new-poll message.+ */+ function createPollWith(client, pollId, extra = {}) {+ client.sendPollsMessage(POLLS_COMPONENT, JSON.stringify({+ answers: [ { name: 'A' }, { name: 'B' }, { name: 'C' } ],+ command: 'new-poll',+ pollId,+ question: 'Pick one',+ type: 'polls',+ ...extra+ }));+ }++ /**+ * Joins a creator and a voter and creates a poll that both received.+ *+ * @param {object} [extra] Extra fields of the new-poll message.+ */+ async function setup(extra) {+ const r = nextRoom();++ await focusJoin(r);+ const creator = await joinParticipant(r);+ const voter = await joinParticipant(r);+ const pollId = nextPollId();++ createPollWith(creator, pollId, extra);++ const [ poll ] = await Promise.all([+ waitForPollCommand(voter, 'new-poll'),+ waitForPollCommand(creator, 'new-poll')+ ]);++ return { creator,+ poll,+ pollId,+ r,+ voter };+ }++ it('broadcasts singleAnswer with the new poll', async () => {+ const { poll } = await setup({ singleAnswer: true });++ assert.strictEqual(poll.singleAnswer, true);+ });++ it('a poll without singleAnswer is broadcast without it', async () => {+ const { poll } = await setup();++ assert.ok(!('singleAnswer' in poll), 'singleAnswer must not be added to a regular poll');+ });++ it('accepts one answer for a single answer poll', async () => {+ const { pollId, voter } = await setup({ singleAnswer: true });++ voter.answerPoll(POLLS_COMPONENT, pollId, [ false, true, false ]);++ const answer = await waitForPollCommand(voter, 'answer-poll');++ assert.deepEqual(answer.answers, [ false, true, false ]);+ });++ it('keeps only the first of several answers for a single answer poll', async () => {+ const { creator, pollId, voter } = await setup({ singleAnswer: true });++ voter.answerPoll(POLLS_COMPONENT, pollId, [ false, true, true ]);++ const [ voterCopy, creatorCopy ] = await Promise.all([+ waitForPollCommand(voter, 'answer-poll'),+ waitForPollCommand(creator, 'answer-poll')+ ]);++ assert.deepEqual(voterCopy.answers, [ false, true, false ],+ 'the voter must get back the vote the server kept');+ assert.deepEqual(creatorCopy.answers, [ false, true, false ]);+ });++ it('stores only the first of several answers for a single answer poll', async () => {+ // Only the voter joins first, the test rooms are limited to two participants.+ const r = nextRoom();++ await focusJoin(r);+ const voter = await joinParticipant(r);+ const pollId = nextPollId();++ createPollWith(voter, pollId, { singleAnswer: true });+ await waitForPollCommand(voter, 'new-poll');++ voter.answerPoll(POLLS_COMPONENT, pollId, [ true, false, true ]);+ await waitForPollCommand(voter, 'answer-poll');++ const late = await joinParticipant(r);+ const history = await waitForPollCommand(late, 'old-polls');+ const stored = history.polls.find(p => p.pollId === pollId);++ assert.deepEqual(stored.answers.map(a => a.voters?.length ?? 0), [ 1, 0, 0 ],+ 'only the first chosen answer must be counted');+ });++ it('still accepts several answers for a regular poll', async () => {+ const { pollId, voter } = await setup();++ voter.answerPoll(POLLS_COMPONENT, pollId, [ true, true, false ]);++ const answer = await waitForPollCommand(voter, 'answer-poll');++ assert.deepEqual(answer.answers, [ true, true, false ]);+ });++ it('a late joiner receives singleAnswer via old-polls', async () => {+ // Only the creator joins first, the test rooms are limited to two participants.+ const r = nextRoom();++ await focusJoin(r);+ const creator = await joinParticipant(r);+ const pollId = nextPollId();++ createPollWith(creator, pollId, { singleAnswer: true });+ await waitForPollCommand(creator, 'new-poll');++ const late = await joinParticipant(r);+ const history = await waitForPollCommand(late, 'old-polls');+ const stored = history.polls.find(p => p.pollId === pollId);++ assert.strictEqual(stored?.singleAnswer, true);+ });++ it('a new poll with a non-boolean singleAnswer is rejected', async () => {+ const r = nextRoom();++ await focusJoin(r);+ const creator = await joinParticipant(r);++ createPollWith(creator, nextPollId(), { singleAnswer: 'yes' });++ await assertNoPollBroadcast(creator);+ });+ });});