Skip to content
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
129 changes: 109 additions & 20 deletions src/components/Card.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ReactNode } from "react";
import { ReactNode, useState, useRef, useEffect, useCallback } from "react";
import { breakpoints, colors, layouts, mixins } from "../theme";
import { AvailablePoints, StepBase, StepWithData } from "../types";
import styled from "styled-components";
Expand Down Expand Up @@ -194,6 +194,21 @@ const StepCardQuestion = styled.div<{ unpadded?: boolean }>`
}
`;

export const StyledOverlay = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
background-color: #FFFFFF80;
z-index: 2;
`;

interface SharedProps {
questionNumber: number;
numberOfQuestions: number;
Expand All @@ -212,6 +227,7 @@ export interface StepCardProps extends SharedProps {
questionId?: string;
multipartBadge?: ReactNode;
isHomework: boolean;
overlayChildren?: React.ReactNode;
}

const StepCard = ({
Expand All @@ -229,35 +245,104 @@ const StepCard = ({
leftHeaderChildren,
rightHeaderChildren,
headerTitleChildren,
overlayChildren,
...otherProps }: StepCardProps) => {

// Helps to stop focusing first child when is already focused
const [previousFocusedElement, setPreviousFocusedElement] = useState<HTMLElement | null>(null);
const overlayRef = useRef<HTMLDivElement>(null);
const [showOverlay, setShowOverlay] = useState<boolean>(false);

const formattedQuestionNumber = numberOfQuestions > 1
? `Questions ${questionNumber} - ${questionNumber + numberOfQuestions - 1}`
: `Question ${questionNumber}`;

const handleOverlayBlur = (event: React.FocusEvent<HTMLDivElement>) => {
if (overlayRef.current && !overlayRef.current.contains(event.relatedTarget as Node)) {
setShowOverlay(false);
}
};

const handleOverlayFocus = useCallback((event: FocusEvent) => {
setShowOverlay(true);
const firstOverlayFocusableElement = document.getElementById('overlay-element')?.querySelector(
'button, [href], input, select, textarea'
) as HTMLElement;

if (
(firstOverlayFocusableElement !== previousFocusedElement) &&
(event.target === overlayRef.current)
) {
setPreviousFocusedElement(firstOverlayFocusableElement);
firstOverlayFocusableElement.focus();
}
}, [overlayRef, previousFocusedElement]);

const hideFocusableElements = useCallback(() => {
const focusableElements = Array.from(document.getElementById("step-card")?.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
) || []);

focusableElements.forEach((el) => {
(el as HTMLElement).setAttribute('tabindex', '-1');
});
}, []);

useEffect(() => {
const currentOverlayRef = overlayRef.current;
if (currentOverlayRef && overlayChildren) {
currentOverlayRef.addEventListener('focus', handleOverlayFocus);
hideFocusableElements();
}
return () => {
currentOverlayRef?.removeEventListener('focus', handleOverlayFocus);
};
}, [overlayChildren, overlayRef, handleOverlayFocus, hideFocusableElements]);

return (
<OuterStepCard {...otherProps}>
{multipartBadge}
<InnerStepCard className={className}>
{questionNumber && isHomework && stepType === 'exercise' &&
<StepCardHeader className="step-card-header">
<div>
{leftHeaderChildren}
<h2 className="question-info">
{headerTitleChildren}
<span>{formattedQuestionNumber}</span>
{showTotalQuestions ? <span className="num-questions">&nbsp;/ {numberOfQuestions}</span> : null}
<span className="separator">|</span>
<span className="question-id">ID: {questionId}</span>
</h2>
</div>
{availablePoints || rightHeaderChildren ? <div>
{availablePoints && <div className="points">{availablePoints} Points</div>}
{rightHeaderChildren}
</div> : null}
</StepCardHeader>
}
<StepCardQuestion unpadded={unpadded}>{children}</StepCardQuestion>
<div
ref={overlayRef}
{
...(overlayChildren
? {
onMouseOver: () => setShowOverlay(true),
onMouseLeave: () => setShowOverlay(false),
onBlur: handleOverlayBlur,
tabIndex: 0,
}
: {})
}
>
{(overlayChildren && showOverlay) &&
<StyledOverlay id="overlay-element">
{overlayChildren}
</StyledOverlay>
}
<div id="step-card">
{questionNumber && isHomework && stepType === 'exercise' &&
<StepCardHeader className="step-card-header">
<div>
{leftHeaderChildren}
<h2 className="question-info">
{headerTitleChildren}
<span>{formattedQuestionNumber}</span>
{showTotalQuestions ? <span className="num-questions">&nbsp;/ {numberOfQuestions}</span> : null}
<span className="separator">|</span>
<span className="question-id">ID: {questionId}</span>
</h2>
</div>
{availablePoints || rightHeaderChildren ? <div>
{availablePoints && <div className="points">{availablePoints} Points</div>}
{rightHeaderChildren}
</div> : null}
</StepCardHeader>
}
<StepCardQuestion unpadded={unpadded}>{children}</StepCardQuestion>
</div>
</div>
</InnerStepCard>
</OuterStepCard>
)
Expand All @@ -267,9 +352,11 @@ StepCard.displayName = 'OSStepCard';
export interface TaskStepCardProps extends SharedProps {
className?: string;
children?: ReactNode;
tabIndex?: number;
step: StepBase | StepWithData;
questionNumber: number;
numberOfQuestions: number;
overlayChildren?: React.ReactNode;
}

const TaskStepCard = ({
Expand All @@ -278,6 +365,7 @@ const TaskStepCard = ({
numberOfQuestions,
children,
className,
overlayChildren,
...otherProps
}: TaskStepCardProps) =>
(<StepCard {...otherProps}
Expand All @@ -291,6 +379,7 @@ const TaskStepCard = ({
// availablePoints={step.available_points}
className={cn(`${('type' in step ? step.type : 'exercise')}-step`, className)}
questionId={step.uid}
overlayChildren={overlayChildren}
>
{children}
</StepCard>);
Expand Down
80 changes: 79 additions & 1 deletion src/components/Exercise.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Exercise, ExerciseWithStepDataProps, ExerciseWithQuestionStatesProps } from './Exercise';
import { Exercise, ExerciseWithStepDataProps, ExerciseWithQuestionStatesProps, OverlayProps } from './Exercise';
import renderer from 'react-test-renderer';
import React from 'react';

Expand Down Expand Up @@ -299,4 +299,82 @@ describe('Exercise', () => {
expect(tree.toJSON()).toMatchSnapshot();
});
});

describe('with overlay rendering', () => {

let props: ExerciseWithStepDataProps & OverlayProps;

beforeEach(() => {
props = {
overlayChildren: <span>Overlay</span>,
exercise: {
uid: '1@1',
uuid: 'e4e27897-4abc-40d3-8565-5def31795edc',
group_uuid: '20e82bf6-232e-40c8-ba68-2d22c6498f69',
number: 1,
version: 1,
published_at: '2022-09-06T20:32:21.981Z',
context: 'Context',
stimulus_html: '<b>Stimulus HTML</b>',
tags: [],
authors: [{ user_id: 1, name: 'OpenStax' }],
copyright_holders: [{ user_id: 1, name: 'OpenStax' }],
derived_from: [],
is_vocab: false,
solutions_are_public: false,
versions: [1],
questions: [{
id: '1234@5',
collaborator_solutions: [],
formats: ['true-false'],
stimulus_html: '',
stem_html: '',
is_answer_order_important: false,
answers: [{
id: '1',
correctness: undefined,
content_html: 'True',
}, {
id: '2',
correctness: undefined,
content_html: 'False',
}],
}],
},
questionNumber: 1,
hasMultipleAttempts: false,
onAnswerChange: () => null,
onAnswerSave: () => null,
onNextStep: () => null,
canAnswer: false,
needsSaved: false,
apiIsPending: false,
canUpdateCurrentStep: false,
step: {
uid: '1234@4',
id: 1,
available_points: '1.0',
is_completed: false,
answer_id_order: ['1', '2'],
answer_id: '1',
free_response: '',
feedback_html: '',
correct_answer_id: '',
correct_answer_feedback_html: '',
is_feedback_available: true,
attempts_remaining: 0,
attempt_number: 1,
incorrectAnswerId: 0
},
numberOfQuestions: 1
}
});

it('matches snapshot', () => {
const tree = renderer.create(
<Exercise {...props} show_all_feedback />
).toJSON();
expect(tree).toMatchSnapshot();
});
});
});
Loading
Loading