Skip to content
Open
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
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"i18next-browser-languagedetector": "^8.2.0",
"i18next-http-backend": "^3.0.2",
"luxon": "^3.7.2",
"markdown-to-jsx": "^9.3.3",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-grid-layout": "^1.5.2",
Expand Down Expand Up @@ -90,8 +91,8 @@
"start": "vite",
"build": "vite build",
"serve": "vite preview",
"test": "LANG=de_de jest",
"test:coverage": "LANG=de_de jest --coverage --collectCoverageFrom='!src/pages/**/*.tsx'",
"test": "LANG=de_de jest --testTimeout=15000",
"test:coverage": "LANG=de_de jest --coverage --collectCoverageFrom='!src/pages/**/*.tsx' --testTimeout=15000",
"i18n": "i18next",
"lint": "eslint src",
"lint:quiet": "eslint --quiet src",
Expand All @@ -113,7 +114,8 @@
"moduleNameMapper": {
"^axios$": "<rootDir>/node_modules/axios/dist/node/axios.cjs",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"^react-markdown$": "<rootDir>/__mocks__/react-markdown.js"
},
"preset": "ts-jest",
"testEnvironment": "jest-environment-jsdom",
Expand All @@ -125,4 +127,4 @@
]
},
"packageManager": "npm@10.5.0"
}
}
84 changes: 84 additions & 0 deletions src/components/Common/forms/MarkdownEditor.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { MarkdownEditor } from './MarkdownEditor';
import '@testing-library/jest-dom';

describe('MarkdownEditor', () => {
const mockChange = jest.fn();

it('renders in Write mode by default', () => {
render(<MarkdownEditor value="Test content" onChange={mockChange} />);
// Check for the textarea
expect(screen.getByRole('textbox')).toBeInTheDocument();
// Check content exists inside textbox
expect(screen.getByDisplayValue('Test content')).toBeInTheDocument();
});

it('calls onChange when typing', () => {
render(<MarkdownEditor value="" onChange={mockChange} />);
const input = screen.getByRole('textbox');
fireEvent.change(input, { target: { value: 'New text' } });
expect(mockChange).toHaveBeenCalledWith('New text');
});

it('toggles to preview mode and renders basic formatting', () => {
const markdown = "This is **bold** and *italic*";
render(<MarkdownEditor value={markdown} onChange={mockChange} />);

// Switch to Preview
fireEvent.click(screen.getByText('Preview'));

// Check that bold and italic tags are rendered
// Note: markdown-to-jsx might use <strong> or <b>, check your overrides.
// We overrode 'strong' to 'strong', so we look for that.
const boldElement = screen.getByText('bold');
expect(boldElement.tagName).toBe('STRONG');

const italicElement = screen.getByText('italic');
expect(italicElement.tagName).toBe('EM');
});

it('blocks Heading tags (h1-h6) and renders them as plain text/paragraphs', () => {
// We provide a # Heading.
// Expected result: Text "Forbidden Heading" is visible, but NOT inside an <h1> tag.
render(<MarkdownEditor value="# Forbidden Heading" onChange={mockChange} />);

fireEvent.click(screen.getByText('Preview'));

// 1. The text should still be readable
expect(screen.getByText('Forbidden Heading')).toBeInTheDocument();

// 2. But there should be NO heading role in the document
const heading = screen.queryByRole('heading', { level: 1 });
expect(heading).toBeNull();
});

it('blocks Link tags (a) and renders plain text', () => {
const markdown = "[Malicious Link](http://evil.com)";
render(<MarkdownEditor value={markdown} onChange={mockChange} />);

fireEvent.click(screen.getByText('Preview'));

// 1. The text anchor should be visible
expect(screen.getByText('Malicious Link')).toBeInTheDocument();

// 2. But it should NOT be a link (no anchor tag)
const link = screen.queryByRole('link');
expect(link).toBeNull();

// 3. Ensure the href is not present in the DOM (security check)
const textElement = screen.getByText('Malicious Link');
expect(textElement).not.toHaveAttribute('href');
});

it('blocks Images', () => {
// Image syntax: ![alt text](url)
render(<MarkdownEditor value="![Hidden Image](image.png)" onChange={mockChange} />);

fireEvent.click(screen.getByText('Preview'));

// Ensure the image tag is not rendered
const img = screen.queryByRole('img');
expect(img).toBeNull();
});
});
113 changes: 113 additions & 0 deletions src/components/Common/forms/MarkdownEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import React, { useState } from 'react';
import Markdown, { MarkdownToJSX } from 'markdown-to-jsx';
import { Box, Button, TextField, Typography, Paper, ButtonGroup } from '@mui/material';

const StripElement = ({ children }: { children: React.ReactNode }) => <span>{children}</span>;

const StripBlock = ({ children }: { children: React.ReactNode }) => (
<Typography variant="body1" component="div" sx={{ mb: 1.5 }}>
{children}
</Typography>
);

