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

Extend persistor to problem set components #114

Closed
wants to merge 13 commits into from
Closed
2 changes: 1 addition & 1 deletion data/content-versions.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"defaultVersion": "d194749e",
"defaultVersion": "2d6223ee",
"overrides": {
"raiselearning.org": {
"39": "latest",
Expand Down
Binary file added docs/static/textheavyadjustedtable.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
59 changes: 59 additions & 0 deletions docs/styles.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
- [Styling Content for RAISE](#styling-content-for-raise)
- Tables
- [Text Heavy Tables](#text-heavy-table)
- [Text Heavy Adjusted Tables](#text-heavy-adjusted-table)
- [Horizontal Tables](#horizontal-table)
- [Mid-Sized Tables](#mid-size-table)
- Skinny Tables
Expand Down Expand Up @@ -83,6 +84,64 @@ Add as a class attribute to a table html tag.

---

## Text Heavy Adjusted Table

Adds a solid border, styled table header, and padding to a table with column widths determined by the widest content in a column.

**Example**

<div style="text-align: center;">
<img src="./static/textheavyadjustedtable.png" width="600">
</div>

**Availability**

Add as a class attribute to a table html tag.

**Usage**

```html
<table class="os-raise-textheavyadjustedtable">
<thead>
<tr>
<th scope="col">Lesson Number</th>
<th scope="col">Lesson Title</th>
<th scope="col">Associated Texas Essential Knowledge and Skills [TEKS]</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.1</td>
<td>Exploring Expressions and Equations</td>
<td><p>A1(A) apply mathematics to problems arising in everyday life, society, and the workplace</p>
<p>A2(C) write linear equations in two variables given a table of values, a graph, and a verbal description</p></td>
</tr>
<tr>
<td>1.2</td>
<td>Writing Equations to Model Relationships (Part 1)</td>
<td><p>A1(A) apply mathematics to problems arising in everyday life, society, and the workplace</p>
<p>A2(C) write linear equations in two variables given a table of values, a graph, and a verbal description</p></td>
</tr>
<tr>
<td>1.3</td>
<td>Writing Equations to Model Relationships (Part 2)</td>
<td><p>A1(A) apply mathematics to problems arising in everyday life, society, and the workplace</p>
<p>A1(C) select tools, including real objects, manipulatives, paper and pencil, and technology as appropriate, and techniques, including mental math, estimation, and number sense as appropriate, to solve problems</p>
<p>A2(C) write linear equations in two variables given a table of values, a graph, and a verbal description.</p></td>
</tr>
<tr>
<td>1.4</td>
<td>Equations and Their Solutions</td>
<td><p>A1(A) apply mathematics to problems arising in everyday life, society, and the workplace</p>
<p>A1(C) select tools, including real objects, manipulatives, paper and pencil, and technology as appropriate, and techniques, including mental math, estimation, and number sense as appropriate, to solve problems</p>
<p>A2(C) write linear equations in two variables given a table of values, a graph, and a verbal description</p></td>
</tr>
</tbody>
</table>
```

---

## Horizontal Table

Adds a solid border, styled header cell, and padding to a horizontal table.
Expand Down
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> => {
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)
}
setPersistorGetStatus(PersistorGetStatus.Success)
} catch (err) {
setPersistorGetStatus(PersistorGetStatus.Failure)
}
}

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

const handleSubmit = async (values: InputFormValues, { setFieldError }: FormikHelpers<InputFormValues>): Promise<void> => {
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