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

Add persistor to pset components #115

Merged
merged 5 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
98 changes: 88 additions & 10 deletions src/components/DropdownProblem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { BaseProblemProps } from './ProblemSetBlock'
import { determineFeedback } from '../lib/problems'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import { mathifyElement } from '../lib/math'
import React, { useCallback, useState } from 'react'
import React, { useCallback, useEffect, useState } from 'react'
import * as Yup from 'yup'
import { AttemptsCounter } from './AttemptsCounter'
import { CorrectAnswerIcon, WrongAnswerIcon } from './Icons'
Expand All @@ -15,11 +15,21 @@ interface DropdownFormValues {
response: string
}

interface PersistorData {
userResponse: string
formDisabled: boolean
retriesAllowed: number
feedback: string
}

enum PersistorGetStatus {
Uninitialized,
Success,
Failure
}

export function buildClassName(response: string, solution: string, formDisabled: boolean): string {
let className = 'os-form-select'
if (response !== '') {
className += ' os-selected-answer-choice'
}
if (solution === response && formDisabled) {
className += ' os-correct-answer-choice os-disabled'
}
Expand All @@ -32,11 +42,13 @@ export function buildClassName(response: string, solution: string, formDisabled:
export const DropdownProblem = ({
solvedCallback, exhaustedCallback, allowedRetryCallback, content, contentId, buttonText, solutionOptions,
encourageResponse, correctResponse, solution, retryLimit, answerResponses, attemptsExhaustedResponse,
onProblemAttempt
onProblemAttempt, persistor
}: DropdownProblemProps): JSX.Element => {
const [feedback, setFeedback] = useState('')
const [formDisabled, setFormDisabled] = useState(false)
const [retriesAllowed, setRetriesAllowed] = useState(0)
const [response, setResponse] = useState('')
const [persistorGetStatus, setPersistorGetStatus] = useState<number>(PersistorGetStatus.Uninitialized)

const schema = Yup.object({
response: Yup.string().trim().required('Please select an answer')
Expand Down Expand Up @@ -66,11 +78,54 @@ export const DropdownProblem = ({
return input === answer
}

const setPersistedState = async (): Promise<void> => {
try {
if (contentId === undefined || persistor === undefined) {
return
}

if (response !== '' || formDisabled || retriesAllowed !== 0) {
const newPersistedData: PersistorData = { userResponse: response, formDisabled, retriesAllowed, feedback }
await persistor.put(contentId, JSON.stringify(newPersistedData))
}
} catch (err) {
console.error(err)
}
}

const getPersistedState = async (): Promise<void> => {
try {
if (contentId === undefined || persistor === undefined) {
setPersistorGetStatus(PersistorGetStatus.Success)
return
}

const persistedState = await persistor.get(contentId)
if (persistedState !== null) {
const parsedPersistedState = JSON.parse(persistedState)
setResponse(parsedPersistedState.userResponse)
setFormDisabled(parsedPersistedState.formDisabled)
setRetriesAllowed(parsedPersistedState.retriesAllowed)
setFeedback(parsedPersistedState.feedback)
}
setPersistorGetStatus(PersistorGetStatus.Success)
} catch (err) {
setPersistorGetStatus(PersistorGetStatus.Failure)
}
}

useEffect(() => {
setPersistedState().catch(() => { })
getPersistedState().catch(() => { })
}, [response, formDisabled, retriesAllowed])

const handleSubmit = async (values: DropdownFormValues): Promise<void> => {
let correct = false
let finalAttempt = false
const attempt = retriesAllowed + 1

setResponse(values.response)

if (evaluateInput(values.response, solution)) {
correct = true
setFeedback(correctResponse)
Expand Down Expand Up @@ -99,33 +154,56 @@ export const DropdownProblem = ({
}
}

if (persistorGetStatus === PersistorGetStatus.Failure) {
return (
<div className="os-raise-bootstrap">
<div className="text-center">
<span className="text-danger">There was an error loading content. Please try refreshing the page.</span>
</div>
</div>
)
}

if (persistorGetStatus === PersistorGetStatus.Uninitialized) {
return (
<div className="os-raise-bootstrap">
<div className="text-center">
<div className="spinner-border text-primary" role="status">
<span className="visually-hidden">Loading...</span>
</div>
</div>
</div>
)
}

return (
<div className="os-raise-bootstrap">
<div className="my-3" ref={contentRefCallback} dangerouslySetInnerHTML={{ __html: content }} />
<Formik
initialValues={{ response: '' }}
initialValues={{ response }}
onSubmit={handleSubmit}
validationSchema={schema}
enableReinitialize={true}
>
{({ isSubmitting, values, setFieldValue }) => (
<Form>
<div className='os-flex os-align-items-center'>
{solution === values.response && formDisabled &&
{solution === response && formDisabled &&
<div>
<CorrectAnswerIcon className={'os-mr'} />
</div>
}
{solution !== values.response && formDisabled &&
{solution !== response && formDisabled &&
<div>
<WrongAnswerIcon className={'os-mr'} />
</div>
}
<Field
name="response"
as="select"
value={values.response}
value={formDisabled ? response : values.response}
disabled={isSubmitting || formDisabled}
className={buildClassName(values.response, solution, formDisabled)}
className={buildClassName(response, solution, formDisabled)}
onChange={(e: React.ChangeEvent<HTMLSelectElement>) => { clearFeedback(); void setFieldValue('response', e.target.value) }}
>
{generateOptions()}
Expand Down
93 changes: 88 additions & 5 deletions src/components/InputProblem.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useCallback } from 'react'
import React, { useState, useCallback, useEffect } from 'react'
import type { BaseProblemProps } from './ProblemSetBlock'
import { determineFeedback } from '../lib/problems'
import { Formik, Form, Field, ErrorMessage, type FormikHelpers } from 'formik'
Expand All @@ -24,6 +24,19 @@ interface InputFormValues {
response: string
}

interface PersistorData {
userResponse: string
inputDisabled: boolean
retriesAllowed: number
feedback: string
}

enum PersistorGetStatus {
Uninitialized,
Success,
Failure
}

export function buildClassName(correct: boolean, formDisabled: boolean, errorResponse: string | undefined): string {
let className = 'os-form-control'
if (correct && formDisabled) {
Expand All @@ -40,11 +53,14 @@ export function buildClassName(correct: boolean, formDisabled: boolean, errorRes

export const InputProblem = ({
solvedCallback, exhaustedCallback, allowedRetryCallback, attemptsExhaustedResponse,
solution, retryLimit, content, contentId, comparator, encourageResponse, buttonText, correctResponse, answerResponses, onProblemAttempt
solution, retryLimit, content, contentId, comparator, encourageResponse, buttonText, correctResponse, answerResponses, onProblemAttempt,
persistor
}: InputProblemProps): JSX.Element => {
const [retriesAllowed, setRetriesAllowed] = useState(0)
const [inputDisabled, setInputDisabled] = useState(false)
const [feedback, setFeedback] = useState('')
const [response, setResponse] = useState('')
const [persistorGetStatus, setPersistorGetStatus] = useState<number>(PersistorGetStatus.Uninitialized)
const NUMERIC_INPUT_ERROR = 'Enter numeric values only'
const EXCEEDED_MAX_INPUT_ERROR = 'Input is too long'
const NON_EMPTY_VALUE_ERROR = 'Please provide valid input'
Expand Down Expand Up @@ -105,11 +121,54 @@ export const InputProblem = ({
return trimmedInput.toLowerCase() === trimmedAnswer.toLowerCase()
}

const setPersistedState = async (): Promise<void> => {
rnathuji marked this conversation as resolved.
Show resolved Hide resolved
try {
if (contentId === undefined || persistor === undefined) {
return
}

if (response !== '' || inputDisabled || retriesAllowed !== 0) {
const newPersistedData: PersistorData = { userResponse: response, inputDisabled, retriesAllowed, feedback }
await persistor.put(contentId, JSON.stringify(newPersistedData))
}
} catch (err) {
console.error(err)
}
}

const getPersistedState = async (): Promise<void> => {
try {
if (contentId === undefined || persistor === undefined) {
setPersistorGetStatus(PersistorGetStatus.Success)
return
}

const persistedState = await persistor.get(contentId)
if (persistedState !== null) {
const parsedPersistedState = JSON.parse(persistedState)
setResponse(parsedPersistedState.userResponse)
setInputDisabled(parsedPersistedState.inputDisabled)
setRetriesAllowed(parsedPersistedState.retriesAllowed)
setFeedback(parsedPersistedState.feedback)
rnathuji marked this conversation as resolved.
Show resolved Hide resolved
}
setPersistorGetStatus(PersistorGetStatus.Success)
} catch (err) {
setPersistorGetStatus(PersistorGetStatus.Failure)
}
}

useEffect(() => {
setPersistedState().catch(() => { })
getPersistedState().catch(() => { })
}, [response, inputDisabled, retriesAllowed])
rnathuji marked this conversation as resolved.
Show resolved Hide resolved

const handleSubmit = async (values: InputFormValues, { setFieldError }: FormikHelpers<InputFormValues>): Promise<void> => {
rnathuji marked this conversation as resolved.
Show resolved Hide resolved
let correct = false
let finalAttempt = false
const attempt = retriesAllowed + 1

setResponse(values.response)

if (values.response.trim() === '') {
if ((comparator.toLowerCase() === 'integer') || (comparator.toLowerCase() === 'float')) {
setFieldError('response', NUMERIC_INPUT_ERROR)
Expand Down Expand Up @@ -149,26 +208,50 @@ export const InputProblem = ({
const clearFeedback = (): void => {
setFeedback('')
}

if (persistorGetStatus === PersistorGetStatus.Failure) {
return (
<div className="os-raise-bootstrap">
<div className="text-center">
<span className="text-danger">There was an error loading content. Please try refreshing the page.</span>
</div>
</div>
)
}

if (persistorGetStatus === PersistorGetStatus.Uninitialized) {
return (
<div className="os-raise-bootstrap">
<div className="text-center">
<div className="spinner-border text-primary" role="status">
<span className="visually-hidden">Loading...</span>
</div>
</div>
</div>
)
}

return (
<div className="os-raise-bootstrap">

<div className="my-3" ref={contentRefCallback} dangerouslySetInnerHTML={{ __html: content }} />
<Formik
initialValues={{ response: '' }}
initialValues={{ response }}
onSubmit={handleSubmit}
validationSchema={schema}
validateOnBlur={false}
enableReinitialize={true}
>
{({ isSubmitting, setFieldValue, values, errors }) => (
<Form >
<div className='os-flex os-align-items-center'>

{evaluateInput(values.response, solution) && inputDisabled &&
{evaluateInput(response, solution) && inputDisabled &&
<div>
<CorrectAnswerIcon className={'os-mr'} />
</div>
}
{!evaluateInput(values.response, solution) && inputDisabled &&
{!evaluateInput(response, solution) && inputDisabled &&
<div>
<WrongAnswerIcon className={'os-mr'} />
</div>
Expand Down
Loading