Skip to content

Commit

Permalink
refactored my resources page tables (#1115)
Browse files Browse the repository at this point in the history
* refactored my resources page tables

* fix

* refactor props

* fix type

* rebase

* fix
  • Loading branch information
Tolik170 authored Sep 11, 2023
1 parent 41a73bb commit 4c7128a
Show file tree
Hide file tree
Showing 21 changed files with 299 additions and 374 deletions.
2 changes: 1 addition & 1 deletion src/components/enhanced-table/EnhancedTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
TableSort
} from '~/types'

interface EnhancedTableProps<I, F> extends TableProps {
export interface EnhancedTableProps<I, F> extends TableProps {
columns: TableColumn<I>[]
isSelection?: boolean
rowActions?: TableRowAction[]
Expand Down
18 changes: 9 additions & 9 deletions src/constants/translations/en/my-resources-page.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,35 @@
"attachments": "Attachments"
},
"lessons": {
"newLessonBtn": "New lesson",
"addBtn": "New lesson",
"title": "Title",
"attachmentQty": "Attachment",
"attachmentsQty": "Attachments",
"attachments": "Attachments",
"lastUpdates": "Last updates",
"emptyLessons":"You have no lessons yet",
"confirmLessonDeletionTitle":"Do you confirm lesson deletion?",
"emptyItems":"You have no lessons yet",
"confirmDeletionTitle":"Do you confirm lesson deletion?",
"successDeletion":"Lesson was deleted successfully"
},
"attachments": {
"addAttachment": "Add Attachment",
"addBtn": "Add Attachment",
"addFromAttachments": "Add files from your Attachments",
"file": "File",
"size": "Size",
"lastUpdate": "Last update",
"emptyAttachments": "You have no attachments yet",
"confirmAttachmentDeletionTitle":"Do you confirm attachment deletion?",
"emptyItems": "You have no attachments yet",
"confirmDeletionTitle":"Do you confirm attachment deletion?",
"successDeletion":"Attachment was deleted successfully",
"validationError": "File name cannot be longer than 55 symbol."
},
"quizzes": {
"newQuizBtn": "New quiz",
"addBtn": "New quiz",
"title": "Title",
"question": "Question",
"questions": "Questions",
"updated": "Last updates",
"emptyQuizzes": "You have no quizzes yet",
"confirmQuizDeletionTitle":"Do you confirm quiz deletion?",
"emptyItems": "You have no quizzes yet",
"confirmDeletionTitle":"Do you confirm quiz deletion?",
"successDeletion":"Quiz was deleted successfully"
},
"confirmDeletionMessage":"This action is permanent and will remove all related content. Please review your decision before proceeding."
Expand Down
19 changes: 10 additions & 9 deletions src/constants/translations/ua/my-resources-page.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,36 @@
"attachments": "Вкладення"
},
"lessons": {
"newLessonBtn": "Новий урок",
"addBtn": "Новий урок",
"title": "Заголовок",
"attachments": "Файли",
"attachmentQty": "Файл",
"attachmentsQty": "Файлів",
"lastUpdates": "Останнє оновлення",
"emptyLessons":"У вас ще немає уроків",
"confirmLessonDeletionTitle":"Ви підтверджуєте видалення уроку?",
"confirmLessonDeletionMessage":"Ця дія є постійною та призведе до видалення всього пов’язаного вмісту. Перш ніж продовжити, перегляньте своє рішення.",
"emptyItems":"У вас ще немає уроків",
"confirmDeletionTitle":"Ви підтверджуєте видалення уроку?",
"successDeletion":"Урок було успішно видалено"
},
"attachments": {
"addFromAttachments": "Додайте файли з Вкладень",
"addBtn": "Додайте файли з Вкладень",
"file": "Файл",
"size": "Розмір",
"lastUpdate": "Останнє оновлення",
"emptyAttachments": "У вас ще немає вкладень",
"confirmAttachmentDeletionTitle":"Ви підтверджуєте видалення вкладення?",
"emptyItems": "У вас ще немає вкладень",
"confirmDeletionTitle":"Ви підтверджуєте видалення вкладення?",
"successDeletion":"Вкладення було успішно видалено",
"addAttachment": "Добавити файл",
"validationError": "Назва файлу не може бути довшою за 55 символів."
},
"quizzes": {
"newQuizBtn": "Новий тест",
"addBtn": "Новий тест",
"quizTitle": "Заголовок",
"question": "Питання",
"questions": "Питання",
"updated": "Останнє оновлення",
"emptyQuizzes": "У вас ще немає тестів"
"emptyItems": "У вас ще немає тестів",
"confirmDeletionTitle":"Ви підтверджуєте видалення тесту?",
"successDeletion":"Тест було успішно видалено"
},
"confirmDeletionMessage":"Ця дія є остаточною, та призведе до видалення всього пов’язаного вмісту. Перш ніж продовжити, перегляньте своє рішення."
}
6 changes: 3 additions & 3 deletions src/containers/add-attachments/AddAttachments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import useSort from '~/hooks/table/use-sort'
import useAxios from '~/hooks/use-axios'
import useBreakpoints from '~/hooks/use-breakpoints'
import { useSnackBarContext } from '~/context/snackbar-context'
import { attachmentService } from '~/services/attachment-service'
import { ResourceService } from '~/services/resource-service'

