Spaces:
Running

pic4 / index.html
masterseb's picture
après un enregistrement proposer une nouvelle semaine - Follow Up Deployment
cd0f9e3 verified
Raw History Blame Contribute Delete
32.4 kB
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Classement des sous-catégories PIC</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
.block {
transition: all 0.3s ease;
cursor: grab;
}
.block:active {
cursor: grabbing;
}
.block.dragging {
opacity: 0.5;
transform: scale(1.02);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}
.placeholder {
border: 2px dashed #6366f1;
background-color: #e0e7ff;
height: 60px;
opacity: 0.8;
}
.block.selected {
background-color: #e0e7ff;
border: 1px solid #6366f1;
}
</style>
</head>
<body class="bg-gray-50 min-h-screen">
<div class="container mx-auto px-4 py-8">
<h1 class="text-3xl font-bold text-center text-indigo-700 mb-2">Classement des sous-catégories PIC</h1>
<p class="text-center text-gray-600 mb-8">Empilez les blocs pour créer votre classement hebdomadaire</p>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
<!-- Zone de classement -->
<div class="bg-white p-6 rounded-lg shadow-md">
<h2 class="text-xl font-semibold text-indigo-600 mb-4">Votre classement</h2>
<div class="flex justify-between mb-4">
<div class="flex items-center space-x-2">
<span class="text-sm font-medium text-gray-500">Semaine :</span>
<select id="week-selector" class="border rounded px-2 py-1 text-sm">
<!-- Options seront ajoutées dynamiquement -->
</select>
</div>
<div class="flex space-x-2">
<button id="save-btn" class="bg-indigo-600 text-white px-4 py-1 rounded text-sm hover:bg-indigo-700 transition cursor-pointer">
Enregistrer
</button>
<button id="reset-btn" class="bg-red-600 text-white px-4 py-1 rounded text-sm hover:bg-red-700 transition">
Réinitialiser
</button>
</div>
</div>
<div id="ranking-container" class="space-y-2 mb-4">
<!-- Les blocs seront ajoutés ici dynamiquement -->
</div>
<div id="placeholder" class="placeholder rounded flex items-center justify-center hidden">
<span class="text-gray-500">Déposez ici pour ajouter</span>
</div>
</div>
<!-- Graphique d'évolution -->
<div class="bg-white p-6 rounded-lg shadow-md">
<h2 class="text-xl font-semibold text-indigo-600 mb-4">Synthèse des classements</h2>
<div id="ranking-chart-container" class="flex flex-col gap-4">
<canvas id="ranking-chart"></canvas>
<div class="text-sm text-gray-500">
<p>Tendance par rapport à la semaine précédente (↑ = amélioration, ↓ = baisse, → = stable)</p>
</div>
</div>
<!-- Nouveau graphique d'importance globale -->
<h2 class="text-xl font-semibold text-indigo-600 mb-4 mt-8">Classement d'importance global</h2>
<div class="h-64">
<canvas id="importance-chart"></canvas>
</div>
<div class="mt-4 text-sm text-gray-500">
<p>Ce graphique montre le classement moyen de chaque catégorie sur toutes les semaines.</p>
</div>
<!-- Boutons d'export/import déplacés ici -->
<div class="flex justify-center space-x-4 mt-6">
<button id="export-btn" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 transition">
Exporter données
</button>
<button id="import-btn" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition">
Importer données
</button>
</div>
</div>
</div>
</div>
<!-- Modal de confirmation -->
<div id="save-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
<div class="bg-white rounded-lg p-6 max-w-sm w-full">
<h3 class="text-xl font-semibold text-indigo-700 mb-4">Enregistrement réussi</h3>
<p class="text-gray-600 mb-6">Votre classement pour la semaine {state.currentWeek - 1} a été enregistré avec succès. La semaine {state.currentWeek} est maintenant disponible.</p>
<div class="flex justify-end">
<button id="modal-ok-btn" class="bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700 transition">
OK
</button>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Catégories PIC
const categories = [
'Primo-info',
'Conseil',
'Protection contre la discrimination',
'Langue',
'Petite enfance',
'Employabilité',
'Interprétariat',
'Vivre-ensemble'
];
// État de l'application
let state = {
currentWeek: 1,
rankings: {},
draggedItem: null
};
// Éléments DOM
const rankingContainer = document.getElementById('ranking-container');
const placeholder = document.getElementById('placeholder');
const weekSelector = document.getElementById('week-selector');
const saveBtn = document.getElementById('save-btn');
const chartCtx = document.getElementById('ranking-chart').getContext('2d');
const importanceCtx = document.getElementById('importance-chart').getContext('2d');
let rankingChart = null;
let importanceChart = null;
// Initialisation
init();
function initImportanceChart() {
const weeks = Object.keys(state.rankings).sort((a, b) => a - b);
const categoryScores = {};
// Calculer le score moyen pour chaque catégorie
categories.forEach(category => {
let totalScore = 0;
let count = 0;
weeks.forEach(week => {
const ranking = state.rankings[week];
const position = ranking.indexOf(category) + 1;
totalScore += position;
count++;
});
categoryScores[category] = totalScore / count;
});
// Trier les catégories par score moyen (le plus bas en premier)
const sortedCategories = [...categories].sort((a, b) => categoryScores[a] - categoryScores[b]);
const sortedScores = sortedCategories.map(cat => categoryScores[cat]);
if (importanceChart) {
importanceChart.destroy();
}
importanceChart = new Chart(importanceCtx, {
type: 'bar',
data: {
labels: sortedCategories,
datasets: [{
label: 'Score moyen (plus bas = mieux)',
data: sortedScores,
backgroundColor: '#6366f1',
borderColor: '#4f46e5',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: 'y',
scales: {
x: {
beginAtZero: true,
title: {
display: true,
text: 'Position moyenne'
}
}
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
return `Position moyenne: ${context.raw.toFixed(2)}`;
}
}
}
}
}
});
}
function init() {
// Charger les données depuis le localStorage
loadData();
// Initialiser le sélecteur de semaine
initWeekSelector();
// Afficher les blocs pour la semaine courante
renderBlocks();
// Initialiser les graphiques
initCharts();
// Écouteurs d'événements
setupEventListeners();
}
function loadData() {
const savedData = localStorage.getItem('picRankings');
if (savedData) {
state.rankings = JSON.parse(savedData);
// Trouver la dernière semaine enregistrée
const weeks = Object.keys(state.rankings).map(Number);
if (weeks.length > 0) {
state.currentWeek = Math.max(...weeks);
}
} else {
// Premier chargement - initialiser avec la semaine 1
state.rankings = {
1: [...categories]
};
}
}
function saveData() {
localStorage.setItem('picRankings', JSON.stringify(state.rankings));
}
function initWeekSelector() {
weekSelector.innerHTML = '';
const weeks = Object.keys(state.rankings).sort((a, b) => a - b);
if (weeks.length === 0) {
const option = document.createElement('option');
option.value = '1';
option.textContent = 'Semaine 1';
weekSelector.appendChild(option);
return;
}
weeks.forEach(week => {
const option = document.createElement('option');
option.value = week;
option.textContent = `Semaine ${week}`;
option.selected = week == state.currentWeek;
weekSelector.appendChild(option);
});
}
function renderBlocks() {
rankingContainer.innerHTML = '';
const currentRanking = state.rankings[state.currentWeek] || [...categories];
currentRanking.forEach((category, index) => {
const block = createBlock(category, index + 1);
rankingContainer.appendChild(block);
});
}
function createBlock(category, position) {
const block = document.createElement('div');
block.className = 'block bg-white border border-gray-200 rounded p-4 shadow-sm flex items-center justify-between';
block.draggable = true;
block.dataset.category = category;
// Drag events
block.addEventListener('dragstart', handleDragStart);
block.addEventListener('dragend', handleDragEnd);
block.innerHTML = `
<div class="flex items-center">
<span class="bg-indigo-100 text-indigo-800 rounded-full w-6 h-6 flex items-center justify-center text-xs font-semibold mr-3">${position}</span>
<span class="font-medium text-gray-700">${category}</span>
</div>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16" />
</svg>
`;
return block;
}
function initCharts() {
initRankingChart();
initImportanceChart();
}
function initRankingChart() {
const weeks = Object.keys(state.rankings).sort((a, b) => a - b);
if (weeks.length < 2) return; // Need at least 2 weeks to show trend
// Get current and previous week rankings
const currentWeek = Math.max(...weeks);
const prevWeek = Math.max(...weeks.filter(w => w < currentWeek));
const currentRanking = state.rankings[currentWeek];
const prevRanking = state.rankings[prevWeek];
// Calculate trend for each category
const trendData = categories.map(category => {
const currentPos = currentRanking.indexOf(category) + 1;
const prevPos = prevRanking.indexOf(category) + 1;
return {
category: category,
trend: currentPos < prevPos ? '↑' : currentPos > prevPos ? '↓' : '→'
};
});
if (rankingChart) {
rankingChart.destroy();
}
// Create custom HTML legend
const legendContainer = document.createElement('div');
legendContainer.className = 'flex flex-wrap gap-4 mt-4';
trendData.forEach(item => {
const itemEl = document.createElement('div');
itemEl.className = 'flex items-center';
const arrowColor = item.trend === '↑' ? 'text-green-500' :
item.trend === '↓' ? 'text-red-500' : 'text-gray-500';
itemEl.innerHTML = `
<span class="font-medium mr-2">${item.category}</span>
<span class="${arrowColor} font-bold">${item.trend}</span>
`;
legendContainer.appendChild(itemEl);
});
// Replace chart canvas with our legend
const chartContainer = document.getElementById('ranking-chart').parentNode;
chartContainer.innerHTML = '';
chartContainer.appendChild(legendContainer);
chartContainer.classList.remove('h-64'); // Remove fixed height
legendContainer.className = 'flex flex-col gap-2'; // Stack legend items vertically
}
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function handleDragStart(e) {
const selectedBlocks = document.querySelectorAll('.block.selected');
// If clicking on a non-selected block while others are selected, prevent drag
if (selectedBlocks.length > 0 && !this.classList.contains('selected')) {
e.preventDefault();
return;
}
// Toggle selection if not shift-clicking
if (!e.shiftKey) {
document.querySelectorAll('.block.selected').forEach(block => {
block.classList.remove('selected', 'bg-indigo-50');
});
this.classList.add('selected', 'bg-indigo-50');
}
// Get all selected blocks including this one
const currentSelected = document.querySelectorAll('.block.selected');
if (currentSelected.length > 1) {
state.draggedItems = Array.from(currentSelected);
state.draggedItems.forEach(item => {
item.classList.add('dragging');
item.style.opacity = '0.5';
});
} else {
this.classList.add('dragging');
state.draggedItem = this;
}
e.dataTransfer.effectAllowed = 'move';
placeholder.classList.remove('hidden');
}
function handleDragEnd() {
const items = state.draggedItems || [state.draggedItem];
items.forEach(item => {
if (item) {
item.classList.remove('dragging');
item.style.opacity = '';
}
});
placeholder.classList.add('hidden');
state.draggedItem = null;
state.draggedItems = null;
}
function setupEventListeners() {
// Bouton d'export
document.getElementById('export-btn').addEventListener('click', () => {
const dataStr = JSON.stringify(state.rankings, null, 2);
const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
const exportFileDefaultName = `pic-classement-export-${new Date().toISOString().slice(0,10)}.json`;
const linkElement = document.createElement('a');
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
});
// Bouton d'import
document.getElementById('import-btn').addEventListener('click', () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = e => {
const file = e.target.files[0];
const reader = new FileReader();
reader.readAsText(file,'UTF-8');
reader.onload = readerEvent => {
try {
const content = JSON.parse(readerEvent.target.result);
state.rankings = content;
saveData();
renderBlocks();
initWeekSelector();
initChart();
// Afficher un message de confirmation
const notification = document.createElement('div');
notification.className = 'fixed bottom-4 right-4 bg-green-500 text-white px-4 py-2 rounded shadow-lg';
notification.textContent = 'Données importées avec succès!';
document.body.appendChild(notification);
setTimeout(() => {
notification.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => notification.remove(), 300);
}, 2000);
} catch (err) {
alert('Erreur lors de l\'import: le fichier n\'est pas valide');
console.error(err);
}
}
}
input.click();
});
// Multi-selection avec shift+click
rankingContainer.addEventListener('click', e => {
const clickedBlock = e.target.closest('.block');
if (!clickedBlock) return;
if (e.shiftKey) {
// Shift+click: toggle selection
clickedBlock.classList.toggle('selected');
clickedBlock.classList.toggle('bg-indigo-50');
} else {
// Regular click: clear other selections and select this one
document.querySelectorAll('.block.selected').forEach(block => {
if (block !== clickedBlock) {
block.classList.remove('selected', 'bg-indigo-50');
}
});
clickedBlock.classList.add('selected', 'bg-indigo-50');
}
});
// Bouton de réinitialisation
document.getElementById('reset-btn').addEventListener('click', () => {
if (confirm('Êtes-vous sûr de vouloir réinitialiser toutes les données? Cette action est irréversible.')) {
localStorage.removeItem('picRankings');
state = {
currentWeek: 1,
rankings: {1: [...categories]},
draggedItem: null
};
renderBlocks();
initWeekSelector();
initChart();
// Afficher un message de confirmation
const notification = document.createElement('div');
notification.className = 'fixed bottom-4 right-4 bg-green-500 text-white px-4 py-2 rounded shadow-lg';
notification.textContent = 'Données réinitialisées avec succès!';
document.body.appendChild(notification);
setTimeout(() => {
notification.classList.add('opacity-0', 'transition-opacity', 'duration-300');
setTimeout(() => notification.remove(), 300);
}, 2000);
}
});
// Drag and drop
rankingContainer.addEventListener('dragstart', e => {
if (e.target.classList.contains('block')) {
state.draggedItem = e.target;
e.target.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', e.target.innerHTML);
// Afficher le placeholder
placeholder.classList.remove('hidden');
}
});
rankingContainer.addEventListener('dragend', () => {
if (state.draggedItem) {
state.draggedItem.classList.remove('dragging');
placeholder.classList.add('hidden');
state.draggedItem = null;
}
});
rankingContainer.addEventListener('dragover', e => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
if (!state.draggedItem || e.target === rankingContainer) return;
// Déterminer la position du placeholder
const afterElement = getDragAfterElement(rankingContainer, e.clientY);
if (afterElement) {
rankingContainer.insertBefore(placeholder, afterElement);
} else {
rankingContainer.appendChild(placeholder);
}
});
rankingContainer.addEventListener('drop', e => {
e.preventDefault();
if (!state.draggedItem && !state.draggedItems) return;
placeholder.classList.add('hidden');
// Get the drop position
const afterElement = getDragAfterElement(rankingContainer, e.clientY);
if (state.draggedItems) {
// Move multiple blocks while maintaining their order
const firstBlock = state.draggedItems[0];
const referenceNode = afterElement ?
(afterElement === firstBlock.nextSibling ? afterElement.nextSibling : afterElement) :
null;
// Create a temporary container to hold the blocks in order
const tempContainer = document.createElement('div');
state.draggedItems.forEach(item => {
item.classList.remove('selected', 'bg-indigo-50', 'dragging');
item.style.opacity = '';
tempContainer.appendChild(item);
});
if (afterElement) {
rankingContainer.insertBefore(tempContainer, referenceNode);
} else {
rankingContainer.appendChild(tempContainer);
}
// Move the blocks out of the temporary container
while (tempContainer.firstChild) {
if (afterElement) {
rankingContainer.insertBefore(tempContainer.firstChild, tempContainer);
} else {
rankingContainer.appendChild(tempContainer.firstChild);
}
}
tempContainer.remove();
} else {
// Move single block
state.draggedItem.classList.remove('dragging');
state.draggedItem.style.opacity = '';
if (afterElement) {
rankingContainer.insertBefore(state.draggedItem, afterElement);
} else {
rankingContainer.appendChild(state.draggedItem);
}
}
// Update the ranking
updateCurrentRanking();
});
// Sélecteur de semaine
weekSelector.addEventListener('change', e => {
const selectedWeek = parseInt(e.target.value);
state.currentWeek = selectedWeek;
renderBlocks();
initWeekSelector();
initChart();
});
// Bouton d'enregistrement
saveBtn.addEventListener('click', () => {
updateCurrentRanking();
saveData();
// Créer une nouvelle semaine après l'enregistrement
const newWeek = state.currentWeek + 1;
if (!state.rankings[newWeek]) {
state.rankings[newWeek] = [...categories];
}
state.currentWeek = newWeek;
// Afficher la modal de confirmation
const modal = document.getElementById('save-modal');
// Mettre à jour le texte avec le numéro de semaine
modal.querySelector('p').textContent = `Votre classement pour la semaine ${state.currentWeek - 1} a été enregistré avec succès. La semaine ${newWeek} est maintenant disponible.`;
modal.classList.remove('hidden');
// Gérer le bouton OK de la modal
document.getElementById('modal-ok-btn').addEventListener('click', () => {
modal.classList.add('hidden');
// Mettre à jour l'affichage
initWeekSelector();
renderBlocks();
initCharts();
}, { once: true }); // Le listener s'enlève automatiquement après utilisation
});
}
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.block:not(.opacity-50)')];
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child };
} else {
return closest;
}
}, { offset: Number.NEGATIVE_INFINITY }).element;
}
function updateCurrentRanking() {
const blocks = rankingContainer.querySelectorAll('.block');
state.rankings[state.currentWeek] = Array.from(blocks).map(block => block.dataset.category);
// Mettre à jour les numéros de position
blocks.forEach((block, index) => {
const positionSpan = block.querySelector('span:first-child');
positionSpan.textContent = index + 1;
});
// Mettre à jour le graphique
initCharts();
}
});
</script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=masterseb/pic4" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>