fix #29 : envoyer le lien magique par email (envoyer_mail_smtp)

This commit is contained in:
Cedric Abonnel
2026-05-13 23:41:58 +02:00
commit 8a85c15372
129 changed files with 22818 additions and 0 deletions
+118
View File
@@ -0,0 +1,118 @@
document.addEventListener('DOMContentLoaded', function () {
var panel = document.getElementById('sf-panel');
if (!panel) return;
var input = document.getElementById('sf-input');
var btn = document.getElementById('sf-btn');
var box = document.getElementById('sf-results');
var toUuid = panel.dataset.uuid;
function fileIcon(mime) {
if (mime.startsWith('video/')) return '🎬';
if (mime.startsWith('audio/')) return '🎵';
if (mime === 'application/pdf') return '📑';
return '📄';
}
async function doSearch() {
var q = input.value.trim();
if (!q) return;
btn.disabled = true;
box.innerHTML = '<p class="text-muted small">Recherche…</p>';
try {
var res = await fetch('/?action=search_files&q=' + encodeURIComponent(q) + '&exclude=' + encodeURIComponent(toUuid));
var data = await res.json();
box.innerHTML = '';
if (!data.length) {
box.innerHTML = '<p class="text-muted small">Aucun fichier trouvé.</p>';
return;
}
data.forEach(function (group) {
var section = document.createElement('div');
section.className = 'mb-4';
var header = document.createElement('p');
header.className = 'fw-semibold small mb-2';
header.textContent = group.article.title;
section.appendChild(header);
var grid = document.createElement('div');
grid.className = 'd-flex flex-wrap gap-2';
group.files.forEach(function (f) {
var wrap = document.createElement('div');
wrap.style.cssText = 'position:relative;cursor:pointer';
wrap.title = f.name + ' (' + (f.size / 1024).toFixed(1) + ' Ko)';
if (f.is_image) {
var img = document.createElement('img');
img.src = f.url;
img.alt = f.name;
img.style.cssText = 'width:72px;height:72px;object-fit:cover;border-radius:6px;border:2px solid transparent;transition:border-color .15s,opacity .15s;display:block';
wrap.appendChild(img);
} else {
var icon = document.createElement('div');
icon.style.cssText = 'width:72px;height:72px;border-radius:6px;border:2px solid #dee2e6;display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:1.6rem;background:#f8f9fa;transition:border-color .15s';
icon.innerHTML = fileIcon(f.mime) + '<span style="font-size:.6rem;margin-top:2px;color:#6c757d;max-width:68px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + f.name.split('.').pop().toUpperCase() + '</span>';
wrap.appendChild(icon);
}
var overlay = document.createElement('div');
overlay.style.cssText = 'position:absolute;inset:0;border-radius:6px;display:none;align-items:center;justify-content:center;background:rgba(25,135,84,.8);color:#fff;font-size:1.4rem';
overlay.textContent = '✓';
wrap.appendChild(overlay);
wrap.addEventListener('mouseenter', function () {
if (!wrap._copied) wrap.firstChild.style.borderColor = '#0d6efd';
});
wrap.addEventListener('mouseleave', function () {
if (!wrap._copied) wrap.firstChild.style.borderColor = 'transparent';
});
wrap.addEventListener('click', async function () {
if (wrap._copying || wrap._copied) return;
wrap._copying = true;
wrap.firstChild.style.opacity = '.5';
try {
var fd = new FormData();
fd.append('from_uuid', group.article.uuid);
fd.append('name', f.name);
fd.append('to_uuid', toUuid);
var r = await fetch('/?action=copy_file&uuid=' + encodeURIComponent(toUuid), {method: 'POST', body: fd});
var d = await r.json();
if (d.ok) {
wrap._copied = true;
wrap.firstChild.style.opacity = '1';
wrap.firstChild.style.borderColor = '#198754';
overlay.style.display = 'flex';
} else {
wrap.firstChild.style.opacity = '1';
wrap.firstChild.style.borderColor = '#dc3545';
wrap.title = d.error || 'Erreur';
}
} catch (e) {
wrap.firstChild.style.opacity = '1';
} finally {
wrap._copying = false;
}
});
grid.appendChild(wrap);
});
section.appendChild(grid);
box.appendChild(section);
});
} catch (e) {
box.innerHTML = '<p class="text-danger small">Erreur de recherche.</p>';
} finally {
btn.disabled = false;
}
}
btn.addEventListener('click', doSearch);
input.addEventListener('keydown', function (e) {
if (e.key === 'Enter') { e.preventDefault(); doSearch(); }
});
doSearch();
});
+48
View File
@@ -0,0 +1,48 @@
document.addEventListener('DOMContentLoaded', function () {
// Confirmation data-confirm sur les formulaires (evite confirm() inline bloqué par CSP)
document.querySelectorAll('form[data-confirm]').forEach(function (form) {
form.addEventListener('submit', function (e) {
var msg = form.getAttribute('data-confirm') || 'Confirmer ?';
if (!window.confirm(msg)) {
e.preventDefault();
}
});
});
// Sélection globale articles
var checkAll = document.getElementById('check-all');
if (checkAll) {
checkAll.addEventListener('change', function () {
document.querySelectorAll('.bulk-check').forEach(function (cb) {
cb.checked = checkAll.checked;
});
});
}
// Indicateurs de traitement formulaire SMTP (config + tester connexion)
var smtpForm = document.getElementById('smtp-config-form');
if (smtpForm) {
smtpForm.addEventListener('submit', function (e) {
var clicked = e.submitter;
if (!clicked) return;
smtpForm.querySelectorAll('button[type="submit"]').forEach(function (btn) {
btn.disabled = true;
});
var isSave = clicked.id === 'smtp-save-btn';
clicked.innerHTML = '<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>'
+ (isSave ? 'Enregistrement…' : 'En cours…');
});
}
// Indicateur de traitement envoi email de test
var smtpTestForm = document.getElementById('smtp-test-form');
if (smtpTestForm) {
smtpTestForm.addEventListener('submit', function () {
var btn = document.getElementById('smtp-send-btn');
if (btn) {
btn.disabled = true;
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>En cours…';
}
});
}
});
+462
View File
@@ -0,0 +1,462 @@
// varlog — app.js
document.addEventListener('DOMContentLoaded', function () {
// ─── Auto-resize textareas ───────────────────────────────────────────────
document.querySelectorAll('textarea.form-control').forEach(function (ta) {
function resize() {
ta.style.height = 'auto';
ta.style.height = ta.scrollHeight + 'px';
}
ta.addEventListener('input', resize);
resize();
});
// ─── Ctrl+Enter : soumettre le formulaire ────────────────────────────────
var form = document.querySelector('form[method="POST"]');
if (form) {
form.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
form.submit();
}
});
}
// ─── Slug auto-génération ────────────────────────────────────────────────
const titleInput = document.getElementById('title');
const slugField = document.getElementById('slug');
const slugPreview = document.getElementById('slug-preview');
if (titleInput && slugField) {
if (slugField.value !== '') slugField._auto = false;
titleInput.addEventListener('input', function () {
if (slugField._auto !== false) {
const generated = slugify(this.value);
slugField.value = generated;
if (slugPreview) slugPreview.textContent = generated;
}
});
slugField.addEventListener('input', function () {
this._auto = (this.value === '');
if (slugPreview) slugPreview.textContent = this.value;
});
}
function slugify(s) {
const map = {'à':'a','â':'a','ä':'a','é':'e','è':'e','ê':'e','ë':'e','î':'i','ï':'i','ô':'o','ö':'o','ù':'u','û':'u','ü':'u','ç':'c','æ':'ae','œ':'oe'};
return s.toLowerCase().replace(/[àâäéèêëîïôöùûüçæœ]/g, c => map[c] || c)
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
}
// ─── Rôle : nom technique auto depuis le label ───────────────────────────
var roleLabelInput = document.getElementById('role-label');
var roleNameInput = document.getElementById('role-name');
if (roleLabelInput && roleNameInput) {
roleLabelInput.addEventListener('input', function () {
if (roleNameInput._manual) return;
roleNameInput.value = slugify(this.value);
});
roleNameInput.addEventListener('input', function () {
this._manual = (this.value !== '');
});
roleNameInput.addEventListener('blur', function () {
if (this.value === '') {
this._manual = false;
this.value = slugify(roleLabelInput.value);
}
});
}
// ─── Aperçu couleur catégorie ────────────────────────────────────────────
const KNOWN_CATS = {
'actualité': 10, 'travaux': 35, 'scolaire': 55,
'linux': 120, 'domotique': 160, 'télécom': 190,
'blog': 220, 'informatique': 255, 'réflexion': 285,
'loisirs': 320, 'perso': 345,
};
const FREE_HUES = [87, 140, 205, 237, 302];
function gradient(hue) {
return `linear-gradient(135deg,hsl(${hue},70%,88%) 0%,hsl(${hue},60%,28%) 100%)`;
}
function hashHue(str) {
let h = 5381;
for (let i = 0; i < str.length; i++) h = (((h << 5) + h) + str.charCodeAt(i)) | 0;
return ((Math.abs(h) * 0.6180339887) * 360 | 0) % 360;
}
function nearestKnown(hue) {
let best = null, bestDist = Infinity;
for (const [name, h] of Object.entries(KNOWN_CATS)) {
const d = Math.min(Math.abs(hue - h), 360 - Math.abs(hue - h));
if (d < bestDist) { bestDist = d; best = name; }
}
return { name: best, dist: bestDist };
}
function updateCatPreview(val) {
const key = val.trim().toLowerCase();
const swatch = document.getElementById('cat-swatch');
const hint = document.getElementById('cat-hint');
const freeEl = document.getElementById('cat-free-swatches');
if (!swatch) return;
freeEl.innerHTML = '';
if (!key) {
swatch.style.background = '#e5e7eb';
swatch.title = '';
hint.textContent = '';
return;
}
if (KNOWN_CATS[key] !== undefined) {
const hue = KNOWN_CATS[key];
swatch.style.background = gradient(hue);
swatch.title = `${hue}°`;
hint.textContent = `Catégorie existante · teinte fixe (${hue}°)`;
hint.className = 'text-muted d-block mt-1';
return;
}
const hue = hashHue(key);
const { name, dist } = nearestKnown(hue);
swatch.style.background = gradient(hue);
swatch.title = `${hue}°`;
if (dist < 20) {
hint.innerHTML = `⚠ Teinte proche de <strong>${name}</strong> (${dist}° d'écart) · couleurs disponibles :`;
hint.className = 'text-warning d-block mt-1';
FREE_HUES.forEach(h => {
const el = document.createElement('span');
el.title = `${h}°`;
el.style.cssText = `display:inline-block;width:28px;height:20px;border-radius:4px;cursor:help;background:${gradient(h)}`;
freeEl.appendChild(el);
});
} else {
hint.textContent = `Nouvelle catégorie · teinte libre (${hue}°)`;
hint.className = 'text-muted d-block mt-1';
}
}
const catInput = document.getElementById('category');
if (catInput) {
catInput.addEventListener('input', function () { updateCatPreview(this.value); });
updateCatPreview(catInput.value);
}
// ─── Copier la référence Markdown ────────────────────────────────────────
document.querySelectorAll('[data-copy-md-name]').forEach(function (btn) {
btn.addEventListener('click', function () {
const name = this.dataset.copyMdName;
const isImage = this.dataset.copyMdIsImage === '1';
const ref = isImage ? `![](${name})` : `[${name}](${name})`;
navigator.clipboard.writeText(ref).then(() => {
const orig = this.textContent;
this.textContent = 'Copié !';
setTimeout(() => { this.textContent = orig; }, 1500);
});
});
});
// ─── Boîtes de confirmation (suppression) ───────────────────────────────
document.querySelectorAll('button[data-confirm], a[data-confirm]').forEach(function (el) {
el.addEventListener('click', function (e) {
if (!confirm(this.dataset.confirm)) e.preventDefault();
});
});
document.querySelectorAll('form[data-confirm]').forEach(function (form) {
form.addEventListener('submit', function (e) {
if (!confirm(this.dataset.confirm)) e.preventDefault();
});
});
// ─── Insérer une référence Markdown au curseur ───────────────────────────
const ta = document.getElementById('content');
if (ta) {
ta._savedStart = null;
ta._savedEnd = null;
function saveCursor() {
if (document.activeElement === ta) {
ta._savedStart = ta.selectionStart;
ta._savedEnd = ta.selectionEnd;
}
}
document.addEventListener('mousedown', saveCursor);
ta.addEventListener('keyup', saveCursor);
ta.addEventListener('mouseup', saveCursor);
document.querySelectorAll('[data-insert-ref]').forEach(function (el) {
el.addEventListener('click', function () {
insertRef(this.dataset.insertRef);
});
if (el.tagName === 'IMG') {
el.addEventListener('mouseenter', function () { this.style.borderColor = '#0d6efd'; });
el.addEventListener('mouseleave', function () { this.style.borderColor = 'transparent'; });
}
});
}
function insertRef(url) {
if (!ta) return;
const isImage = /\.(jpe?g|png|gif|webp|svg|avif)(\?.*)?$/i.test(url);
const label = url.startsWith('http')
? (decodeURIComponent(url.split('/').pop().split('?')[0]) || url)
: url;
const ref = isImage ? `![](${url})` : `[${label}](${url})`;
const len = ta.value.length;
const start = ta._savedStart !== null ? ta._savedStart : len;
const end = ta._savedEnd !== null ? ta._savedEnd : len;
ta.focus();
ta.setRangeText(ref, start, end, 'end');
ta._savedStart = ta._savedEnd = start + ref.length;
ta.dispatchEvent(new Event('input'));
}
// ─── Compteurs SEO ───────────────────────────────────────────────────────
function initCounter(inputId, counterId, max) {
const input = document.getElementById(inputId);
const counter = document.getElementById(counterId);
if (!input || !counter) return;
function update() {
const len = input.value.length;
counter.textContent = `${len} / ${max}`;
counter.className = len > max ? 'text-danger' : 'text-muted';
}
input.addEventListener('input', update);
update();
}
initCounter('seo_title', 'seo_title_counter', 60);
initCounter('seo_description', 'seo_desc_counter', 155);
// ─── Page catégories ─────────────────────────────────────────────────────
function catComputeGradient(val) {
const key = val.trim().toLowerCase();
if (!key) return null;
if (KNOWN_CATS[key] !== undefined) return { hue: KNOWN_CATS[key], known: true };
const hue = hashHue(key);
const { name, dist } = nearestKnown(hue);
return { hue, known: false, conflict: dist < 20 ? name : null };
}
document.querySelectorAll('form[action="/?action=rename_category"] input[name="new"]').forEach(function (input) {
input.addEventListener('input', function () {
const swatch = input.closest('form').querySelector('.rename-swatch');
const result = catComputeGradient(input.value);
if (swatch) swatch.style.background = result ? gradient(result.hue) : '#e5e7eb';
});
});
const newCatInput = document.getElementById('new-cat-input');
if (newCatInput) {
newCatInput.addEventListener('input', function () {
const swatch = document.getElementById('new-cat-swatch');
const hint = document.getElementById('new-cat-hint');
const result = catComputeGradient(this.value);
if (!result) {
swatch.style.background = '#e5e7eb';
hint.textContent = '';
return;
}
swatch.style.background = gradient(result.hue);
if (result.known) {
hint.textContent = `Catégorie existante · teinte fixe (${result.hue}°)`;
hint.className = 'text-muted d-block mb-3';
} else if (result.conflict) {
hint.textContent = `⚠ Teinte proche de « ${result.conflict} » — choisissez un autre nom ou une couleur disponible ci-dessous`;
hint.className = 'text-warning d-block mb-3';
} else {
hint.textContent = `Couleur libre · teinte ${result.hue}°`;
hint.className = 'text-success d-block mb-3';
}
});
}
// ─── Import image : récupérer les métadonnées ────────────────────────────
const fetchMetaBtn = document.getElementById('fetch-meta-btn');
if (fetchMetaBtn) {
fetchMetaBtn.addEventListener('click', async function () {
const urlInput = document.getElementById('import-url');
const resultDiv = document.getElementById('meta-result');
const url = urlInput ? urlInput.value.trim() : '';
if (!url) {
resultDiv.innerHTML = '<small class="text-danger">Saisissez une URL d\'abord.</small>';
return;
}
fetchMetaBtn.disabled = true;
fetchMetaBtn.textContent = 'Chargement…';
resultDiv.innerHTML = '';
try {
const res = await fetch(`/?action=fetch_file_meta&url=${encodeURIComponent(url)}`);
const data = await res.json();
if (!data.ok) {
resultDiv.innerHTML = `<small class="text-danger">${data.error || 'Erreur lors de la récupération.'}</small>`;
return;
}
// Auto-remplissage dynamique des champs (si vides)
const AUTOFILL = {
img_author: { keys: ['author', 'credit'], label: 'Auteur / crédit' },
img_source: { keys: ['canonical', 'source'], label: 'URL source' },
};
const autofillKeys = new Set();
const autofillNotice = [];
for (const [fieldName, cfg] of Object.entries(AUTOFILL)) {
const f = document.querySelector(`input[name="${fieldName}"]`);
if (!f || f.value) continue;
for (const key of cfg.keys) {
if (data[key]) {
f.value = data[key];
autofillKeys.add(key);
autofillNotice.push(`<strong>${cfg.label}</strong> : ${data[key]}`);
break;
}
}
}
// Affichage dynamique de tous les champs retournés
const isPdf = (data.mime === 'application/pdf');
const isHtml = (data.mime || '').startsWith('text/html');
const META_ORDER = ['mime','size','pages','page_size','pdf_version',
'width','site_name','og_type','language',
'title','description','author','subject','keywords',
'credit','source','creator','producer','date','camera','copyright',
'canonical','og_image'];
const META_LABELS = {
mime: 'Type', size: 'Taille', width: 'Dimensions',
pages: 'Pages', page_size: 'Format', pdf_version: 'Version PDF',
site_name: 'Site', og_type: 'Type OG', language: 'Langue',
title: isPdf || isHtml ? 'Titre' : 'Titre EXIF/IPTC',
author: isPdf || isHtml ? 'Auteur' : 'Auteur EXIF/IPTC',
date: isPdf ? 'Créé le' : isHtml ? 'Publié le' : 'Prise de vue',
description: 'Description', subject: 'Sujet', keywords: 'Mots-clés',
credit: 'Crédit', source: 'Source IPTC',
creator: 'Créé avec', producer: 'Produit par',
camera: 'Appareil', copyright: 'Copyright',
canonical: 'URL canonique', og_image: 'Image OG',
};
function fmtVal(key, val) {
if (key === 'size') return (val/1024).toFixed(0) + ' Ko' + (val >= 1048576 ? ` (${(val/1048576).toFixed(1)} Mo)` : '');
if (key === 'width') return `${data.width} × ${data.height} px`;
if (key === 'og_image') return `<img src="${val}" style="max-width:120px;max-height:80px;border-radius:4px" alt="">`;
if (key === 'canonical') return `<a href="${val}" target="_blank" rel="noopener">${val}</a>`;
return String(val);
}
const SKIP = new Set(['ok', 'height']);
const seen = new Set();
const rows = [];
for (const key of META_ORDER) {
const val = data[key];
if (val == null || val === '' || key === 'height') continue;
seen.add(key);
const badge = autofillKeys.has(key)
? ' <span class="badge text-bg-primary ms-1" title="Pré-rempli dans le formulaire">↓ pré-rempli</span>'
: '';
rows.push([META_LABELS[key] ?? key, fmtVal(key, val) + badge]);
}
for (const [key, val] of Object.entries(data)) {
if (seen.has(key) || SKIP.has(key) || val == null || val === '') continue;
rows.push([key, fmtVal(key, val)]);
}
let html = '';
if (rows.length > 0) {
const trs = rows.map(([k, v]) =>
`<tr><th class="text-muted fw-normal pe-3 text-nowrap">${k}</th><td>${v}</td></tr>`
).join('');
html = `<table class="table table-sm table-borderless mb-0 small"><tbody>${trs}</tbody></table>`;
} else {
html = '<small class="text-muted">Aucune métadonnée disponible pour ce fichier.</small>';
}
if (autofillNotice.length > 0) {
html += `<div class="small text-primary mt-1">✓ Pré-rempli — ${autofillNotice.join(' · ')}</div>`;
}
resultDiv.innerHTML = html;
} catch {
resultDiv.innerHTML = '<small class="text-danger">Erreur de connexion.</small>';
} finally {
fetchMetaBtn.disabled = false;
fetchMetaBtn.textContent = 'Métadonnées';
}
});
}
// ─── Import image : toggle mode download ────────────────────────────────
document.querySelectorAll('input[name="mode"]').forEach(function (r) {
r.addEventListener('change', function () {
const dl = this.value === 'download';
const ss = this.value === 'screenshot';
const warn = document.getElementById('copyright-warning');
const fields = document.getElementById('download-fields');
if (warn) warn.style.display = dl ? 'block' : 'none';
if (fields) fields.style.display = (dl || ss) ? 'block' : 'none';
});
});
// ─── Données page (mode édition uniquement) ──────────────────────────────
const pageEl = document.getElementById('vl-page');
if (!pageEl) return;
const uuid = pageEl.dataset.uuid;
const insertUrl = pageEl.dataset.insertUrl;
// Auto-insertion après import d'image
if (insertUrl && ta) {
const isImage = /\.(jpe?g|png|gif|webp|svg|avif)(\?.*)?$/i.test(insertUrl);
const name = decodeURIComponent(insertUrl.split('/').pop().split('?')[0]) || 'fichier';
const ref = isImage ? `![](${insertUrl})` : `[${name}](${insertUrl})`;
const sep = ta.value.length > 0 && !ta.value.endsWith('\n') ? '\n' : '';
ta.value += sep + ref;
ta.focus();
ta.selectionStart = ta.selectionEnd = ta.value.length;
ta.dispatchEvent(new Event('input'));
}
// ─── Autosave ────────────────────────────────────────────────────────────
const indicator = document.getElementById('autosave-indicator');
if (!indicator || !uuid) return;
let timer = null;
function scheduleAutosave() {
clearTimeout(timer);
timer = setTimeout(doAutosave, 3000);
}
async function doAutosave() {
const title = document.getElementById('title').value;
const slug = document.getElementById('slug').value;
const content = document.getElementById('content').value;
indicator.textContent = 'Sauvegarde…';
try {
const res = await fetch(`/?action=autosave&uuid=${encodeURIComponent(uuid)}`, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({title, slug, content}),
});
const data = await res.json();
indicator.textContent = data.ok ? `Brouillon sauvegardé à ${data.time}` : 'Erreur de sauvegarde';
} catch {
indicator.textContent = 'Erreur de sauvegarde';
}
}
['title', 'slug', 'content'].forEach(id => {
document.getElementById(id)?.addEventListener('input', scheduleAutosave);
});
});
+14
View File
@@ -0,0 +1,14 @@
(function(){
var bio = document.getElementById('author-bio');
var btn = document.getElementById('bio-toggle');
if (!bio || !btn) return;
requestAnimationFrame(function() {
if (bio.scrollHeight > bio.clientHeight + 2) { btn.hidden = false; }
});
btn.addEventListener('click', function() {
var exp = btn.getAttribute('aria-expanded') === 'true';
bio.classList.toggle('bio-clamped', exp);
btn.textContent = exp ? 'plus' : 'moins';
btn.setAttribute('aria-expanded', exp ? 'false' : 'true');
});
})();
File diff suppressed because one or more lines are too long
+29
View File
@@ -0,0 +1,29 @@
(function() {
const list = document.getElementById('links-sortable');
if (!list) return;
let dragged = null;
list.querySelectorAll('li').forEach(li => {
li.setAttribute('draggable', true);
li.addEventListener('dragstart', () => { dragged = li; li.style.opacity = '.4'; });
li.addEventListener('dragend', () => { dragged = null; li.style.opacity = ''; saveOrder(); });
li.addEventListener('dragover', e => { e.preventDefault(); const after = getDragAfter(list, e.clientY); after ? list.insertBefore(dragged, after) : list.appendChild(dragged); });
});
function getDragAfter(container, y) {
return [...container.querySelectorAll('li:not([style*="opacity"])')].reduce((closest, el) => {
const box = el.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
return offset < 0 && offset > closest.offset ? { offset, element: el } : closest;
}, { offset: Number.NEGATIVE_INFINITY }).element;
}
function saveOrder() {
const form = document.getElementById('reorder-form');
if (!form) return;
form.querySelectorAll('input').forEach(i => i.remove());
list.querySelectorAll('li[data-id]').forEach(li => {
const inp = document.createElement('input');
inp.type = 'hidden'; inp.name = 'order[]'; inp.value = li.dataset.id;
form.appendChild(inp);
});
form.submit();
}
})();
+62
View File
@@ -0,0 +1,62 @@
document.addEventListener('DOMContentLoaded', function () {
var data = document.getElementById('pc-data');
if (!data) return;
var defaultTitle = data.dataset.defaultTitle;
var defaultDesc = data.dataset.defaultDesc;
var baseUrl = data.dataset.baseUrl;
function initCounter(inputId, counterId, max) {
var el = document.getElementById(inputId);
var ct = document.getElementById(counterId);
if (!el || !ct) return;
function upd() {
var n = el.value.length;
ct.textContent = n + ' / ' + max;
ct.className = n > max ? 'text-danger' : 'text-muted';
}
el.addEventListener('input', upd);
upd();
}
initCounter('seo_title', 'seo_title_counter', 60);
initCounter('seo_description', 'seo_desc_counter', 155);
function updatePreview() {
var seoTitle = document.getElementById('seo_title').value.trim();
var seoDesc = document.getElementById('seo_description').value.trim();
var slug = document.getElementById('confirm-slug').value.trim();
document.getElementById('preview-title').textContent = seoTitle || defaultTitle;
document.getElementById('preview-desc').textContent = seoDesc || defaultDesc;
document.getElementById('preview-url').textContent = baseUrl + slug;
}
['seo_title', 'seo_description', 'confirm-slug'].forEach(function (id) {
var el = document.getElementById(id);
if (el) el.addEventListener('input', updatePreview);
});
var slugInput = document.getElementById('confirm-slug');
var slugDisplay = document.getElementById('slug-display');
var btnSuggest = document.getElementById('slug-btn-suggest');
if (btnSuggest) {
btnSuggest.addEventListener('click', function () {
var val = btnSuggest.dataset.slugSuggest;
slugInput.value = val;
slugDisplay.textContent = val;
updatePreview();
});
}
var btnKeep = document.getElementById('slug-btn-keep');
if (btnKeep) {
btnKeep.addEventListener('click', function () {
var val = btnKeep.dataset.slugKeep;
slugInput.value = val;
slugDisplay.textContent = val;
updatePreview();
});
}
updatePreview();
});
+45
View File
@@ -0,0 +1,45 @@
// reactions.js — toggle réactions via fetch, fallback formulaire natif
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.reaction-form').forEach(function (form) {
form.addEventListener('submit', function (e) {
e.preventDefault();
var btn = form.querySelector('.reaction-btn');
var type = form.querySelector('[name="type"]').value;
var uuid = form.querySelector('[name="uuid"]').value;
var badge = form.querySelector('.reaction-count');
var active = btn.classList.contains('btn-primary');
var data = new URLSearchParams();
data.append('uuid', uuid);
data.append('type', type);
data.append('_ajax', '1');
fetch('/react', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: data.toString(),
})
.then(function (r) { return r.json(); })
.then(function (json) {
if (!json.ok) { form.submit(); return; }
var nowActive = json.active;
if (btn.classList.contains('hero-reaction-btn')) {
btn.classList.toggle('hero-reaction-btn--active', nowActive);
} else {
btn.classList.toggle('btn-primary', nowActive);
btn.classList.toggle('btn-outline-secondary', !nowActive);
if (badge) {
badge.classList.toggle('bg-light', nowActive);
badge.classList.toggle('text-primary', nowActive);
badge.classList.toggle('bg-secondary', !nowActive);
}
}
if (badge) { badge.textContent = json.count; }
})
.catch(function () { form.submit(); });
});
});
});
+37
View File
@@ -0,0 +1,37 @@
(function () {
var headings = document.querySelectorAll('.post-content h2, .post-content h3');
var links = document.querySelectorAll('.toc-list a');
if (headings.length && links.length) {
var map = {};
links.forEach(function (a) {
map[decodeURIComponent(a.getAttribute('href').slice(1))] = a;
});
var active = null;
var observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
if (active) active.classList.remove('toc-active');
active = map[entry.target.id] || null;
if (active) active.classList.add('toc-active');
}
});
}, { rootMargin: '-8% 0px -82% 0px', threshold: 0 });
headings.forEach(function (h) { observer.observe(h); });
}
var btnTop = document.getElementById('toc-go-top');
var btnBot = document.getElementById('toc-go-bottom');
if (btnTop) {
btnTop.addEventListener('click', function () {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
}
if (btnBot) {
btnBot.addEventListener('click', function () {
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
});
}
})();