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 4 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
116 changes: 108 additions & 8 deletions src/components/DropdownProblem.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { BaseProblemProps } from './ProblemSetBlock'
import { determineFeedback } from '../lib/problems'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import { Formik, Form, Field, ErrorMessage, type FormikHelpers } 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,6 +15,18 @@ interface DropdownFormValues {
response: string
}

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

enum PersistorGetStatus {
Uninitialized,
Success,
Failure
}

export function buildClassName(response: string, solution: string, formDisabled: boolean): string {
let className = 'os-form-select'
if (response !== '') {
Expand All @@ -32,11 +44,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,28 +80,92 @@ export const DropdownProblem = ({
return input === answer
}

const handleSubmit = async (values: DropdownFormValues): Promise<void> => {
const handleFeedback = (userResponse: string, userAttempts: number): void => {
if (evaluateInput(userResponse, solution)) {
setFeedback(correctResponse)
} else if (retryLimit === 0 || userAttempts !== retryLimit) {
setFeedback(determineFeedback(userResponse, encourageResponse, answerResponses, evaluateInput))
} else {
setFeedback(attemptsExhaustedResponse)
}
}

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)
handleFeedback(parsedPersistedState.userResponse, parsedPersistedState.retriesAllowed > 0 ? parsedPersistedState.retriesAllowed - 1 : 0)
}
setPersistorGetStatus(PersistorGetStatus.Success)
} catch (err) {
setPersistorGetStatus(PersistorGetStatus.Failure)
}
}

useEffect(() => {
getPersistedState().catch(() => { })
}, [])

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

const setPersistedState = async (persistorData: PersistorData): Promise<void> => {
if (contentId === undefined || persistor === undefined) {
return
}
await persistor.put(contentId, JSON.stringify(persistorData))
}

if (evaluateInput(values.response, solution)) {
correct = true
setFeedback(correctResponse)

try {
await setPersistedState({ userResponse: values.response, formDisabled: true, retriesAllowed })
} catch (error) {
setFieldError('response', 'Error saving response. Please try again.')
return
}

solvedCallback()
setFormDisabled(true)
} else if (retryLimit === 0 || retriesAllowed !== retryLimit) {
try {
await setPersistedState({ userResponse: values.response, formDisabled, retriesAllowed: retriesAllowed + 1 })
} catch (error) {
setFieldError('response', 'Error saving response. Please try again.')
return
}

setRetriesAllowed(currRetries => currRetries + 1)
setFeedback(determineFeedback(values.response, encourageResponse, answerResponses, evaluateInput))
allowedRetryCallback()
} else {
try {
await setPersistedState({ userResponse: values.response, formDisabled: true, retriesAllowed: retriesAllowed + 1 })
} catch (error) {
setFieldError('response', 'Error saving response. Please try again.')
return
}

setRetriesAllowed((currRetries) => currRetries + 1)
setFeedback(attemptsExhaustedResponse)
exhaustedCallback()
setFormDisabled(true)
finalAttempt = true
}

handleFeedback(values.response, retriesAllowed)
setResponse(values.response)
rnathuji marked this conversation as resolved.
Show resolved Hide resolved

if (onProblemAttempt !== undefined) {
onProblemAttempt(
values.response,
Expand All @@ -99,11 +177,33 @@ 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}
>
Expand Down
114 changes: 108 additions & 6 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,18 @@ interface InputFormValues {
response: string
}

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

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 +52,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 +120,53 @@ export const InputProblem = ({
return trimmedInput.toLowerCase() === trimmedAnswer.toLowerCase()
}

const handleFeedback = (userResponse: string, userAttempts: number): void => {
if (evaluateInput(userResponse, solution)) {
setFeedback(correctResponse)
} else if (retryLimit === 0 || userAttempts !== retryLimit) {
setFeedback(determineFeedback(userResponse, encourageResponse, answerResponses, evaluateInput))
} else {
setFeedback(attemptsExhaustedResponse)
}
}

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)
handleFeedback(parsedPersistedState.userResponse, parsedPersistedState.retriesAllowed > 0 ? parsedPersistedState.retriesAllowed - 1 : 0)
}
setPersistorGetStatus(PersistorGetStatus.Success)
} catch (err) {
setPersistorGetStatus(PersistorGetStatus.Failure)
}
}

useEffect(() => {
getPersistedState().catch(() => { })
}, [])

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

const setPersistedState = async (persistorData: PersistorData): Promise<void> => {
if (contentId === undefined || persistor === undefined) {
return
}
await persistor.put(contentId, JSON.stringify(persistorData))
}

if (values.response.trim() === '') {
if ((comparator.toLowerCase() === 'integer') || (comparator.toLowerCase() === 'float')) {
setFieldError('response', NUMERIC_INPUT_ERROR)
Expand All @@ -121,21 +178,43 @@ export const InputProblem = ({

if (evaluateInput(values.response, solution)) {
correct = true
setFeedback(correctResponse)

try {
await setPersistedState({ userResponse: values.response, inputDisabled: true, retriesAllowed })
} catch (error) {
setFieldError('response', 'Error saving response. Please try again.')
return
}

solvedCallback()
setInputDisabled(true)
} else if (retryLimit === 0 || retriesAllowed !== retryLimit) {
try {
await setPersistedState({ userResponse: values.response, inputDisabled, retriesAllowed: retriesAllowed + 1 })
} catch (error) {
setFieldError('response', 'Error saving response. Please try again.')
return
}

setRetriesAllowed(currRetries => currRetries + 1)
setFeedback(determineFeedback(values.response, encourageResponse, answerResponses, evaluateInput))
allowedRetryCallback()
} else {
try {
await setPersistedState({ userResponse: values.response, inputDisabled: true, retriesAllowed: retriesAllowed + 1 })
} catch (error) {
setFieldError('response', 'Error saving response. Please try again.')
return
}

setRetriesAllowed(currRetries => currRetries + 1)
setFeedback(attemptsExhaustedResponse)
exhaustedCallback()
setInputDisabled(true)
finalAttempt = true
}

handleFeedback(values.response, retriesAllowed)
setResponse(values.response)

if (onProblemAttempt !== undefined) {
onProblemAttempt(
values.response,
Expand All @@ -149,12 +228,35 @@ 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}
Expand Down
Loading