Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b56713cfb4 | ||
|
|
eac927d70c | ||
|
|
41307ca69d |
-16
@@ -1,16 +0,0 @@
|
||||
FROM node:22-alpine
|
||||
|
||||
WORKDIR /app
|
||||
COPY server.js ./
|
||||
COPY public ./public
|
||||
|
||||
# La to-do list est enregistrée dans /data (à monter en volume pour la conserver)
|
||||
ENV PORT=3000 \
|
||||
DATA_FILE=/data/todos.json
|
||||
RUN mkdir -p /data && chown node:node /data
|
||||
VOLUME /data
|
||||
|
||||
USER node
|
||||
EXPOSE 3000
|
||||
HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://localhost:3000/healthz || exit 1
|
||||
CMD ["node", "server.js"]
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
{"bassines":[
|
||||
{"Nom":"Grande bassine ronde en fer","tare":6.500},
|
||||
{"Nom":"Grande bassine ronde verte","tare":2.700},
|
||||
{"Nom":"Grande bassine ronde verte","tare":2.700},
|
||||
{"Nom":"Grande bassine ronde verte","tare":2.700},
|
||||
{"Nom":"Moyenne bassine ovale en fer","tare":6.000},
|
||||
{"Nom":"Petite bassine ronde en fer","tare":2.700},
|
||||
{"Nom":"Petite bassine ronde bleue (Tonton Pierre)","tare":1.700},
|
||||
{"Nom":"Petite bassine ronde verte (JM)","tare":1.700},
|
||||
{"Nom":"Grande bassine verte","tare":2.700},
|
||||
{"Nom":"Moyenne bassine ronde (Couenne)","tare":4.900},
|
||||
{"Nom":"Grande bassine ovale en fer (Jeannot)","tare":6.000},
|
||||
{"Nom":"Caisse grise","tare":2.450},
|
||||
{"Nom":"Caisse verte","tare":2.600},
|
||||
{"Nom":"Bassine bleue (JM1)","tare":2.500},
|
||||
{"Nom":"Bassine verte (JM3)","tare":2.700}
|
||||
]}
|
||||
Executable
+248
@@ -0,0 +1,248 @@
|
||||
/* =========================================================
|
||||
1️⃣ RESET GÉNÉRAL
|
||||
========================================================= */
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
2️⃣ BASE GLOBALE
|
||||
========================================================= */
|
||||
body {
|
||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
|
||||
Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
||||
font-size: 10pt;
|
||||
padding: 3mm;
|
||||
color: #000;
|
||||
background-color: #344d59d5;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2 {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
3️⃣ TABLEAUX
|
||||
========================================================= */
|
||||
table {
|
||||
margin: 2mm auto;
|
||||
width: auto;
|
||||
max-width: calc(297mm - 6mm);
|
||||
border: 2px solid #b8cbd0;
|
||||
border-radius: 7px;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
overflow: hidden;
|
||||
text-align: center;
|
||||
font-size: 9pt;
|
||||
}
|
||||
|
||||
table+table {
|
||||
margin-top: 1mm;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
border: 2px solid #b8cbd0;
|
||||
background-clip: padding-box;
|
||||
padding: 2px 4px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
#TableauBassines,
|
||||
#TableauRendement,
|
||||
#TableauProportions {
|
||||
background-color: #709ca7;
|
||||
}
|
||||
|
||||
#TableauTotaux {
|
||||
background-color: #137c8b;
|
||||
}
|
||||
|
||||
#TableauRendement {
|
||||
margin: 2mm auto !important;
|
||||
display: table;
|
||||
float: none !important;
|
||||
clear: both;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 0fr repeat(4, auto);
|
||||
grid-template-rows: repeat(3, auto);
|
||||
grid-column-gap: 0px;
|
||||
grid-row-gap: 0px;
|
||||
}
|
||||
|
||||
#tabProp {
|
||||
grid-area: 2 / 3 / 3 / 4;
|
||||
}
|
||||
|
||||
#button-wrapper {
|
||||
grid-area: 2 / 4 / 3 / 5;
|
||||
}
|
||||
|
||||
#tabBass {
|
||||
grid-area: 3 / 2 / 4 / 6;
|
||||
}
|
||||
|
||||
#tabTot {
|
||||
grid-area: 4 / 3 / 5 / 4;
|
||||
}
|
||||
|
||||
#tabRend {
|
||||
grid-area: 4 / 4 / 5 / 5;
|
||||
}
|
||||
|
||||
.button-wrapper {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
4️⃣ FORMULAIRES — CASES À COCHER
|
||||
========================================================= */
|
||||
|
||||
input[type="checkbox"] {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin: 0 4px;
|
||||
border: 2px solid #6b6b6b;
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.12s ease;
|
||||
}
|
||||
|
||||
input[type="checkbox"]::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 6px;
|
||||
height: 9px;
|
||||
border: solid #000;
|
||||
border-width: 0 3px 3px 0;
|
||||
transform: translate(-50%, -80%) rotate(43deg);
|
||||
opacity: 0;
|
||||
transition: opacity 0.12s ease, transform 0.12s ease;
|
||||
}
|
||||
|
||||
input[type="checkbox"]:checked {
|
||||
border-color: #4f4f4f;
|
||||
}
|
||||
|
||||
input[type="checkbox"]:checked::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
input[type="checkbox"]:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(19, 124, 139, 0.15);
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
5️⃣ BOUTONS — STYLE GOOGLE MATERIAL
|
||||
========================================================= */
|
||||
|
||||
#button-wrapper {
|
||||
position: relative;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
#button-wrapper .button-17 {
|
||||
justify-content: center;
|
||||
appearance: none;
|
||||
border: none;
|
||||
border-radius: 24px;
|
||||
background: #fff;
|
||||
color: #3c4043;
|
||||
font-family: "Google Sans", Roboto, Arial, sans-serif;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.25px;
|
||||
height: 48px;
|
||||
padding: 2px 24px;
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
user-select: none;
|
||||
touch-action: manipulation;
|
||||
}
|
||||
|
||||
#button-wrapper .button-17:hover {
|
||||
background: #f6f9fe;
|
||||
color: #174ea6;
|
||||
box-shadow: rgba(60, 64, 67, 0.3) 0 2px 3px,
|
||||
rgba(60, 64, 67, 0.15) 0 6px 10px 4px;
|
||||
}
|
||||
|
||||
#button-wrapper .button-17:active {
|
||||
box-shadow: rgba(60, 64, 67, 0.3) 0 4px 4px,
|
||||
rgba(60, 64, 67, 0.15) 0 8px 12px 6px;
|
||||
}
|
||||
|
||||
#button-wrapper .button-17:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.7;
|
||||
box-shadow: rgba(60, 64, 67, 0.3) 0 1px 3px,
|
||||
rgba(60, 64, 67, 0.15) 0 4px 8px 3px;
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
6️⃣ IMPRESSION — FORMAT A4 PAYSAGE
|
||||
========================================================= */
|
||||
@media print {
|
||||
@page {
|
||||
size: A4 landscape;
|
||||
margin: 3mm;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
width: 297mm;
|
||||
height: 210mm;
|
||||
margin: 0;
|
||||
padding: 3mm;
|
||||
background: none !important;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
table {
|
||||
font-size: 8.5pt;
|
||||
margin: 0;
|
||||
page-break-inside: avoid;
|
||||
break-inside: avoid;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 1px 3px;
|
||||
font-size: 8.5pt;
|
||||
}
|
||||
|
||||
input[type="checkbox"] {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
body>* {
|
||||
transform-origin: top left;
|
||||
transform: scale(0.94);
|
||||
}
|
||||
|
||||
/* Masquer tous les boutons et éléments non imprimables */
|
||||
.no-print{
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
services:
|
||||
epices:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- reverse-proxy_default
|
||||
volumes:
|
||||
- epices-data:/data
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
|
||||
- "traefik.http.routers.saucissons-dev-epices-1.rule=Host(`saucissons.tuttifruitti.ddns.net`)"
|
||||
- "traefik.http.routers.saucissons-dev-epices-1.entrypoints=websecure"
|
||||
- "traefik.http.routers.saucissons-dev-epices-1.tls=true"
|
||||
- "traefik.http.routers.saucissons-dev-epices-1.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.routers.saucissons-dev-epices-1.service=saucissons-dev-epices-1"
|
||||
|
||||
- "traefik.http.services.saucissons-dev-epices-1.loadbalancer.server.port=3000"
|
||||
|
||||
volumes:
|
||||
epices-data:
|
||||
|
||||
networks:
|
||||
reverse-proxy_default:
|
||||
external: true
|
||||
Regular → Executable
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 56 KiB |
Executable
+493
@@ -0,0 +1,493 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="stylesheet" href="assets/style.css" />
|
||||
<title>Calculateur d'épices</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="titre">
|
||||
<h1 id="grandTitre">Calcul des épices</h1>
|
||||
</div>
|
||||
<br />
|
||||
<script>
|
||||
let poids_planche = 4.4;
|
||||
const bassines = [
|
||||
{ Nom: "Niagara", tare: 6.5 },
|
||||
{ Nom: "Manu Chao", tare: 2.7 },
|
||||
{ Nom: "Kamini", tare: 2.7 },
|
||||
{ Nom: "Tina", tare: 2.7 },
|
||||
{ Nom: "Garou", tare: 6.0 },
|
||||
{ Nom: "Johnny", tare: 2.7 },
|
||||
{ Nom: "Vanessa", tare: 1.7 },
|
||||
{ Nom: "Joséphine", tare: 4.9 },
|
||||
{ Nom: "Céline", tare: 6.0 },
|
||||
{ Nom: "Dalida", tare: 2.5 },
|
||||
{ Nom: "Florent", tare: 2.7 },
|
||||
{ Nom: "Petite bassine ronde verte (JM)", tare: 1.7 },
|
||||
{ Nom: "Grande bassine verte", tare: 2.7 },
|
||||
{ Nom: "Caisse grise", tare: 2.45 },
|
||||
{ Nom: "Caisse verte", tare: 2.6 },
|
||||
];
|
||||
|
||||
const col = [
|
||||
"Bassine",
|
||||
"Couenne ?",
|
||||
"Poids brut",
|
||||
"Tare bassine",
|
||||
"Net",
|
||||
"Sel (Kg)",
|
||||
"Poivre (g)",
|
||||
"Poivre concassé (g)",
|
||||
"Muscade (g)",
|
||||
"Ail (g)",
|
||||
];
|
||||
|
||||
const getElementValue = (id) =>
|
||||
parseFloat(document.getElementById(id).value) || 0;
|
||||
const getElementText = (id) => {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) {
|
||||
console.warn("Element introuvable :", id);
|
||||
return 0;
|
||||
}
|
||||
return parseFloat(el.innerHTML) || 0;
|
||||
};
|
||||
|
||||
function calculEpices(ligne) {
|
||||
const poidsBrut = getElementValue("Poids_bassine_" + ligne);
|
||||
if (poidsBrut) {
|
||||
const tare = getElementText("tare_" + ligne);
|
||||
const net = (poidsBrut - tare - poids_planche).toFixed(3);
|
||||
document.getElementById("Net" + ligne).innerHTML = net;
|
||||
const propSel = getElementValue("Prop_sel");
|
||||
const propPoivre = getElementValue("Prop_poivre");
|
||||
const propMuscade = getElementValue("Prop_muscade");
|
||||
const propAil = getElementValue("Prop_ail");
|
||||
let qteSel;
|
||||
if (!document.getElementById("isCouenne" + ligne).checked) {
|
||||
qteSel = net * propSel;
|
||||
} else {
|
||||
qteSel = net * (propSel / 2);
|
||||
}
|
||||
document.getElementById("Sel (Kg)" + ligne).innerHTML =
|
||||
qteSel.toFixed(3);
|
||||
document.getElementById("Poivre (g)" + ligne).innerHTML = (
|
||||
net *
|
||||
propPoivre *
|
||||
0.6
|
||||
).toFixed(3);
|
||||
document.getElementById(
|
||||
"Poivre concassé (g)" + ligne,
|
||||
).innerHTML = (net * propPoivre * 0.4).toFixed(3);
|
||||
document.getElementById("Muscade (g)" + ligne).innerHTML = (
|
||||
net * propMuscade
|
||||
).toFixed(3);
|
||||
document.getElementById("Ail (g)" + ligne).innerHTML = (
|
||||
net * propAil
|
||||
).toFixed(3);
|
||||
} else {
|
||||
[
|
||||
"Net",
|
||||
"Sel (Kg)",
|
||||
"Poivre (g)",
|
||||
"Poivre concassé (g)",
|
||||
"Muscade (g)",
|
||||
"Ail (g)",
|
||||
].forEach((colonne) => {
|
||||
document.getElementById(colonne + ligne).innerHTML = "";
|
||||
});
|
||||
}
|
||||
calculerTotaux(); // Recalcul des totaux après chaque changement
|
||||
}
|
||||
|
||||
const recalculerToutesLignes = () => {
|
||||
for (let i = 1; i <= bassines.length; i++) {
|
||||
calculEpices(i);
|
||||
}
|
||||
};
|
||||
|
||||
function calculerTotaux() {
|
||||
let totalNet = 0,
|
||||
totalSel = 0,
|
||||
totalPoivre = 0,
|
||||
totalPoivreConcasse = 0,
|
||||
totalMuscade = 0,
|
||||
totalAil = 0;
|
||||
|
||||
for (let i = 1; i <= bassines.length; i++) {
|
||||
totalNet += getElementText("Net" + i);
|
||||
totalSel += getElementText("Sel (Kg)" + i);
|
||||
totalPoivre += getElementText("Poivre (g)" + i);
|
||||
totalPoivreConcasse += getElementText(
|
||||
"Poivre concassé (g)" + i,
|
||||
);
|
||||
totalMuscade += getElementText("Muscade (g)" + i);
|
||||
totalAil += getElementText("Ail (g)" + i);
|
||||
}
|
||||
|
||||
document.getElementById("Total_Net").innerHTML =
|
||||
totalNet.toFixed(3);
|
||||
document.getElementById("Total_Sel").innerHTML =
|
||||
totalSel.toFixed(3);
|
||||
document.getElementById("Total_Poivre").innerHTML =
|
||||
totalPoivre.toFixed(3);
|
||||
document.getElementById("Total_Poivre_Concasse").innerHTML =
|
||||
totalPoivreConcasse.toFixed(3);
|
||||
document.getElementById("Total_Muscade").innerHTML =
|
||||
totalMuscade.toFixed(3);
|
||||
document.getElementById("Total_Ail").innerHTML =
|
||||
totalAil.toFixed(3);
|
||||
|
||||
// Calcul du total assaisonné et rendement
|
||||
calculerTotalAssaisonne();
|
||||
}
|
||||
|
||||
function calculerTotalAssaisonne() {
|
||||
const totalNet = getElementText("Total_Net");
|
||||
const totalSel = getElementText("Total_Sel");
|
||||
const totalPoivre = getElementText("Total_Poivre");
|
||||
const totalPoivreConcasse = getElementText(
|
||||
"Total_Poivre_Concasse",
|
||||
);
|
||||
const totalMuscade = getElementText("Total_Muscade");
|
||||
const totalAil = getElementText("Total_Ail");
|
||||
|
||||
const totalAssaisonne =
|
||||
totalNet +
|
||||
totalSel +
|
||||
totalPoivre / 1000 +
|
||||
totalPoivreConcasse / 1000 +
|
||||
totalMuscade / 1000 +
|
||||
totalAil / 1000;
|
||||
document.getElementById("Total_Assaisonne").innerHTML =
|
||||
totalAssaisonne.toFixed(3);
|
||||
|
||||
const totalAchete = getElementValue("Total_Achete");
|
||||
if (totalAchete > 0) {
|
||||
const totalNet =
|
||||
document.getElementById("Total_Net").innerHTML;
|
||||
const rendement = (totalNet / totalAchete) * 100;
|
||||
document.getElementById("Rendement").innerHTML =
|
||||
rendement.toFixed(3) + " %";
|
||||
} else {
|
||||
document.getElementById("Rendement").innerHTML = "0 %";
|
||||
}
|
||||
}
|
||||
|
||||
const body = document.body;
|
||||
const formulaire = document.createElement("form");
|
||||
formulaire.setAttribute("class", "form-grid");
|
||||
|
||||
// ---- Début Intégration LocalStorage ----
|
||||
const STORAGE_KEY = "calculateurEpices";
|
||||
const MAX_AGE = 48 * 60 * 60 * 1000; // 72h
|
||||
|
||||
function sauvegarderFormulaire() {
|
||||
const data = { timestamp: Date.now(), values: {} };
|
||||
document.querySelectorAll("input").forEach((input) => {
|
||||
data.values[input.id] =
|
||||
input.type === "checkbox" ? input.checked : input.value;
|
||||
});
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
|
||||
}
|
||||
|
||||
function restaurerFormulaire() {
|
||||
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY));
|
||||
if (saved && Date.now() - saved.timestamp < MAX_AGE) {
|
||||
for (const [id, value] of Object.entries(saved.values)) {
|
||||
const input = document.getElementById(id);
|
||||
if (input) {
|
||||
if (input.type === "checkbox")
|
||||
input.checked = value;
|
||||
else input.value = value;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("DOMContentLoaded", () => {
|
||||
restaurerFormulaire();
|
||||
recalculerToutesLignes();
|
||||
});
|
||||
|
||||
document.body.addEventListener("input", sauvegarderFormulaire);
|
||||
document.body.addEventListener("change", sauvegarderFormulaire);
|
||||
// Table des proportions et du poids de la planche
|
||||
const proportionTable = document.createElement("table");
|
||||
proportionTable.setAttribute("id", "TableauProportions");
|
||||
const proportionBody = document.createElement("tbody");
|
||||
|
||||
// Ajout du poids de la planche
|
||||
const poidsPlancheRow = document.createElement("tr");
|
||||
const poidsPlancheLabelCell = document.createElement("td");
|
||||
const poidsPlancheInputCell = document.createElement("td");
|
||||
|
||||
const poidsPlancheLabel = document.createElement("label");
|
||||
poidsPlancheLabel.setAttribute("for", "Poids_planche");
|
||||
poidsPlancheLabel.innerHTML = "Poids de la planche (Kg)";
|
||||
|
||||
const poidsPlancheInput = document.createElement("input");
|
||||
poidsPlancheInput.setAttribute("id", "Poids_planche");
|
||||
poidsPlancheInput.value = 4.4;
|
||||
poidsPlancheInput.onchange = () => {
|
||||
poids_planche = getElementValue("Poids_planche");
|
||||
recalculerToutesLignes();
|
||||
};
|
||||
|
||||
poidsPlancheLabelCell.appendChild(poidsPlancheLabel);
|
||||
poidsPlancheInputCell.appendChild(poidsPlancheInput);
|
||||
poidsPlancheRow.appendChild(poidsPlancheLabelCell);
|
||||
poidsPlancheRow.appendChild(poidsPlancheInputCell);
|
||||
proportionBody.appendChild(poidsPlancheRow);
|
||||
|
||||
// Ajout des proportions dans le tableau
|
||||
const proportions = [
|
||||
{
|
||||
label: "Proportion de sel (Kg)",
|
||||
id: "Prop_sel",
|
||||
defaultValue: 0.028,
|
||||
},
|
||||
{
|
||||
label: "Proportion de poivre (g)",
|
||||
id: "Prop_poivre",
|
||||
defaultValue: 2,
|
||||
},
|
||||
{
|
||||
label: "Proportion de muscade (g)",
|
||||
id: "Prop_muscade",
|
||||
defaultValue: 1,
|
||||
},
|
||||
{
|
||||
label: "Proportion d'ail (g)",
|
||||
id: "Prop_ail",
|
||||
defaultValue: 2,
|
||||
},
|
||||
];
|
||||
|
||||
proportions.forEach((prop) => {
|
||||
const row = document.createElement("tr");
|
||||
|
||||
const labelCell = document.createElement("td");
|
||||
const inputCell = document.createElement("td");
|
||||
|
||||
const label = document.createElement("label");
|
||||
label.setAttribute("for", prop.id);
|
||||
label.innerHTML = prop.label;
|
||||
|
||||
const input = document.createElement("input");
|
||||
input.setAttribute("id", prop.id);
|
||||
input.value = prop.defaultValue;
|
||||
input.onchange = recalculerToutesLignes;
|
||||
|
||||
labelCell.appendChild(label);
|
||||
inputCell.appendChild(input);
|
||||
|
||||
row.appendChild(labelCell);
|
||||
row.appendChild(inputCell);
|
||||
|
||||
proportionBody.appendChild(row);
|
||||
});
|
||||
|
||||
const boutonDiv = document.createElement("div");
|
||||
boutonDiv.setAttribute("id", "button-wrapper");
|
||||
boutonDiv.style.display = "inline-block";
|
||||
boutonDiv.style.verticalAlign = "top";
|
||||
boutonDiv.style.marginLeft = "20px"; // espace entre le tableau et le bouton
|
||||
|
||||
const boutonAction = document.createElement("button");
|
||||
boutonAction.setAttribute("class", "no-print button-17");
|
||||
boutonAction.textContent = "Imprimer la page";
|
||||
boutonAction.type = "button";
|
||||
boutonAction.onclick = () => {
|
||||
window.print();
|
||||
alert("Page imprimée !");
|
||||
};
|
||||
|
||||
boutonDiv.appendChild(boutonAction);
|
||||
|
||||
// wrapper pour le tableau des proportions
|
||||
const tabPropDiv = document.createElement("div");
|
||||
tabPropDiv.id = "tabProp";
|
||||
|
||||
proportionTable.appendChild(proportionBody);
|
||||
tabPropDiv.appendChild(proportionTable);
|
||||
|
||||
formulaire.appendChild(boutonDiv);
|
||||
formulaire.appendChild(tabPropDiv);
|
||||
|
||||
// Création du tableau des bassines avec les titres
|
||||
const tbl = document.createElement("table");
|
||||
tbl.setAttribute("id", "TableauBassines");
|
||||
const tblBody = document.createElement("tbody");
|
||||
|
||||
// Ajout des titres
|
||||
const headerRow = document.createElement("tr");
|
||||
headerRow.setAttribute("id", "Titres_tableau");
|
||||
col.forEach((titre) => {
|
||||
const cell = document.createElement("td");
|
||||
const cellText = document.createTextNode(titre);
|
||||
cell.appendChild(cellText);
|
||||
headerRow.appendChild(cell);
|
||||
});
|
||||
tblBody.appendChild(headerRow);
|
||||
|
||||
// Ajout des lignes pour chaque bassine
|
||||
bassines.forEach((bassine, index) => {
|
||||
const row = document.createElement("tr");
|
||||
row.id = "Bassine_" + (index + 1);
|
||||
|
||||
col.forEach((colonne, colIndex) => {
|
||||
const cell = document.createElement("td");
|
||||
cell.setAttribute("class", "tdBassine");
|
||||
if (colIndex === 0) {
|
||||
cell.textContent = bassine.Nom;
|
||||
cell.setAttribute("class", "NomBassine");
|
||||
} else if (colIndex === 1) {
|
||||
const checkbox = document.createElement("input");
|
||||
checkbox.type = "checkbox";
|
||||
checkbox.id = "isCouenne" + (index + 1);
|
||||
checkbox.onchange = () => calculEpices(index + 1);
|
||||
cell.appendChild(checkbox);
|
||||
} else if (colIndex === 2) {
|
||||
const input = document.createElement("input");
|
||||
input.id = "Poids_bassine_" + (index + 1);
|
||||
input.onchange = () => calculEpices(index + 1);
|
||||
cell.appendChild(input);
|
||||
} else if (colIndex === 3) {
|
||||
cell.id = "tare_" + (index + 1);
|
||||
cell.textContent = bassine.tare.toFixed(3);
|
||||
} else {
|
||||
cell.id = colonne + (index + 1);
|
||||
}
|
||||
row.appendChild(cell);
|
||||
});
|
||||
|
||||
tblBody.appendChild(row);
|
||||
});
|
||||
|
||||
tbl.appendChild(tblBody);
|
||||
|
||||
// wrapper pour le tableau des bassines
|
||||
const tabBassDiv = document.createElement("div");
|
||||
tabBassDiv.id = "tabBass";
|
||||
tabBassDiv.appendChild(document.createElement("br"));
|
||||
tabBassDiv.appendChild(tbl);
|
||||
formulaire.appendChild(tabBassDiv);
|
||||
|
||||
//
|
||||
// Tableau des totaux
|
||||
const totalTable = document.createElement("table");
|
||||
totalTable.setAttribute("id", "TableauTotaux");
|
||||
const totalBody = document.createElement("tbody");
|
||||
|
||||
// Première ligne : titres
|
||||
const totalHeaderRow = document.createElement("tr");
|
||||
[
|
||||
"Total Viande Net",
|
||||
"Total Sel (Kg)",
|
||||
"Total Poivre (g)",
|
||||
"Total Poivre Concassé (g)",
|
||||
"Total Muscade (g)",
|
||||
"Total Ail (g)",
|
||||
].forEach((titre) => {
|
||||
const cell = document.createElement("td");
|
||||
cell.setAttribute("class", "cellule_totaux");
|
||||
const cellText = document.createTextNode(titre);
|
||||
cell.appendChild(cellText);
|
||||
totalHeaderRow.appendChild(cell);
|
||||
});
|
||||
totalBody.appendChild(totalHeaderRow);
|
||||
|
||||
// Deuxième ligne : totaux
|
||||
const totalRow = document.createElement("tr");
|
||||
const totalIds = [
|
||||
"Total_Net",
|
||||
"Total_Sel",
|
||||
"Total_Poivre",
|
||||
"Total_Poivre_Concasse",
|
||||
"Total_Muscade",
|
||||
"Total_Ail",
|
||||
];
|
||||
totalIds.forEach((id) => {
|
||||
const cell = document.createElement("td");
|
||||
cell.setAttribute("class", "cellule_totaux");
|
||||
cell.id = id;
|
||||
cell.innerHTML = "0.000"; // Valeurs initiales à 0
|
||||
totalRow.appendChild(cell);
|
||||
});
|
||||
totalBody.appendChild(totalRow);
|
||||
|
||||
totalTable.appendChild(totalBody);
|
||||
|
||||
// wrapper pour le tableau des totaux
|
||||
const tabTotDiv = document.createElement("div");
|
||||
tabTotDiv.id = "tabTot";
|
||||
tabTotDiv.appendChild(document.createElement("br"));
|
||||
tabTotDiv.appendChild(totalTable);
|
||||
formulaire.appendChild(tabTotDiv);
|
||||
//
|
||||
// Tableau supplémentaire à droite
|
||||
const rendementTable = document.createElement("table");
|
||||
rendementTable.setAttribute("id", "TableauRendement");
|
||||
const rendementBody = document.createElement("tbody");
|
||||
|
||||
// Première ligne : titres
|
||||
const rendementHeaderRow = document.createElement("tr");
|
||||
["Total acheté", "Total assaisonné", "Rendement"].forEach(
|
||||
(titre) => {
|
||||
const cell = document.createElement("td");
|
||||
cell.setAttribute("class", "tdRendement");
|
||||
const cellText = document.createTextNode(titre);
|
||||
cell.appendChild(cellText);
|
||||
rendementHeaderRow.appendChild(cell);
|
||||
},
|
||||
);
|
||||
rendementBody.appendChild(rendementHeaderRow);
|
||||
|
||||
// Deuxième ligne : contenu
|
||||
const rendementRow = document.createElement("tr");
|
||||
|
||||
// Total acheté (input)
|
||||
const totalAcheteCell = document.createElement("td");
|
||||
totalAcheteCell.setAttribute("class", "tdRendement");
|
||||
const totalAcheteInput = document.createElement("input");
|
||||
totalAcheteInput.setAttribute("id", "Total_Achete");
|
||||
totalAcheteInput.setAttribute("type", "number");
|
||||
totalAcheteInput.onchange = calculerTotalAssaisonne;
|
||||
totalAcheteCell.appendChild(totalAcheteInput);
|
||||
rendementRow.appendChild(totalAcheteCell);
|
||||
|
||||
// Total assaisonné
|
||||
const totalAssaisonneCell = document.createElement("td");
|
||||
totalAssaisonneCell.setAttribute("class", "tdRendement");
|
||||
totalAssaisonneCell.setAttribute("id", "Total_Assaisonne");
|
||||
totalAssaisonneCell.innerHTML = "0.000"; // Initialement 0
|
||||
rendementRow.appendChild(totalAssaisonneCell);
|
||||
|
||||
// Rendement
|
||||
const rendementCell = document.createElement("td");
|
||||
rendementCell.setAttribute("class", "tdRendement");
|
||||
rendementCell.setAttribute("id", "Rendement");
|
||||
rendementCell.innerHTML = "0 %"; // Initialement 0
|
||||
rendementRow.appendChild(rendementCell);
|
||||
|
||||
rendementBody.appendChild(rendementRow);
|
||||
rendementTable.appendChild(rendementBody);
|
||||
|
||||
// wrapper pour le tableau rendement
|
||||
const tabRendDiv = document.createElement("div");
|
||||
tabRendDiv.id = "tabRend";
|
||||
tabRendDiv.appendChild(document.createElement("br"));
|
||||
tabRendDiv.appendChild(rendementTable);
|
||||
|
||||
// Ajout du tableau rendement au formulaire
|
||||
formulaire.appendChild(tabRendDiv);
|
||||
body.appendChild(formulaire);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,175 +0,0 @@
|
||||
/**
|
||||
* Décompte jusqu'à la prochaine édition, affiché à côté du titre sur toutes les pages.
|
||||
* La date est enregistrée sur le serveur : tout le monde voit le même décompte, en direct.
|
||||
*
|
||||
* - pas de date (ou date dépassée) : « date à définir pour la prochaine édition des saucissons Murats »
|
||||
* - le jour même : « C'est le jour J ! »
|
||||
* - avant : « Prochaine édition : dans 2 mois et 12 jours »
|
||||
*/
|
||||
(() => {
|
||||
const PLACEHOLDER = "date à définir pour la prochaine édition des saucissons Murats";
|
||||
|
||||
// ---------- Calcul du décompte (jours calendaires, sans heure ni fuseau) ----------
|
||||
|
||||
// Ajoute n mois à une date en ramenant le jour au dernier jour du mois si besoin (31 janvier + 1 mois = 28 février)
|
||||
function ajouterMois(annee, mois, jour, n) {
|
||||
const total = annee * 12 + mois + n;
|
||||
const a = Math.floor(total / 12);
|
||||
const m = total % 12;
|
||||
const dernierJour = new Date(Date.UTC(a, m + 1, 0)).getUTCDate();
|
||||
return Date.UTC(a, m, Math.min(jour, dernierJour));
|
||||
}
|
||||
|
||||
function etatEdition(dateIso, maintenant) {
|
||||
if (typeof dateIso !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(dateIso)) {
|
||||
return { type: "vide", texte: PLACEHOLDER };
|
||||
}
|
||||
|
||||
const [a, m, j] = dateIso.split("-").map(Number);
|
||||
const cible = Date.UTC(a, m - 1, j);
|
||||
const aA = maintenant.getFullYear();
|
||||
const mA = maintenant.getMonth();
|
||||
const jA = maintenant.getDate();
|
||||
const aujourdhui = Date.UTC(aA, mA, jA);
|
||||
|
||||
if (cible < aujourdhui) return { type: "vide", texte: PLACEHOLDER }; // date dépassée
|
||||
if (cible === aujourdhui) return { type: "jour", texte: "C'est le jour J !" };
|
||||
|
||||
// Nombre de mois entiers, puis jours restants
|
||||
let mois = (a - aA) * 12 + (m - 1 - mA);
|
||||
if (ajouterMois(aA, mA, jA, mois) > cible) mois--;
|
||||
const jours = Math.round((cible - ajouterMois(aA, mA, jA, mois)) / 86400000);
|
||||
|
||||
const morceaux = [];
|
||||
if (mois > 0) morceaux.push(`${mois} mois`);
|
||||
if (jours > 0) morceaux.push(`${jours} jour${jours > 1 ? "s" : ""}`);
|
||||
return { type: "compte", texte: "dans " + morceaux.join(" et ") };
|
||||
}
|
||||
|
||||
// Pour les tests en ligne de commande
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = { etatEdition, PLACEHOLDER };
|
||||
|
||||
// ---------- Affichage à côté du titre ----------
|
||||
function demarrer() {
|
||||
const titre = document.querySelector(".topbar h1");
|
||||
if (!titre) return;
|
||||
|
||||
// La puce entière est cliquable : un vrai champ date, invisible, la recouvre (le sélecteur natif s'ouvre au toucher)
|
||||
const puce = document.createElement("label");
|
||||
puce.className = "edition";
|
||||
puce.hidden = true; // cachée jusqu'à la réponse du serveur : pas de faux « date à définir » au chargement
|
||||
|
||||
const etiquette = document.createElement("span");
|
||||
etiquette.className = "edition-label";
|
||||
etiquette.textContent = "Prochaine édition :";
|
||||
|
||||
const texte = document.createElement("span");
|
||||
texte.className = "edition-texte";
|
||||
texte.setAttribute("aria-live", "polite");
|
||||
|
||||
const champ = document.createElement("input");
|
||||
champ.type = "date";
|
||||
champ.setAttribute("aria-label", "Date de la prochaine édition des saucissons Murats");
|
||||
|
||||
const effacer = document.createElement("button");
|
||||
effacer.type = "button";
|
||||
effacer.className = "edition-clear";
|
||||
effacer.textContent = "✕";
|
||||
effacer.title = "Effacer la date";
|
||||
effacer.setAttribute("aria-label", "Effacer la date");
|
||||
|
||||
puce.append(etiquette, texte, champ, effacer);
|
||||
titre.after(puce);
|
||||
|
||||
let date = null; // date affichée (AAAA-MM-JJ ou null)
|
||||
let connue = null; // dernière date confirmée par le serveur
|
||||
let message = null; // message d'erreur temporaire
|
||||
|
||||
function afficher() {
|
||||
const info = etatEdition(date, new Date());
|
||||
puce.dataset.etat = info.type;
|
||||
etiquette.hidden = info.type !== "compte" || !!message;
|
||||
texte.textContent = message || info.texte;
|
||||
effacer.hidden = info.type === "vide";
|
||||
champ.value = date || "";
|
||||
}
|
||||
|
||||
async function charger() {
|
||||
try {
|
||||
const reponse = await fetch("/api/edition", { cache: "no-store" });
|
||||
if (reponse.ok) {
|
||||
connue = date = (await reponse.json()).date;
|
||||
message = null; // une donnée fraîche du serveur remplace un éventuel message d'erreur
|
||||
}
|
||||
} catch {
|
||||
/* hors ligne : on garde ce qu'on a */
|
||||
}
|
||||
puce.hidden = false;
|
||||
afficher();
|
||||
}
|
||||
|
||||
async function enregistrer(nouvelle) {
|
||||
date = nouvelle;
|
||||
afficher();
|
||||
try {
|
||||
const reponse = await fetch("/api/edition", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ date: nouvelle }),
|
||||
});
|
||||
if (!reponse.ok) throw new Error("HTTP " + reponse.status);
|
||||
connue = nouvelle;
|
||||
} catch {
|
||||
date = connue; // on revient à la date réellement enregistrée
|
||||
message = "Enregistrement impossible, réessaie.";
|
||||
afficher();
|
||||
setTimeout(() => {
|
||||
message = null;
|
||||
afficher();
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
// Changement fait par quelqu'un d'autre : mise à jour en direct
|
||||
function ecouter() {
|
||||
if (typeof EventSource === "undefined") return;
|
||||
const flux = new EventSource("/api/edition/events");
|
||||
flux.onmessage = (e) => {
|
||||
try {
|
||||
connue = date = JSON.parse(e.data).date;
|
||||
message = null;
|
||||
puce.hidden = false;
|
||||
afficher();
|
||||
} catch {
|
||||
/* message illisible : on ignore */
|
||||
}
|
||||
};
|
||||
flux.onerror = () => {
|
||||
if (flux.readyState === EventSource.CLOSED) setTimeout(ecouter, 3000);
|
||||
};
|
||||
}
|
||||
|
||||
champ.addEventListener("change", () => enregistrer(champ.value || null));
|
||||
champ.addEventListener("click", () => {
|
||||
try {
|
||||
champ.showPicker(); // ordinateur : ouvre le calendrier au clic
|
||||
} catch {
|
||||
/* déjà ouvert, ou non supporté : le navigateur gère */
|
||||
}
|
||||
});
|
||||
effacer.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
enregistrer(null);
|
||||
});
|
||||
|
||||
setInterval(afficher, 60 * 1000); // le décompte passe à minuit tout seul
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "visible") charger(); // retour sur l'onglet : on se remet à jour
|
||||
});
|
||||
|
||||
charger();
|
||||
ecouter();
|
||||
}
|
||||
|
||||
if (typeof document !== "undefined") demarrer();
|
||||
})();
|
||||
@@ -1,496 +0,0 @@
|
||||
/* =====================================================================
|
||||
Calcul des épices : feuille de style unique pour toutes les pages
|
||||
|
||||
1. Variables et base
|
||||
2. En-tête et menu
|
||||
3. Composants communs (cartes, champs, boutons)
|
||||
4. Page « Calculateur » (index.html)
|
||||
5. Page « To-do » (todo.html)
|
||||
6. Grands écrans
|
||||
7. Impression
|
||||
===================================================================== */
|
||||
|
||||
|
||||
/* ---------- 1. Variables et base ---------- */
|
||||
:root {
|
||||
--bg: #f6f1ea;
|
||||
--card: #ffffff;
|
||||
--ink: #2b2420;
|
||||
--muted: #7a6e65;
|
||||
--line: #e6ddd2;
|
||||
--accent: #8c2f2f;
|
||||
--accent-dark: #742626;
|
||||
--accent-soft: #f7e8e5;
|
||||
--ok: #2f6b4f;
|
||||
--warn: #b35a00;
|
||||
--warn-soft: #fff1e0;
|
||||
--radius: 16px;
|
||||
--shadow: 0 1px 2px rgba(43, 36, 32, 0.06), 0 6px 18px rgba(43, 36, 32, 0.06);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
line-height: 1.35;
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
}
|
||||
|
||||
.wrap { max-width: 760px; margin: 0 auto; padding: 14px 14px 40px; }
|
||||
|
||||
|
||||
/* ---------- 2. En-tête et menu (toutes les pages) ---------- */
|
||||
.topbar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
padding: calc(8px + env(safe-area-inset-top)) 16px 0;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.18);
|
||||
}
|
||||
|
||||
/* Ligne du titre : titre à gauche, récapitulatif / statut à droite, puce de date en dessous (téléphone) ou à côté du titre (écran large) */
|
||||
.topbar-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
align-items: center;
|
||||
column-gap: 12px;
|
||||
row-gap: 6px;
|
||||
}
|
||||
.topbar-row > h1 { grid-column: 1; grid-row: 1; }
|
||||
.topbar-row > :not(h1):not(.edition) { grid-column: 2; grid-row: 1; }
|
||||
|
||||
.topbar h1 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 40px;
|
||||
margin: 0;
|
||||
font-family: Georgia, "Times New Roman", serif;
|
||||
font-size: 1.15rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.menu { display: flex; gap: 4px; margin: 2px -6px 0; }
|
||||
|
||||
.menu a {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 42px;
|
||||
padding: 0 14px;
|
||||
color: rgba(255, 255, 255, 0.78);
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
border-bottom: 3px solid transparent;
|
||||
}
|
||||
|
||||
.menu a:active { background: rgba(255, 255, 255, 0.12); }
|
||||
.menu a[aria-current="page"] { color: #fff; border-bottom-color: #fff; }
|
||||
|
||||
@media (min-width: 600px) {
|
||||
.menu a { flex: 0 0 auto; padding: 0 22px; }
|
||||
}
|
||||
|
||||
/* Décompte de la prochaine édition (créé par assets/edition.js) */
|
||||
.edition {
|
||||
position: relative;
|
||||
grid-column: 1 / -1;
|
||||
grid-row: 2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 2px 6px;
|
||||
min-height: 36px;
|
||||
margin-bottom: 6px;
|
||||
padding: 5px 40px 5px 12px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.35);
|
||||
border-radius: 12px;
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
color: #fff;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.25;
|
||||
cursor: pointer;
|
||||
}
|
||||
.edition-label { opacity: 0.8; }
|
||||
.edition-texte { font-weight: 700; }
|
||||
.edition[data-etat="vide"] .edition-texte { font-weight: 400; font-style: italic; opacity: 0.9; }
|
||||
.edition[data-etat="jour"] { background: #fff; border-color: #fff; color: var(--accent); }
|
||||
.edition[data-etat="jour"] .edition-texte { font-size: 1.05rem; }
|
||||
.edition:focus-within { box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.5); }
|
||||
|
||||
/* Le vrai champ date recouvre la puce, invisible : on touche la puce, le calendrier s'ouvre */
|
||||
.edition input { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; padding: 0; border: 0; opacity: 0; cursor: pointer; }
|
||||
.edition-clear {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
right: 2px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font-size: 0.95rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.edition-clear:active { background: rgba(0, 0, 0, 0.12); }
|
||||
|
||||
@media (min-width: 600px) {
|
||||
.topbar-row { grid-template-columns: auto 1fr auto; }
|
||||
.topbar-row > :not(h1):not(.edition) { grid-column: 3; }
|
||||
.edition { grid-column: 2; grid-row: 1; justify-self: start; margin-bottom: 0; }
|
||||
}
|
||||
|
||||
|
||||
/* ---------- 3. Composants communs ---------- */
|
||||
.card {
|
||||
background: var(--card);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
padding: 16px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.card h2 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 0.78rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.field label { display: block; font-size: 0.85rem; color: var(--muted); margin-bottom: 5px; }
|
||||
|
||||
/* 16px minimum : évite le zoom automatique d'iOS au focus */
|
||||
input[type="text"], input[type="number"] {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
font: inherit;
|
||||
font-size: 1.1rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
padding: 0 12px;
|
||||
border: 1.5px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: #fffdfa;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(140, 47, 47, 0.18); }
|
||||
|
||||
.btn {
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
min-height: 52px;
|
||||
padding: 0 18px;
|
||||
border-radius: 14px;
|
||||
border: 1.5px solid var(--line);
|
||||
background: var(--card);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:active { transform: scale(0.99); }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||
.btn.primary:active { background: var(--accent-dark); }
|
||||
|
||||
|
||||
/* ---------- 4. Page « Calculateur » ---------- */
|
||||
|
||||
/* Récapitulatif dans la barre du haut */
|
||||
.summary { display: flex; gap: 16px; text-align: right; }
|
||||
.summary .lbl { display: block; font-size: 0.68rem; opacity: 0.8; text-transform: uppercase; letter-spacing: 0.06em; }
|
||||
.summary b { font-size: 1.05rem; font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* Rendement */
|
||||
.yield { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.yield .field { grid-column: 1 / -1; }
|
||||
|
||||
.stat { background: #fbf7f1; border-radius: 12px; padding: 10px 12px; }
|
||||
.stat .label { font-size: 0.75rem; color: var(--muted); }
|
||||
.stat .value { font-size: 1.25rem; font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
.stat.big .value { color: var(--accent); }
|
||||
|
||||
/* Réglages repliables */
|
||||
details.card { padding: 0; }
|
||||
details summary {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-height: 52px;
|
||||
padding: 0 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
details summary::-webkit-details-marker { display: none; }
|
||||
details summary::after { content: "▾"; color: var(--muted); transition: transform 0.15s; }
|
||||
details[open] summary::after { transform: rotate(180deg); }
|
||||
details .settings { padding: 0 16px 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
details .hint { grid-column: 1 / -1; margin: 0; font-size: 0.8rem; color: var(--muted); }
|
||||
|
||||
/* Interrupteurs (couenne, filtre) */
|
||||
.switch {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 44px;
|
||||
padding: 0 14px 0 10px;
|
||||
border: 1.5px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
font-weight: 600;
|
||||
font-size: 0.92rem;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.switch input { position: absolute; opacity: 0; width: 1px; height: 1px; }
|
||||
.switch .track { width: 38px; height: 22px; border-radius: 999px; background: #d9cfc3; position: relative; transition: background 0.15s; flex: none; }
|
||||
.switch .track::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2px; left: 2px;
|
||||
width: 18px; height: 18px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
transition: transform 0.15s;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
.switch:has(input:checked) { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
|
||||
.switch input:checked + .track { background: var(--accent); }
|
||||
.switch input:checked + .track::after { transform: translateX(16px); }
|
||||
.switch:has(input:focus-visible) { box-shadow: 0 0 0 3px rgba(140, 47, 47, 0.25); }
|
||||
|
||||
.filterbar { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 4px 0 12px; flex-wrap: wrap; }
|
||||
.count { font-size: 0.9rem; color: var(--muted); }
|
||||
.count b { color: var(--accent); }
|
||||
|
||||
/* Cartes bassines */
|
||||
.bassines { display: grid; gap: 12px; }
|
||||
|
||||
.bassine {
|
||||
background: var(--card);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
border: 2px solid transparent;
|
||||
padding: 14px;
|
||||
}
|
||||
.bassine.filled { border-color: var(--accent); background: #fffaf9; }
|
||||
.bassine.warn { border-color: var(--warn); background: var(--warn-soft); }
|
||||
|
||||
.b-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
|
||||
.b-name { font-weight: 700; font-size: 1.05rem; }
|
||||
.b-tare { font-size: 0.8rem; color: var(--muted); }
|
||||
|
||||
.b-input label { display: block; font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; }
|
||||
.input-wrap { position: relative; }
|
||||
.input-wrap input { height: 56px; font-size: 1.5rem; font-weight: 600; padding-right: 52px; }
|
||||
.clear {
|
||||
position: absolute;
|
||||
right: 6px; top: 6px;
|
||||
width: 44px; height: 44px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-size: 1.1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.clear:active { background: var(--line); }
|
||||
.input-wrap input:placeholder-shown + .clear { display: none; }
|
||||
|
||||
.b-results { margin-top: 12px; }
|
||||
.b-net { display: flex; align-items: baseline; justify-content: space-between; margin-bottom: 8px; }
|
||||
.b-net .lbl { font-size: 0.8rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; }
|
||||
.b-net .val { font-size: 1.7rem; font-weight: 800; color: var(--accent); font-variant-numeric: tabular-nums; }
|
||||
.b-net .unit { font-size: 0.9rem; font-weight: 600; color: var(--muted); margin-left: 3px; }
|
||||
.warn .b-net .val { color: var(--warn); }
|
||||
|
||||
.tiles { display: grid; grid-template-columns: repeat(6, 1fr); gap: 8px; }
|
||||
.tile { grid-column: span 2; background: #fbf7f1; border-radius: 10px; padding: 8px 6px; text-align: center; }
|
||||
.tile:nth-child(n+4) { grid-column: span 3; }
|
||||
.tile .t-lbl { display: block; font-size: 0.7rem; color: var(--muted); }
|
||||
.tile .t-val { font-weight: 700; font-variant-numeric: tabular-nums; font-size: 1rem; }
|
||||
|
||||
.b-warn { margin: 10px 0 0; font-size: 0.85rem; color: var(--warn); font-weight: 600; }
|
||||
|
||||
/* Totaux */
|
||||
.totals { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||
.totals .stat:first-child { grid-column: 1 / -1; background: var(--accent-soft); }
|
||||
.totals .unit { font-size: 0.8rem; font-weight: 400; color: var(--muted); }
|
||||
|
||||
/* Boutons du bas de page */
|
||||
.actions { display: grid; gap: 10px; }
|
||||
|
||||
|
||||
/* ---------- 5. Page « To-do » ---------- */
|
||||
|
||||
/* Statut de connexion (barre du haut) */
|
||||
.live { display: inline-flex; align-items: center; gap: 6px; font-size: 0.78rem; opacity: 0.95; }
|
||||
.live::before { content: ""; width: 9px; height: 9px; border-radius: 50%; background: #7be0a8; }
|
||||
.live.off::before { background: #ffc266; }
|
||||
|
||||
/* Ajout d'une tâche */
|
||||
.add { display: flex; gap: 10px; margin-bottom: 14px; }
|
||||
.add input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 56px;
|
||||
padding: 0 14px;
|
||||
border-radius: 14px;
|
||||
background: var(--card);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.add input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(140, 47, 47, 0.18); }
|
||||
.add .btn.primary { min-height: 56px; }
|
||||
|
||||
.info { display: flex; justify-content: space-between; align-items: center; margin: 0 2px 10px; font-size: 0.9rem; color: var(--muted); }
|
||||
.info b { color: var(--accent); }
|
||||
|
||||
/* Liste */
|
||||
.liste { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
|
||||
|
||||
.item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: var(--card);
|
||||
border-radius: 14px;
|
||||
box-shadow: var(--shadow);
|
||||
border: 2px solid transparent;
|
||||
}
|
||||
.item.flash { animation: flash 1.8s ease-out; }
|
||||
@keyframes flash {
|
||||
0% { background: #fde9c4; border-color: var(--warn); }
|
||||
100% { background: var(--card); border-color: transparent; }
|
||||
}
|
||||
|
||||
/* Poignée de réorganisation */
|
||||
.grip {
|
||||
flex: none;
|
||||
width: 46px;
|
||||
height: 56px;
|
||||
margin-left: 2px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
background: transparent;
|
||||
color: #b5a99b;
|
||||
cursor: grab;
|
||||
touch-action: none; /* le doigt déplace la tâche au lieu de faire défiler la page */
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
-webkit-touch-callout: none;
|
||||
}
|
||||
.grip::before {
|
||||
content: "";
|
||||
display: block;
|
||||
width: 18px;
|
||||
height: 12px;
|
||||
margin: auto;
|
||||
background: repeating-linear-gradient(to bottom, currentColor 0 2px, transparent 2px 5px);
|
||||
}
|
||||
.grip:active, .grip:focus-visible { color: var(--accent); background: var(--accent-soft); outline: none; }
|
||||
|
||||
.item.dragging {
|
||||
position: relative;
|
||||
z-index: 5;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 10px 28px rgba(43, 36, 32, 0.28);
|
||||
will-change: transform;
|
||||
}
|
||||
body.glisse { user-select: none; -webkit-user-select: none; cursor: grabbing; }
|
||||
|
||||
.check {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-height: 60px;
|
||||
padding: 8px 6px 8px 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.check input { position: absolute; opacity: 0; width: 1px; height: 1px; }
|
||||
.box {
|
||||
flex: none;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 9px;
|
||||
border: 2px solid #cfc3b5;
|
||||
background: #fffdfa;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
transition: background 0.12s, border-color 0.12s;
|
||||
}
|
||||
.box::after {
|
||||
content: "";
|
||||
width: 7px;
|
||||
height: 14px;
|
||||
border: solid #fff;
|
||||
border-width: 0 3px 3px 0;
|
||||
transform: translateY(-1px) rotate(45deg) scale(0);
|
||||
transition: transform 0.12s;
|
||||
}
|
||||
.check input:checked + .box { background: var(--ok); border-color: var(--ok); }
|
||||
.check input:checked + .box::after { transform: translateY(-1px) rotate(45deg) scale(1); }
|
||||
.check input:focus-visible + .box { box-shadow: 0 0 0 3px rgba(140, 47, 47, 0.25); }
|
||||
|
||||
.txt { font-size: 1.05rem; overflow-wrap: anywhere; }
|
||||
.item.done .txt { color: var(--muted); text-decoration: line-through; }
|
||||
|
||||
.del {
|
||||
flex: none;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
margin-right: 4px;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-size: 1.1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.del:active { background: var(--line); }
|
||||
|
||||
.vide { text-align: center; color: var(--muted); padding: 36px 12px; }
|
||||
|
||||
.erreur {
|
||||
margin: 0 0 12px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 12px;
|
||||
background: var(--warn-soft);
|
||||
color: var(--warn);
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.todo-actions { margin-top: 16px; display: grid; }
|
||||
|
||||
|
||||
/* ---------- 6. Grands écrans ---------- */
|
||||
@media (min-width: 900px) {
|
||||
.wrap-large { max-width: 1000px; } /* page Calculateur : deux colonnes de bassines */
|
||||
.bassines { grid-template-columns: 1fr 1fr; }
|
||||
.actions { grid-template-columns: 1fr 1fr; }
|
||||
}
|
||||
|
||||
|
||||
/* ---------- 7. Impression ---------- */
|
||||
@media print {
|
||||
body { background: #fff; }
|
||||
.topbar, .no-print, .clear { display: none !important; }
|
||||
.card, .bassine { box-shadow: none; border: 1px solid #ccc; break-inside: avoid; }
|
||||
.bassine:not(.filled) { display: none; } /* on n'imprime que les bassines pesées */
|
||||
.bassines { grid-template-columns: 1fr 1fr; }
|
||||
input { border: none; background: none; }
|
||||
details { display: none; }
|
||||
}
|
||||
@@ -1,387 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#8c2f2f" />
|
||||
<title>Calculateur d'épices</title>
|
||||
<link rel="stylesheet" href="assets/style.css" />
|
||||
<script src="assets/edition.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<div class="topbar-row">
|
||||
<h1>Calcul des épices</h1>
|
||||
<div class="summary" aria-live="polite">
|
||||
<div><span class="lbl">Viande nette</span><b id="Resume_Net">0.000</b> kg</div>
|
||||
<div><span class="lbl">Rendement</span><b id="Resume_Rendement">0 %</b></div>
|
||||
</div>
|
||||
</div>
|
||||
<nav class="menu" aria-label="Menu principal">
|
||||
<a href="index.html" aria-current="page">Calculateur</a>
|
||||
<a href="todo.html">To-do</a>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="wrap wrap-large">
|
||||
<section class="card">
|
||||
<h2>Rendement</h2>
|
||||
<div class="yield">
|
||||
<div class="field">
|
||||
<label for="Total_Achete">Total acheté (kg)</label>
|
||||
<input type="number" id="Total_Achete" step="any" inputmode="decimal" placeholder="0" />
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="label">Total assaisonné (kg)</div>
|
||||
<div class="value" id="Total_Assaisonne">0.000</div>
|
||||
</div>
|
||||
<div class="stat big">
|
||||
<div class="label">Rendement</div>
|
||||
<div class="value" id="Rendement">0 %</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<details class="card no-print">
|
||||
<summary>Réglages (planche et proportions)</summary>
|
||||
<div class="settings" id="settings"></div>
|
||||
</details>
|
||||
|
||||
<div class="filterbar no-print">
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="Filtre_pesees" />
|
||||
<span class="track"></span>
|
||||
<span>Seulement les pesées</span>
|
||||
</label>
|
||||
<span class="count"><b id="Compteur">0</b> / <span id="CompteurMax">0</span> pesées</span>
|
||||
</div>
|
||||
|
||||
<section class="bassines" id="bassines"></section>
|
||||
|
||||
<section class="card" style="margin-top: 14px">
|
||||
<h2>Totaux</h2>
|
||||
<div class="totals" id="totals"></div>
|
||||
</section>
|
||||
|
||||
<div class="actions no-print">
|
||||
<button type="button" class="btn primary" id="btnPrint">Imprimer la page</button>
|
||||
<button type="button" class="btn" id="btnReset">Vider les pesées</button>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
// ---------- Données ----------
|
||||
const bassines = [
|
||||
{ nom: "Niagara", tare: 6.5 },
|
||||
{ nom: "Manu Chao", tare: 2.7 },
|
||||
{ nom: "Kamini", tare: 2.7 },
|
||||
{ nom: "Tina", tare: 2.7 },
|
||||
{ nom: "Garou", tare: 6.0 },
|
||||
{ nom: "Johnny", tare: 2.7 },
|
||||
{ nom: "Vanessa", tare: 1.7 },
|
||||
{ nom: "Joséphine", tare: 4.9 },
|
||||
{ nom: "Céline", tare: 6.0 },
|
||||
{ nom: "Dalida", tare: 2.5 },
|
||||
{ nom: "Florent", tare: 2.7 },
|
||||
{ nom: "Petite bassine ronde verte (JM)", tare: 1.7 },
|
||||
{ nom: "Grande bassine verte", tare: 2.7 },
|
||||
{ nom: "Caisse grise", tare: 2.45 },
|
||||
{ nom: "Caisse verte", tare: 2.6 },
|
||||
];
|
||||
|
||||
const reglages = [
|
||||
{ id: "Poids_planche", label: "Poids de la planche (kg)", defaut: 4.4 },
|
||||
{ id: "Prop_sel", label: "Sel (kg)", defaut: 0.028 },
|
||||
{ id: "Prop_poivre", label: "Poivre (g)", defaut: 2 },
|
||||
{ id: "Prop_muscade", label: "Muscade (g)", defaut: 1 },
|
||||
{ id: "Prop_ail", label: "Ail (g)", defaut: 2 },
|
||||
];
|
||||
|
||||
// Colonnes calculées : clé, libellé, unité des totaux
|
||||
const colonnes = [
|
||||
{ cle: "net", titre: "Viande nette", unite: "kg", totalId: "Total_Net" },
|
||||
{ cle: "sel", titre: "Sel", unite: "kg", totalId: "Total_Sel" },
|
||||
{ cle: "poivre", titre: "Poivre", unite: "g", totalId: "Total_Poivre" },
|
||||
{ cle: "concasse", titre: "Poivre concassé", unite: "g", totalId: "Total_Poivre_Concasse" },
|
||||
{ cle: "muscade", titre: "Muscade", unite: "g", totalId: "Total_Muscade" },
|
||||
{ cle: "ail", titre: "Ail", unite: "g", totalId: "Total_Ail" },
|
||||
];
|
||||
|
||||
// ---------- Utilitaires ----------
|
||||
const $ = (id) => document.getElementById(id);
|
||||
// Accepte la virgule comme séparateur décimal
|
||||
const nombre = (valeur) => parseFloat(String(valeur).replace(",", ".")) || 0;
|
||||
const valeurChamp = (id) => nombre($(id).value);
|
||||
|
||||
// ---------- Construction de l'interface ----------
|
||||
function construireReglages() {
|
||||
$("settings").innerHTML =
|
||||
reglages
|
||||
.map(
|
||||
(r) => `
|
||||
<div class="field">
|
||||
<label for="${r.id}">${r.label}</label>
|
||||
<input type="text" id="${r.id}" inputmode="decimal" value="${r.defaut}" />
|
||||
</div>`,
|
||||
)
|
||||
.join("") + `<p class="hint">Les proportions s'appliquent par kg de viande nette.</p>`;
|
||||
}
|
||||
|
||||
function construireTotaux() {
|
||||
$("totals").innerHTML = colonnes
|
||||
.map(
|
||||
(c) => `
|
||||
<div class="stat">
|
||||
<div class="label">${c.titre} <span class="unit">(${c.unite})</span></div>
|
||||
<div class="value" id="${c.totalId}">0.000</div>
|
||||
</div>`,
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
function construireBassines() {
|
||||
const tuiles = [
|
||||
["sel", "Sel (kg)"],
|
||||
["poivre", "Poivre (g)"],
|
||||
["concasse", "Concassé (g)"],
|
||||
["muscade", "Muscade (g)"],
|
||||
["ail", "Ail (g)"],
|
||||
];
|
||||
|
||||
$("bassines").innerHTML = bassines
|
||||
.map((b, i) => {
|
||||
const n = i + 1;
|
||||
return `
|
||||
<article class="bassine" id="Bassine_${n}">
|
||||
<div class="b-head">
|
||||
<div>
|
||||
<div class="b-name">${b.nom}</div>
|
||||
<div class="b-tare">Tare ${b.tare.toFixed(3)} kg</div>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="isCouenne${n}" />
|
||||
<span class="track"></span>
|
||||
<span>Couenne</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="b-input">
|
||||
<label for="Poids_bassine_${n}">Poids brut (kg)</label>
|
||||
<div class="input-wrap">
|
||||
<input type="text" class="brut" id="Poids_bassine_${n}" inputmode="decimal"
|
||||
enterkeyhint="next" autocomplete="off" placeholder="0.0" />
|
||||
<button type="button" class="clear" aria-label="Effacer ${b.nom}">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="b-results" data-zone="resultats" hidden>
|
||||
<div class="b-net">
|
||||
<span class="lbl">Viande nette</span>
|
||||
<span><span class="val" data-cle="net"></span><span class="unit">kg</span></span>
|
||||
</div>
|
||||
<div class="tiles">
|
||||
${tuiles
|
||||
.map(
|
||||
([cle, label]) => `
|
||||
<div class="tile"><span class="t-lbl">${label}</span><span class="t-val" data-cle="${cle}"></span></div>`,
|
||||
)
|
||||
.join("")}
|
||||
</div>
|
||||
</div>
|
||||
<p class="b-warn" data-zone="alerte" hidden>Net négatif ou nul : vérifie la pesée.</p>
|
||||
</article>`;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
// ---------- Calculs ----------
|
||||
function calculer() {
|
||||
const planche = valeurChamp("Poids_planche");
|
||||
const propSel = valeurChamp("Prop_sel");
|
||||
const propPoivre = valeurChamp("Prop_poivre");
|
||||
const propMuscade = valeurChamp("Prop_muscade");
|
||||
const propAil = valeurChamp("Prop_ail");
|
||||
const filtre = $("Filtre_pesees").checked;
|
||||
|
||||
const totaux = { net: 0, sel: 0, poivre: 0, concasse: 0, muscade: 0, ail: 0 };
|
||||
let nbPesees = 0;
|
||||
|
||||
bassines.forEach((b, i) => {
|
||||
const n = i + 1;
|
||||
const carte = $("Bassine_" + n);
|
||||
const brut = valeurChamp("Poids_bassine_" + n);
|
||||
const cellule = (cle) => carte.querySelector(`[data-cle="${cle}"]`);
|
||||
const zone = (nom) => carte.querySelector(`[data-zone="${nom}"]`);
|
||||
|
||||
carte.classList.toggle("filled", !!brut);
|
||||
zone("resultats").hidden = !brut;
|
||||
|
||||
// En mode « seulement les pesées », on garde visible la carte en cours de saisie
|
||||
const enSaisie = carte.contains(document.activeElement);
|
||||
carte.hidden = filtre && !brut && !enSaisie;
|
||||
|
||||
if (!brut) {
|
||||
Object.keys(totaux).forEach((cle) => (cellule(cle).textContent = ""));
|
||||
carte.classList.remove("warn");
|
||||
zone("alerte").hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
nbPesees++;
|
||||
|
||||
// Valeurs arrondies à 3 décimales, comme avant
|
||||
const net = parseFloat((brut - b.tare - planche).toFixed(3));
|
||||
const couenne = $("isCouenne" + n).checked;
|
||||
const resultats = {
|
||||
net,
|
||||
sel: parseFloat((net * (couenne ? propSel / 2 : propSel)).toFixed(3)),
|
||||
poivre: parseFloat((net * propPoivre * 0.6).toFixed(3)),
|
||||
concasse: parseFloat((net * propPoivre * 0.4).toFixed(3)),
|
||||
muscade: parseFloat((net * propMuscade).toFixed(3)),
|
||||
ail: parseFloat((net * propAil).toFixed(3)),
|
||||
};
|
||||
|
||||
Object.entries(resultats).forEach(([cle, v]) => {
|
||||
cellule(cle).textContent = v.toFixed(3);
|
||||
totaux[cle] += v;
|
||||
});
|
||||
|
||||
const negatif = net <= 0;
|
||||
carte.classList.toggle("warn", negatif);
|
||||
zone("alerte").hidden = !negatif;
|
||||
});
|
||||
|
||||
colonnes.forEach((c) => ($(c.totalId).textContent = totaux[c.cle].toFixed(3)));
|
||||
$("Compteur").textContent = nbPesees;
|
||||
|
||||
calculerTotalAssaisonne(totaux);
|
||||
|
||||
// Récapitulatif de la barre du haut
|
||||
$("Resume_Net").textContent = $("Total_Net").textContent;
|
||||
$("Resume_Rendement").textContent = $("Rendement").textContent;
|
||||
}
|
||||
|
||||
// Rendement : formule inchangée (net total / total acheté × 100)
|
||||
function calculerTotalAssaisonne(totaux) {
|
||||
const totalNet = parseFloat(totaux.net.toFixed(3));
|
||||
const totalSel = parseFloat(totaux.sel.toFixed(3));
|
||||
const totalPoivre = parseFloat(totaux.poivre.toFixed(3));
|
||||
const totalPoivreConcasse = parseFloat(totaux.concasse.toFixed(3));
|
||||
const totalMuscade = parseFloat(totaux.muscade.toFixed(3));
|
||||
const totalAil = parseFloat(totaux.ail.toFixed(3));
|
||||
|
||||
const totalAssaisonne =
|
||||
totalNet +
|
||||
totalSel +
|
||||
totalPoivre / 1000 +
|
||||
totalPoivreConcasse / 1000 +
|
||||
totalMuscade / 1000 +
|
||||
totalAil / 1000;
|
||||
$("Total_Assaisonne").textContent = totalAssaisonne.toFixed(3);
|
||||
|
||||
const totalAchete = valeurChamp("Total_Achete");
|
||||
if (totalAchete > 0) {
|
||||
const rendement = (totalNet / totalAchete) * 100;
|
||||
$("Rendement").textContent = rendement.toFixed(3) + " %";
|
||||
} else {
|
||||
$("Rendement").textContent = "0 %";
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Sauvegarde locale (48 h) ----------
|
||||
const STORAGE_KEY = "calculateurEpices";
|
||||
const MAX_AGE = 48 * 60 * 60 * 1000; // 48 h
|
||||
|
||||
function sauvegarder() {
|
||||
try {
|
||||
const values = {};
|
||||
document.querySelectorAll("input").forEach((input) => {
|
||||
values[input.id] = input.type === "checkbox" ? input.checked : input.value;
|
||||
});
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify({ timestamp: Date.now(), values }));
|
||||
} catch (e) {
|
||||
/* stockage indisponible : on ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function restaurer() {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY));
|
||||
if (saved && Date.now() - saved.timestamp < MAX_AGE) {
|
||||
for (const [id, value] of Object.entries(saved.values)) {
|
||||
const input = $(id);
|
||||
if (!input) continue;
|
||||
if (input.type === "checkbox") input.checked = value;
|
||||
else input.value = value;
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
} catch (e) {
|
||||
/* données illisibles : on repart de zéro */
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Démarrage ----------
|
||||
function demarrer() {
|
||||
construireReglages();
|
||||
construireTotaux();
|
||||
construireBassines();
|
||||
$("CompteurMax").textContent = bassines.length;
|
||||
restaurer();
|
||||
calculer();
|
||||
|
||||
const maj = () => {
|
||||
calculer();
|
||||
sauvegarder();
|
||||
};
|
||||
document.body.addEventListener("input", maj);
|
||||
document.body.addEventListener("change", maj);
|
||||
|
||||
// Sélectionne le contenu au focus : on remplace une valeur d'un seul geste
|
||||
document.body.addEventListener("focusin", (e) => {
|
||||
if (e.target.matches('input[type="text"], input[type="number"]')) {
|
||||
setTimeout(() => e.target.select(), 0);
|
||||
}
|
||||
});
|
||||
|
||||
// « Entrée / Suivant » passe à la bassine suivante
|
||||
document.body.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter" || !e.target.matches(".brut")) return;
|
||||
e.preventDefault();
|
||||
const champs = [...document.querySelectorAll(".brut")].filter((c) => !c.closest("[hidden]"));
|
||||
const suivant = champs[champs.indexOf(e.target) + 1];
|
||||
if (suivant) {
|
||||
suivant.focus();
|
||||
suivant.scrollIntoView({ block: "center", behavior: "smooth" });
|
||||
} else {
|
||||
e.target.blur();
|
||||
}
|
||||
});
|
||||
|
||||
// Bouton ✕ : efface la pesée de la bassine
|
||||
document.body.addEventListener("click", (e) => {
|
||||
const bouton = e.target.closest(".clear");
|
||||
if (!bouton) return;
|
||||
const champ = bouton.previousElementSibling;
|
||||
champ.value = "";
|
||||
champ.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
champ.focus();
|
||||
});
|
||||
|
||||
$("btnPrint").addEventListener("click", () => window.print());
|
||||
|
||||
$("btnReset").addEventListener("click", () => {
|
||||
if (!confirm("Vider toutes les pesées et le total acheté ? (les réglages sont conservés)")) return;
|
||||
bassines.forEach((_, i) => {
|
||||
$("Poids_bassine_" + (i + 1)).value = "";
|
||||
$("isCouenne" + (i + 1)).checked = false;
|
||||
});
|
||||
$("Total_Achete").value = "";
|
||||
maj();
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
});
|
||||
}
|
||||
|
||||
demarrer();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,387 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#8c2f2f" />
|
||||
<title>To-do – Calcul des épices</title>
|
||||
<link rel="stylesheet" href="assets/style.css" />
|
||||
<script src="assets/edition.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<div class="topbar-row">
|
||||
<h1>Liste de tâches</h1>
|
||||
<span class="live off" id="statut" role="status">Connexion…</span>
|
||||
</div>
|
||||
<nav class="menu" aria-label="Menu principal">
|
||||
<a href="index.html">Calculateur</a>
|
||||
<a href="todo.html" aria-current="page">To-do</a>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="wrap">
|
||||
<form class="add" id="formAjout" autocomplete="off">
|
||||
<input type="text" id="champAjout" placeholder="Nouvelle tâche…" maxlength="200" enterkeyhint="done"
|
||||
aria-label="Nouvelle tâche" />
|
||||
<button type="submit" class="btn primary">Ajouter</button>
|
||||
</form>
|
||||
|
||||
<p class="erreur" id="erreur" hidden></p>
|
||||
|
||||
<div class="info">
|
||||
<span><b id="restantes">0</b> à faire · <span id="faites">0</span> faites</span>
|
||||
<span>Partagée en direct</span>
|
||||
</div>
|
||||
|
||||
<ul class="liste" id="liste"></ul>
|
||||
<p class="vide" id="vide" hidden>Aucune tâche pour l'instant.</p>
|
||||
|
||||
<div class="todo-actions">
|
||||
<button type="button" class="btn" id="btnNettoyer" hidden>Supprimer les tâches cochées</button>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
let todos = [];
|
||||
let premierChargement = true;
|
||||
let minuterieErreur;
|
||||
let glisse = null; // état du glissement en cours (null = aucun)
|
||||
let enAttente = null; // liste reçue pendant un glissement, appliquée ensuite
|
||||
|
||||
// ---------- Affichage ----------
|
||||
function rendre(modifies = new Set()) {
|
||||
const liste = $("liste");
|
||||
// On retient l'élément qui avait le focus pour le lui rendre après le redessin
|
||||
const actif = document.activeElement;
|
||||
const lignActive = actif && actif.closest ? actif.closest(".item") : null;
|
||||
const focus = lignActive ? { id: lignActive.dataset.id, poignee: actif.classList.contains("grip") } : null;
|
||||
liste.textContent = "";
|
||||
|
||||
for (const t of todos) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "item" + (t.done ? " done" : "") + (modifies.has(t.id) ? " flash" : "");
|
||||
li.dataset.id = t.id;
|
||||
|
||||
const etiquette = document.createElement("label");
|
||||
etiquette.className = "check";
|
||||
const caseACocher = document.createElement("input");
|
||||
caseACocher.type = "checkbox";
|
||||
caseACocher.checked = t.done;
|
||||
const boite = document.createElement("span");
|
||||
boite.className = "box";
|
||||
const texte = document.createElement("span");
|
||||
texte.className = "txt";
|
||||
texte.textContent = t.text; // textContent : jamais de HTML injecté
|
||||
etiquette.append(caseACocher, boite, texte);
|
||||
|
||||
const suppr = document.createElement("button");
|
||||
suppr.type = "button";
|
||||
suppr.className = "del";
|
||||
suppr.setAttribute("aria-label", "Supprimer : " + t.text);
|
||||
suppr.textContent = "✕";
|
||||
|
||||
const poignee = document.createElement("button");
|
||||
poignee.type = "button";
|
||||
poignee.className = "grip";
|
||||
poignee.title = "Glisser pour déplacer";
|
||||
poignee.setAttribute("aria-label", "Déplacer : " + t.text + " (glisser, ou flèches haut et bas)");
|
||||
|
||||
li.append(poignee, etiquette, suppr);
|
||||
liste.append(li);
|
||||
}
|
||||
|
||||
const faites = todos.filter((t) => t.done).length;
|
||||
$("restantes").textContent = todos.length - faites;
|
||||
$("faites").textContent = faites;
|
||||
$("vide").hidden = todos.length > 0;
|
||||
$("btnNettoyer").hidden = faites === 0;
|
||||
|
||||
if (focus) {
|
||||
const ligne = liste.querySelector(`.item[data-id="${CSS.escape(focus.id)}"]`);
|
||||
const cible = ligne && ligne.querySelector(focus.poignee ? ".grip" : 'input[type="checkbox"]');
|
||||
if (cible) cible.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
|
||||
// Reçoit la liste du serveur ; met en évidence ce que les autres viennent de changer
|
||||
function recevoir(nouvelle) {
|
||||
// Pendant un glissement, on ne redessine pas la liste (la carte déplacée disparaîtrait)
|
||||
if (glisse) {
|
||||
enAttente = nouvelle;
|
||||
return;
|
||||
}
|
||||
const avant = new Map(todos.map((t) => [t.id, t]));
|
||||
const modifies = new Set();
|
||||
if (!premierChargement) {
|
||||
for (const t of nouvelle) {
|
||||
const p = avant.get(t.id);
|
||||
if (!p || p.done !== t.done || p.text !== t.text) modifies.add(t.id);
|
||||
}
|
||||
}
|
||||
premierChargement = false;
|
||||
todos = nouvelle;
|
||||
rendre(modifies);
|
||||
}
|
||||
|
||||
function etat(enLigne) {
|
||||
const el = $("statut");
|
||||
el.classList.toggle("off", !enLigne);
|
||||
el.textContent = enLigne ? "En direct" : "Hors ligne…";
|
||||
}
|
||||
|
||||
function afficherErreur(message) {
|
||||
const el = $("erreur");
|
||||
el.textContent = message;
|
||||
el.hidden = false;
|
||||
clearTimeout(minuterieErreur);
|
||||
minuterieErreur = setTimeout(() => (el.hidden = true), 4000);
|
||||
}
|
||||
|
||||
// ---------- Appels au serveur ----------
|
||||
async function appeler(methode, url, corps) {
|
||||
const reponse = await fetch(url, {
|
||||
method: methode,
|
||||
headers: corps ? { "Content-Type": "application/json" } : undefined,
|
||||
body: corps ? JSON.stringify(corps) : undefined,
|
||||
});
|
||||
if (!reponse.ok) throw new Error("HTTP " + reponse.status);
|
||||
return reponse.json();
|
||||
}
|
||||
|
||||
async function resynchroniser() {
|
||||
try {
|
||||
recevoir(await appeler("GET", "/api/todos"));
|
||||
etat(true);
|
||||
} catch {
|
||||
etat(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function basculer(id, done) {
|
||||
const tache = todos.find((t) => t.id === id);
|
||||
if (!tache) return;
|
||||
tache.done = done; // affichage immédiat, le serveur confirme ensuite
|
||||
rendre();
|
||||
try {
|
||||
await appeler("PATCH", "/api/todos/" + id, { done });
|
||||
} catch {
|
||||
afficherErreur("Action impossible, réessaie.");
|
||||
resynchroniser();
|
||||
}
|
||||
}
|
||||
|
||||
async function supprimer(id) {
|
||||
todos = todos.filter((t) => t.id !== id);
|
||||
rendre();
|
||||
try {
|
||||
await appeler("DELETE", "/api/todos/" + id);
|
||||
} catch {
|
||||
afficherErreur("Suppression impossible, réessaie.");
|
||||
resynchroniser();
|
||||
}
|
||||
}
|
||||
|
||||
async function ajouter(texte) {
|
||||
try {
|
||||
const tache = await appeler("POST", "/api/todos", { text: texte });
|
||||
if (!todos.some((t) => t.id === tache.id)) {
|
||||
todos.push(tache);
|
||||
rendre();
|
||||
}
|
||||
} catch {
|
||||
afficherErreur("Ajout impossible, réessaie.");
|
||||
$("champAjout").value = texte;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Temps réel ----------
|
||||
function connecter() {
|
||||
const flux = new EventSource("/api/events");
|
||||
flux.onopen = () => etat(true);
|
||||
flux.onmessage = (e) => {
|
||||
etat(true);
|
||||
recevoir(JSON.parse(e.data));
|
||||
};
|
||||
flux.onerror = () => {
|
||||
etat(false);
|
||||
// Le navigateur se reconnecte seul ; si la connexion est fermée pour de bon, on la relance
|
||||
if (flux.readyState === EventSource.CLOSED) setTimeout(connecter, 3000);
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- Réorganisation : glisser la poignée (doigt ou souris) ou flèches haut/bas ----------
|
||||
// Le serveur ne reçoit qu'un déplacement : « cette tâche juste avant celle-là » (ou à la fin)
|
||||
async function validerOrdre(li) {
|
||||
// L'ordre local suit déjà l'ordre affiché à l'écran
|
||||
const parId = new Map(todos.map((t) => [t.id, t]));
|
||||
todos = [...$("liste").children].map((el) => parId.get(el.dataset.id)).filter(Boolean);
|
||||
const suivante = li.nextElementSibling;
|
||||
try {
|
||||
await appeler("POST", "/api/todos/" + li.dataset.id + "/move", {
|
||||
beforeId: suivante ? suivante.dataset.id : null,
|
||||
});
|
||||
} catch {
|
||||
afficherErreur("Déplacement impossible, réessaie.");
|
||||
await resynchroniser();
|
||||
}
|
||||
}
|
||||
|
||||
// Replace la carte sous le doigt et échange sa place avec ses voisines quand il le faut
|
||||
function majGlisser() {
|
||||
const { li } = glisse;
|
||||
const liste = $("liste");
|
||||
li.style.transform = `translateY(${glisse.y - glisse.departY}px)`;
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const r = li.getBoundingClientRect();
|
||||
const centre = r.top + r.height / 2;
|
||||
const suivante = li.nextElementSibling;
|
||||
const precedente = li.previousElementSibling;
|
||||
let voisine = null;
|
||||
let apres = false;
|
||||
if (suivante && centre > suivante.getBoundingClientRect().top + suivante.offsetHeight / 2) {
|
||||
voisine = suivante;
|
||||
apres = true;
|
||||
} else if (precedente && centre < precedente.getBoundingClientRect().top + precedente.offsetHeight / 2) {
|
||||
voisine = precedente;
|
||||
}
|
||||
if (!voisine) break;
|
||||
|
||||
const hautAvant = li.getBoundingClientRect().top;
|
||||
liste.insertBefore(li, apres ? voisine.nextSibling : voisine);
|
||||
// Sa place « de base » a changé : on corrige pour que la carte reste exactement sous le doigt
|
||||
glisse.departY += li.getBoundingClientRect().top - hautAvant;
|
||||
li.style.transform = `translateY(${glisse.y - glisse.departY}px)`;
|
||||
}
|
||||
}
|
||||
|
||||
// Fait défiler la page quand on approche du bord de l'écran pendant un glissement
|
||||
function defilementAuto() {
|
||||
if (!glisse) return;
|
||||
const haut = 150; // sous la barre du haut, qui reste collée
|
||||
const bas = window.innerHeight - 90;
|
||||
let vitesse = 0;
|
||||
if (glisse.y < haut) vitesse = -Math.ceil((haut - glisse.y) / 8);
|
||||
else if (glisse.y > bas) vitesse = Math.ceil((glisse.y - bas) / 8);
|
||||
vitesse = Math.max(-24, Math.min(24, vitesse));
|
||||
if (vitesse) {
|
||||
const avant = window.scrollY;
|
||||
window.scrollBy(0, vitesse);
|
||||
const reel = window.scrollY - avant;
|
||||
if (reel) {
|
||||
glisse.departY -= reel; // la page a bougé : la carte doit suivre le doigt
|
||||
majGlisser();
|
||||
}
|
||||
}
|
||||
requestAnimationFrame(defilementAuto);
|
||||
}
|
||||
|
||||
async function finGlisser() {
|
||||
if (!glisse) return;
|
||||
const { li, indexDepart } = glisse;
|
||||
li.classList.remove("dragging");
|
||||
li.style.transform = "";
|
||||
document.body.classList.remove("glisse");
|
||||
const aBouge = [...$("liste").children].indexOf(li) !== indexDepart;
|
||||
glisse = null;
|
||||
if (aBouge) await validerOrdre(li);
|
||||
if (enAttente) {
|
||||
enAttente = null;
|
||||
await resynchroniser(); // des changements d'autres personnes sont arrivés pendant le glissement
|
||||
}
|
||||
}
|
||||
|
||||
$("liste").addEventListener("pointerdown", (e) => {
|
||||
const poignee = e.target.closest(".grip");
|
||||
if (!poignee || glisse || (e.pointerType === "mouse" && e.button !== 0)) return;
|
||||
e.preventDefault();
|
||||
const li = poignee.closest(".item");
|
||||
poignee.setPointerCapture(e.pointerId);
|
||||
glisse = {
|
||||
li,
|
||||
pointerId: e.pointerId,
|
||||
departY: e.clientY,
|
||||
y: e.clientY,
|
||||
indexDepart: [...$("liste").children].indexOf(li),
|
||||
};
|
||||
li.classList.add("dragging");
|
||||
document.body.classList.add("glisse");
|
||||
requestAnimationFrame(defilementAuto);
|
||||
});
|
||||
|
||||
$("liste").addEventListener("pointermove", (e) => {
|
||||
if (!glisse || e.pointerId !== glisse.pointerId) return;
|
||||
glisse.y = e.clientY;
|
||||
majGlisser();
|
||||
});
|
||||
|
||||
const relacher = (e) => {
|
||||
if (glisse && e.pointerId === glisse.pointerId) finGlisser();
|
||||
};
|
||||
$("liste").addEventListener("pointerup", relacher);
|
||||
$("liste").addEventListener("pointercancel", relacher);
|
||||
$("liste").addEventListener("lostpointercapture", relacher);
|
||||
|
||||
// Pas de menu contextuel au toucher long sur la poignée
|
||||
$("liste").addEventListener("contextmenu", (e) => {
|
||||
if (e.target.closest(".grip")) e.preventDefault();
|
||||
});
|
||||
|
||||
// Clavier : la poignée prise au focus se déplace avec les flèches haut / bas
|
||||
$("liste").addEventListener("keydown", (e) => {
|
||||
if (!e.target.matches(".grip") || (e.key !== "ArrowUp" && e.key !== "ArrowDown")) return;
|
||||
e.preventDefault();
|
||||
const li = e.target.closest(".item");
|
||||
if (e.key === "ArrowUp" && li.previousElementSibling) {
|
||||
li.parentNode.insertBefore(li, li.previousElementSibling);
|
||||
} else if (e.key === "ArrowDown" && li.nextElementSibling) {
|
||||
li.parentNode.insertBefore(li.nextElementSibling, li);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
e.target.focus();
|
||||
validerOrdre(li);
|
||||
});
|
||||
|
||||
// ---------- Interactions ----------
|
||||
$("formAjout").addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
const champ = $("champAjout");
|
||||
const texte = champ.value.trim();
|
||||
if (!texte) return;
|
||||
champ.value = ""; // le champ garde le focus : on enchaîne les ajouts
|
||||
ajouter(texte);
|
||||
});
|
||||
|
||||
$("liste").addEventListener("change", (e) => {
|
||||
if (!e.target.matches('input[type="checkbox"]')) return;
|
||||
basculer(e.target.closest(".item").dataset.id, e.target.checked);
|
||||
});
|
||||
|
||||
$("liste").addEventListener("click", (e) => {
|
||||
const bouton = e.target.closest(".del");
|
||||
if (bouton) supprimer(bouton.closest(".item").dataset.id);
|
||||
});
|
||||
|
||||
$("btnNettoyer").addEventListener("click", async () => {
|
||||
if (!confirm("Supprimer les tâches cochées pour tout le monde ?")) return;
|
||||
try {
|
||||
recevoir(await appeler("POST", "/api/todos/clear-done"));
|
||||
} catch {
|
||||
afficherErreur("Action impossible, réessaie.");
|
||||
}
|
||||
});
|
||||
|
||||
// Au retour sur l'onglet (téléphone en veille), on se remet à jour
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "visible") resynchroniser();
|
||||
});
|
||||
|
||||
resynchroniser();
|
||||
connecter();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,284 +0,0 @@
|
||||
"use strict";
|
||||
/**
|
||||
* Mini-serveur sans dépendance :
|
||||
* - sert les fichiers du dossier public/
|
||||
* - garde la to-do list partagée dans un fichier JSON
|
||||
* - diffuse chaque changement en direct à tous les appareils connectés (SSE)
|
||||
*/
|
||||
const http = require("http");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
|
||||
const PORT = Number(process.env.PORT) || 3000;
|
||||
const PUBLIC_DIR = path.join(__dirname, "public");
|
||||
const DATA_FILE = process.env.DATA_FILE || path.join(__dirname, "data", "todos.json");
|
||||
const MAX_ITEMS = 500;
|
||||
const MAX_TEXT = 200;
|
||||
const MAX_BODY = 10 * 1024;
|
||||
|
||||
const MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".json": "application/json; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
".ico": "image/x-icon",
|
||||
".webmanifest": "application/manifest+json",
|
||||
};
|
||||
|
||||
// ---------- Données ----------
|
||||
function charger() {
|
||||
try {
|
||||
const liste = JSON.parse(fs.readFileSync(DATA_FILE, "utf8"));
|
||||
return Array.isArray(liste) ? liste : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
let todos = charger();
|
||||
|
||||
function sauvegarder() {
|
||||
fs.mkdirSync(path.dirname(DATA_FILE), { recursive: true });
|
||||
const tmp = DATA_FILE + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(todos));
|
||||
fs.renameSync(tmp, DATA_FILE); // écriture atomique
|
||||
}
|
||||
|
||||
// ---------- Date de la prochaine édition (partagée par tout le monde) ----------
|
||||
const CONFIG_FILE = process.env.CONFIG_FILE || path.join(path.dirname(DATA_FILE), "config.json");
|
||||
|
||||
function dateValide(valeur) {
|
||||
if (typeof valeur !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(valeur)) return false;
|
||||
const d = new Date(valeur + "T00:00:00Z");
|
||||
return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === valeur; // refuse le 31 février, etc.
|
||||
}
|
||||
|
||||
function chargerEdition() {
|
||||
try {
|
||||
const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
|
||||
return { date: dateValide(config.date) ? config.date : null };
|
||||
} catch {
|
||||
return { date: null };
|
||||
}
|
||||
}
|
||||
|
||||
let edition = chargerEdition();
|
||||
|
||||
function sauvegarderEdition() {
|
||||
fs.mkdirSync(path.dirname(CONFIG_FILE), { recursive: true });
|
||||
const tmp = CONFIG_FILE + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(edition));
|
||||
fs.renameSync(tmp, CONFIG_FILE);
|
||||
}
|
||||
|
||||
// ---------- Temps réel (Server-Sent Events) ----------
|
||||
const clients = new Set(); // flux de la to-do list
|
||||
const clientsEdition = new Set(); // flux de la date de l'édition
|
||||
|
||||
function diffuser() {
|
||||
const message = `data: ${JSON.stringify(todos)}\n\n`;
|
||||
for (const res of clients) res.write(message);
|
||||
}
|
||||
|
||||
function diffuserEdition() {
|
||||
const message = `data: ${JSON.stringify(edition)}\n\n`;
|
||||
for (const res of clientsEdition) res.write(message);
|
||||
}
|
||||
|
||||
function ouvrirFlux(req, res, ensemble, donnees) {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
});
|
||||
res.write("retry: 3000\n\n");
|
||||
res.write(`data: ${JSON.stringify(donnees)}\n\n`);
|
||||
ensemble.add(res);
|
||||
req.on("close", () => ensemble.delete(res));
|
||||
}
|
||||
|
||||
// Un signe de vie régulier empêche les proxys de couper la connexion
|
||||
setInterval(() => {
|
||||
for (const res of clients) res.write(": ping\n\n");
|
||||
for (const res of clientsEdition) res.write(": ping\n\n");
|
||||
}, 25000);
|
||||
|
||||
// ---------- Utilitaires HTTP ----------
|
||||
function envoyerJson(res, statut, donnees) {
|
||||
res.writeHead(statut, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
||||
res.end(JSON.stringify(donnees));
|
||||
}
|
||||
|
||||
function lireJson(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let taille = 0;
|
||||
const morceaux = [];
|
||||
req.on("data", (morceau) => {
|
||||
taille += morceau.length;
|
||||
if (taille > MAX_BODY) {
|
||||
reject(new Error("Requête trop volumineuse"));
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
morceaux.push(morceau);
|
||||
});
|
||||
req.on("end", () => {
|
||||
try {
|
||||
resolve(morceaux.length ? JSON.parse(Buffer.concat(morceaux).toString("utf8")) : {});
|
||||
} catch {
|
||||
reject(new Error("JSON invalide"));
|
||||
}
|
||||
});
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
const nettoyerTexte = (valeur) => String(valeur ?? "").replace(/\s+/g, " ").trim().slice(0, MAX_TEXT);
|
||||
|
||||
// ---------- API ----------
|
||||
async function api(req, res, url) {
|
||||
const [, ressource, id, action] = url.pathname.split("/").filter(Boolean); // /api/<ressource>/<id>/<action>
|
||||
|
||||
if (ressource === "events" && req.method === "GET") {
|
||||
return ouvrirFlux(req, res, clients, todos);
|
||||
}
|
||||
|
||||
// Date de la prochaine édition : GET / PUT { date: "AAAA-MM-JJ" | null } / flux /api/edition/events
|
||||
if (ressource === "edition") {
|
||||
if (id === "events" && req.method === "GET") return ouvrirFlux(req, res, clientsEdition, edition);
|
||||
if (!id && req.method === "GET") return envoyerJson(res, 200, edition);
|
||||
if (!id && req.method === "PUT") {
|
||||
const corps = await lireJson(req);
|
||||
if (corps.date === null || corps.date === "") edition = { date: null };
|
||||
else if (dateValide(corps.date)) edition = { date: corps.date };
|
||||
else return envoyerJson(res, 400, { erreur: "Date invalide (format AAAA-MM-JJ)" });
|
||||
sauvegarderEdition();
|
||||
diffuserEdition();
|
||||
return envoyerJson(res, 200, edition);
|
||||
}
|
||||
return envoyerJson(res, 405, { erreur: "Méthode non autorisée" });
|
||||
}
|
||||
|
||||
if (ressource !== "todos") return envoyerJson(res, 404, { erreur: "Introuvable" });
|
||||
|
||||
// GET /api/todos
|
||||
if (!id && req.method === "GET") return envoyerJson(res, 200, todos);
|
||||
|
||||
// POST /api/todos { text }
|
||||
if (!id && req.method === "POST") {
|
||||
const corps = await lireJson(req);
|
||||
const text = nettoyerTexte(corps.text);
|
||||
if (!text) return envoyerJson(res, 400, { erreur: "Texte vide" });
|
||||
if (todos.length >= MAX_ITEMS) return envoyerJson(res, 400, { erreur: "Liste pleine" });
|
||||
const tache = { id: crypto.randomUUID(), text, done: false, createdAt: Date.now() };
|
||||
todos.push(tache);
|
||||
sauvegarder();
|
||||
diffuser();
|
||||
return envoyerJson(res, 201, tache);
|
||||
}
|
||||
|
||||
// POST /api/todos/clear-done : supprime toutes les tâches cochées
|
||||
if (id === "clear-done" && req.method === "POST") {
|
||||
todos = todos.filter((t) => !t.done);
|
||||
sauvegarder();
|
||||
diffuser();
|
||||
return envoyerJson(res, 200, todos);
|
||||
}
|
||||
|
||||
// POST /api/todos/:id/move { beforeId } : place la tâche juste avant beforeId (ou à la fin si null)
|
||||
// Un déplacement = une seule tâche qui bouge : pas de conflit si quelqu'un d'autre modifie la liste en même temps
|
||||
if (id && action === "move" && req.method === "POST") {
|
||||
const corps = await lireJson(req);
|
||||
const index = todos.findIndex((t) => t.id === id);
|
||||
if (index === -1) return envoyerJson(res, 404, { erreur: "Tâche introuvable" });
|
||||
const [tache] = todos.splice(index, 1);
|
||||
const cible = typeof corps.beforeId === "string" ? todos.findIndex((t) => t.id === corps.beforeId) : -1;
|
||||
if (cible === -1) todos.push(tache);
|
||||
else todos.splice(cible, 0, tache);
|
||||
sauvegarder();
|
||||
diffuser();
|
||||
return envoyerJson(res, 200, todos);
|
||||
}
|
||||
|
||||
if (action) return envoyerJson(res, 404, { erreur: "Introuvable" });
|
||||
|
||||
// PATCH /api/todos/:id { done?, text? }
|
||||
if (id && req.method === "PATCH") {
|
||||
const tache = todos.find((t) => t.id === id);
|
||||
if (!tache) return envoyerJson(res, 404, { erreur: "Tâche introuvable" });
|
||||
const corps = await lireJson(req);
|
||||
if (typeof corps.done === "boolean") tache.done = corps.done;
|
||||
if (typeof corps.text === "string" && nettoyerTexte(corps.text)) tache.text = nettoyerTexte(corps.text);
|
||||
sauvegarder();
|
||||
diffuser();
|
||||
return envoyerJson(res, 200, tache);
|
||||
}
|
||||
|
||||
// DELETE /api/todos/:id
|
||||
if (id && req.method === "DELETE") {
|
||||
const avant = todos.length;
|
||||
todos = todos.filter((t) => t.id !== id);
|
||||
if (todos.length === avant) return envoyerJson(res, 404, { erreur: "Tâche introuvable" });
|
||||
sauvegarder();
|
||||
diffuser();
|
||||
return envoyerJson(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
return envoyerJson(res, 405, { erreur: "Méthode non autorisée" });
|
||||
}
|
||||
|
||||
// ---------- Fichiers statiques ----------
|
||||
function statique(req, res, url) {
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
res.writeHead(405);
|
||||
return res.end();
|
||||
}
|
||||
|
||||
let relatif;
|
||||
try {
|
||||
relatif = decodeURIComponent(url.pathname);
|
||||
} catch {
|
||||
res.writeHead(400);
|
||||
return res.end();
|
||||
}
|
||||
if (relatif.endsWith("/")) relatif += "index.html";
|
||||
|
||||
const fichier = path.normalize(path.join(PUBLIC_DIR, relatif));
|
||||
if (!fichier.startsWith(PUBLIC_DIR + path.sep)) {
|
||||
res.writeHead(403);
|
||||
return res.end();
|
||||
}
|
||||
|
||||
fs.readFile(fichier, (erreur, contenu) => {
|
||||
if (erreur) {
|
||||
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
||||
return res.end("Page introuvable");
|
||||
}
|
||||
res.writeHead(200, {
|
||||
"Content-Type": MIME[path.extname(fichier).toLowerCase()] || "application/octet-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
});
|
||||
res.end(req.method === "HEAD" ? undefined : contenu);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- Serveur ----------
|
||||
const serveur = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
if (url.pathname === "/healthz") return envoyerJson(res, 200, { ok: true });
|
||||
if (url.pathname.startsWith("/api/")) return await api(req, res, url);
|
||||
return statique(req, res, url);
|
||||
} catch (erreur) {
|
||||
if (!res.headersSent) envoyerJson(res, 400, { erreur: erreur.message });
|
||||
else res.end();
|
||||
}
|
||||
});
|
||||
|
||||
serveur.listen(PORT, "0.0.0.0", () => {
|
||||
console.log(`Serveur démarré sur le port ${PORT} (données : ${DATA_FILE})`);
|
||||
});
|
||||
Reference in New Issue
Block a user