import { route } from 'preact-router' import { useContext, useEffect, useState } from 'preact/hooks' import { isAdministrator, Problem as ProblemModel, Solution as SolutionModel } from '../../shared/model' import { prependBaseUrl, server } from '../api' import { Header } from '../components/Header' import { MarkdownEditor } from '../components/MarkdownEditor' import { Problem } from '../components/Problem' import { Solution } from '../components/Solution' import { MetadataContext, useListResource, useResource } from '../hooks' import { useCurrentUser } from '../hooks/useCurrentUser' type RouteProps = { id: string } export const ProblemPage = ({ id }: RouteProps) => { const metadata = useContext(MetadataContext) metadata.title = `Problem ${id}` metadata.description = 'Bacheca di problemi del PHC' const [user] = useCurrentUser() const [source, setSource] = useState('') const [problem, refreshProblem] = useResource(`/api/problem/${id}`, null, problem => { if (problem === null) { route(prependBaseUrl('/')) } }) const [solutions, refreshSolutions, setSolutionHeuristic] = useListResource(`/api/solutions?problem=${id}`) const userSolutions: [number, SolutionModel][] = solutions.flatMap((s, index) => (user && s.sentBy === user.id ? [[index, s]] : [])) const otherSolutions: [number, SolutionModel][] = solutions.flatMap((s, index) => (user && s.sentBy !== user.id ? [[index, s]] : [])) const notLoggedSolutions: [number, SolutionModel][] = user ? [] : solutions.map((s, index) => [index, s]) const sendSolution = async () => { if (source.trim().length === 0) { alert('La soluzione che hai inserito è vuota!') return } await server.post('/api/solution', { forProblem: id, content: source, }) setSource('') refreshSolutions() } const [editing, setEditing] = useState(false) const [modifiedProblemSource, setModifiedProblemSource] = useState('') useEffect(() => { if (problem) { setModifiedProblemSource(problem.content) } }, [problem?.content]) const updateProblem = async () => { await server.patch(`/api/problem/${id}`, { content: modifiedProblemSource, }) refreshProblem() setEditing(false) } const deleteProblem = async () => { if (confirm('Sei veramente sicuro di voler eliminare questo problema?')) { await server.delete(`/api/problem/${id}`) route(prependBaseUrl('/')) } } return ( <>
Testo del problema
{!editing ? ( <> {problem && } {user && isAdministrator(user.role) && ( <> )} ) : ( <>
)} {userSolutions.length > 0 && (
Le tue soluzioni
{userSolutions.map(([index, s]) => ( setSolutionHeuristic(index, solFn)} /> ))}
)} {otherSolutions.length > 0 && (
Altre soluzioni
{otherSolutions.map(([index, s]) => ( setSolutionHeuristic(index, solFn)} /> ))}
)} {notLoggedSolutions.length > 0 && (
Soluzioni
{notLoggedSolutions.map(([index, s]) => ( setSolutionHeuristic(index, solFn)} /> ))}
)} {user && ( <>
Invia una soluzione al problema

warning Attenzione, una soluzione inviata non può essere modificata!

)}
) }