Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor components #68

Merged
merged 5 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/app/components/container.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useEffect, useState } from 'react'
import LoadingSpinner from './loading'

function useFetchData<D>(fetchAction: () => D) {
const [isLoading, setLoading] = useState(true)
const [data, setData] = useState<D>()

useEffect(() => {
setData(fetchAction())
setLoading(false)
}, [fetchAction])

return { data, isLoading }
}

export function DataLoader<D>({
fetchAction,
render,
}: {
fetchAction: () => D
render: (data: D) => React.ReactElement
}) {
const { data, isLoading } = useFetchData(fetchAction)

if (isLoading) {
return <LoadingSpinner />
}

return render(data as D)
}
69 changes: 27 additions & 42 deletions src/app/components/editor.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client'

import { useEffect, useRef, useState } from 'react'
import { useState } from 'react'
import {
QuestionSetRepo,
LocalStorageQuestionSetRepo,
Expand All @@ -15,7 +15,7 @@ import {
} from '../../model/mc'
import { useRouter } from 'next/navigation'
import Error from 'next/error'
import LoadingSpinner from './loading'
import { DataLoader } from './container'

export class QuestionSetEditorAriaLabel {
// If update of labels in this class, may need also to update e2e test
Expand Down Expand Up @@ -106,16 +106,15 @@ export class QuestionSetEditorUIService {
return (
<QuestionSetEditor
saveQuestionSet={this.saveQuestionSet}
fetchQuestionSet={() => QuestionSet.create({ name: '', questions: [] })}
originalQuestionSet={QuestionSet.create({ name: '', questions: [] })}
/>
)
}

getModifyingPageElement(questionSetId: string) {
return (
<QuestionSetEditor
saveQuestionSet={this.saveQuestionSet}
fetchQuestionSet={() => {
<DataLoader
fetchAction={() => {
try {
return this.questionSetRepo.getQuestionSetById(questionSetId)
} catch (e) {
Expand All @@ -125,7 +124,21 @@ export class QuestionSetEditorUIService {
throw e
}
}}
deleteQuestionSet={(id) => this.questionSetRepo.deleteQuestionSet(id)}
render={(questionSet) => {
if (!questionSet) {
return <Error statusCode={404} />
}

return (
<QuestionSetEditor
saveQuestionSet={this.saveQuestionSet}
originalQuestionSet={questionSet}
deleteQuestionSet={(id) =>
this.questionSetRepo.deleteQuestionSet(id)
}
/>
)
}}
/>
)
}
Expand Down Expand Up @@ -299,39 +312,22 @@ const buildQuestion = (
}

function QuestionSetEditor({
originalQuestionSet,
saveQuestionSet,
fetchQuestionSet,
deleteQuestionSet,
}: {
fetchQuestionSet: () => QuestionSet | null
originalQuestionSet: QuestionSet
saveQuestionSet: (questionSet: QuestionSet) => OperationResult
deleteQuestionSet?: (questionSetId: string) => void
}) {
const router = useRouter()
const [isLoading, setLoading] = useState(true)
const [isNotFound, setNotFound] = useState(false)

const questionSetIdRef = useRef<string>('')

const [questionSetInput, setQuestionSetInput] = useState<QuestionSetInput>({
name: '',
questions: [],
})
const [questionSetInput, setQuestionSetInput] = useState<QuestionSetInput>(
mapQuestionSetToQuestionSetInput(originalQuestionSet),
)
const [errorMessage, setErrorMessage] = useState<string | null>(null)
const [isConfirmDelete, setIsConfirmDelete] = useState<boolean>(false)

useEffect(() => {
const questionSet = fetchQuestionSet()
if (questionSet == null) {
setNotFound(true)
return
}

questionSetIdRef.current = questionSet.id
setQuestionSetInput(mapQuestionSetToQuestionSetInput(questionSet))
setLoading(false)
}, [fetchQuestionSet])

const handleQuestionUpdate = (newQuestion: QuestionInput) => {
setQuestionSetInput({
...questionSetInput,
Expand Down Expand Up @@ -364,30 +360,19 @@ function QuestionSetEditor({
}

const saveChanges = (): OperationResult => {
const response = buildQuestionSet(
questionSetInput,
questionSetIdRef.current,
)
const response = buildQuestionSet(questionSetInput, originalQuestionSet.id)
if ('error' in response) {
return response
}
return saveQuestionSet(response.result)
}

if (isNotFound) {
return <Error statusCode={404} />
}

if (isLoading) {
return <LoadingSpinner />
}

return (
<div className="container mx-auto p-4">
{isConfirmDelete &&
ConfirmDeleteDiaLog({
onConfirm: () => {
deleteQuestionSet!(questionSetIdRef.current)
deleteQuestionSet!(originalQuestionSet.id)
router.push('/')
},
onCancel: () => {
Expand Down
29 changes: 11 additions & 18 deletions src/app/components/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import {
QuestionSetRepo,
LocalStorageQuestionSetRepo,
} from '../../repo/question_set'
import { useEffect, useState } from 'react'
import LoadingSpinner from './loading'
import { DataLoader } from './container'

export class HomePageUIService {
static create() {
Expand Down Expand Up @@ -41,29 +40,23 @@ export class HomePageUIService {
}

getElement() {
return <HomePage fetchQuestionSets={this.getSortedQuestionSets}></HomePage>
return (
<DataLoader
fetchAction={this.getSortedQuestionSets}
render={(questionSets) => {
return <HomePage questionSets={questionSets}></HomePage>
}}
/>
)
}
}

function HomePage({
fetchQuestionSets,
questionSets,
}: {
fetchQuestionSets: () => ReadonlyArray<QuestionSet>
questionSets: ReadonlyArray<QuestionSet>
}) {
const router = useRouter()
const [isLoading, setLoading] = useState(true)

const [questionSets, setQuestionSets] = useState<ReadonlyArray<QuestionSet>>(
[],
)
useEffect(() => {
setQuestionSets(fetchQuestionSets())
setLoading(false)
}, [fetchQuestionSets])

if (isLoading) {
return <LoadingSpinner />
}

return (
<div className="p-4">
Expand Down
63 changes: 22 additions & 41 deletions src/app/components/quiz.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use client'

import { useEffect, useState } from 'react'
import { useState } from 'react'
import { Question, QuestionSet } from '../../model/question_set'
import {
GetQuestionSetError,
QuestionSetRepo,
LocalStorageQuestionSetRepo,
} from '../../repo/question_set'
import LoadingSpinner from './loading'
import Error from 'next/error'
import { DataLoader } from './container'

export class MultipleChoiceQuizUIService {
static create({ questionSetId }: { questionSetId: string }) {
Expand Down Expand Up @@ -47,8 +47,8 @@ export class MultipleChoiceQuizUIService {

getElement() {
return (
<MultipleChoiceQuiz
fetchQuestionSet={() => {
<DataLoader
fetchAction={() => {
try {
return this.questionSetRepo.getQuestionSetById(this.questionSetId)
} catch (e) {
Expand All @@ -58,46 +58,35 @@ export class MultipleChoiceQuizUIService {
throw e
}
}}
onSubmit={(questionSet) => {
this.questionSetRepo.upsertQuestionSet(
questionSet.newSwappedChoicesQuestionSet(),
render={(questionSet: QuestionSet | null) => {
if (questionSet === null) {
return <Error statusCode={404} />
}
return (
<MultipleChoiceQuiz
questionSet={questionSet}
onSubmit={() => {
this.questionSetRepo.upsertQuestionSet(
questionSet.newSwappedChoicesQuestionSet(),
)
}}
/>
)
}}
></MultipleChoiceQuiz>
/>
)
}
}

function MultipleChoiceQuiz({
fetchQuestionSet,
questionSet,
onSubmit,
}: {
fetchQuestionSet: () => QuestionSet | null
onSubmit: (questionSet: QuestionSet) => void
questionSet: QuestionSet
onSubmit: () => void
}) {
const [isLoading, setLoading] = useState(true)
const [isNotFound, setNotFound] = useState(false)

const [questionSet, setQuestionSet] = useState<QuestionSet>(
QuestionSet.create({
id: '',
name: '',
questions: [],
}),
)
const [score, setScore] = useState<number | null>(null)

useEffect(() => {
const questionSet = fetchQuestionSet()
if (questionSet === null) {
setNotFound(true)
return
}

setQuestionSet(questionSet)
setLoading(false)
}, [fetchQuestionSet])

const [questionToCheckedChoiceMap, setCheckedChoice] = useState<
Map<number, number>
>(new Map<number, number>())
Expand All @@ -110,7 +99,7 @@ function MultipleChoiceQuiz({

const handleSubmit = () => {
setScore(calculateScore())
onSubmit(questionSet)
onSubmit()
}

const isSubmitted = () => score !== null
Expand All @@ -128,14 +117,6 @@ function MultipleChoiceQuiz({
return score
}

if (isNotFound) {
return <Error statusCode={404} />
}

if (isLoading) {
return <LoadingSpinner />
}

return (
<div className="p-4">
<h1 className="text-xl font-semibold mb-6">{questionSet.name}</h1>
Expand Down
Loading