Add autosave draft system for partage form with HTMX-based session persistence

- New fragment endpoint POST/GET /partage/fragments/draft.php:
  saves all form fields to PHP session, excludes file/csrf/slug fields
  GET returns JSON for JS hydration on page load
  rotates both global CSRF and share CSRF tokens in sync

- form.php accepts optional $formExtraAttrs and $showAutosaveStatus:
  allows injecting HTMX attributes and 'Brouillon enregistré' indicator

- renderShareLinkForm adds hx-post with change/input debounce trigger,
  loads autosave-handler.js, hydrate fields from draft on page load

- Draft cleared on successful form submission in handleShareLinkSubmission

- autosave-handler.js now also updates share_link_token hidden input
  when rotating CSRF token (partage form uses both csrf_token and share_link_token)

- Added .autosave-status CSS to form.css (was admin.css-only)

- Updated fragment routing to accept GET requests (needed for draft hydration)
This commit is contained in:
Pontoporeia
2026-06-11 10:32:53 +02:00
parent 4b37a05be3
commit 99125cc8e3
33 changed files with 1388 additions and 806 deletions

File diff suppressed because one or more lines are too long

View File

@@ -19,7 +19,7 @@ return (new Config())
->setFinder(
(new Finder())
->in(__DIR__ . '/app/src')
->in(__DIR__ . '/app/tests')
->in(__DIR__ . '/tests')
->name('*.php')
)
;

File diff suppressed because one or more lines are too long

View File

