Restructuration

This commit is contained in:
2024-06-17 18:40:26 +02:00
parent b46a58101b
commit 1844354164
5 changed files with 599 additions and 554 deletions

View File

@ -0,0 +1,374 @@
import {trierCandidats, regrouperVoix} from "../utils"
import TableContainer from "@mui/material/TableContainer"
import Paper from "@mui/material/Paper"
import Table from "@mui/material/Table"
import TableHead from "@mui/material/TableHead"
import TableRow from "@mui/material/TableRow"
import TableCell from "@mui/material/TableCell"
import TableBody from "@mui/material/TableBody"
import {useEffect, useMemo, useState} from "react"
import {GeoJSON, MapContainer, Popup, TileLayer, useMap} from "react-leaflet"
import bbox from "geojson-bbox"
import {FormControl, InputLabel, MenuItem, Select} from "@mui/material"
import * as Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";
import Switch from "@mui/material/Switch";
import FormControlLabel from "@mui/material/FormControlLabel";
export function HistogrammeVoix({titre, resultats, voixParNuance, voixParBloc, blocs, nuances, grouperParBloc}) {
const [categoriesVoix, dataVoix] = useMemo(() => {
const categories = []
const data = []
if (grouperParBloc) {
for (let bloc of blocs) {
categories.push(bloc.nom)
data.push([bloc.nom, voixParBloc[bloc.nom], bloc.couleur, bloc.nom])
}
}
else {
for (let nuance of nuances) {
categories.push(nuance.nom)
data.push([nuance.nom, voixParNuance[nuance.code], nuance.couleur, nuance.nom])
}
}
return [categories, data]
}, [voixParBloc, voixParNuance, blocs, nuances, grouperParBloc])
const scoreOptions = {
chart: {
type: 'column'
},
title: {
text: titre,
},
tooltip: {
formatter: function () {
return `<span>${this.x}</span> : <strong>${this.y}</strong> voix (${(100 * this.y / resultats.exprimes).toFixed(2)} %)<br>`
}
},
xAxis: {
categories: categoriesVoix,
},
series: [{
name: "Nombre de voix",
keys: ['name', 'y', 'color', 'label'],
data: dataVoix,
}]
}
return <HighchartsReact
highcharts={Highcharts}
options={scoreOptions}
/>
}
export function CompositionHemicycle({titre, blocs, nuances, siegesParBloc, siegesParNuance, grouperParBloc}) {
const dataSieges = useMemo(() => {
const data = []
if (grouperParBloc) {
for (let bloc of blocs) {
data.push([bloc.nom, siegesParBloc[bloc.nom], bloc.couleur, bloc.nom])
}
}
else {
for (let nuance of nuances) {
data.push([nuance.nom, siegesParNuance[nuance.code], nuance.couleur, nuance.nom])
}
}
return data
}, [blocs, nuances, siegesParBloc, siegesParNuance, grouperParBloc])
const compositonOptions = {
chart: {
type: 'item'
},
title: {
text: titre,
},
legend: {
labelFormat: '{name} <span style="opacity: 0.4">{y}</span>'
},
series: [{
name: 'Nombre de sièges',
keys: ['name', 'y', 'color', 'label'],
data: dataSieges,
dataLabels: {
enabled: false,
format: '{point.label}'
},
// Circular options
center: ['50%', '88%'],
size: '170%',
startAngle: -100,
endAngle: 100
}]
}
return <HighchartsReact
highcharts={Highcharts}
options={compositonOptions}
/>
}
/**
* Tableau de participation de l'élection dans la zone concernée
* @param resultats
* @return {JSX.Element}
* @constructor
*/
export function TableauParticipation({resultats}) {
return <>
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell></TableCell>
<TableCell>Nombre</TableCell>
<TableCell>% Inscrites</TableCell>
<TableCell>% Votantes</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow key={"Inscrit⋅es"}>
<TableCell>Inscrites</TableCell>
<TableCell>{resultats.inscrits}</TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
<TableRow key={"Abstentions"}>
<TableCell>Abstention</TableCell>
<TableCell>{resultats.abstentions}</TableCell>
<TableCell>{(100 * resultats.abstentions / resultats.inscrits).toFixed(2)} %</TableCell>
<TableCell></TableCell>
</TableRow>
<TableRow key={"Votant⋅es"}>
<TableCell>Votantes</TableCell>
<TableCell>{resultats.votants}</TableCell>
<TableCell>{(100 * resultats.votants / resultats.inscrits).toFixed(2)} %</TableCell>
<TableCell></TableCell>
</TableRow>
<TableRow key={"Blancs"}>
<TableCell>Blancs</TableCell>
<TableCell>{resultats.blancs}</TableCell>
<TableCell>{(100 * resultats.blancs / resultats.inscrits).toFixed(2)} %</TableCell>
<TableCell>{(100 * resultats.blancs / resultats.votants).toFixed(2)} %</TableCell>
</TableRow>
<TableRow key={"Nuls"}>
<TableCell>Nuls</TableCell>
<TableCell>{resultats.nuls}</TableCell>
<TableCell>{(100 * resultats.nuls / resultats.inscrits).toFixed(2)} %</TableCell>
<TableCell>{(100 * resultats.nuls / resultats.votants).toFixed(2)} %</TableCell>
</TableRow>
<TableRow key={"Exprimés"}>
<TableCell>Exprimés</TableCell>
<TableCell>{resultats.exprimes}</TableCell>
<TableCell>{(100 * resultats.exprimes / resultats.inscrits).toFixed(2)} %</TableCell>
<TableCell>{(100 * resultats.exprimes / resultats.votants).toFixed(2)} %</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
</>
}
export function GroupementParBloc({grouperParBloc, setGrouperParBloc}) {
return <FormControlLabel control={<Switch checked={grouperParBloc} onChange={event => setGrouperParBloc(event.target.checked)} inputProps={{ 'aria-label': 'controlled' }} />}
label="Grouper par bloc plutôt que nuance politique" />
}
export function RetirerSeuil({retirerSeuil, setRetirerSeuil}) {
return <FormControlLabel control={<Switch checked={retirerSeuil} onChange={event => setRetirerSeuil(event.target.checked)} inputProps={{ 'aria-label': 'controlled' }} />}
label="Retirer le seuil des 5 %" />
}
export function SelectionAffichage({typeResultats, typeZone, setTypeZone}) {
const items = useMemo(() => {
const items = []
if (typeResultats === "france") {
setTypeZone("region")
items.push(<MenuItem value="region">Région</MenuItem>)
}
if (typeResultats === "france" || typeResultats === "region") {
if (typeResultats !== "france")
setTypeZone("departement")
items.push(<MenuItem value="departement">Département</MenuItem>)
}
if (typeResultats === "france" || typeResultats === "region" || typeResultats === "departement") {
if (typeResultats !== "france" && typeResultats !== "region")
setTypeZone("circonscription")
items.push(<MenuItem value="circonscription">Circonscription</MenuItem>)
}
if (typeResultats === "departement") {
items.push(<MenuItem value="commune">Communes</MenuItem>)
}
if (typeResultats === "circonscription" || typeResultats === "commune" || typeResultats === "bureau_vote") {
setTypeZone("bureau_vote")
items.push(<MenuItem value="bureau_vote">Bureau de vote</MenuItem>)
}
return items
}, [typeResultats, setTypeZone])
return <FormControl>
<InputLabel>
Zone à afficher
</InputLabel>
<Select value={typeZone}
onChange={event => setTypeZone(event.target.value)}
label="Zone à afficher">
{items}
</Select>
</FormControl>
}
function ZoneGeoJSON({typeElection, anneeElection, resultatsZone, typeZone,
candidats, blocs, nuances, grouperParBloc = false}) {
const [idZone, nomZone] = useMemo(() => {
if (!resultatsZone[typeZone])
return ["", ""]
if (typeZone === "region" || typeZone === "departement" || typeZone === "commune")
return [resultatsZone[typeZone].code_insee, resultatsZone[typeZone].nom]
else if (typeZone === "circonscription")
return [resultatsZone.circonscription.id, `Circonscription ${resultatsZone.circonscription.id}`]
else if (typeZone === "bureau_vote")
return [resultatsZone.bureau_vote.id, resultatsZone.bureau_vote.libelle]
else
return ["", ""]
}, [typeZone, resultatsZone])
const voixCandidats = useMemo(() => resultatsZone?.voix ?? {}, [resultatsZone])
const candidatsTries = trierCandidats(candidats, voixCandidats)
const [voixParBloc, voixParNuance] = regrouperVoix(voixCandidats, candidats, blocs, nuances)
let couleur = 'grey'
if (grouperParBloc) {
let maxVoix = 0
for (let bloc of blocs) {
if (voixParBloc[bloc.nom] > maxVoix) {
maxVoix = voixParBloc[bloc.nom]
couleur = bloc.couleur
}
}
}
else {
let maxVoix = 0
for (let nuance of nuances) {
if (voixParNuance[nuance.code] > maxVoix) {
maxVoix = voixParNuance[nuance.code]
couleur = nuance.couleur
}
}
}
return <GeoJSON
data={{'type': "Feature", 'geometry': resultatsZone.geometry}}
style={{fillColor: couleur, fillOpacity: 0.5, color: 'white', weight: 1}}>
<Popup>
<strong><a href={`/elections/${typeElection}/${anneeElection}/${typeZone}/${idZone}/`}>{nomZone}</a></strong>
<ul>
{candidatsTries.slice(0, 5).map(candidat =>
<li key={candidat.numero}>
{candidat.nom} : {voixCandidats[candidat.numero]} ({(100 * voixCandidats[candidat.numero] / resultatsZone.exprimes).toFixed(2)} %)
</li>)}
</ul>
</Popup>
</GeoJSON>
}
function ContenuCarte({typeElection, anneeElection, typeResultats, resultats,
typeZone, candidats, blocs, nuances, grouperParBloc = false}) {
const map = useMap()
const [resultatsZones, setResultatsZones] = useState([])
const zones = useMemo(() => {
const data = resultats[typeResultats]
if (!data)
return []
if (typeZone === "region")
return data?.regions ?? []
else if (typeZone === "departement")
return data?.departements ?? []
else if (typeZone === "circonscription")
return data?.circonscriptions ?? []
else if (typeZone === "commune")
return data?.communes ?? []
else if (typeZone === "bureau_vote") {
if (typeResultats === "bureau_vote")
return data ? [data.id] : []
else
return data?.bureaux_vote ?? []
}
else
return []
}, [typeResultats, resultats, typeZone])
useEffect(() => {
if (typeResultats === "france")
return
const geometry = resultats.geometry
if (geometry) {
// On centre la carte sur la zone
const geometry_bbox = bbox(geometry)
map.fitBounds([[geometry_bbox[1], geometry_bbox[0]], [geometry_bbox[3], geometry_bbox[2]]])
}
}, [typeResultats, resultats, map])
useEffect(() => {
if (!zones)
return
setResultatsZones(resultatsZones => [])
zones.forEach(zoneId => {
fetch(`/data/resultats/${typeElection}/${anneeElection}/${typeZone}/${zoneId}.json`)
.then(response => response.json())
.then(resultatsZone => setResultatsZones(resultatsZones => [...resultatsZones, resultatsZone]))
})
}, [typeElection, anneeElection, typeZone, zones, resultats])
function getZoneIdentifier(typeZone, zone) {
if (typeZone === "region" || typeZone === "departement" || typeZone === "commune")
return zone.code_insee
else if (typeZone === "circonscription" || typeZone === "bureau_vote")
return zone.id
else
return ""
}
return <>
{resultatsZones.filter(resultatsZone => resultatsZone.geometry['type']).map(resultatsZone =>
<ZoneGeoJSON key={getZoneIdentifier(resultatsZone[typeZone])}
typeElection={typeElection} anneeElection={anneeElection}
resultatsZone={resultatsZone} typeZone={typeZone} candidats={candidats}
blocs={blocs} nuances={nuances} grouperParBloc={grouperParBloc}/>)}
</>
}
export function CarteResultats({typeElection, anneeElection, typeResultats, resultats,
typeZone, candidats, blocs, nuances, grouperParBloc = false}) {
const center = typeResultats === "france" ? [46.603354, 1.888334] : [0, 0]
return <>
<MapContainer center={center} zoom={6} style={{height: "90vh"}}>
<TileLayer
attribution='&copy; Les contributeur⋅rices <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<ContenuCarte typeElection={typeElection} anneeElection={anneeElection} typeResultats={typeResultats}
resultats={resultats} typeZone={typeZone} candidats={candidats}
blocs={blocs} nuances={nuances} grouperParBloc={grouperParBloc} />
</MapContainer>
</>
}