mirror of
https://codeberg.org/PostERG/xamxam.git
synced 2026-06-26 08:39:18 +02:00
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:
@@ -6,25 +6,31 @@
|
||||
*
|
||||
* Provides visual feedback on the originating button.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
window.copyTextToClipboard = function (text) {
|
||||
if (!text) return;
|
||||
navigator.clipboard.writeText(text).then(function () {
|
||||
var btn = window.event && 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);
|
||||
btn.innerHTML = origHTML;
|
||||
}, 1200);
|
||||
}
|
||||
}).catch(function () {
|
||||
// Clipboard write failed — silently ignore
|
||||
});
|
||||
};
|
||||
(() => {
|
||||
window.copyTextToClipboard = (text) => {
|
||||
var btn;
|
||||
var origTitle;
|
||||
var origHTML;
|
||||
if (!text) return;
|
||||
navigator.clipboard
|
||||
.writeText(text)
|
||||
.then(() => {
|
||||
btn = window.event?.target
|
||||
? window.event.target.closest("button")
|
||||
: null;
|
||||
if (btn) {
|
||||
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(() => {
|
||||
// Clipboard write failed — silently ignore
|
||||
});
|
||||
};
|
||||
})();
|
||||
|
||||
@@ -12,86 +12,90 @@
|
||||
* #access-justification — justification textarea
|
||||
* #access-request-message — message display div
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
(() => {
|
||||
var form = document.getElementById("access-request-form");
|
||||
if (!form) return;
|
||||
|
||||
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;
|
||||
|
||||
if (!emailInput || !messageDiv) return;
|
||||
// Show/hide justification based on email domain
|
||||
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";
|
||||
if (justificationInput) justificationInput.required = !isErg;
|
||||
});
|
||||
|
||||
// Show/hide justification based on email domain
|
||||
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';
|
||||
if (justificationInput) justificationInput.required = !isErg;
|
||||
});
|
||||
function showRetryPrompt(rejectedEmail, serverMessage) {
|
||||
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, "<") +
|
||||
"</small><br><br>" +
|
||||
"Corrigez votre adresse e-mail et réessayez.";
|
||||
emailInput.value = rejectedEmail;
|
||||
emailInput.classList.add("input-error");
|
||||
emailInput.focus();
|
||||
emailInput.select();
|
||||
emailInput.addEventListener("input", function clearError() {
|
||||
emailInput.classList.remove("input-error");
|
||||
emailInput.removeEventListener("input", clearError);
|
||||
});
|
||||
}
|
||||
|
||||
function showRetryPrompt(rejectedEmail, serverMessage) {
|
||||
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, '<') + '</small><br><br>' +
|
||||
'Corrigez votre adresse e-mail et réessayez.';
|
||||
emailInput.value = rejectedEmail;
|
||||
emailInput.classList.add('input-error');
|
||||
emailInput.focus();
|
||||
emailInput.select();
|
||||
emailInput.addEventListener('input', function clearError() {
|
||||
emailInput.classList.remove('input-error');
|
||||
emailInput.removeEventListener('input', clearError);
|
||||
});
|
||||
}
|
||||
form.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
form.addEventListener('submit', function (e) {
|
||||
e.preventDefault();
|
||||
var submitBtn = form.querySelector('button[type="submit"]');
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = "Envoi en cours...";
|
||||
messageDiv.style.display = "none";
|
||||
|
||||
var submitBtn = form.querySelector('button[type="submit"]');
|
||||
submitBtn.disabled = true;
|
||||
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"));
|
||||
|
||||
var submittedEmail = emailInput.value.trim();
|
||||
var formData = new FormData(form);
|
||||
formData.append('thesis_id', form.getAttribute('data-thesis-id'));
|
||||
fetch("/request-access", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.then((data) => {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = "Demander l'accès";
|
||||
|
||||
fetch('/request-access', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(function (response) { return response.json(); })
|
||||
.then(function (data) {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Demander l\'accès';
|
||||
if (data.status === "recipient_rejected") {
|
||||
showRetryPrompt(submittedEmail, data.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.status === 'recipient_rejected') {
|
||||
showRetryPrompt(submittedEmail, data.message);
|
||||
return;
|
||||
}
|
||||
|
||||
messageDiv.style.display = 'block';
|
||||
if (data.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.';
|
||||
}
|
||||
})
|
||||
.catch(function () {
|
||||
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.';
|
||||
});
|
||||
});
|
||||
messageDiv.style.display = "block";
|
||||
if (data.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.";
|
||||
}
|
||||
})
|
||||
.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.";
|
||||
});
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -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 = (btn) => {
|
||||
var logOut = document.querySelector("#log-output");
|
||||
if (!logOut) return;
|
||||
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.copyLogContent = function (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);
|
||||
});
|
||||
} else {
|
||||
window._fallbackCopy(text, btn);
|
||||
}
|
||||
};
|
||||
window._fallbackCopy = (text, btn) => {
|
||||
var ta = document.createElement("textarea");
|
||||
ta.value = text;
|
||||
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(() => {
|
||||
btn.textContent = "Copier";
|
||||
btn.classList.remove("copied");
|
||||
}, 2000);
|
||||
} catch (_e) {}
|
||||
document.body.removeChild(ta);
|
||||
};
|
||||
|
||||
window._fallbackCopy = function (text, btn) {
|
||||
var ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
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.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;
|
||||
var rc = evt.detail.requestConfig;
|
||||
var tab = null;
|
||||
// Tab clicks carry ?tab=… in the path
|
||||
var qIdx = rc.path.indexOf('?');
|
||||
if (qIdx !== -1) {
|
||||
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');
|
||||
});
|
||||
});
|
||||
// Update active tab class after each HTMX swap on #sys-tab-panel
|
||||
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("?");
|
||||
if (qIdx !== -1) {
|
||||
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((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");
|
||||
});
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -5,58 +5,62 @@
|
||||
* parse errors instead of silently swallowing them (unlike the
|
||||
* old autosave.js .catch(() => {}) pattern).
|
||||
*/
|
||||
function handleAutosaveResponse(event) {
|
||||
const form = event.target.closest("form");
|
||||
const status = form ? form.querySelector("[data-autosave-status]") : null;
|
||||
function _handleAutosaveResponse(event) {
|
||||
const form = event.target.closest("form");
|
||||
const status = form ? form.querySelector("[data-autosave-status]") : null;
|
||||
|
||||
if (!event.detail.successful) {
|
||||
if (status) {
|
||||
status.textContent = "Erreur !";
|
||||
status.className = "autosave-status autosave-status--error";
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!event.detail.successful) {
|
||||
if (status) {
|
||||
status.textContent = "Erreur !";
|
||||
status.className = "autosave-status autosave-status--error";
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = JSON.parse(event.detail.xhr.responseText);
|
||||
try {
|
||||
const data = JSON.parse(event.detail.xhr.responseText);
|
||||
|
||||
// Rotate CSRF token in both the form and the meta tag
|
||||
if (data.csrf_token) {
|
||||
const csrfInput = form.querySelector('input[name="csrf_token"]');
|
||||
if (csrfInput) csrfInput.value = data.csrf_token;
|
||||
const meta = document.querySelector('meta[name="csrf-token"]');
|
||||
if (meta) meta.content = data.csrf_token;
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
|
||||
if (status) {
|
||||
if (data.success) {
|
||||
status.textContent = "Enregistré ✓";
|
||||
status.className = "autosave-status autosave-status--saved";
|
||||
} else {
|
||||
status.textContent = "Erreur !";
|
||||
status.className = "autosave-status autosave-status--error";
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// JSON parse failed (e.g. PHP warning in output) — surface it
|
||||
if (status) {
|
||||
status.textContent = "Erreur !";
|
||||
status.className = "autosave-status autosave-status--error";
|
||||
}
|
||||
console.warn(
|
||||
"Autosave: could not parse response",
|
||||
event.detail.xhr.responseText,
|
||||
);
|
||||
}
|
||||
if (status) {
|
||||
if (data.success) {
|
||||
status.textContent = "Enregistré ✓";
|
||||
status.className = "autosave-status autosave-status--saved";
|
||||
} else {
|
||||
status.textContent = "Erreur !";
|
||||
status.className = "autosave-status autosave-status--error";
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// JSON parse failed (e.g. PHP warning in output) — surface it
|
||||
if (status) {
|
||||
status.textContent = "Erreur !";
|
||||
status.className = "autosave-status autosave-status--error";
|
||||
}
|
||||
console.warn(
|
||||
"Autosave: could not parse response",
|
||||
event.detail.xhr.responseText,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Show saving indicator while request is in flight
|
||||
document.body.addEventListener("htmx:beforeRequest", (e) => {
|
||||
const el = e.target;
|
||||
if (!el) return;
|
||||
const status = el.querySelector("[data-autosave-status]");
|
||||
if (status) {
|
||||
status.textContent = "Enregistrement…";
|
||||
status.className = "autosave-status autosave-status--saving";
|
||||
}
|
||||
const el = e.target;
|
||||
if (!el) return;
|
||||
const status = el.querySelector("[data-autosave-status]");
|
||||
if (status) {
|
||||
status.textContent = "Enregistrement…";
|
||||
status.className = "autosave-status autosave-status--saving";
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6,20 +6,27 @@
|
||||
* No effect when JavaScript is unavailable (form posts normally).
|
||||
*/
|
||||
(() => {
|
||||
const forms = document.querySelectorAll('form[data-beforeunload-guard]');
|
||||
if (!forms.length) return;
|
||||
const forms = document.querySelectorAll("form[data-beforeunload-guard]");
|
||||
if (!forms.length) return;
|
||||
|
||||
let dirty = false;
|
||||
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; });
|
||||
}
|
||||
for (const form of forms) {
|
||||
form.addEventListener("input", () => {
|
||||
dirty = true;
|
||||
});
|
||||
form.addEventListener("change", () => {
|
||||
dirty = true;
|
||||
});
|
||||
form.addEventListener("submit", () => {
|
||||
dirty = false;
|
||||
window.__xamxamDirty = false;
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener('beforeunload', (e) => {
|
||||
if (dirty || window.__xamxamDirty) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
window.addEventListener("beforeunload", (e) => {
|
||||
if (dirty || window.__xamxamDirty) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -8,31 +8,32 @@
|
||||
* Or with a custom selector pattern:
|
||||
* <button onclick="copyUrlFrom(document.getElementById('my-url'))">Copier</button>
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
(() => {
|
||||
window.copyUrl = (id) => {
|
||||
var input = document.getElementById(`url-${id}`);
|
||||
if (input) {
|
||||
window.copyUrlFrom(input);
|
||||
}
|
||||
};
|
||||
|
||||
window.copyUrl = function (id) {
|
||||
var input = document.getElementById('url-' + id);
|
||||
if (input) {
|
||||
window.copyUrlFrom(input);
|
||||
}
|
||||
};
|
||||
|
||||
window.copyUrlFrom = function (sourceEl) {
|
||||
var text = sourceEl.value || sourceEl.textContent || '';
|
||||
if (!text) return;
|
||||
navigator.clipboard.writeText(text).then(function () {
|
||||
var btn = window.event && 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);
|
||||
btn.textContent = origText;
|
||||
}, 1200);
|
||||
}
|
||||
});
|
||||
};
|
||||
window.copyUrlFrom = (sourceEl) => {
|
||||
var text = sourceEl.value || sourceEl.textContent || "";
|
||||
var btn;
|
||||
var origTitle;
|
||||
var origText;
|
||||
if (!text) return;
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
btn = window.event?.target ? window.event.target.closest("button") : null;
|
||||
if (btn) {
|
||||
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);
|
||||
}
|
||||
});
|
||||
};
|
||||
})();
|
||||
|
||||
@@ -56,8 +56,8 @@
|
||||
// so numeric literals are required (string suffixes like "1GB" become
|
||||
// parseInt("1GB") = 1 byte inside the plugin).
|
||||
perExtensionMaxSize: {
|
||||
pdf: 104857600, // 100 MB
|
||||
mp4: 8589934592, // 8 GB
|
||||
pdf: 104857600, // 100 MB
|
||||
mp4: 8589934592, // 8 GB
|
||||
webm: 8589934592,
|
||||
ogv: 8589934592,
|
||||
mov: 8589934592,
|
||||
@@ -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,48 +697,81 @@
|
||||
* 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 || {};
|
||||
var thesisId = ctx.thesisId;
|
||||
var thesisId = ctx.thesisId;
|
||||
var queueType = ctx.queueType;
|
||||
|
||||
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(({ 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>`;
|
||||
return;
|
||||
}
|
||||
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');
|
||||
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');
|
||||
if (block && window.htmx) {
|
||||
var url = '/admin/fragments/fichiers.php';
|
||||
if (window.__xamxamRelinkCtx && window.__xamxamRelinkCtx.thesisId) {
|
||||
url += '?_thesis_id=' + encodeURIComponent(window.__xamxamRelinkCtx.thesisId);
|
||||
}
|
||||
htmx.ajax('GET', url, {
|
||||
target: '#format-fichiers-block',
|
||||
swap: 'outerHTML'
|
||||
});
|
||||
.then((r) =>
|
||||
r.json().then((data) => ({ ok: r.ok, status: r.status, data })),
|
||||
)
|
||||
.then(({ ok, status, data }) => {
|
||||
if (!ok || (data && data.ok === false)) {
|
||||
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;
|
||||
}
|
||||
};
|
||||
if (input) {
|
||||
var pond = FilePond.find(input);
|
||||
console.log('[relink] looking for pond | found=' + !!pond);
|
||||
if (pond) {
|
||||
pond.addFile(String(data.id), {
|
||||
type: 'limbo',
|
||||
file: {
|
||||
name: fileName,
|
||||
size: fileSize,
|
||||
type: mimeType
|
||||
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 = () => {
|
||||
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");
|
||||
if (block && window.htmx) {
|
||||
let url = "/admin/fragments/fichiers.php";
|
||||
if (window.__xamxamRelinkCtx?.thesisId) {
|
||||
url +=
|
||||
"?_thesis_id=" +
|
||||
encodeURIComponent(window.__xamxamRelinkCtx.thesisId);
|
||||
}
|
||||
}).then(function() {
|
||||
console.log('[relink] addFile resolved | source=' + String(data.id) + ' | queueType=' + queueType);
|
||||
htmx.ajax("GET", url, {
|
||||
target: "#format-fichiers-block",
|
||||
swap: "outerHTML",
|
||||
});
|
||||
}
|
||||
};
|
||||
if (input) {
|
||||
const pond = FilePond.find(input);
|
||||
console.log(`[relink] looking for pond | found=${!!pond}`);
|
||||
if (pond) {
|
||||
pond
|
||||
.addFile(String(data.id), {
|
||||
type: "limbo",
|
||||
file: {
|
||||
name: fileName,
|
||||
size: fileSize,
|
||||
type: mimeType,
|
||||
},
|
||||
})
|
||||
.then(() => {
|
||||
console.log(
|
||||
"[relink] addFile resolved | source=" +
|
||||
String(data.id) +
|
||||
" | queueType=" +
|
||||
queueType,
|
||||
);
|
||||
closeAndRefresh();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("[relink] addFile rejected", err);
|
||||
closeAndRefresh();
|
||||
});
|
||||
} else {
|
||||
console.error(
|
||||
"[relink] FilePond.find returned null for input",
|
||||
input,
|
||||
);
|
||||
closeAndRefresh();
|
||||
}).catch(function(err) {
|
||||
console.error('[relink] addFile rejected', err);
|
||||
closeAndRefresh();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.error('[relink] FilePond.find returned null for input', input);
|
||||
console.warn(
|
||||
"[relink] input not found, page may have reloaded | queueType=" +
|
||||
queueType,
|
||||
);
|
||||
closeAndRefresh();
|
||||
}
|
||||
} else {
|
||||
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>';
|
||||
});
|
||||
// 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>';
|
||||
});
|
||||
};
|
||||
})();
|
||||
|
||||
@@ -11,130 +11,142 @@
|
||||
* 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((fieldset) => {
|
||||
fieldset.setAttribute("data-jury-autocomplete-initialized", "1");
|
||||
initFieldset(fieldset);
|
||||
});
|
||||
}
|
||||
|
||||
function initAll() {
|
||||
document.querySelectorAll('[data-jury-autocomplete]:not([data-jury-autocomplete-initialized])').forEach(function (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 list;
|
||||
var activeInput;
|
||||
var selectedIdx;
|
||||
var debounceTimer;
|
||||
|
||||
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');
|
||||
if (!dropdown) {
|
||||
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');
|
||||
if (list) {
|
||||
list.insertAdjacentElement('afterend', dropdown);
|
||||
} else {
|
||||
fieldset.appendChild(dropdown);
|
||||
}
|
||||
}
|
||||
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");
|
||||
// Insert after the list container
|
||||
list = fieldset.querySelector(".admin-jury-list");
|
||||
if (list) {
|
||||
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", (e) => {
|
||||
var btn = e.target.closest(".tag-search-item");
|
||||
if (!btn) return;
|
||||
var name = (btn.getAttribute("data-tag-name") || "").trim();
|
||||
if (!name || !activeInput) return;
|
||||
activeInput.value = btn.classList.contains("tag-search-item--create")
|
||||
? activeInput.value.trim()
|
||||
: name;
|
||||
dropdown.innerHTML = "";
|
||||
selectedIdx = -1;
|
||||
activeInput.focus();
|
||||
});
|
||||
|
||||
// Click on suggestion → fill the active input
|
||||
dropdown.addEventListener('click', function (e) {
|
||||
var btn = e.target.closest('.tag-search-item');
|
||||
if (!btn) return;
|
||||
var name = (btn.getAttribute('data-tag-name') || '').trim();
|
||||
if (!name || !activeInput) return;
|
||||
activeInput.value = btn.classList.contains('tag-search-item--create')
|
||||
? activeInput.value.trim()
|
||||
: name;
|
||||
dropdown.innerHTML = '';
|
||||
selectedIdx = -1;
|
||||
activeInput.focus();
|
||||
});
|
||||
// Highlighting helper
|
||||
function highlight(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);
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
fieldset.addEventListener("input", (e) => {
|
||||
var inp = e.target.closest('input[type="text"]');
|
||||
if (!inp) return;
|
||||
|
||||
fieldset.addEventListener('input', function (e) {
|
||||
var inp = e.target.closest('input[type="text"]');
|
||||
if (!inp) return;
|
||||
activeInput = inp;
|
||||
var q = inp.value.trim();
|
||||
|
||||
activeInput = inp;
|
||||
var q = inp.value.trim();
|
||||
// Build the hx-include query — include hidden type=supervisor
|
||||
var _typeInput = fieldset.querySelector(
|
||||
'input[name="type"][value="supervisor"]',
|
||||
);
|
||||
|
||||
// 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"]' : '';
|
||||
if (debounceTimer) clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(() => {
|
||||
if (q === "") {
|
||||
dropdown.innerHTML = "";
|
||||
selectedIdx = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (debounceTimer) clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(function () {
|
||||
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 = () => {
|
||||
if (xhr.status === 200) {
|
||||
dropdown.innerHTML = xhr.responseText;
|
||||
selectedIdx = -1;
|
||||
}
|
||||
};
|
||||
var params =
|
||||
"type=supervisor&q=" +
|
||||
encodeURIComponent(q) +
|
||||
(role ? `&role=${encodeURIComponent(role)}` : "");
|
||||
xhr.send(params);
|
||||
}, 200);
|
||||
});
|
||||
|
||||
// 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 () {
|
||||
if (xhr.status === 200) {
|
||||
dropdown.innerHTML = xhr.responseText;
|
||||
selectedIdx = -1;
|
||||
}
|
||||
};
|
||||
var params = 'type=supervisor&q=' + encodeURIComponent(q) + (role ? '&role=' + encodeURIComponent(role) : '');
|
||||
xhr.send(params);
|
||||
}, 200);
|
||||
});
|
||||
// Keyboard navigation
|
||||
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") {
|
||||
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 !== "") {
|
||||
e.preventDefault();
|
||||
if (selectedIdx >= 0 && selectedIdx < items.length) {
|
||||
items[selectedIdx].click();
|
||||
} else {
|
||||
items[0].click();
|
||||
}
|
||||
}
|
||||
} else if (e.key === "Escape") {
|
||||
dropdown.innerHTML = "";
|
||||
selectedIdx = -1;
|
||||
}
|
||||
});
|
||||
|
||||
// Keyboard navigation
|
||||
fieldset.addEventListener('keydown', function (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') {
|
||||
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 !== '') {
|
||||
e.preventDefault();
|
||||
if (selectedIdx >= 0 && selectedIdx < items.length) {
|
||||
items[selectedIdx].click();
|
||||
} else {
|
||||
items[0].click();
|
||||
}
|
||||
}
|
||||
} else if (e.key === 'Escape') {
|
||||
dropdown.innerHTML = '';
|
||||
selectedIdx = -1;
|
||||
}
|
||||
});
|
||||
|
||||
// Close dropdown on outside click
|
||||
document.addEventListener('click', function (e) {
|
||||
if (!fieldset.contains(e.target)) {
|
||||
dropdown.innerHTML = '';
|
||||
selectedIdx = -1;
|
||||
}
|
||||
});
|
||||
}
|
||||
// Close dropdown on outside click
|
||||
document.addEventListener("click", (e) => {
|
||||
if (!fieldset.contains(e.target)) {
|
||||
dropdown.innerHTML = "";
|
||||
selectedIdx = -1;
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -20,152 +20,172 @@
|
||||
* 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((container) => {
|
||||
container.setAttribute("data-pill-search-initialized", "1");
|
||||
initPillSearch(container);
|
||||
});
|
||||
}
|
||||
|
||||
function initAll() {
|
||||
document.querySelectorAll('[data-pill-search]:not([data-pill-search-initialized])').forEach(function (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) || 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;
|
||||
|
||||
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 selectedIdx = -1;
|
||||
if (!pills || !search || !dropdown) return;
|
||||
|
||||
if (!pills || !search || !dropdown) return;
|
||||
function normalize(name) {
|
||||
return name.trim().replace(/\s+/g, " ").toLowerCase();
|
||||
}
|
||||
|
||||
function normalize(name) {
|
||||
return name.trim().replace(/\s+/g, ' ').toLowerCase();
|
||||
}
|
||||
function pillAlreadyExists(name) {
|
||||
var norm = normalize(name);
|
||||
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 pillAlreadyExists(name) {
|
||||
var norm = normalize(name);
|
||||
var existing = pills.querySelectorAll('.tag-pill-name');
|
||||
for (var 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";
|
||||
if (countEl && required) {
|
||||
countEl.style.color =
|
||||
n < minTags ? "var(--text-danger)" : "var(--accent)";
|
||||
}
|
||||
|
||||
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';
|
||||
if (countEl && required) {
|
||||
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");
|
||||
if (n >= maxTags) {
|
||||
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";
|
||||
}
|
||||
}
|
||||
|
||||
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 = '';
|
||||
} else {
|
||||
if (wrap) { wrap.style.display = ''; if (search) search.style.display = ''; }
|
||||
if (maxMsg) maxMsg.style.display = 'none';
|
||||
}
|
||||
}
|
||||
pills.addEventListener("click", (e) => {
|
||||
var btn = e.target.closest(".tag-pill-remove");
|
||||
if (!btn) return;
|
||||
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 = "";
|
||||
}
|
||||
});
|
||||
|
||||
pills.addEventListener('click', function (e) {
|
||||
var btn = e.target.closest('.tag-pill-remove');
|
||||
if (!btn) return;
|
||||
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 = ''; }
|
||||
});
|
||||
function highlight(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 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);
|
||||
}
|
||||
}
|
||||
function selectPill(btn) {
|
||||
var name = normalize(btn.getAttribute("data-tag-name") || "");
|
||||
if (!name) return;
|
||||
if (pillAlreadyExists(name)) return;
|
||||
if (pills.querySelectorAll(".tag-pill").length >= maxTags) return;
|
||||
|
||||
function selectPill(btn) {
|
||||
var name = normalize(btn.getAttribute('data-tag-name') || '');
|
||||
if (!name) return;
|
||||
if (pillAlreadyExists(name)) 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>";
|
||||
pills.appendChild(pill);
|
||||
updateCount();
|
||||
search.value = "";
|
||||
dropdown.innerHTML = "";
|
||||
selectedIdx = -1;
|
||||
search.focus();
|
||||
}
|
||||
|
||||
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>';
|
||||
pills.appendChild(pill);
|
||||
updateCount();
|
||||
search.value = '';
|
||||
dropdown.innerHTML = '';
|
||||
selectedIdx = -1;
|
||||
search.focus();
|
||||
}
|
||||
dropdown.addEventListener("click", (e) => {
|
||||
var btn = e.target.closest(".tag-search-item");
|
||||
if (!btn) return;
|
||||
selectPill(btn);
|
||||
});
|
||||
|
||||
dropdown.addEventListener('click', function (e) {
|
||||
var btn = e.target.closest('.tag-search-item');
|
||||
if (!btn) return;
|
||||
selectPill(btn);
|
||||
});
|
||||
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") {
|
||||
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) {
|
||||
e.preventDefault();
|
||||
if (selectedIdx >= 0 && selectedIdx < items.length) {
|
||||
selectPill(items[selectedIdx]);
|
||||
} else {
|
||||
selectPill(items[0]);
|
||||
}
|
||||
}
|
||||
} else if (e.key === "Escape") {
|
||||
dropdown.innerHTML = "";
|
||||
selectedIdx = -1;
|
||||
}
|
||||
});
|
||||
|
||||
search.addEventListener('keydown', function (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') {
|
||||
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) {
|
||||
e.preventDefault();
|
||||
if (selectedIdx >= 0 && selectedIdx < items.length) {
|
||||
selectPill(items[selectedIdx]);
|
||||
} else {
|
||||
selectPill(items[0]);
|
||||
}
|
||||
}
|
||||
} else if (e.key === 'Escape') {
|
||||
dropdown.innerHTML = '';
|
||||
selectedIdx = -1;
|
||||
}
|
||||
});
|
||||
search.addEventListener("blur", () => {
|
||||
setTimeout(() => {
|
||||
if (!dropdown.contains(document.activeElement)) {
|
||||
dropdown.innerHTML = "";
|
||||
selectedIdx = -1;
|
||||
}
|
||||
}, 150);
|
||||
});
|
||||
|
||||
search.addEventListener('blur', function () {
|
||||
setTimeout(function () {
|
||||
if (!dropdown.contains(document.activeElement)) {
|
||||
dropdown.innerHTML = '';
|
||||
selectedIdx = -1;
|
||||
}
|
||||
}, 150);
|
||||
});
|
||||
|
||||
function htmlEscape(str) {
|
||||
var el = document.createElement('span');
|
||||
el.textContent = str;
|
||||
return el.innerHTML;
|
||||
}
|
||||
}
|
||||
function htmlEscape(str) {
|
||||
var el = document.createElement("span");
|
||||
el.textContent = str;
|
||||
return el.innerHTML;
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -11,203 +11,211 @@
|
||||
* 100% : response received — "Téléversé avec succès", then redirect
|
||||
*/
|
||||
(() => {
|
||||
'use strict';
|
||||
const FORMS = document.querySelectorAll("form[data-upload-progress]");
|
||||
if (!FORMS.length) return;
|
||||
|
||||
const FORMS = document.querySelectorAll('form[data-upload-progress]');
|
||||
if (!FORMS.length) return;
|
||||
const POLL_INTERVAL = 400;
|
||||
const UPLOAD_CAP = 25;
|
||||
const PROCESSING_MAX = 99;
|
||||
const SUCCESS_DELAY = 800;
|
||||
|
||||
const POLL_INTERVAL = 400;
|
||||
const UPLOAD_CAP = 25;
|
||||
const PROCESSING_MAX = 99;
|
||||
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 submitBtn = form.querySelector('button[type="submit"]');
|
||||
const tokenInput = form.querySelector('input[name="progress_token"]');
|
||||
|
||||
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 submitBtn = form.querySelector('button[type="submit"]');
|
||||
const tokenInput = form.querySelector('input[name="progress_token"]');
|
||||
if (!progressBar || !progressWrap) continue;
|
||||
|
||||
if (!progressBar || !progressWrap) continue;
|
||||
function collectFileNames() {
|
||||
const names = [];
|
||||
// Check raw <input type="file"> elements (non-FilePond)
|
||||
const inputs = form.querySelectorAll('input[type="file"]');
|
||||
for (const fi of inputs) {
|
||||
if (fi.files) {
|
||||
for (const f of fi.files) {
|
||||
if (f.name) names.push(f.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Read processed file names from FilePond instances (async mode)
|
||||
if (typeof FilePond !== "undefined") {
|
||||
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) {
|
||||
// Only count successfully uploaded files (have serverId)
|
||||
if (pf.serverId) {
|
||||
const name = pf.filename || pf.file?.name || pf.serverId;
|
||||
if (name) names.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
function collectFileNames() {
|
||||
const names = [];
|
||||
// Check raw <input type="file"> elements (non-FilePond)
|
||||
const inputs = form.querySelectorAll('input[type="file"]');
|
||||
for (const fi of inputs) {
|
||||
if (fi.files) {
|
||||
for (const f of fi.files) {
|
||||
if (f.name) names.push(f.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Read processed file names from FilePond instances (async mode)
|
||||
if (typeof FilePond !== 'undefined') {
|
||||
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) {
|
||||
// Only count successfully uploaded files (have serverId)
|
||||
if (pf.serverId) {
|
||||
const name = pf.filename || (pf.file && pf.file.name) || pf.serverId;
|
||||
if (name) names.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
form.addEventListener("submit", (e) => {
|
||||
// ── Guard: block submit if any FilePond item is still uploading ──
|
||||
if (typeof FilePond !== "undefined") {
|
||||
let stillUploading = false;
|
||||
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
|
||||
) {
|
||||
stillUploading = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stillUploading) break;
|
||||
}
|
||||
if (stillUploading) {
|
||||
e.preventDefault();
|
||||
progressLabel.textContent =
|
||||
"Veuillez attendre la fin du téléversement…";
|
||||
progressWrap.style.display = "";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
form.addEventListener('submit', function (e) {
|
||||
// ── Guard: block submit if any FilePond item is still uploading ──
|
||||
if (typeof FilePond !== 'undefined') {
|
||||
let stillUploading = false;
|
||||
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) {
|
||||
stillUploading = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stillUploading) break;
|
||||
}
|
||||
if (stillUploading) {
|
||||
e.preventDefault();
|
||||
progressLabel.textContent = 'Veuillez attendre la fin du téléversement…';
|
||||
progressWrap.style.display = '';
|
||||
return;
|
||||
}
|
||||
}
|
||||
const fileNames = collectFileNames();
|
||||
if (!fileNames.length) return;
|
||||
|
||||
const fileNames = collectFileNames();
|
||||
if (!fileNames.length) return;
|
||||
e.preventDefault();
|
||||
|
||||
e.preventDefault();
|
||||
const token = tokenInput ? tokenInput.value : "";
|
||||
|
||||
const token = tokenInput ? tokenInput.value : '';
|
||||
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`;
|
||||
if (submitBtn) submitBtn.disabled = true;
|
||||
|
||||
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';
|
||||
if (submitBtn) submitBtn.disabled = true;
|
||||
const fd = new FormData(form);
|
||||
const xhr = new XMLHttpRequest();
|
||||
|
||||
const fd = new FormData(form);
|
||||
const xhr = new XMLHttpRequest();
|
||||
let _uploadDone = false;
|
||||
let lastUploadPct = 0;
|
||||
let pollingTimer = null;
|
||||
|
||||
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(() => {
|
||||
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(() => {
|
||||
/* ignore poll errors */
|
||||
});
|
||||
}, POLL_INTERVAL);
|
||||
}
|
||||
|
||||
/** 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));
|
||||
progressBar.value = pct;
|
||||
if (data.file) {
|
||||
progressFile.textContent = data.file;
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(function () { /* ignore poll errors */ });
|
||||
}, POLL_INTERVAL);
|
||||
}
|
||||
function stopPolling() {
|
||||
if (pollingTimer) {
|
||||
clearInterval(pollingTimer);
|
||||
pollingTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollingTimer) {
|
||||
clearInterval(pollingTimer);
|
||||
pollingTimer = null;
|
||||
}
|
||||
}
|
||||
function finishSuccess() {
|
||||
stopPolling();
|
||||
progressBar.value = 100;
|
||||
progressBar.setAttribute("data-complete", "");
|
||||
progressLabel.textContent = "Téléversé avec succès";
|
||||
progressFile.textContent = "";
|
||||
}
|
||||
|
||||
function finishSuccess() {
|
||||
stopPolling();
|
||||
progressBar.value = 100;
|
||||
progressBar.setAttribute('data-complete', '');
|
||||
progressLabel.textContent = 'Téléversé avec succès';
|
||||
progressFile.textContent = '';
|
||||
}
|
||||
// ── Upload phase (0% → UPLOAD_CAP) ──
|
||||
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);
|
||||
if (scaled > lastUploadPct) {
|
||||
lastUploadPct = scaled;
|
||||
progressBar.value = scaled;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ── Upload phase (0% → UPLOAD_CAP) ──
|
||||
xhr.upload.addEventListener('progress', function (evt) {
|
||||
if (evt.lengthComputable) {
|
||||
const rawPct = Math.round((evt.loaded / evt.total) * 100);
|
||||
const scaled = Math.round((rawPct / 100) * UPLOAD_CAP);
|
||||
if (scaled > lastUploadPct) {
|
||||
lastUploadPct = scaled;
|
||||
progressBar.value = scaled;
|
||||
}
|
||||
}
|
||||
});
|
||||
xhr.upload.addEventListener("loadend", () => {
|
||||
_uploadDone = true;
|
||||
progressBar.value = UPLOAD_CAP;
|
||||
startPolling();
|
||||
});
|
||||
|
||||
xhr.upload.addEventListener('loadend', function () {
|
||||
uploadDone = true;
|
||||
progressBar.value = UPLOAD_CAP;
|
||||
startPolling();
|
||||
});
|
||||
// ── Response handling ──
|
||||
xhr.addEventListener("readystatechange", () => {
|
||||
if (xhr.readyState !== XMLHttpRequest.DONE) return;
|
||||
|
||||
// ── Response handling ──
|
||||
xhr.addEventListener('readystatechange', function () {
|
||||
if (xhr.readyState !== XMLHttpRequest.DONE) return;
|
||||
stopPolling();
|
||||
|
||||
stopPolling();
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
finishSuccess();
|
||||
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
finishSuccess();
|
||||
setTimeout(() => {
|
||||
const finalUrl = xhr.responseURL || "";
|
||||
if (finalUrl && finalUrl !== form.action) {
|
||||
window.location.href = finalUrl;
|
||||
} else {
|
||||
document.open();
|
||||
document.write(xhr.responseText);
|
||||
document.close();
|
||||
}
|
||||
}, SUCCESS_DELAY);
|
||||
} else {
|
||||
progressLabel.textContent = "Erreur";
|
||||
progressFile.textContent = "Échec du téléversement";
|
||||
document.open();
|
||||
document.write(xhr.responseText);
|
||||
document.close();
|
||||
}
|
||||
});
|
||||
|
||||
setTimeout(function () {
|
||||
const finalUrl = xhr.responseURL || '';
|
||||
if (finalUrl && finalUrl !== form.action) {
|
||||
window.location.href = finalUrl;
|
||||
} else {
|
||||
document.open();
|
||||
document.write(xhr.responseText);
|
||||
document.close();
|
||||
}
|
||||
}, SUCCESS_DELAY);
|
||||
} else {
|
||||
progressLabel.textContent = 'Erreur';
|
||||
progressFile.textContent = 'Échec du téléversement';
|
||||
document.open();
|
||||
document.write(xhr.responseText);
|
||||
document.close();
|
||||
}
|
||||
});
|
||||
xhr.addEventListener("error", () => {
|
||||
stopPolling();
|
||||
progressLabel.textContent = "Erreur réseau";
|
||||
progressFile.textContent = "";
|
||||
if (submitBtn) submitBtn.disabled = false;
|
||||
});
|
||||
|
||||
xhr.addEventListener('error', function () {
|
||||
stopPolling();
|
||||
progressLabel.textContent = 'Erreur réseau';
|
||||
progressFile.textContent = '';
|
||||
if (submitBtn) submitBtn.disabled = false;
|
||||
});
|
||||
xhr.addEventListener("abort", () => {
|
||||
stopPolling();
|
||||
progressWrap.style.display = "none";
|
||||
if (submitBtn) submitBtn.disabled = false;
|
||||
});
|
||||
|
||||
xhr.addEventListener('abort', function () {
|
||||
stopPolling();
|
||||
progressWrap.style.display = 'none';
|
||||
if (submitBtn) submitBtn.disabled = false;
|
||||
});
|
||||
|
||||
xhr.open('POST', form.action, true);
|
||||
xhr.send(fd);
|
||||
});
|
||||
}
|
||||
xhr.open("POST", form.action, true);
|
||||
xhr.send(fd);
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user