@@ -6,24 +6,30 @@
*
* Provides visual feedback on the originating button.
*/
(function () {
'use strict';
window.copyTextToClipboard = function (text) {
(() => {
window.copyTextToClipboard = (text) => {
var btn;
var origTitle;
var origHTML;
if (!text) return;
navigator.clipboard.writeText(text).then(function () {
var btn = window.event && window.event.target ? window.event.target.closest('button') : null;
navigator.clipboard
.writeText(text)
.then(() => {
btn = window.event?.target
? window.event.target.closest("button")
: null;
if (btn) {
var origTitle = btn.getAttribute('title') || '';
var origHTML = btn.innerHTML;
btn.setAttribute('title', '\u2713 Copi\u00e9');
btn.innerHTML = '\u2713';
setTimeout(function () {
btn.setAttribute('title', origTitle);
origTitle = btn.getAttribute("title") || "";
origHTML = btn.innerHTML;
btn.setAttribute("title", "\u2713 Copi\u00e9");
btn.innerHTML = "\u2713";
setTimeout(() => {
btn.setAttribute("title", origTitle);
btn.innerHTML = origHTML;
}, 1200);
}
}).catch(function () {
})
.catch(() => {
// Clipboard write failed — silently ignore
});
};

View File

@@ -12,86 +12,90 @@
* #access-justification — justification textarea
* #access-request-message — message display div
*/
(function () {
'use strict';
var form = document.getElementById('access-request-form');
(() => {
var form = document.getElementById("access-request-form");
if (!form) return;
var emailInput = document.getElementById('access-email');
var justificationContainer = document.getElementById('justification-container');
var justificationInput = document.getElementById('access-justification');
var messageDiv = document.getElementById('access-request-message');
var emailInput = document.getElementById("access-email");
var justificationContainer = document.getElementById(
"justification-container",
);
var justificationInput = document.getElementById("access-justification");
var messageDiv = document.getElementById("access-request-message");
if (!emailInput || !messageDiv) return;
// Show/hide justification based on email domain
emailInput.addEventListener('input', function () {
emailInput.addEventListener("input", function () {
var email = this.value.trim().toLowerCase();
var isErg = email.endsWith('@erg.school') || email.endsWith('@erg.be');
if (justificationContainer) justificationContainer.style.display = isErg ? 'none' : 'block';
var isErg = email.endsWith("@erg.school") || email.endsWith("@erg.be");
if (justificationContainer)
justificationContainer.style.display = isErg ? "none" : "block";
if (justificationInput) justificationInput.required = !isErg;
});
function showRetryPrompt(rejectedEmail, serverMessage) {
messageDiv.style.display = 'block';
messageDiv.className = 'tfe-access-message tfe-access-error';
messageDiv.style.display = "block";
messageDiv.className = "tfe-access-message tfe-access-error";
messageDiv.innerHTML =
'<strong>Adresse e-mail introuvable sur le serveur de l\'ERG.</strong><br>' +
'<small>' + serverMessage.replace(/</g, '&lt;') + '</small><br><br>' +
'Corrigez votre adresse e-mail et réessayez.';
"<strong>Adresse e-mail introuvable sur le serveur de l'ERG.</strong><br>" +
"<small>" +
serverMessage.replace(/</g, "&lt;") +
"</small><br><br>" +
"Corrigez votre adresse e-mail et réessayez.";
emailInput.value = rejectedEmail;
emailInput.classList.add('input-error');
emailInput.classList.add("input-error");
emailInput.focus();
emailInput.select();
emailInput.addEventListener('input', function clearError() {
emailInput.classList.remove('input-error');
emailInput.removeEventListener('input', clearError);
emailInput.addEventListener("input", function clearError() {
emailInput.classList.remove("input-error");
emailInput.removeEventListener("input", clearError);
});
}
form.addEventListener('submit', function (e) {
form.addEventListener("submit", (e) => {
e.preventDefault();
var submitBtn = form.querySelector('button[type="submit"]');
submitBtn.disabled = true;
submitBtn.textContent = 'Envoi en cours...';
messageDiv.style.display = 'none';
submitBtn.textContent = "Envoi en cours...";
messageDiv.style.display = "none";
var submittedEmail = emailInput.value.trim();
var formData = new FormData(form);
formData.append('thesis_id', form.getAttribute('data-thesis-id'));
formData.append("thesis_id", form.getAttribute("data-thesis-id"));
fetch('/request-access', {
method: 'POST',
body: formData
fetch("/request-access", {
method: "POST",
body: formData,
})
.then(function (response) { return response.json(); })
.then(function (data) {
.then((response) => response.json())
.then((data) => {
submitBtn.disabled = false;
submitBtn.textContent = 'Demander l\'accès';
submitBtn.textContent = "Demander l'accès";
if (data.status === 'recipient_rejected') {
if (data.status === "recipient_rejected") {
showRetryPrompt(submittedEmail, data.message);
return;
}
messageDiv.style.display = 'block';
messageDiv.style.display = "block";
if (data.success) {
messageDiv.className = 'tfe-access-message tfe-access-success';
messageDiv.className = "tfe-access-message tfe-access-success";
messageDiv.textContent = data.message;
form.reset();
} else {
messageDiv.className = 'tfe-access-message tfe-access-error';
messageDiv.textContent = data.message || 'Une erreur est survenue. Veuillez réessayer.';
messageDiv.className = "tfe-access-message tfe-access-error";
messageDiv.textContent =
data.message || "Une erreur est survenue. Veuillez réessayer.";
}
})
.catch(function () {
.catch(() => {
submitBtn.disabled = false;
submitBtn.textContent = 'Demander l\'accès';
messageDiv.style.display = 'block';
messageDiv.className = 'tfe-access-message tfe-access-error';
messageDiv.textContent = 'Erreur de connexion. Veuillez réessayer.';
submitBtn.textContent = "Demander l'accès";
messageDiv.style.display = "block";
messageDiv.className = "tfe-access-message tfe-access-error";
messageDiv.textContent = "Erreur de connexion. Veuillez réessayer.";
});
});
})();

View File

@@ -5,60 +5,66 @@
* - copyLogContent(btn) — copy visible log lines to clipboard
* - HTMX afterSwap handler to update active tab class on #sys-tab-panel
*/
(function () {
'use strict';
window.copyLogContent = function (btn) {
var logOut = document.querySelector('#log-output');
(() => {
window.copyLogContent = (btn) => {
var logOut = document.querySelector("#log-output");
if (!logOut) return;
var text = Array.from(logOut.querySelectorAll('.log-line'))
.map(function (el) { return el.textContent; }).join('\n');
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(function () {
btn.textContent = '\u2713 Copi\u00e9';
btn.classList.add('copied');
setTimeout(function () { btn.textContent = 'Copier'; btn.classList.remove('copied'); }, 2000);
var text = Array.from(logOut.querySelectorAll(".log-line"))
.map((el) => el.textContent)
.join("\n");
if (navigator.clipboard?.writeText) {
navigator.clipboard.writeText(text).then(() => {
btn.textContent = "\u2713 Copi\u00e9";
btn.classList.add("copied");
setTimeout(() => {
btn.textContent = "Copier";
btn.classList.remove("copied");
}, 2000);
});
} else {
window._fallbackCopy(text, btn);
}
};
window._fallbackCopy = function (text, btn) {
var ta = document.createElement('textarea');
window._fallbackCopy = (text, btn) => {
var ta = document.createElement("textarea");
ta.value = text;
ta.style.cssText = 'position:fixed;opacity:0';
ta.style.cssText = "position:fixed;opacity:0";
document.body.appendChild(ta);
ta.select();
try {
document.execCommand('copy');
btn.textContent = '\u2713 Copi\u00e9';
btn.classList.add('copied');
setTimeout(function () { btn.textContent = 'Copier'; btn.classList.remove('copied'); }, 2000);
} catch (e) {}
document.execCommand("copy");
btn.textContent = "\u2713 Copi\u00e9";
btn.classList.add("copied");
setTimeout(() => {
btn.textContent = "Copier";
btn.classList.remove("copied");
}, 2000);
} catch (_e) {}
document.body.removeChild(ta);
};
// Update active tab class after each HTMX swap on #sys-tab-panel
document.body.addEventListener('htmx:afterSwap', function (evt) {
if (!(evt.detail.target && evt.detail.target.id === 'sys-tab-panel')) return;
document.body.addEventListener("htmx:afterSwap", (evt) => {
if (!(evt.detail.target && evt.detail.target.id === "sys-tab-panel"))
return;
var rc = evt.detail.requestConfig;
var tab = null;
// Tab clicks carry ?tab=… in the path
var qIdx = rc.path.indexOf('?');
var qIdx = rc.path.indexOf("?");
if (qIdx !== -1) {
tab = new URLSearchParams(rc.path.substring(qIdx + 1)).get('tab');
tab = new URLSearchParams(rc.path.substring(qIdx + 1)).get("tab");
}
// Line-count form sends tab via hx-vals in parameters
if (!tab && rc.parameters && rc.parameters.tab) {
tab = rc.parameters.tab;
}
if (!tab) return;
document.querySelectorAll('.sys-tabs .sys-tab').forEach(function (a) {
var isActive = a.getAttribute('data-tab') === tab;
a.classList.toggle('active', isActive);
if (isActive) a.setAttribute('aria-current', 'page');
else a.removeAttribute('aria-current');
document.querySelectorAll(".sys-tabs .sys-tab").forEach((a) => {
var isActive = a.getAttribute("data-tab") === tab;
a.classList.toggle("active", isActive);
if (isActive) a.setAttribute("aria-current", "page");
else a.removeAttribute("aria-current");
});
});
})();

View File

@@ -5,7 +5,7 @@
* parse errors instead of silently swallowing them (unlike the
* old autosave.js .catch(() => {}) pattern).
*/
function handleAutosaveResponse(event) {
function _handleAutosaveResponse(event) {
const form = event.target.closest("form");
const status = form ? form.querySelector("[data-autosave-status]") : null;
@@ -20,10 +20,14 @@ function handleAutosaveResponse(event) {
try {
const data = JSON.parse(event.detail.xhr.responseText);
// Rotate CSRF token in both the form and the meta tag
// Rotate CSRF token in the form, any share_link_token fields, and the meta tag
if (data.csrf_token) {
const csrfInput = form.querySelector('input[name="csrf_token"]');
if (csrfInput) csrfInput.value = data.csrf_token;
const shareTokenInput = form.querySelector(
'input[name="share_link_token"]',
);
if (shareTokenInput) shareTokenInput.value = data.csrf_token;
const meta = document.querySelector('meta[name="csrf-token"]');
if (meta) meta.content = data.csrf_token;
}

View File

@@ -6,18 +6,25 @@
* No effect when JavaScript is unavailable (form posts normally).
*/
(() => {
const forms = document.querySelectorAll('form[data-beforeunload-guard]');
const forms = document.querySelectorAll("form[data-beforeunload-guard]");
if (!forms.length) return;
let dirty = false;
for (const form of forms) {
form.addEventListener('input', () => { dirty = true; });
form.addEventListener('change', () => { dirty = true; });
form.addEventListener('submit', () => { dirty = false; window.__xamxamDirty = false; });
form.addEventListener("input", () => {
dirty = true;
});
form.addEventListener("change", () => {
dirty = true;
});
form.addEventListener("submit", () => {
dirty = false;
window.__xamxamDirty = false;
});
}
window.addEventListener('beforeunload', (e) => {
window.addEventListener("beforeunload", (e) => {
if (dirty || window.__xamxamDirty) {
e.preventDefault();
}

View File

@@ -8,28 +8,29 @@
* Or with a custom selector pattern:
* <button onclick="copyUrlFrom(document.getElementById('my-url'))">Copier</button>
*/
(function () {
'use strict';
window.copyUrl = function (id) {
var input = document.getElementById('url-' + id);
(() => {
window.copyUrl = (id) => {
var input = document.getElementById(`url-${id}`);
if (input) {
window.copyUrlFrom(input);
}
};
window.copyUrlFrom = function (sourceEl) {
var text = sourceEl.value || sourceEl.textContent || '';
window.copyUrlFrom = (sourceEl) => {
var text = sourceEl.value || sourceEl.textContent || "";
var btn;
var origTitle;
var origText;
if (!text) return;
navigator.clipboard.writeText(text).then(function () {
var btn = window.event && window.event.target ? window.event.target.closest('button') : null;
navigator.clipboard.writeText(text).then(() => {
btn = window.event?.target ? window.event.target.closest("button") : null;
if (btn) {
var origTitle = btn.getAttribute('title') || '';
var origText = btn.textContent;
btn.setAttribute('title', '\u2713 Copi\u00e9');
btn.textContent = '\u2713 Copi\u00e9';
setTimeout(function () {
btn.setAttribute('title', origTitle);
origTitle = btn.getAttribute("title") || "";
origText = btn.textContent;
btn.setAttribute("title", "\u2713 Copi\u00e9");
btn.textContent = "\u2713 Copi\u00e9";
setTimeout(() => {
btn.setAttribute("title", origTitle);
btn.textContent = origText;
}, 1200);
}

View File

@@ -123,7 +123,7 @@
*/
function parseSize(str) {
// Already a number (bytes) — pass through
if (typeof str === 'number') return str;
if (typeof str === "number") return str;
var m = str.match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)$/i);
if (!m) return 0;
var val = parseFloat(m[1]);
@@ -187,7 +187,7 @@
var oldHidden = form.querySelectorAll(
`input[name='queue_file[${queueType}][]'][data-filepond-id]`,
);
for (var h = 0; h < oldHidden.length; h++) {
for (let h = 0; h < oldHidden.length; h++) {
oldHidden[h].remove();
}
@@ -195,13 +195,13 @@
// Create hidden inputs per file: queue_file[<queueType>][] = serverId
var ids = [];
for (var i = 0; i < files.length; i++) {
var f = files[i];
for (let i = 0; i < files.length; i++) {
const f = files[i];
// Only include files that have been uploaded and have a serverId
var id = f.serverId || null;
const id = f.serverId || null;
if (id) {
ids.push(id);
var hidden = document.createElement("input");
const hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = `queue_file[${queueType}][]`;
hidden.value = id;
@@ -212,7 +212,7 @@
// Create order input
if (ids.length > 0) {
var orderInput = document.createElement("input");
const orderInput = document.createElement("input");
orderInput.type = "hidden";
orderInput.name = `queue_order[${queueType}]`;
orderInput.value = ids.join("|");
@@ -257,8 +257,11 @@
// return a distinguishable error marker instead of a valid serverId.
// Throwing here crashes FilePond internally (no try/catch in the wrapper).
if (id.length > 64 || /[<>\n\r]/.test(id)) {
console.error("[filepond] process onload | unexpected response | body=" + id.substring(0, 200));
return "__error__" + id.substring(0, 32);
console.error(
"[filepond] process onload | unexpected response | body=" +
id.substring(0, 200),
);
return `__error__${id.substring(0, 32)}`;
}
console.log(`[filepond] process onload | serverId=${id}`);
return id; // file_id stored as serverId
@@ -266,8 +269,13 @@
onerror: (response) => {
// response is the raw XHR response text (string), not an XHR object.
// Log it and return a human-readable error message.
var body = typeof response === 'string' ? response : (response && response.body ? response.body : String(response || ''));
console.error("[filepond] process onerror | body=" + body);
var body =
typeof response === "string"
? response
: response?.body
? response.body
: String(response || "");
console.error(`[filepond] process onerror | body=${body}`);
return body || "Erreur lors du téléversement.";
},
},
@@ -280,7 +288,7 @@
console.log("[filepond] revert OK");
},
onerror: (r) => {
var body = typeof r === 'string' ? r : (r && r.body ? r.body : '');
var body = typeof r === "string" ? r : r?.body ? r.body : "";
console.error(`[filepond] revert ERROR | body=${body || r}`);
},
},
@@ -293,8 +301,13 @@
return response;
},
onerror: (response) => {
var body = typeof response === 'string' ? response : (response && response.body ? response.body : String(response || ''));
console.error("[filepond] load onerror | body=" + body);
var body =
typeof response === "string"
? response
: response?.body
? response.body
: String(response || "");
console.error(`[filepond] load onerror | body=${body}`);
// Return a descriptive error — FilePond will fire an error event.
return body || "Fichier introuvable.";
},
@@ -311,7 +324,12 @@
body: source,
})
.then((r) => {
console.log("[filepond] revert (from remove) response | ok=" + r.ok + " | status=" + r.status);
console.log(
"[filepond] revert (from remove) response | ok=" +
r.ok +
" | status=" +
r.status,
);
r.ok ? load() : error("Erreur suppression");
})
.catch((e) => {
@@ -403,7 +421,7 @@
var f = item.file;
var ext = getExt(f.name);
if (ext && perExtMax[ext]) {
var limit = parseSize(perExtMax[ext]);
const limit = parseSize(perExtMax[ext]);
if (limit > 0 && f.size > limit) {
return false;
}
@@ -503,20 +521,20 @@
if (pond) {
try {
// Remove order/hidden inputs before destroying
var form = input.closest("form");
const form = input.closest("form");
if (form) {
var queueType = input.dataset.queueType || null;
const queueType = input.dataset.queueType || null;
if (queueType) {
var orderInput = form.querySelector(
const orderInput = form.querySelector(
`input[name='queue_order[${queueType}]']`,
);
if (orderInput) orderInput.remove();
var hiddenInputs = form.querySelectorAll(
const hiddenInputs = form.querySelectorAll(
"input[name='queue_file[" +
queueType +
"][]'][data-filepond-id]",
);
for (var h = 0; h < hiddenInputs.length; h++) {
for (let h = 0; h < hiddenInputs.length; h++) {
hiddenInputs[h].remove();
}
}
@@ -524,14 +542,16 @@
// Abort any in-flight uploads before destroying to prevent
// FilePond internal crashes when XHR callbacks fire on a
// torn-down instance ("can't access property main").
var files = pond.getFiles();
for (var i = 0; i < files.length; i++) {
var f = files[i];
const files = pond.getFiles();
for (let i = 0; i < files.length; i++) {
const f = files[i];
if (f.status === 4 || f.status === 2 || f.status === 3) {
// FileStatus: PROCESSING=4, PROCESSING_QUEUED=2, PROCESSING=4
// (FilePond 4.x internal: 4 = processing)
// Abort processing to avoid stale XHR callbacks
try { pond.removeFile(f); } catch (_abort) {}
try {
pond.removeFile(f);
} catch (_abort) {}
}
}
pond.destroy();
@@ -612,13 +632,15 @@
setTimeout(tryRegisterHtmx, 50);
return;
}
console.log('[filepond] htmx detected, registering swap listeners');
console.log("[filepond] htmx detected, registering swap listeners");
window.htmx.on("htmx:beforeSwap", onHtmxBeforeSwap);
window.htmx.on("htmx:afterSwap", () => {
enableFilepondMode();
_xamxamFilepondReady = false;
window.XamxamInitFilePonds();
setTimeout(() => { _xamxamFilepondReady = true; }, 0);
setTimeout(() => {
_xamxamFilepondReady = true;
}, 0);
});
}
// ── Enable filepond_mode hidden input (no-JS safety) ────────────────
@@ -627,7 +649,7 @@
// will handle uploads asynchronously.
function enableFilepondMode() {
var inputs = document.querySelectorAll("input[name='filepond_mode']");
for (var i = 0; i < inputs.length; i++) {
for (let i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
inputs[i].value = "1";
}
@@ -675,8 +697,8 @@
* The file browser is loaded inside #relink-modal-body via HTMX.
*/
window.XamxamRelinkFile = (el) => {
var li = el.closest('.file-browser-entry');
console.log('[relink] XamxamRelinkFile called | el=', el, '| li=', li);
var li = el.closest(".file-browser-entry");
console.log("[relink] XamxamRelinkFile called | el=", el, "| li=", li);
if (!li) return;
var ctx = window.__xamxamRelinkCtx || {};
@@ -686,37 +708,70 @@
var filePath = li.dataset.filePath;
var fileName = li.dataset.fileName;
var fileSize = parseInt(li.dataset.fileSize, 10) || 0;
var ext = li.dataset.fileExt || '';
var ext = li.dataset.fileExt || "";
console.log('[relink] data | thesisId=' + thesisId + ' | queueType=' + queueType + ' | filePath=' + filePath + ' | fileName=' + fileName + ' | ext=' + ext);
console.log(
"[relink] data | thesisId=" +
thesisId +
" | queueType=" +
queueType +
" | filePath=" +
filePath +
" | fileName=" +
fileName +
" | ext=" +
ext,
);
if (!filePath || !thesisId || !queueType) {
console.error('[relink] missing data', { filePath, thesisId, queueType });
console.error("[relink] missing data", { filePath, thesisId, queueType });
return;
}
// Determine MIME from extension
var mimeMap = {
pdf: 'application/pdf',
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', gif: 'image/gif',
mp4: 'video/mp4', webm: 'video/webm', ogv: 'video/ogg', mov: 'video/quicktime',
mp3: 'audio/mpeg', ogg: 'audio/ogg', wav: 'audio/wav', flac: 'audio/flac', aac: 'audio/aac', m4a: 'audio/mp4',
vtt: 'text/vtt',
zip: 'application/zip', tar: 'application/x-tar', gz: 'application/gzip',
pdf: "application/pdf",
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
webp: "image/webp",
gif: "image/gif",
mp4: "video/mp4",
webm: "video/webm",
ogv: "video/ogg",
mov: "video/quicktime",
mp3: "audio/mpeg",
ogg: "audio/ogg",
wav: "audio/wav",
flac: "audio/flac",
aac: "audio/aac",
m4a: "audio/mp4",
vtt: "text/vtt",
zip: "application/zip",
tar: "application/x-tar",
gz: "application/gzip",
};
var mimeType = mimeMap[ext] || 'application/octet-stream';
var mimeType = mimeMap[ext] || "application/octet-stream";
var csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
console.log('[relink] csrfToken=' + (csrfToken ? csrfToken.substring(0, 8) + '...' : 'MISSING'));
var csrfToken =
document
.querySelector('meta[name="csrf-token"]')
?.getAttribute("content") || "";
console.log(
"[relink] csrfToken=" +
(csrfToken ? `${csrfToken.substring(0, 8)}...` : "MISSING"),
);
var bodyEl = document.getElementById('relink-modal-body');
if (bodyEl) bodyEl.innerHTML = '<p class="file-browser-loading">Reliage en cours…</p>';
var bodyEl = document.getElementById("relink-modal-body");
if (bodyEl)
bodyEl.innerHTML =
'<p class="file-browser-loading">Reliage en cours…</p>';
fetch('/admin/actions/filepond/relink.php', {
method: 'POST',
fetch("/admin/actions/filepond/relink.php", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken,
},
body: JSON.stringify({
thesis_id: parseInt(thesisId, 10),
@@ -727,71 +782,102 @@
queue_type: queueType,
}),
})
.then(r => r.json().then(data => ({ ok: r.ok, status: r.status, data })))
.then((r) =>
r.json().then((data) => ({ ok: r.ok, status: r.status, data })),
)
.then(({ ok, status, data }) => {
if (!ok || (data && data.ok === false)) {
var msg = (data && data.error) ? data.error : (typeof data === 'string' ? data : 'Erreur ' + status);
if (bodyEl) bodyEl.innerHTML = `<p class="file-browser-error">Erreur : ${msg}</p>`;
const msg = data?.error
? data.error
: typeof data === "string"
? data
: `Erreur ${status}`;
if (bodyEl)
bodyEl.innerHTML = `<p class="file-browser-error">Erreur : ${msg}</p>`;
return;
}
console.log('[relink] success | new_id=' + data.id);
console.log(`[relink] success | new_id=${data.id}`);
// Add the new file to the FilePond pool, then close the modal.
// If the DOM was replaced (e.g. live-reload), refresh the
// form fragment via HTMX so the server re-renders the pools
// with the newly-linked file included.
var input = document.querySelector(`.tfe-file-picker[data-queue-type="${queueType}"]`);
console.log('[relink] looking for input | selector=' + `.tfe-file-picker[data-queue-type="${queueType}"]` + ' | found=' + !!input);
var closeAndRefresh = function() {
var modal = document.getElementById('relink-modal');
var input = document.querySelector(
`.tfe-file-picker[data-queue-type="${queueType}"]`,
);
console.log(
"[relink] looking for input | selector=" +
`.tfe-file-picker[data-queue-type="${queueType}"]` +
" | found=" +
!!input,
);
var closeAndRefresh = () => {
var modal = document.getElementById("relink-modal");
if (modal) modal.close();
// Re-fetch the fichiers fragment from the server so the
// newly-linked file appears in the FilePond pools.
var block = document.getElementById('format-fichiers-block');
var block = document.getElementById("format-fichiers-block");
if (block && window.htmx) {
var url = '/admin/fragments/fichiers.php';
if (window.__xamxamRelinkCtx && window.__xamxamRelinkCtx.thesisId) {
url += '?_thesis_id=' + encodeURIComponent(window.__xamxamRelinkCtx.thesisId);
let url = "/admin/fragments/fichiers.php";
if (window.__xamxamRelinkCtx?.thesisId) {
url +=
"?_thesis_id=" +
encodeURIComponent(window.__xamxamRelinkCtx.thesisId);
}
htmx.ajax('GET', url, {
target: '#format-fichiers-block',
swap: 'outerHTML'
htmx.ajax("GET", url, {
target: "#format-fichiers-block",
swap: "outerHTML",
});
}
};
if (input) {
var pond = FilePond.find(input);
console.log('[relink] looking for pond | found=' + !!pond);
const pond = FilePond.find(input);
console.log(`[relink] looking for pond | found=${!!pond}`);
if (pond) {
pond.addFile(String(data.id), {
type: 'limbo',
pond
.addFile(String(data.id), {
type: "limbo",
file: {
name: fileName,
size: fileSize,
type: mimeType
}
}).then(function() {
console.log('[relink] addFile resolved | source=' + String(data.id) + ' | queueType=' + queueType);
type: mimeType,
},
})
.then(() => {
console.log(
"[relink] addFile resolved | source=" +
String(data.id) +
" | queueType=" +
queueType,
);
closeAndRefresh();
}).catch(function(err) {
console.error('[relink] addFile rejected', err);
})
.catch((err) => {
console.error("[relink] addFile rejected", err);
closeAndRefresh();
});
} else {
console.error('[relink] FilePond.find returned null for input', input);
console.error(
"[relink] FilePond.find returned null for input",
input,
);
closeAndRefresh();
}
} else {
console.warn('[relink] input not found, page may have reloaded | queueType=' + queueType);
console.warn(
"[relink] input not found, page may have reloaded | queueType=" +
queueType,
);
closeAndRefresh();
}
// Mark form dirty
window.__xamxamDirty = true;
})
.catch(err => {
console.error('[relink] fetch error', err);
if (bodyEl) bodyEl.innerHTML = '<p class="file-browser-error">Erreur réseau.</p>';
.catch((err) => {
console.error("[relink] fetch error", err);
if (bodyEl)
bodyEl.innerHTML = '<p class="file-browser-error">Erreur réseau.</p>';
});
};
})();

View File

@@ -11,63 +11,68 @@
* data-jury-hx-post — HTMX endpoint URL (required)
* data-jury-hx-target — CSS selector for the shared dropdown (optional)
*/
(function () {
'use strict';
(() => {
function initAll() {
document.querySelectorAll('[data-jury-autocomplete]:not([data-jury-autocomplete-initialized])').forEach(function (fieldset) {
fieldset.setAttribute('data-jury-autocomplete-initialized', '1');
document
.querySelectorAll(
"[data-jury-autocomplete]:not([data-jury-autocomplete-initialized])",
)
.forEach((fieldset) => {
fieldset.setAttribute("data-jury-autocomplete-initialized", "1");
initFieldset(fieldset);
});
}
document.addEventListener('DOMContentLoaded', initAll);
document.body.addEventListener('htmx:afterSwap', initAll);
document.addEventListener("DOMContentLoaded", initAll);
document.body.addEventListener("htmx:afterSwap", initAll);
function initFieldset(fieldset) {
var hxPost = fieldset.getAttribute('data-jury-hx-post') || '/admin/fragments/pill-search.php';
var role = fieldset.getAttribute('data-jury-role') || '';
var dropdown = fieldset.querySelector('.jury-suggestions');
var list;
var activeInput;
var selectedIdx;
var debounceTimer;
var hxPost =
fieldset.getAttribute("data-jury-hx-post") ||
"/admin/fragments/pill-search.php";
var role = fieldset.getAttribute("data-jury-role") || "";
var dropdown = fieldset.querySelector(".jury-suggestions");
if (!dropdown) {
dropdown = document.createElement('div');
dropdown.className = 'jury-suggestions tag-search-suggestions';
dropdown.setAttribute('role', 'listbox');
dropdown = document.createElement("div");
dropdown.className = "jury-suggestions tag-search-suggestions";
dropdown.setAttribute("role", "listbox");
// Insert after the list container
var list = fieldset.querySelector('.admin-jury-list');
list = fieldset.querySelector(".admin-jury-list");
if (list) {
list.insertAdjacentElement('afterend', dropdown);
list.insertAdjacentElement("afterend", dropdown);
} else {
fieldset.appendChild(dropdown);
}
}
var activeInput = null;
var selectedIdx = -1;
var debounceTimer = null;
// Click on suggestion → fill the active input
dropdown.addEventListener('click', function (e) {
var btn = e.target.closest('.tag-search-item');
dropdown.addEventListener("click", (e) => {
var btn = e.target.closest(".tag-search-item");
if (!btn) return;
var name = (btn.getAttribute('data-tag-name') || '').trim();
var name = (btn.getAttribute("data-tag-name") || "").trim();
if (!name || !activeInput) return;
activeInput.value = btn.classList.contains('tag-search-item--create')
activeInput.value = btn.classList.contains("tag-search-item--create")
? activeInput.value.trim()
: name;
dropdown.innerHTML = '';
dropdown.innerHTML = "";
selectedIdx = -1;
activeInput.focus();
});
// Highlighting helper
function highlight(idx) {
var items = dropdown.querySelectorAll('.tag-search-item');
for (var i = 0; i < items.length; i++) {
items[i].classList.toggle('tag-search-item--highlight', i === idx);
var items = dropdown.querySelectorAll(".tag-search-item");
for (let i = 0; i < items.length; i++) {
items[i].classList.toggle("tag-search-item--highlight", i === idx);
}
}
fieldset.addEventListener('input', function (e) {
fieldset.addEventListener("input", (e) => {
var inp = e.target.closest('input[type="text"]');
if (!inp) return;
@@ -75,47 +80,54 @@
var q = inp.value.trim();
// Build the hx-include query — include hidden type=supervisor
var typeInput = fieldset.querySelector('input[name="type"][value="supervisor"]');
var includeSelector = typeInput ? '[name="type"][value="supervisor"]' : '';
var _typeInput = fieldset.querySelector(
'input[name="type"][value="supervisor"]',
);
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(function () {
if (q === '') {
dropdown.innerHTML = '';
debounceTimer = setTimeout(() => {
if (q === "") {
dropdown.innerHTML = "";
selectedIdx = -1;
return;
}
// Manual HTMX POST
var xhr = new XMLHttpRequest();
xhr.open('POST', hxPost);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('HX-Request', 'true');
xhr.onload = function () {
xhr.open("POST", hxPost);
xhr.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded",
);
xhr.setRequestHeader("HX-Request", "true");
xhr.onload = () => {
if (xhr.status === 200) {
dropdown.innerHTML = xhr.responseText;
selectedIdx = -1;
}
};
var params = 'type=supervisor&q=' + encodeURIComponent(q) + (role ? '&role=' + encodeURIComponent(role) : '');
var params =
"type=supervisor&q=" +
encodeURIComponent(q) +
(role ? `&role=${encodeURIComponent(role)}` : "");
xhr.send(params);
}, 200);
});
// Keyboard navigation
fieldset.addEventListener('keydown', function (e) {
var items = dropdown.querySelectorAll('.tag-search-item');
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
fieldset.addEventListener("keydown", (e) => {
var items = dropdown.querySelectorAll(".tag-search-item");
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
if (items.length === 0) return;
e.preventDefault();
if (e.key === 'ArrowDown') {
if (e.key === "ArrowDown") {
selectedIdx = (selectedIdx + 1) % items.length;
} else {
selectedIdx = selectedIdx <= 0 ? items.length - 1 : selectedIdx - 1;
}
highlight(selectedIdx);
} else if (e.key === 'Enter') {
if (items.length > 0 && dropdown.innerHTML !== '') {
} else if (e.key === "Enter") {
if (items.length > 0 && dropdown.innerHTML !== "") {
e.preventDefault();
if (selectedIdx >= 0 && selectedIdx < items.length) {
items[selectedIdx].click();
@@ -123,16 +135,16 @@
items[0].click();
}
}
} else if (e.key === 'Escape') {
dropdown.innerHTML = '';
} else if (e.key === "Escape") {
dropdown.innerHTML = "";
selectedIdx = -1;
}
});
// Close dropdown on outside click
document.addEventListener('click', function (e) {
document.addEventListener("click", (e) => {
if (!fieldset.contains(e.target)) {
dropdown.innerHTML = '';
dropdown.innerHTML = "";
selectedIdx = -1;
}
});

View File

@@ -20,125 +20,145 @@
* data-pill-required → si "1", active l'affichage du minimum
* data-pill-role → "tag" (lowercase) ou "lang" (ucfirst)
*/
(function () {
'use strict';
(() => {
function initAll() {
document.querySelectorAll('[data-pill-search]:not([data-pill-search-initialized])').forEach(function (container) {
container.setAttribute('data-pill-search-initialized', '1');
document
.querySelectorAll(
"[data-pill-search]:not([data-pill-search-initialized])",
)
.forEach((container) => {
container.setAttribute("data-pill-search-initialized", "1");
initPillSearch(container);
});
}
document.addEventListener('DOMContentLoaded', initAll);
document.body.addEventListener('htmx:afterSwap', initAll);
document.addEventListener("DOMContentLoaded", initAll);
document.body.addEventListener("htmx:afterSwap", initAll);
function initPillSearch(container) {
var pills = container.querySelector('.tag-search-pills');
var search = container.querySelector('.tag-search-input');
var dropdown = container.querySelector('.tag-search-suggestions');
var countEl = container.querySelector('.tag-search-count');
var counter = container.querySelector('.tag-search-counter');
var maxTags = parseInt(container.getAttribute('data-pill-max')) || 10;
var minTags = parseInt(container.getAttribute('data-pill-min')) || 0;
var required = container.getAttribute('data-pill-required') === '1';
var inputName = container.getAttribute('data-pill-name') || 'tag';
var role = container.getAttribute('data-pill-role') || 'tag';
var pills = container.querySelector(".tag-search-pills");
var search = container.querySelector(".tag-search-input");
var dropdown = container.querySelector(".tag-search-suggestions");
var countEl = container.querySelector(".tag-search-count");
var counter = container.querySelector(".tag-search-counter");
var maxTags = parseInt(container.getAttribute("data-pill-max"), 10) || 10;
var minTags = parseInt(container.getAttribute("data-pill-min"), 10) || 0;
var required = container.getAttribute("data-pill-required") === "1";
var inputName = container.getAttribute("data-pill-name") || "tag";
var _role = container.getAttribute("data-pill-role") || "tag";
var selectedIdx = -1;
if (!pills || !search || !dropdown) return;
function normalize(name) {
return name.trim().replace(/\s+/g, ' ').toLowerCase();
return name.trim().replace(/\s+/g, " ").toLowerCase();
}
function pillAlreadyExists(name) {
var norm = normalize(name);
var existing = pills.querySelectorAll('.tag-pill-name');
for (var i = 0; i < existing.length; i++) {
var existing = pills.querySelectorAll(".tag-pill-name");
for (let i = 0; i < existing.length; i++) {
if (normalize(existing[i].textContent) === norm) return true;
}
return false;
}
function updateCount() {
var n = pills.querySelectorAll('.tag-pill').length;
var suffix = required ? ' (min ' + minTags + ')' : '';
if (countEl) countEl.textContent = n + '/' + maxTags + suffix;
if (counter) counter.style.display = (n > 0 || required) ? '' : 'none';
var n = pills.querySelectorAll(".tag-pill").length;
var suffix = required ? ` (min ${minTags})` : "";
if (countEl) countEl.textContent = `${n}/${maxTags}${suffix}`;
if (counter) counter.style.display = n > 0 || required ? "" : "none";
if (countEl && required) {
countEl.style.color = n < minTags ? 'var(--text-danger)' : 'var(--accent)';
countEl.style.color =
n < minTags ? "var(--text-danger)" : "var(--accent)";
}
var wrap = container.querySelector('.tag-search-input-wrap');
var maxMsg = container.querySelector('.tag-search-max-msg');
var wrap = container.querySelector(".tag-search-input-wrap");
var maxMsg = container.querySelector(".tag-search-max-msg");
if (n >= maxTags) {
if (wrap) wrap.style.display = 'none';
if (maxMsg) maxMsg.style.display = '';
if (wrap) wrap.style.display = "none";
if (maxMsg) maxMsg.style.display = "";
} else {
if (wrap) { wrap.style.display = ''; if (search) search.style.display = ''; }
if (maxMsg) maxMsg.style.display = 'none';
if (wrap) {
wrap.style.display = "";
if (search) search.style.display = "";
}
if (maxMsg) maxMsg.style.display = "none";
}
}
pills.addEventListener('click', function (e) {
var btn = e.target.closest('.tag-pill-remove');
pills.addEventListener("click", (e) => {
var btn = e.target.closest(".tag-pill-remove");
if (!btn) return;
var pill = btn.closest('.tag-pill');
var pill = btn.closest(".tag-pill");
pill.remove();
updateCount();
var wrap = container.querySelector('.tag-search-input-wrap');
var inp = container.querySelector('.tag-search-input');
if (wrap && inp) { wrap.style.display = ''; inp.style.display = ''; }
var wrap = container.querySelector(".tag-search-input-wrap");
var inp = container.querySelector(".tag-search-input");
if (wrap && inp) {
wrap.style.display = "";
inp.style.display = "";
}
});
function highlight(idx) {
var items = dropdown.querySelectorAll('.tag-search-item');
for (var i = 0; i < items.length; i++) {
items[i].classList.toggle('tag-search-item--highlight', i === idx);
var items = dropdown.querySelectorAll(".tag-search-item");
for (let i = 0; i < items.length; i++) {
items[i].classList.toggle("tag-search-item--highlight", i === idx);
}
}
function selectPill(btn) {
var name = normalize(btn.getAttribute('data-tag-name') || '');
var name = normalize(btn.getAttribute("data-tag-name") || "");
if (!name) return;
if (pillAlreadyExists(name)) return;
if ((pills.querySelectorAll('.tag-pill').length) >= maxTags) return;
if (pills.querySelectorAll(".tag-pill").length >= maxTags) return;
var escaped = htmlEscape(name);
var pill = document.createElement('span');
pill.className = 'tag-pill';
pill.innerHTML = '<input type="hidden" name="' + inputName + '[]" value="' + escaped + '">'
+ '<span class="tag-pill-name">' + escaped + '</span>'
+ '<button type="button" class="tag-pill-remove" title="Retirer \u00AB\u00A0' + escaped + '\u00A0\u00BB" aria-label="Retirer ' + escaped + '">'
+ '<svg width="16" height="16" fill="currentColor" viewBox="0 0 256 256"><path d="M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM112,168V104a8,8,0,0,1,16,0v64a8,8,0,0,1-16,0Zm48,0V104a8,8,0,0,1,16,0v64a8,8,0,0,1-16,0Z"></path></svg>'
+ '</button>';
var pill = document.createElement("span");
pill.className = "tag-pill";
pill.innerHTML =
'<input type="hidden" name="' +
inputName +
'[]" value="' +
escaped +
'">' +
'<span class="tag-pill-name">' +
escaped +
"</span>" +
'<button type="button" class="tag-pill-remove" title="Retirer \u00AB\u00A0' +
escaped +
'\u00A0\u00BB" aria-label="Retirer ' +
escaped +
'">' +
'<svg width="16" height="16" fill="currentColor" viewBox="0 0 256 256"><path d="M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM112,168V104a8,8,0,0,1,16,0v64a8,8,0,0,1-16,0Zm48,0V104a8,8,0,0,1,16,0v64a8,8,0,0,1-16,0Z"></path></svg>' +
"</button>";
pills.appendChild(pill);
updateCount();
search.value = '';
dropdown.innerHTML = '';
search.value = "";
dropdown.innerHTML = "";
selectedIdx = -1;
search.focus();
}
dropdown.addEventListener('click', function (e) {
var btn = e.target.closest('.tag-search-item');
dropdown.addEventListener("click", (e) => {
var btn = e.target.closest(".tag-search-item");
if (!btn) return;
selectPill(btn);
});
search.addEventListener('keydown', function (e) {
var items = dropdown.querySelectorAll('.tag-search-item');
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
search.addEventListener("keydown", (e) => {
var items = dropdown.querySelectorAll(".tag-search-item");
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
if (items.length === 0) return;
if (e.key === 'ArrowDown') {
if (e.key === "ArrowDown") {
selectedIdx = (selectedIdx + 1) % items.length;
} else {
selectedIdx = selectedIdx <= 0 ? items.length - 1 : selectedIdx - 1;
}
highlight(selectedIdx);
} else if (e.key === 'Enter') {
} else if (e.key === "Enter") {
if (items.length > 0) {
e.preventDefault();
if (selectedIdx >= 0 && selectedIdx < items.length) {
@@ -147,23 +167,23 @@
selectPill(items[0]);
}
}
} else if (e.key === 'Escape') {
dropdown.innerHTML = '';
} else if (e.key === "Escape") {
dropdown.innerHTML = "";
selectedIdx = -1;
}
});
search.addEventListener('blur', function () {
setTimeout(function () {
search.addEventListener("blur", () => {
setTimeout(() => {
if (!dropdown.contains(document.activeElement)) {
dropdown.innerHTML = '';
dropdown.innerHTML = "";
selectedIdx = -1;
}
}, 150);
});
function htmlEscape(str) {
var el = document.createElement('span');
var el = document.createElement("span");
el.textContent = str;
return el.innerHTML;
}

View File

@@ -11,9 +11,7 @@
* 100% : response received — "Téléversé avec succès", then redirect
*/
(() => {
'use strict';
const FORMS = document.querySelectorAll('form[data-upload-progress]');
const FORMS = document.querySelectorAll("form[data-upload-progress]");
if (!FORMS.length) return;
const POLL_INTERVAL = 400;
@@ -22,10 +20,10 @@
const SUCCESS_DELAY = 800;
for (const form of FORMS) {
const progressWrap = form.querySelector('#upload-progress-wrap');
const progressBar = form.querySelector('#upload-progress-bar');
const progressLabel = form.querySelector('#upload-progress-label');
const progressFile = form.querySelector('#upload-progress-file');
const progressWrap = form.querySelector("#upload-progress-wrap");
const progressBar = form.querySelector("#upload-progress-bar");
const progressLabel = form.querySelector("#upload-progress-label");
const progressFile = form.querySelector("#upload-progress-file");
const submitBtn = form.querySelector('button[type="submit"]');
const tokenInput = form.querySelector('input[name="progress_token"]');
@@ -43,8 +41,8 @@
}
}
// Read processed file names from FilePond instances (async mode)
if (typeof FilePond !== 'undefined') {
const pondInputs = form.querySelectorAll('.tfe-file-picker');
if (typeof FilePond !== "undefined") {
const pondInputs = form.querySelectorAll(".tfe-file-picker");
for (const pi of pondInputs) {
const pond = FilePond.find(pi);
if (pond) {
@@ -52,7 +50,7 @@
for (const pf of pondFiles) {
// Only count successfully uploaded files (have serverId)
if (pf.serverId) {
const name = pf.filename || (pf.file && pf.file.name) || pf.serverId;
const name = pf.filename || pf.file?.name || pf.serverId;
if (name) names.push(name);
}
}
@@ -62,18 +60,20 @@
return names;
}
form.addEventListener('submit', function (e) {
form.addEventListener("submit", (e) => {
// ── Guard: block submit if any FilePond item is still uploading ──
if (typeof FilePond !== 'undefined') {
if (typeof FilePond !== "undefined") {
let stillUploading = false;
const pondInputs = form.querySelectorAll('.tfe-file-picker');
const pondInputs = form.querySelectorAll(".tfe-file-picker");
for (const pi of pondInputs) {
const pond = FilePond.find(pi);
if (pond) {
const pondFiles = pond.getFiles();
for (const pf of pondFiles) {
if (pf.status === FilePond.FileStatus.PROCESSING ||
pf.status === FilePond.FileStatus.IDLE) {
if (
pf.status === FilePond.FileStatus.PROCESSING ||
pf.status === FilePond.FileStatus.IDLE
) {
stillUploading = true;
break;
}
@@ -83,8 +83,9 @@
}
if (stillUploading) {
e.preventDefault();
progressLabel.textContent = 'Veuillez attendre la fin du téléversement…';
progressWrap.style.display = '';
progressLabel.textContent =
"Veuillez attendre la fin du téléversement…";
progressWrap.style.display = "";
return;
}
}
@@ -94,41 +95,48 @@
e.preventDefault();
const token = tokenInput ? tokenInput.value : '';
const token = tokenInput ? tokenInput.value : "";
progressWrap.style.display = '';
progressWrap.style.display = "";
progressBar.value = 0;
progressBar.removeAttribute('data-complete');
progressLabel.textContent = 'Téléversement en cours…';
progressFile.textContent = fileNames.length === 1
? fileNames[0]
: fileNames.length + ' fichiers';
progressBar.removeAttribute("data-complete");
progressLabel.textContent = "Téléversement en cours…";
progressFile.textContent =
fileNames.length === 1 ? fileNames[0] : `${fileNames.length} fichiers`;
if (submitBtn) submitBtn.disabled = true;
const fd = new FormData(form);
const xhr = new XMLHttpRequest();
let uploadDone = false;
let _uploadDone = false;
let lastUploadPct = 0;
let pollingTimer = null;
/** Poll server-side progress */
function startPolling() {
if (pollingTimer || !token) return;
progressLabel.textContent = 'Traitement en cours…';
pollingTimer = setInterval(function () {
fetch('/admin/actions/upload-progress.php?token=' + encodeURIComponent(token))
.then(function (r) { return r.json(); })
.then(function (data) {
if (data && data.stage && data.stage !== 'upload') {
const pct = Math.min(PROCESSING_MAX, Math.max(UPLOAD_CAP, data.pct || UPLOAD_CAP));
progressLabel.textContent = "Traitement en cours…";
pollingTimer = setInterval(() => {
fetch(
"/admin/actions/upload-progress.php?token=" +
encodeURIComponent(token),
)
.then((r) => r.json())
.then((data) => {
if (data?.stage && data.stage !== "upload") {
const pct = Math.min(
PROCESSING_MAX,
Math.max(UPLOAD_CAP, data.pct || UPLOAD_CAP),
);
progressBar.value = pct;
if (data.file) {
progressFile.textContent = data.file;
}
}
})
.catch(function () { /* ignore poll errors */ });
.catch(() => {
/* ignore poll errors */
});
}, POLL_INTERVAL);
}
@@ -142,13 +150,13 @@
function finishSuccess() {
stopPolling();
progressBar.value = 100;
progressBar.setAttribute('data-complete', '');
progressLabel.textContent = 'Téléversé avec succès';
progressFile.textContent = '';
progressBar.setAttribute("data-complete", "");
progressLabel.textContent = "Téléversé avec succès";
progressFile.textContent = "";
}
// ── Upload phase (0% → UPLOAD_CAP) ──
xhr.upload.addEventListener('progress', function (evt) {
xhr.upload.addEventListener("progress", (evt) => {
if (evt.lengthComputable) {
const rawPct = Math.round((evt.loaded / evt.total) * 100);
const scaled = Math.round((rawPct / 100) * UPLOAD_CAP);
@@ -159,14 +167,14 @@
}
});
xhr.upload.addEventListener('loadend', function () {
uploadDone = true;
xhr.upload.addEventListener("loadend", () => {
_uploadDone = true;
progressBar.value = UPLOAD_CAP;
startPolling();
});
// ── Response handling ──
xhr.addEventListener('readystatechange', function () {
xhr.addEventListener("readystatechange", () => {
if (xhr.readyState !== XMLHttpRequest.DONE) return;
stopPolling();
@@ -174,8 +182,8 @@
if (xhr.status >= 200 && xhr.status < 300) {
finishSuccess();
setTimeout(function () {
const finalUrl = xhr.responseURL || '';
setTimeout(() => {
const finalUrl = xhr.responseURL || "";
if (finalUrl && finalUrl !== form.action) {
window.location.href = finalUrl;
} else {
@@ -185,28 +193,28 @@
}
}, SUCCESS_DELAY);
} else {
progressLabel.textContent = 'Erreur';
progressFile.textContent = 'Échec du téléversement';
progressLabel.textContent = "Erreur";
progressFile.textContent = "Échec du téléversement";
document.open();
document.write(xhr.responseText);
document.close();
}
});
xhr.addEventListener('error', function () {
xhr.addEventListener("error", () => {
stopPolling();
progressLabel.textContent = 'Erreur réseau';
progressFile.textContent = '';
progressLabel.textContent = "Erreur réseau";
progressFile.textContent = "";
if (submitBtn) submitBtn.disabled = false;
});
xhr.addEventListener('abort', function () {
xhr.addEventListener("abort", () => {
stopPolling();
progressWrap.style.display = 'none';
progressWrap.style.display = "none";
if (submitBtn) submitBtn.disabled = false;
});
xhr.open('POST', form.action, true);
xhr.open("POST", form.action, true);
xhr.send(fd);
});
}

View File

@@ -6,4 +6,118 @@
/* eslint-disable */
!function(e,i){"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(e=e||self).FilePondPluginFileValidateSize=i()}(this,function(){"use strict";var e=function(e){var i=e.addFilter,E=e.utils,l=E.Type,_=E.replaceInString,n=E.toNaturalFileSize;return i("ALLOW_HOPPER_ITEM",function(e,i){var E=i.query;if(!E("GET_ALLOW_FILE_SIZE_VALIDATION"))return!0;var l=E("GET_MAX_FILE_SIZE");if(null!==l&&e.size>l)return!1;var _=E("GET_MIN_FILE_SIZE");return!(null!==_&&e.size<_)}),i("LOAD_FILE",function(e,i){var E=i.query;return new Promise(function(i,l){if(!E("GET_ALLOW_FILE_SIZE_VALIDATION"))return i(e);var I=E("GET_FILE_VALIDATE_SIZE_FILTER");if(I&&!I(e))return i(e);var t=E("GET_MAX_FILE_SIZE");if(null!==t&&e.size>t)l({status:{main:E("GET_LABEL_MAX_FILE_SIZE_EXCEEDED"),sub:_(E("GET_LABEL_MAX_FILE_SIZE"),{filesize:n(t,".",E("GET_FILE_SIZE_BASE"),E("GET_FILE_SIZE_LABELS",E))})}});else{var L=E("GET_MIN_FILE_SIZE");if(null!==L&&e.size<L)l({status:{main:E("GET_LABEL_MIN_FILE_SIZE_EXCEEDED"),sub:_(E("GET_LABEL_MIN_FILE_SIZE"),{filesize:n(L,".",E("GET_FILE_SIZE_BASE"),E("GET_FILE_SIZE_LABELS",E))})}});else{var a=E("GET_MAX_TOTAL_FILE_SIZE");if(null!==a)if(E("GET_ACTIVE_ITEMS").reduce(function(e,i){return e+i.fileSize},0)>a)return void l({status:{main:E("GET_LABEL_MAX_TOTAL_FILE_SIZE_EXCEEDED"),sub:_(E("GET_LABEL_MAX_TOTAL_FILE_SIZE"),{filesize:n(a,".",E("GET_FILE_SIZE_BASE"),E("GET_FILE_SIZE_LABELS",E))})}});i(e)}}})}),{options:{allowFileSizeValidation:[!0,l.BOOLEAN],maxFileSize:[null,l.INT],minFileSize:[null,l.INT],maxTotalFileSize:[null,l.INT],fileValidateSizeFilter:[null,l.FUNCTION],labelMinFileSizeExceeded:["File is too small",l.STRING],labelMinFileSize:["Minimum file size is {filesize}",l.STRING],labelMaxFileSizeExceeded:["File is too large",l.STRING],labelMaxFileSize:["Maximum file size is {filesize}",l.STRING],labelMaxTotalFileSizeExceeded:["Maximum total size exceeded",l.STRING],labelMaxTotalFileSize:["Maximum total file size is {filesize}",l.STRING]}}};return"undefined"!=typeof window&&void 0!==window.document&&document.dispatchEvent(new CustomEvent("FilePond:pluginloaded",{detail:e})),e});
!((e, i) => {
"object" == typeof exports && "undefined" != typeof module
? (module.exports = i())
: "function" == typeof define && define.amd
? define(i)
: ((e = e || self).FilePondPluginFileValidateSize = i());
})(this, () => {
var e = (e) => {
var i = e.addFilter,
E = e.utils,
l = E.Type,
_ = E.replaceInString,
n = E.toNaturalFileSize;
return (
i("ALLOW_HOPPER_ITEM", (e, i) => {
var E = i.query;
if (!E("GET_ALLOW_FILE_SIZE_VALIDATION")) return !0;
var l = E("GET_MAX_FILE_SIZE");
if (null !== l && e.size > l) return !1;
var _ = E("GET_MIN_FILE_SIZE");
return !(null !== _ && e.size < _);
}),
i("LOAD_FILE", (e, i) => {
var E = i.query;
return new Promise((i, l) => {
if (!E("GET_ALLOW_FILE_SIZE_VALIDATION")) return i(e);
var I = E("GET_FILE_VALIDATE_SIZE_FILTER");
if (I && !I(e)) return i(e);
var t = E("GET_MAX_FILE_SIZE");
if (null !== t && e.size > t)
l({
status: {
main: E("GET_LABEL_MAX_FILE_SIZE_EXCEEDED"),
sub: _(E("GET_LABEL_MAX_FILE_SIZE"), {
filesize: n(
t,
".",
E("GET_FILE_SIZE_BASE"),
E("GET_FILE_SIZE_LABELS", E),
),
}),
},
});
else {
var L = E("GET_MIN_FILE_SIZE");
if (null !== L && e.size < L)
l({
status: {
main: E("GET_LABEL_MIN_FILE_SIZE_EXCEEDED"),
sub: _(E("GET_LABEL_MIN_FILE_SIZE"), {
filesize: n(
L,
".",
E("GET_FILE_SIZE_BASE"),
E("GET_FILE_SIZE_LABELS", E),
),
}),
},
});
else {
var a = E("GET_MAX_TOTAL_FILE_SIZE");
if (null !== a)
if (
E("GET_ACTIVE_ITEMS").reduce((e, i) => e + i.fileSize, 0) > a
)
return void l({
status: {
main: E("GET_LABEL_MAX_TOTAL_FILE_SIZE_EXCEEDED"),
sub: _(E("GET_LABEL_MAX_TOTAL_FILE_SIZE"), {
filesize: n(
a,
".",
E("GET_FILE_SIZE_BASE"),
E("GET_FILE_SIZE_LABELS", E),
),
}),
},
});
i(e);
}
}
});
}),
{
options: {
allowFileSizeValidation: [!0, l.BOOLEAN],
maxFileSize: [null, l.INT],
minFileSize: [null, l.INT],
maxTotalFileSize: [null, l.INT],
fileValidateSizeFilter: [null, l.FUNCTION],
labelMinFileSizeExceeded: ["File is too small", l.STRING],
labelMinFileSize: ["Minimum file size is {filesize}", l.STRING],
labelMaxFileSizeExceeded: ["File is too large", l.STRING],
labelMaxFileSize: ["Maximum file size is {filesize}", l.STRING],
labelMaxTotalFileSizeExceeded: [
"Maximum total size exceeded",
l.STRING,
],
labelMaxTotalFileSize: [
"Maximum total file size is {filesize}",
l.STRING,
],
},
}
);
};
return (
"undefined" != typeof window &&
void 0 !== window.document &&
document.dispatchEvent(
new CustomEvent("FilePond:pluginloaded", { detail: e }),
),
e
);
});

View File

@@ -6,4 +6,113 @@
/* eslint-disable */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).FilePondPluginFileValidateType=t()}(this,function(){"use strict";var e=function(e){var t=e.addFilter,n=e.utils,i=n.Type,T=n.isString,E=n.replaceInString,l=n.guesstimateMimeType,o=n.getExtensionFromFilename,r=n.getFilenameFromURL,u=function(e,t){return e.some(function(e){return/\*$/.test(e)?(n=e,(/^[^/]+/.exec(t)||[]).pop()===n.slice(0,-2)):e===t;var n})},a=function(e,t,n){if(0===t.length)return!0;var i=function(e){var t="";if(T(e)){var n=r(e),i=o(n);i&&(t=l(i))}else t=e.type;return t}(e);return n?new Promise(function(T,E){n(e,i).then(function(e){u(t,e)?T():E()}).catch(E)}):u(t,i)};return t("SET_ATTRIBUTE_TO_OPTION_MAP",function(e){return Object.assign(e,{accept:"acceptedFileTypes"})}),t("ALLOW_HOPPER_ITEM",function(e,t){var n=t.query;return!n("GET_ALLOW_FILE_TYPE_VALIDATION")||a(e,n("GET_ACCEPTED_FILE_TYPES"))}),t("LOAD_FILE",function(e,t){var n=t.query;return new Promise(function(t,i){if(n("GET_ALLOW_FILE_TYPE_VALIDATION")){var T=n("GET_ACCEPTED_FILE_TYPES"),l=n("GET_FILE_VALIDATE_TYPE_DETECT_TYPE"),o=a(e,T,l),r=function(){var e,t=T.map((e=n("GET_FILE_VALIDATE_TYPE_LABEL_EXPECTED_TYPES_MAP"),function(t){return null!==e[t]&&(e[t]||t)})).filter(function(e){return!1!==e}),l=t.filter(function(e,n){return t.indexOf(e)===n});i({status:{main:n("GET_LABEL_FILE_TYPE_NOT_ALLOWED"),sub:E(n("GET_FILE_VALIDATE_TYPE_LABEL_EXPECTED_TYPES"),{allTypes:l.join(", "),allButLastType:l.slice(0,-1).join(", "),lastType:l[l.length-1]})}})};if("boolean"==typeof o)return o?t(e):r();o.then(function(){t(e)}).catch(r)}else t(e)})}),{options:{allowFileTypeValidation:[!0,i.BOOLEAN],acceptedFileTypes:[[],i.ARRAY],labelFileTypeNotAllowed:["File is of invalid type",i.STRING],fileValidateTypeLabelExpectedTypes:["Expects {allButLastType} or {lastType}",i.STRING],fileValidateTypeLabelExpectedTypesMap:[{},i.OBJECT],fileValidateTypeDetectType:[null,i.FUNCTION]}}};return"undefined"!=typeof window&&void 0!==window.document&&document.dispatchEvent(new CustomEvent("FilePond:pluginloaded",{detail:e})),e});
!((e, t) => {
"object" == typeof exports && "undefined" != typeof module
? (module.exports = t())
: "function" == typeof define && define.amd
? define(t)
: ((e = e || self).FilePondPluginFileValidateType = t());
})(this, () => {
var e = (e) => {
var t = e.addFilter,
n = e.utils,
i = n.Type,
T = n.isString,
E = n.replaceInString,
l = n.guesstimateMimeType,
o = n.getExtensionFromFilename,
r = n.getFilenameFromURL,
u = (e, t) =>
e.some((e) =>
/\*$/.test(e)
? ((n = e), (/^[^/]+/.exec(t) || []).pop() === n.slice(0, -2))
: e === t,
),
a = (e, t, n) => {
if (0 === t.length) return !0;
var i = ((e) => {
var t = "";
if (T(e)) {
var n = r(e),
i = o(n);
i && (t = l(i));
} else t = e.type;
return t;
})(e);
return n
? new Promise((T, E) => {
n(e, i)
.then((e) => {
u(t, e) ? T() : E();
})
.catch(E);
})
: u(t, i);
};
return (
t("SET_ATTRIBUTE_TO_OPTION_MAP", (e) =>
Object.assign(e, { accept: "acceptedFileTypes" }),
),
t("ALLOW_HOPPER_ITEM", (e, t) => {
var n = t.query;
return (
!n("GET_ALLOW_FILE_TYPE_VALIDATION") ||
a(e, n("GET_ACCEPTED_FILE_TYPES"))
);
}),
t("LOAD_FILE", (e, t) => {
var n = t.query;
return new Promise((t, i) => {
if (n("GET_ALLOW_FILE_TYPE_VALIDATION")) {
var T = n("GET_ACCEPTED_FILE_TYPES"),
l = n("GET_FILE_VALIDATE_TYPE_DETECT_TYPE"),
o = a(e, T, l),
r = () => {
var e,
t = T.map(
((e = n("GET_FILE_VALIDATE_TYPE_LABEL_EXPECTED_TYPES_MAP")),
(t) => null !== e[t] && (e[t] || t)),
).filter((e) => !1 !== e),
l = t.filter((e, n) => t.indexOf(e) === n);
i({
status: {
main: n("GET_LABEL_FILE_TYPE_NOT_ALLOWED"),
sub: E(n("GET_FILE_VALIDATE_TYPE_LABEL_EXPECTED_TYPES"), {
allTypes: l.join(", "),
allButLastType: l.slice(0, -1).join(", "),
lastType: l[l.length - 1],
}),
},
});
};
if ("boolean" == typeof o) return o ? t(e) : r();
o.then(() => {
t(e);
}).catch(r);
} else t(e);
});
}),
{
options: {
allowFileTypeValidation: [!0, i.BOOLEAN],
acceptedFileTypes: [[], i.ARRAY],
labelFileTypeNotAllowed: ["File is of invalid type", i.STRING],
fileValidateTypeLabelExpectedTypes: [
"Expects {allButLastType} or {lastType}",
i.STRING,
],
fileValidateTypeLabelExpectedTypesMap: [{}, i.OBJECT],
fileValidateTypeDetectType: [null, i.FUNCTION],
},
}
);
};
return (
"undefined" != typeof window &&
void 0 !== window.document &&
document.dispatchEvent(
new CustomEvent("FilePond:pluginloaded", { detail: e }),
),
e
);
});

View File

@@ -6,4 +6,92 @@
/* eslint-disable */
!function(A,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(A=A||self).FilePondPluginImageExifOrientation=e()}(this,function(){"use strict";var A=65496,e=65505,n=1165519206,t=18761,i=274,r=65280,o=function(A,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return A.getUint16(e,n)},a=function(A,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return A.getUint32(e,n)},u="undefined"!=typeof window&&void 0!==window.document,d=void 0,f=u?new Image:{};f.onload=function(){return d=f.naturalWidth>f.naturalHeight},f.src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4QA6RXhpZgAATU0AKgAAAAgAAwESAAMAAAABAAYAAAEoAAMAAAABAAIAAAITAAMAAAABAAEAAAAAAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wAALCAABAAIBASIA/8QAJgABAAAAAAAAAAAAAAAAAAAAAxABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQAAPwBH/9k=";var l=function(u){var f=u.addFilter,l=u.utils,c=l.Type,g=l.isFile;return f("DID_LOAD_ITEM",function(u,f){var l=f.query;return new Promise(function(f,c){var s=u.file;if(!(g(s)&&function(A){return/^image\/jpeg/.test(A.type)}(s)&&l("GET_ALLOW_IMAGE_EXIF_ORIENTATION")&&d))return f(u);(function(u){return new Promise(function(d,f){var l=new FileReader;l.onload=function(u){var f=new DataView(u.target.result);if(o(f,0)===A){for(var l=f.byteLength,c=2;c<l;){var g=o(f,c);if(c+=2,g===e){if(a(f,c+=2)!==n)break;var s=o(f,c+=6)===t;c+=a(f,c+4,s);var v=o(f,c,s);c+=2;for(var w=0;w<v;w++)if(o(f,c+12*w,s)===i)return void d(o(f,c+12*w+8,s))}else{if((g&r)!==r)break;c+=o(f,c)}}d(-1)}else d(-1)},l.readAsArrayBuffer(u.slice(0,65536))})})(s).then(function(A){u.setMetadata("exif",{orientation:A}),f(u)})})}),{options:{allowImageExifOrientation:[!0,c.BOOLEAN]}}};return"undefined"!=typeof window&&void 0!==window.document&&document.dispatchEvent(new CustomEvent("FilePond:pluginloaded",{detail:l})),l});
!((A, e) => {
"object" == typeof exports && "undefined" != typeof module
? (module.exports = e())
: "function" == typeof define && define.amd
? define(e)
: ((A = A || self).FilePondPluginImageExifOrientation = e());
})(this, () => {
var A = 65496,
e = 65505,
n = 1165519206,
t = 18761,
i = 274,
r = 65280,
o = function (A, e) {
var n = arguments.length > 2 && void 0 !== arguments[2] && arguments[2];
return A.getUint16(e, n);
},
a = function (A, e) {
var n = arguments.length > 2 && void 0 !== arguments[2] && arguments[2];
return A.getUint32(e, n);
},
u = "undefined" != typeof window && void 0 !== window.document,
d = void 0,
f = u ? new Image() : {};
(f.onload = () => (d = f.naturalWidth > f.naturalHeight)),
(f.src =
"data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4QA6RXhpZgAATU0AKgAAAAgAAwESAAMAAAABAAYAAAEoAAMAAAABAAIAAAITAAMAAAABAAEAAAAAAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wAALCAABAAIBASIA/8QAJgABAAAAAAAAAAAAAAAAAAAAAxABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQAAPwBH/9k=");
var l = (u) => {
var f = u.addFilter,
l = u.utils,
c = l.Type,
g = l.isFile;
return (
f("DID_LOAD_ITEM", (u, f) => {
var l = f.query;
return new Promise((f, c) => {
var s = u.file;
if (
!(
g(s) &&
((A) => /^image\/jpeg/.test(A.type))(s) &&
l("GET_ALLOW_IMAGE_EXIF_ORIENTATION") &&
d
)
)
return f(u);
((u) =>
new Promise((d, f) => {
var l = new FileReader();
(l.onload = (u) => {
var f = new DataView(u.target.result);
if (o(f, 0) === A) {
for (var l = f.byteLength, c = 2; c < l; ) {
var g = o(f, c);
if (((c += 2), g === e)) {
if (a(f, (c += 2)) !== n) break;
var s = o(f, (c += 6)) === t;
c += a(f, c + 4, s);
var v = o(f, c, s);
c += 2;
for (var w = 0; w < v; w++)
if (o(f, c + 12 * w, s) === i)
return void d(o(f, c + 12 * w + 8, s));
} else {
if ((g & r) !== r) break;
c += o(f, c);
}
}
d(-1);
} else d(-1);
}),
l.readAsArrayBuffer(u.slice(0, 65536));
}))(s).then((A) => {
u.setMetadata("exif", { orientation: A }), f(u);
});
});
}),
{ options: { allowImageExifOrientation: [!0, c.BOOLEAN] } }
);
};
return (
"undefined" != typeof window &&
void 0 !== window.document &&
document.dispatchEvent(
new CustomEvent("FilePond:pluginloaded", { detail: l }),
),
l
);
});

View File

@@ -0,0 +1,98 @@
<?php
/**
* Partagé autosave draft endpoint.
*
* POST — receive all form fields and persist them to the session draft store.
* GET — return all stored draft fields as JSON for page-load hydration.
*
* The draft is scoped to the share link slug, kept in $_SESSION, and
* cleared on successful form submission.
*
* Excluded field patterns (not persisted as drafts):
* - csrf_token, share_link_token, share_password*
* - FilePond metadata (filepond_mode, queue_file, filepond_*)
* - Files-related fields (couverture, note_intention, files, annexes, etc.)
* - Empty values
*/
require_once __DIR__ . '/../../../bootstrap.php';
App::boot();
$method = $_SERVER['REQUEST_METHOD'];
// ── CSRF check ──────────────────────────────────────────────────────────
if ($method === 'POST') {
if (
!isset($_POST['csrf_token'], $_SESSION['csrf_token'])
|| !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['error' => 'Token de sécurité invalide.']);
exit;
}
}
// ── Slug validation ─────────────────────────────────────────────────────
$slug = $_GET['slug'] ?? ($_POST['slug'] ?? '');
if (!preg_match('#^\d{8}-[A-Z0-9+/]{8}$#', $slug)) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Slug invalide.']);
exit;
}
// Draft storage key
$draftKey = 'partage_draft_' . $slug;
// ── POST: save all form fields ──────────────────────────────────────────
if ($method === 'POST') {
// Fields that should never be persisted as drafts
$excludePrefixes = [
'csrf_token', 'share_link_token', 'share_password',
'filepond_mode', 'queue_file', 'filepond_',
];
$excludeExact = ['slug', 'couverture', 'note_intention', 'files', 'annexes',
'peertube_video', 'peertube_audio', 'cover_remove',
'go', 'MAX_FILE_SIZE'];
$draft = [];
foreach ($_POST as $key => $value) {
// Skip excluded fields
if (in_array($key, $excludeExact, true)) continue;
$skip = false;
foreach ($excludePrefixes as $prefix) {
if (str_starts_with($key, $prefix)) { $skip = true; break; }
}
if ($skip) continue;
// Skip empty values (but keep '0' as valid)
if ($value === '' || $value === null || (is_array($value) && count($value) === 0)) {
continue;
}
$draft[$key] = $value;
}
$_SESSION[$draftKey] = $draft;
// Rotate CSRF after mutation — keep share CSRF in sync
$newToken = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $newToken;
$_SESSION['share_csrf_' . $slug] = $newToken;
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'csrf_token' => $newToken,
]);
exit;
}
// ── GET: return draft fields for hydration ──────────────────────────────
header('Content-Type: application/json');
$draft = $_SESSION[$draftKey] ?? [];
echo json_encode([
'success' => true,
'draft' => $draft,
]);
exit;

View File

@@ -8,15 +8,8 @@
*/
class AppLogger
{
private string $logDir;
private string $logFile;
public function __construct(?string $logDir = null)
public function __construct()
{
$this->logDir = $logDir ?? (defined('STORAGE_ROOT') ? STORAGE_ROOT . '/logs' : __DIR__ . '/../storage/logs');
// Keep for backward compat — actual file I/O is now handled by Monolog via Logger::get('app')
$this->logFile = $this->logDir . '/form-submissions.log';
}
/**

View File

@@ -175,7 +175,7 @@ class ExportController
$ptInstanceUrl = $this->getPeerTubeInstanceUrl();
}
$tid = (int) $f['thesis_id'];
$peertubeLinks[$tid] = $peertubeLinks[$tid] ?? ['dirname' => '', 'links' => []];
$peertubeLinks[$tid] ??= ['dirname' => '', 'links' => []];
$peertubeLinks[$tid]['links'][] = [
'uuid' => $uuid,
'url' => $ptInstanceUrl !== '' ? rtrim($ptInstanceUrl, '/') . '/videos/watch/' . $uuid : '',

View File

@@ -107,10 +107,14 @@ class TfeController
. ' XAMXAM';
// Editable messages
$restrictedMessage = $this->db->getSetting('tfe_restricted_message',
'Les fichiers attachés à ce TFE sont réservés aux utilisateur·ices autorisé·es.');
$forbiddenMessage = $this->db->getSetting('tfe_forbidden_message',
"Ce TFE n'est pas disponible en ligne.");
$restrictedMessage = $this->db->getSetting(
'tfe_restricted_message',
'Les fichiers attachés à ce TFE sont réservés aux utilisateur·ices autorisé·es.'
);
$forbiddenMessage = $this->db->getSetting(
'tfe_forbidden_message',
"Ce TFE n'est pas disponible en ligne."
);
return [
// Core data

View File

@@ -104,7 +104,7 @@ class ThesisEditController
$licenseTypes = $this->db->getAllLicenseTypes();
$enabledAccessTypes = $this->db->getEnabledFormAccessTypes();
$rawRow = $this->db->getThesisRawFields($thesisId);
$rawRow = $this->db->getThesisRawFields($thesisId) ?? [];
$currentLicenseId = $rawRow['license_id'] ?? null;
$currentAccessTypeId = $rawRow['access_type_id'] ?? null;
$currentContextNote = $rawRow['context_note'] ?? '';

View File

@@ -2016,7 +2016,7 @@ class Database
* Return the raw FK fields not exposed through v_theses_full string columns.
* Returns ['license_id', 'access_type_id', 'context_note'] or null if not found.
*
* @return array{license_id:int|null,access_type_id:int|null,context_note:string}|null
* @return array{license_id:int|null,access_type_id:int|null,context_note:string,contact_visible:int|null}|null
*/
public function getThesisRawFields(int $thesisId): ?array
{

View File

@@ -146,7 +146,7 @@ class FilepondHandler
// Track temp file in session so it survives page reloads
if (session_status() === PHP_SESSION_ACTIVE) {
$_SESSION['filepond_tmp'][$queueType] = $_SESSION['filepond_tmp'][$queueType] ?? [];
$_SESSION['filepond_tmp'][$queueType] ??= [];
$_SESSION['filepond_tmp'][$queueType][] = $fileId;
}

View File

@@ -1,8 +1,8 @@
<?php
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\NullHandler;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\NullHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Level;
use Psr\Log\LoggerInterface;

View File

@@ -87,6 +87,7 @@ CREATE TABLE IF NOT EXISTS theses (
finality_id INTEGER,
synopsis TEXT,
context_note TEXT,
contact_visible TEXT DEFAULT NULL,
remarks TEXT,
access_type_id INTEGER,
license_id INTEGER,
@@ -407,6 +408,7 @@ SELECT
ft.name as finality_type,
t.synopsis,
t.context_note,
t.contact_visible,
at.name as access_type,
lt.name as license_type,
t.license_id,

View File

@@ -48,6 +48,10 @@
* ?string $contactPublic — contact visibility flag for edit mode
* ?string $contactInterne — contact email for edit mode
*
* Autosave:
* string $formExtraAttrs — extra HTML attributes to inject into the <form> tag
* bool $showAutosaveStatus — render the "Brouillon enregistré" status indicator
*
* Website:
* string $existingWebsiteUrl
* string $existingWebsiteLabel
@@ -56,6 +60,8 @@
// ── Defaults ──────────────────────────────────────────────────────────────────
$mode = $mode ?? 'add';
$formExtraAttrs = $formExtraAttrs ?? '';
$showAutosaveStatus = $showAutosaveStatus ?? false;
// In admin add/edit, no field is required (admins can save partial records)
$adminMode = ($mode === 'add' || $mode === 'edit');
$formAction = $formAction ?? '';
@@ -146,7 +152,7 @@ $errorFieldName = $errorFieldName ?? null;
<?php endif; ?>
<?php endif; ?>
<form action="<?= $formAction ?>" method="post" enctype="multipart/form-data" class="admin-form" data-beforeunload-guard>
<form action="<?= $formAction ?>" method="post" enctype="multipart/form-data" class="admin-form" data-beforeunload-guard <?= $formExtraAttrs ?>>
<!-- Default: JS-disabled mode (disabled → not submitted → server uses $_FILES path).
On DOMContentLoaded, JS enables this input and sets value="1" → server uses FilePond path. -->
<input type="hidden" name="filepond_mode" value="0" disabled>
@@ -540,6 +546,10 @@ if ($filesMode === 'add'): ?>
</fieldset>
<?php endif; ?>
<?php if ($showAutosaveStatus): ?>
<div class="autosave-status" data-autosave-status></div>
<?php endif; ?>
<div class="form-footer admin-form-footer">
<button type="submit" name="go" class="btn btn--primary"><?= $mode === 'edit' ? 'Enregistrer' : 'Soumettre' ?></button>
<?php if ($mode === 'add' || $mode === 'edit'): ?>

View File

@@ -6,7 +6,8 @@
"**",
"!app/public/assets/js/htmx.min.js",
"!app/public/assets/js/overtype.min.js",
"!app/public/assets/js/sortable.min.js"
"!app/public/assets/js/sortable.min.js",
"!app/public/assets/js/vendor/**"
]
},
"linter": {

View File

@@ -99,7 +99,7 @@ class TestDatabase
}
// Re-seed tags (some tests rely on tags existing)
try {
$pdo->exec("DELETE FROM tags WHERE deleted_at IS NOT NULL");
$pdo->exec('DELETE FROM tags WHERE deleted_at IS NOT NULL');
} catch (Exception $e) {
// tags table already empty
}

View File

@@ -42,7 +42,7 @@ class AutofocusFieldForErrorTest extends TestCase
public function testCreateAutofocusFinality(): void
{
$this->assertSame('finality', ThesisCreateController::autofocusFieldForError("La finalité est manquante."));
$this->assertSame('finality', ThesisCreateController::autofocusFieldForError('La finalité est manquante.'));
}
public function testCreateAutofocusLanguages(): void

View File

@@ -252,20 +252,20 @@ class DatabaseExtendedTest extends TestCase
$pdo = TestDatabase::getPDO();
// Count seed languages first (français, anglais, néerlandais, italian)
$seedCount = (int)$pdo->query("SELECT COUNT(*) FROM languages WHERE deleted_at IS NULL")->fetchColumn();
$seedCount = (int)$pdo->query('SELECT COUNT(*) FROM languages WHERE deleted_at IS NULL')->fetchColumn();
// Insert two languages that differ only by case
$pdo->prepare("INSERT INTO languages (name) VALUES ('TestLang')")->execute();
$pdo->prepare("INSERT INTO languages (name) VALUES ('testlang')")->execute();
// Both seed + 2 new should exist before dedup
$before = $pdo->query("SELECT COUNT(*) FROM languages WHERE deleted_at IS NULL")->fetchColumn();
$before = $pdo->query('SELECT COUNT(*) FROM languages WHERE deleted_at IS NULL')->fetchColumn();
$this->assertSame($seedCount + 2, (int)$before);
$this->db->deduplicateLanguages();
// One of the dupes should be soft-deleted
$after = $pdo->query("SELECT COUNT(*) FROM languages WHERE deleted_at IS NULL")->fetchColumn();
$after = $pdo->query('SELECT COUNT(*) FROM languages WHERE deleted_at IS NULL')->fetchColumn();
$this->assertSame($seedCount + 1, (int)$after);
}
@@ -293,7 +293,7 @@ class DatabaseExtendedTest extends TestCase
// Create a thesis linked to 'Français'
[$authorId, $thesisId] = TestDatabase::seedBasicThesis('Merge Test', 'Author', 2024);
$pdo->prepare("INSERT INTO thesis_languages (thesis_id, language_id) VALUES (?, ?)")
$pdo->prepare('INSERT INTO thesis_languages (thesis_id, language_id) VALUES (?, ?)')
->execute([$thesisId, $francaisId]);
// Merge Français → French
@@ -333,7 +333,7 @@ class DatabaseExtendedTest extends TestCase
$tagB = (int)$pdo->lastInsertId();
[$authorId, $thesisId] = TestDatabase::seedBasicThesis('Tag Merge', 'Author', 2024);
$pdo->prepare("INSERT INTO thesis_tags (tag_id, thesis_id) VALUES (?, ?)")
$pdo->prepare('INSERT INTO thesis_tags (tag_id, thesis_id) VALUES (?, ?)')
->execute([$tagB, $thesisId]);
$this->db->mergeTag($tagB, $tagA);

View File

@@ -15,17 +15,26 @@ class PureLogicTest extends TestCase
// We need a TfeController instance to test protected methods.
// Use the anonymous subclass pattern.
$db = TestDatabase::getInstance();
return new class($db) extends TfeController {
public function exposedSplitJuryByRole(array $jury): array { return $this->splitJuryByRole($jury); }
public function exposedCollectCaptionPaths(array $files): array { return $this->collectCaptionPaths($files); }
return new class ($db) extends TfeController {
public function exposedSplitJuryByRole(array $jury): array
{
return $this->splitJuryByRole($jury);
}
public function exposedCollectCaptionPaths(array $files): array
{
return $this->collectCaptionPaths($files);
}
};
}
private function getThesisCreateController(): ThesisCreateController
{
$db = TestDatabase::getInstance();
return new class($db) extends ThesisCreateController {
public function exposedDetectFileType(string $mimeType, string $ext): string { return $this->detectFileType($mimeType, $ext); }
return new class ($db) extends ThesisCreateController {
public function exposedDetectFileType(string $mimeType, string $ext): string
{
return $this->detectFileType($mimeType, $ext);
}
};
}

View File

@@ -15,7 +15,7 @@ class TfeControllerOgTest extends TestCase
*/
private static function makeController(): object
{
return new class extends TfeController {
return new class () extends TfeController {
public function __construct()
{
// Skip parent constructor — we don't need DB for these pure methods

View File

@@ -106,8 +106,8 @@ class ThesisEditValidationTest extends TestCase
$this->assertCount(3, $members);
$internes = array_filter($members, fn($m) => $m['is_external'] === 0 && $m['role'] === 'lecteur');
$externes = array_filter($members, fn($m) => $m['is_external'] === 1 && $m['role'] === 'lecteur');
$internes = array_filter($members, fn ($m) => $m['is_external'] === 0 && $m['role'] === 'lecteur');
$externes = array_filter($members, fn ($m) => $m['is_external'] === 1 && $m['role'] === 'lecteur');
$this->assertCount(2, $internes);
$this->assertCount(1, $externes);