const MarkdownOptions: MarkdownToJSX.Options = {
overrides: {
p: {
component: Typography,
props: { variant: 'body1', sx: { mb: 1.5 } }
},

// Allowed inline/list tags
strong: { component: 'strong' },
b: { component: 'b' },
em: { component: 'em' },
i: { component: 'i' },
ul: { component: 'ul', props: { style: { paddingLeft: '20px', margin: '0 0 16px 0' } } },
ol: { component: 'ol', props: { style: { paddingLeft: '20px', margin: '0 0 16px 0' } } }, li: { component: 'li' },

// Block links and headings by mapping them to plan spans.
a: { component: StripElement },

// --- BLOCKED TAGS (No headings allowed) ---
h1: { component: StripBlock },
h2: { component: StripBlock },
h3: { component: StripBlock },
h4: { component: StripBlock },
h5: { component: StripBlock },
h6: { component: StripBlock }, // Tables, images, etc. are naturally ignored by markdown-to-jsx if not explicitly defined

img: { component: () => null },

table: { component: 'div' },
},
};

interface MarkdownEditorProps {
value: string;
onChange: (value: string) => void;
label?: string;
error?: boolean;
helperText?: string;
}

export const MarkdownEditor: React.FC<MarkdownEditorProps> = ({
value,
onChange,
label = "Description",
error,
helperText
}) => {
const [isPreview, setIsPreview] = useState(false);

return (
<Box mb={2}>
<Box display="flex" justifyContent="space-between" alignItems="center" mb={1}>
<Typography variant="subtitle2" color={error ? 'error' : 'textSecondary'}>
{label}
</Typography>
<ButtonGroup size="small" variant="outlined">
<Button
variant={!isPreview ? 'contained' : 'outlined'}
onClick={() => setIsPreview(false)}
>
Write
</Button>
<Button
variant={isPreview ? 'contained' : 'outlined'}
onClick={() => setIsPreview(true)}
>
Preview
</Button>
</ButtonGroup>
</Box>

{isPreview ? (
<Paper
variant="outlined"
sx={{
p: 2,
minHeight: '100px',
borderColor: error ? 'error.main' : undefined,
backgroundColor: 'background.default'
}}
>
{/* The library handles the parsing based on our secure options */}
<Markdown options={MarkdownOptions}>
{value || '*No content*'}
</Markdown>
</Paper>
) : (
<TextField
fullWidth
multiline
minRows={4}
value={value}
onChange={(e) => onChange(e.target.value)}
error={error}
helperText={helperText}
placeholder="Use Markdown: *italic*, **bold**, - list"
/>
)}
</Box>
);
};
69 changes: 38 additions & 31 deletions src/components/Exercises/Add/Step3Description.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ import Grid from '@mui/material/Grid';
import { useLanguageCheckQuery } from "components/Core/queries";
import { StepProps } from "components/Exercises/Add/AddExerciseStepper";
import { PaddingBox } from "components/Exercises/Detail/ExerciseDetails";
import { ExerciseDescription } from "components/Exercises/forms/ExerciseDescription";
import { MarkdownEditor } from "components/Common/forms/MarkdownEditor";
import { ExerciseNotes } from "components/Exercises/forms/ExerciseNotes";
import { descriptionValidator, noteValidator } from "components/Exercises/forms/yupValidators";
import { Form, Formik } from "formik";
import React from "react";
import { useTranslation } from "react-i18next";
import { useExerciseSubmissionStateValue } from "state";
import { setDescriptionEn, setNotesEn } from "state/exerciseSubmissionReducer";
Expand Down Expand Up @@ -59,38 +58,46 @@ export const Step3Description = ({ onContinue, onBack }: StepProps) => {

}}
>
<Form>
<Stack>
<ExerciseDescription fieldName={"description"} />
{({ values, errors, touched, setFieldValue }) => (
<Form>
<Stack>
<MarkdownEditor
label={t('exercises.description')}
value={values.description}
onChange={(val) => setFieldValue('description', val)}
error={touched.description && Boolean(errors.description)}
helperText={touched.description ? errors.description : undefined}
/>

<PaddingBox />
<PaddingBox />

<ExerciseNotes fieldName={'notes'} />
<ExerciseNotes fieldName={'notes'} />

<Grid container>
<Grid display="flex" justifyContent={"end"} size={12}>
<Box sx={{ mb: 2 }}>
<div>
<Button
onClick={onBack}
sx={{ mt: 1, mr: 1 }}
>
{t('goBack')}
</Button>
<Button
variant="contained"
type="submit"
disabled={languageCheckQuery.isPending}
sx={{ mt: 1, mr: 1 }}
>
{t('continue')}
</Button>
</div>
</Box>
<Grid container>
<Grid display="flex" justifyContent={"end"} size={12}>
<Box sx={{ mb: 2 }}>
<div>
<Button
onClick={onBack}
sx={{ mt: 1, mr: 1 }}
>
{t('goBack')}
</Button>
<Button
variant="contained"
type="submit"
disabled={languageCheckQuery.isPending}
sx={{ mt: 1, mr: 1 }}
>
{t('continue')}
</Button>
</div>
</Box>
</Grid>
</Grid>
</Grid>
</Stack>
</Form>
</Stack>
</Form>
)}
</Formik>)
);
};
};
3 changes: 2 additions & 1 deletion src/components/Exercises/Detail/ExerciseDetailEdit.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ describe("Exercise translation edit tests", () => {
id: 9,
languageId: 1,
author: "",
description: "Die Kniebeuge ist eine Übung zur Kräftigung der Oberschenkelmuskulatur",
description: "",
descriptionSource: "Die Kniebeuge ist eine Übung zur Kräftigung der Oberschenkelmuskulatur",
name: "Mangalitza"
});
});
Expand Down
Loading