Skip to content

Commit

Permalink
Refactor: Remove unused code related to H5P content retrieval
Browse files Browse the repository at this point in the history
The code changes remove the unused code related to fetching H5P quiz content in the QuestionForm component. The useGetH5PQuizContentByIdQuery hook and its related dependencies have been removed.

The changes also refactor the QuestionList component by introducing a new handleH5PBulkQuestion function to handle adding multiple H5P questions at once. This function is called when selecting H5P content from the H5PContentListModal component.

Additionally, the H5PContentListModal component has been updated to display a checkbox for each H5P content item. The selected H5P content items are stored in the selectedContents state and can be added to the lesson description using the onAddContent callback.

These changes improve the codebase by removing unused code and enhancing the functionality related to H5P content selection and addition.
  • Loading branch information
b-l-i-n-d committed Sep 30, 2024
1 parent b01f6a7 commit 9e76013
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {
type QuizForm,
type QuizQuestionType,
calculateQuizDataStatus,
useGetH5PQuizContentByIdQuery,
} from '@CourseBuilderServices/quiz';
import { styleUtils } from '@Utils/style-utils';

Expand All @@ -42,11 +41,6 @@ const QuestionForm = () => {
const questions = form.watch('questions') || [];
const dataStatus = form.watch(`questions.${activeQuestionIndex}._data_status`);

const getH5PContentByIdQuery = useGetH5PQuizContentByIdQuery(
questions[activeQuestionIndex]?.question_description,
contentType,
);

const questionTypeForm = {
true_false: <TrueFalse key={activeQuestionId} />,
multiple_choice: <MultipleChoiceAndOrdering key={activeQuestionId} />,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ const QuestionList = ({
const addButtonRef = useRef<HTMLButtonElement>(null);

const form = useFormContext<QuizForm>();
const { contentType, activeQuestionIndex, validationError, setActiveQuestionId, setValidationError } = useQuizModalContext();
const { contentType, activeQuestionIndex, validationError, setActiveQuestionId, setValidationError } =
useQuizModalContext();
const {
remove: removeQuestion,
append: appendQuestion,
Expand Down Expand Up @@ -215,6 +216,12 @@ const QuestionList = ({
setIsOpen(false);
};

const handleH5PBulkQuestion = (contents: H5PContent[]) => {
for (const content of contents) {
handleAddQuestion('h5p', content);
}
};

const handleDuplicateQuestion = (data: QuizQuestion, index: number) => {
const currentQuestion = form.watch(`questions.${index}` as 'questions.0');

Expand Down Expand Up @@ -287,10 +294,11 @@ const QuestionList = ({
component: H5PContentListModal,
props: {
title: __('Select H5P Content', 'tutor'),
onAddContent: (content) => {
handleAddQuestion('h5p', content);
onAddContent: (contents) => {
handleH5PBulkQuestion(contents);
},
contentType: 'tutor_h5p_quiz',
addedContentIds: questions.map((question) => question.question_description),
},
});
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { css } from '@emotion/react';
import { __ } from '@wordpress/i18n';
import { format } from 'date-fns';
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import { Controller } from 'react-hook-form';

import Button from '@Atoms/Button';
Expand All @@ -13,22 +13,31 @@ import FormInputWithContent from '@Components/fields/FormInputWithContent';
import BasicModalWrapper from '@Components/modals/BasicModalWrapper';
import type { ModalProps } from '@Components/modals/Modal';

import Checkbox from '@Atoms/CheckBox';
import { DateFormats } from '@Config/constants';
import { colorTokens, spacing } from '@Config/styles';
import { colorTokens, shadow, spacing } from '@Config/styles';
import { typography } from '@Config/typography';
import { type ContentType, useGetH5PLessonContentsQuery } from '@CourseBuilderServices/curriculum';
import Show from '@Controls/Show';
import { type ContentType, type ID, useGetH5PLessonContentsQuery } from '@CourseBuilderServices/curriculum';
import { type H5PContent, useGetH5PQuizContentsQuery } from '@CourseBuilderServices/quiz';
import { useDebounce } from '@Hooks/useDebounce';
import { useFormWithGlobalError } from '@Hooks/useFormWithGlobalError';
import { styleUtils } from '@Utils/style-utils';

interface H5PContentListModalProps extends ModalProps {
closeModal: (props?: { action: 'CONFIRM' | 'CLOSE' }) => void;
onAddContent: (content: H5PContent) => void;
onAddContent: (contents: H5PContent[]) => void;
contentType: ContentType;
addedContentIds: ID[];
}

const H5PContentListModal = ({ title, closeModal, onAddContent, contentType }: H5PContentListModalProps) => {
const H5PContentListModal = ({
title,
closeModal,
onAddContent,
contentType,
addedContentIds = [],
}: H5PContentListModalProps) => {
const form = useFormWithGlobalError<{
search: string;
}>({
Expand All @@ -39,18 +48,59 @@ const H5PContentListModal = ({ title, closeModal, onAddContent, contentType }: H
const search = useDebounce(form.watch('search'), 300);
const getH5PQuizzesQuery = useGetH5PQuizContentsQuery(search, contentType);
const getH5PContentsQuery = useGetH5PLessonContentsQuery(search, contentType);
const [selectedContents, setSelectedContents] = useState<H5PContent[]>([]);

const content = contentType === 'tutor_h5p_quiz' ? getH5PQuizzesQuery.data : getH5PContentsQuery.data;
const filteredContent = content?.output.filter((item) => !addedContentIds.includes(String(item.id)));

const columns: Column<H5PContent>[] = [
{
Header: (
<div data-index css={styles.tableLabel}>
{__('#', 'tutor')}
{filteredContent?.length ? (
<Checkbox
onChange={(isChecked) => {
if (isChecked) {
setSelectedContents(
filteredContent?.filter((item) => !addedContentIds.includes(String(item.id))) || [],
);
} else {
setSelectedContents([]);
}
}}
checked={
selectedContents.length ===
(filteredContent?.filter((item) => !addedContentIds.includes(String(item.id))) || []).length
}
isIndeterminate={
selectedContents.length > 0 &&
selectedContents.length <
(filteredContent?.filter((item) => !addedContentIds.includes(String(item.id))) || []).length
}
/>
) : (
'#'
)}
</div>
),
Cell: (item, index) => {
return <div css={typography.caption()}>{index + 1}</div>;
return (
<div css={typography.caption()}>
<Checkbox
onChange={(isChecked) => {
if (isChecked) {
setSelectedContents([...selectedContents, item]);
} else {
setSelectedContents(selectedContents.filter((content) => content.id !== item.id));
}
}}
checked={
selectedContents.map((content) => content.id).includes(item.id) &&
!addedContentIds.includes(String(item.id))
}
/>
</div>
);
},
},
{
Expand All @@ -65,12 +115,6 @@ const H5PContentListModal = ({ title, closeModal, onAddContent, contentType }: H
return <div css={typography.caption()}>{item.content_type}</div>;
},
},
{
Header: <div css={styles.tableLabel}>{__('Author', 'tutor')}</div>,
Cell: (item) => {
return <div css={typography.caption()}>{item.user_name}</div>;
},
},
{
Header: <div css={styles.tableLabel}>{__('Created At', 'tutor')}</div>,
Cell: (item) => {
Expand All @@ -81,23 +125,6 @@ const H5PContentListModal = ({ title, closeModal, onAddContent, contentType }: H
);
},
},
{
Header: <div css={styles.tableLabel}>{__('Actions', 'tutor')}</div>,
Cell: (item) => {
return (
<Button
size="small"
variant="secondary"
onClick={() => {
closeModal({ action: 'CONFIRM' });
onAddContent(item);
}}
>
{__('Add', 'tutor')}
</Button>
);
},
},
];

useEffect(() => {
Expand Down Expand Up @@ -127,10 +154,29 @@ const H5PContentListModal = ({ title, closeModal, onAddContent, contentType }: H
<div css={styles.tableWrapper}>
<Table
columns={columns}
data={content?.output || []}
data={filteredContent || []}
loading={getH5PQuizzesQuery.isLoading || getH5PContentsQuery.isLoading}
/>
</div>

<Show when={filteredContent?.length}>
<div css={styles.footer}>
<Button size="small" variant="text" onClick={() => closeModal({ action: 'CLOSE' })}>
{__('Cancel', 'tutor')}
</Button>
<Button
type="submit"
size="small"
variant="primary"
onClick={() => {
onAddContent(selectedContents);
closeModal({ action: 'CONFIRM' });
}}
>
{__('Add', 'tutor')}
</Button>
</div>
</Show>
</div>
</BasicModalWrapper>
);
Expand All @@ -141,7 +187,6 @@ export default H5PContentListModal;
const styles = {
modalWrapper: css`
width: 920px;
padding-bottom: ${spacing[28]};
`,
searchWrapper: css`
display: flex;
Expand Down Expand Up @@ -175,6 +220,16 @@ const styles = {
width: 100%;
text-align: left;
${typography.caption()};
max-width: 340px;
min-width: 340px;
max-width: 400px;
`,
footer: css`
box-shadow: ${shadow.dividerTop};
height: 56px;
display: flex;
align-items: center;
justify-content: end;
gap: ${spacing[16]};
padding-inline: ${spacing[16]};
`,
};
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
useLessonDetailsQuery,
useSaveLessonMutation,
} from '@CourseBuilderServices/curriculum';
import type { H5PContent } from '@CourseBuilderServices/quiz';
import { convertLessonDataToPayload, getCourseId, isAddonEnabled } from '@CourseBuilderUtils/utils';
import { useFormWithGlobalError } from '@Hooks/useFormWithGlobalError';
import { normalizeLineEndings } from '@Utils/util';
Expand Down Expand Up @@ -274,13 +275,24 @@ const LessonModal = ({
component: H5PContentListModal,
props: {
title: __('Select H5P Content', 'tutor'),
onAddContent: (content) => {
form.setValue(
'description',
`${form.getValues('description') || ''}[h5p id="${content.id}"]`,
);
onAddContent: (contents) => {
const convertToH5PShortCode = (content: H5PContent) => {
return `[h5p id="${content.id}"]`;
};
const description = form.getValues('description');
const h5pContents = contents.map(convertToH5PShortCode);

form.setValue('description', `${description}\n${h5pContents.join('\n')}`);
},
contentType: 'lesson',
addedContentIds: (() => {
const description = form.getValues('description');
const h5pShortCodes = description.match(/\[h5p id="(\d+)"\]/g) || [];
return h5pShortCodes.map((shortcode) => {
const id = shortcode.match(/\[h5p id="(\d+)"\]/)?.[1] || '';
return String(id);
});
})(),
},
});
}}
Expand Down

0 comments on commit 9e76013

Please sign in to comment.