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
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2011-2024 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<rect width="32" height="32" rx="7" fill="#4f46e5"/>
<text x="16" y="23" text-anchor="middle" font-family="system-ui,sans-serif" font-weight="700" font-size="20" fill="white">v</text>
</svg>

After

Width:  |  Height:  |  Size: 256 B

+92
View File
@@ -0,0 +1,92 @@
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+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' });
});
}
})();