import {
columns,
Expand Down Expand Up @@ -61,7 +61,7 @@ const AddAttachments: FC<AddAttachmentsProps> = ({

const getMyAttachments = useCallback(
() =>
attachmentService.getAttachments({
ResourceService.getAttachments({
sort
}),
[sort]
Expand Down Expand Up @@ -119,7 +119,7 @@ const AddAttachments: FC<AddAttachmentsProps> = ({
)

const createAttachments = useCallback(
(data?: FormData) => attachmentService.createAttachments(data),
(data?: FormData) => ResourceService.createAttachments(data),
[]
)

Expand Down
2 changes: 0 additions & 2 deletions src/containers/my-quizzes/QuizzesContainer.styles.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { TypographyVariantEnum } from '~/types'
import { roundedBorderTable } from '~/containers/my-cooperations/cooperations-container/CooperationContainer.styles'

const captionTitle = {
color: 'primary.400',
typography: TypographyVariantEnum.Caption
}

export const styles = {
table: roundedBorderTable,
quizTitleContainer: {
display: 'flex',
alignItems: 'center',
Expand Down
121 changes: 37 additions & 84 deletions src/containers/my-quizzes/QuizzesContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import { useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import Box from '@mui/material/Box'

import useConfirm from '~/hooks/use-confirm'
import { quizService } from '~/services/quiz-service'
import { useSnackBarContext } from '~/context/snackbar-context'
import EnhancedTable from '~/components/enhanced-table/EnhancedTable'
import { quizService } from '~/services/quiz-service'
import AddResourceWithInput from '~/containers/my-resources/add-resource-with-input/AddResourceWithInput'
import MyResourcesTable from '~/containers/my-resources/my-resources-table/MyResourcesTable'
import Loader from '~/components/loader/Loader'
import useSort from '~/hooks/table/use-sort'
import useBreakpoints from '~/hooks/use-breakpoints'
import useAxios from '~/hooks/use-axios'
import AppPagination from '~/components/app-pagination/AppPagination'
import usePagination from '~/hooks/table/use-pagination'

import { defaultResponses, snackbarVariants } from '~/constants'
Expand All @@ -21,25 +18,31 @@ import {
itemsLoadLimit,
removeColumnRules
} from '~/containers/my-quizzes/QuizzesContainer.constants'

import { styles } from '~/containers/my-quizzes/QuizzesContainer.styles'
import { ErrorResponse, ItemsWithCount, Quiz } from '~/types'
import {
ItemsWithCount,
GetResourcesParams,
Quiz,
ErrorResponse,
ResourcesTabsEnum
} from '~/types'
import { ajustColumns, getScreenBasedLimit } from '~/utils/helper-functions'

const QuizzesContainer = () => {
const { t } = useTranslation()
const { setAlert } = useSnackBarContext()
const { openDialog } = useConfirm()

const { page } = usePagination()
const sortOptions = useSort({ initialSort })
const { sort } = sortOptions
const searchTitle = useRef<string>('')
const breakpoints = useBreakpoints()
const { page, handleChangePage } = usePagination()

const { sort } = sortOptions
const itemsPerPage = getScreenBasedLimit(breakpoints, itemsLoadLimit)
const columnsToShow = ajustColumns(breakpoints, columns, removeColumnRules)
const columnsToShow = ajustColumns<Quiz>(
breakpoints,
columns,
removeColumnRules
)

const onGetQuizzesError = useCallback(
const onResponseError = useCallback(
(error: ErrorResponse) => {
setAlert({
severity: snackbarVariants.error,
Expand All @@ -49,20 +52,6 @@ const QuizzesContainer = () => {
[setAlert]
)

const onDeleteQuizError = (error: ErrorResponse) => {
setAlert({
severity: snackbarVariants.error,
message: error ? `errors.${error.code}` : ''
})
}

const onDeleteQuizResponse = () => {
setAlert({
severity: snackbarVariants.success,
message: 'myResourcesPage.quizzes.successDeletion'
})
}

const getQuizzes = useCallback(
() =>
quizService.getQuizzes({
Expand All @@ -79,74 +68,38 @@ const QuizzesContainer = () => {
[]
)

const { response, loading, fetchData } = useAxios<ItemsWithCount<Quiz>>({
const { response, loading, fetchData } = useAxios<
ItemsWithCount<Quiz>,
GetResourcesParams
>({
service: getQuizzes,
defaultResponse: defaultResponses.itemsWithCount,
onResponseError: onGetQuizzesError
})

const { error, fetchData: fetchDeleteLesson } = useAxios({
service: deleteQuiz,
fetchOnMount: false,
defaultResponse: null,
onResponseError: onDeleteQuizError,
onResponse: onDeleteQuizResponse
onResponseError
})

const handleDeleteQuiz = async (id: string, isConfirmed: boolean) => {
if (isConfirmed) {
await fetchDeleteLesson(id)
if (!error) await fetchData()
}
const props = {
columns: columnsToShow,
data: { response, getData: fetchData },
services: { deleteService: deleteQuiz },
itemsPerPage,
actions: { onEdit: () => null },
resource: ResourcesTabsEnum.Quizzes,
sort: sortOptions
}

const openDeletionConfirmDialog = (id: string) => {
openDialog({
message: 'myResourcesPage.confirmDeletionMessage',
sendConfirm: (isConfirmed: boolean) =>
void handleDeleteQuiz(id, isConfirmed),
title: 'myResourcesPage.quizzes.confirmQuizDeletionTitle'
})
}

const rowActions = [
{
label: t('common.edit'),
func: () => undefined
},
{
label: t('common.delete'),
func: openDeletionConfirmDialog
}
]

const tableWithPagination = (
<>
<EnhancedTable
columns={columnsToShow}
data={{ items: response.items }}
emptyTableKey='myResourcesPage.quizzes.emptyQuizzes'
rowActions={rowActions}
sort={sortOptions}
sx={styles.table}
/>
<AppPagination
onChange={handleChangePage}
page={page}
pageCount={Math.ceil(response.count / itemsPerPage)}
/>
</>
)

return (
<Box>
<AddResourceWithInput
btnText='myResourcesPage.quizzes.newQuizBtn'
btnText={'myResourcesPage.quizzes.addBtn'}
fetchData={fetchData}
link={'#'}
searchRef={searchTitle}
/>
{loading ? <Loader pageLoad size={50} /> : tableWithPagination}
{loading ? (
<Loader pageLoad size={50} />
) : (
<MyResourcesTable<Quiz> {...props} />
)}
</Box>
)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { roundedBorderTable } from '~/containers/my-cooperations/cooperations-container/CooperationContainer.styles'
import { TypographyVariantEnum } from '~/types'

const captionTitle = {
Expand All @@ -25,7 +24,6 @@ export const styles = {
addAttachmentBtn: { width: 'fit-content' },
addAttachmentIcon: { ml: '5px', width: { xs: '18px', sm: '22px' } },
table: {
...roundedBorderTable,
'& td,th': {
'&:first-of-type': { maxWidth: '50%', width: '100%' }
}
Expand Down
Loading

0 comments on commit 4c7128a

Please sign in to comment.