Preview error fix.

The preview matrix question was not being updated when questions was
being updated.
This commit is contained in:
SaiSawant1
2024-10-03 20:10:10 +05:30
parent d208e99f06
commit 14cfb6fdf8
3 changed files with 36 additions and 6 deletions

View File

@@ -236,7 +236,7 @@ export const MatrixQuestionForm = ({
<span>Add column</span>
</Button>
</div>
<div className="flex flex-1 items-center justify-end gap-2">
<div className="mt-3 flex flex-1 items-center justify-end gap-2">
<Select
defaultValue={question.shuffleOption}
value={question.shuffleOption}

View File

@@ -5,7 +5,7 @@ import { QuestionMedia } from "@/components/general/QuestionMedia";
import { Subheader } from "@/components/general/Subheader";
import { ScrollableContainer } from "@/components/wrappers/ScrollableContainer";
import { getUpdatedTtc, useTtc } from "@/lib/ttc";
import { getShuffledRows } from "@/lib/utils";
import { getRandomRowIdx } from "@/lib/utils";
import { JSX } from "preact";
import { useCallback, useMemo, useState } from "preact/hooks";
import { getLocalizedValue } from "@formbricks/lib/i18n/utils";
@@ -43,11 +43,26 @@ export const MatrixQuestion = ({
const isMediaAvailable = question.imageUrl || question.videoUrl;
useTtc(question.id, ttc, setTtc, startTime, setStartTime, question.id === currentQuestionId);
const questionRows = useMemo(() => {
const rowShuffleIdx = useMemo(() => {
if (question.shuffleOption) {
return getShuffledRows(question.rows, question.shuffleOption);
} else return question.rows;
}, [question.shuffleOption, question.rows]);
return getRandomRowIdx(question.rows.length, question.shuffleOption);
} else {
return question.rows.map((_, id) => id);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [question.shuffleOption, question.rows.length]);
const questionRows = useMemo(() => {
if (!question.rows) {
return [];
}
if (question.shuffleOption === "none" || question.shuffleOption === undefined) {
return question.rows;
}
return rowShuffleIdx.map((shuffledIdx) => {
return question.rows[shuffledIdx];
});
}, [question.shuffleOption, question.rows, rowShuffleIdx]);
const handleSelect = useCallback(
(column: string, row: string) => {

View File

@@ -18,6 +18,21 @@ const shuffle = (array: any[]) => {
[array[i], array[j]] = [array[j], array[i]];
}
};
export function getRandomRowIdx(n: number, shuffleOption: TShuffleOption): number[] {
// Create an array with numbers from 0 to n-1
let array = Array.from(Array(n).keys());
if (shuffleOption === "all") {
shuffle(array);
} else if (shuffleOption === "exceptLast") {
const lastElement = array.pop();
if (lastElement) {
shuffle(array);
array.push(lastElement);
}
}
return array;
}
export const getShuffledRows = (rows: TI18nString[], shuffleOption: TShuffleOption): TI18nString[] => {
const rowsCopy = [...rows];