Paquet YunoHost de la page d'accueil personnalisée
Code du site (src/) et paquet YunoHost dans un même dépôt : - éditeur déplacé dans src/edit/, protégé par la permission personalhomepage.editor (SSOwat) au lieu de .editors.json ; - config.json et brouillon dans data_dir, conservés aux mises à jour ; - nom affiché lu depuis /yunohost/portalapi/me (config.json en secours) ; - manifest v2, nginx, scripts install/upgrade/remove/backup/restore/change_url ; - make release : tag + mise à jour du catalogue perso. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
b8861378a5
26 files changed
+2765
No files matched your search
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
// Backend de l'editeur : edit/api.php?action=...
|
||||
//
|
||||
// GET whoami -> { user, canEdit }
|
||||
// GET config -> brouillon s'il existe, sinon config.json
|
||||
// (en-tete X-Homepage-Draft: 1|0)
|
||||
// GET original -> config.json
|
||||
// POST draft -> ecrit le brouillon
|
||||
// POST save -> ecrit config.json et supprime le brouillon
|
||||
// POST discard -> supprime le brouillon
|
||||
//
|
||||
// Securite :
|
||||
// - QUI peut editer n'est pas decide ici : tout le dossier /edit/ est
|
||||
// couvert par la permission YunoHost <app>.editor, et SSOwat refuse les
|
||||
// comptes qui ne l'ont pas avant meme que PHP ne soit appele. Se gerer
|
||||
// dans Admin > Groupes et permissions ;
|
||||
// - une requete sans YNH_USER (visiteur anonyme, si la permission a ete
|
||||
// ouverte aux visiteurs par erreur) est quand meme refusee. YNH_USER est
|
||||
// injecte par SSOwat, qui efface d'abord tout en-tete ynh_* du client ;
|
||||
// - chaque POST doit porter l'en-tete X-Homepage-Editor (impossible a
|
||||
// envoyer depuis un autre site sans preflight CORS) et, si le navigateur
|
||||
// envoie Origin, celui-ci doit etre ce domaine.
|
||||
//
|
||||
// Les donnees vivent dans le data_dir de l'app (HOMEPAGE_DATA_DIR, passe par
|
||||
// nginx), pas a cote du code : une mise a jour remplace le code sans y toucher.
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
header('Cache-Control: no-store');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
|
||||
$dataDir = rtrim((string)($_SERVER['HOMEPAGE_DATA_DIR'] ?? ''), '/');
|
||||
if ($dataDir === '' || !is_dir($dataDir)) {
|
||||
http_response_code(500);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo '{"error":"HOMEPAGE_DATA_DIR absent ou invalide (configuration nginx)"}';
|
||||
exit;
|
||||
}
|
||||
|
||||
define('CONFIG_FILE', $dataDir . '/config.json');
|
||||
define('DRAFT_FILE', $dataDir . '/.config.draft.json');
|
||||
const MAX_BODY = 1024 * 1024;
|
||||
|
||||
function reply(int $status, array $payload): void
|
||||
{
|
||||
http_response_code($status);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
exit;
|
||||
}
|
||||
|
||||
function current_user(): string
|
||||
{
|
||||
return trim((string)($_SERVER['HTTP_YNH_USER'] ?? ''));
|
||||
}
|
||||
|
||||
function send_config_file(string $path, bool $isDraft): void
|
||||
{
|
||||
$body = @file_get_contents($path);
|
||||
if ($body === false) {
|
||||
reply(404, ['error' => basename($path) . ' introuvable']);
|
||||
}
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('X-Homepage-Draft: ' . ($isDraft ? '1' : '0'));
|
||||
echo $body;
|
||||
exit;
|
||||
}
|
||||
|
||||
function read_json_body(): array
|
||||
{
|
||||
$raw = file_get_contents('php://input', false, null, 0, MAX_BODY + 1);
|
||||
if ($raw === false || strlen($raw) > MAX_BODY) {
|
||||
reply(413, ['error' => 'Configuration trop volumineuse']);
|
||||
}
|
||||
$data = json_decode($raw, true);
|
||||
if (!is_array($data) || !isset($data['groups']) || !is_array($data['groups'])) {
|
||||
reply(400, ['error' => 'JSON invalide']);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
function write_json_atomic(string $path, array $data): void
|
||||
{
|
||||
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
$tmp = $path . '.tmp';
|
||||
if ($json === false || file_put_contents($tmp, $json . "\n", LOCK_EX) === false || !rename($tmp, $path)) {
|
||||
@unlink($tmp);
|
||||
reply(500, ['error' => 'Écriture impossible : ' . basename($path)]);
|
||||
}
|
||||
// Le fichier recree appartient a l'app (groupe de l'app, pas www-data) :
|
||||
// nginx doit pouvoir lire config.json par le bit "autres". L'acces reste
|
||||
// limite par le dossier data_dir (750, groupe www-data).
|
||||
@chmod($path, 0644);
|
||||
}
|
||||
|
||||
function check_csrf(): void
|
||||
{
|
||||
if (($_SERVER['HTTP_X_HOMEPAGE_EDITOR'] ?? '') !== '1') {
|
||||
reply(403, ['error' => 'En-tête X-Homepage-Editor manquant']);
|
||||
}
|
||||
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
|
||||
if ($origin !== '') {
|
||||
$parts = parse_url($origin);
|
||||
$originHost = ($parts['host'] ?? '') . (isset($parts['port']) ? ':' . $parts['port'] : '');
|
||||
}
|
||||
if ($origin !== '' && strcasecmp($originHost, (string)($_SERVER['HTTP_HOST'] ?? '')) !== 0) {
|
||||
reply(403, ['error' => 'Origine refusée']);
|
||||
}
|
||||
}
|
||||
|
||||
$action = (string)($_GET['action'] ?? '');
|
||||
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
|
||||
$user = current_user();
|
||||
$allowed = $user !== '';
|
||||
|
||||
if ($action === 'whoami') {
|
||||
reply(200, ['user' => $user, 'canEdit' => $allowed]);
|
||||
}
|
||||
|
||||
if (!$allowed) {
|
||||
reply(403, ['error' => 'Non connecté via le SSO YunoHost']);
|
||||
}
|
||||
|
||||
if ($method === 'GET') {
|
||||
switch ($action) {
|
||||
case 'config':
|
||||
$isDraft = is_file(DRAFT_FILE);
|
||||
send_config_file($isDraft ? DRAFT_FILE : CONFIG_FILE, $isDraft);
|
||||
case 'original':
|
||||
send_config_file(CONFIG_FILE, false);
|
||||
}
|
||||
}
|
||||
|
||||
if ($method === 'POST') {
|
||||
check_csrf();
|
||||
switch ($action) {
|
||||
case 'draft':
|
||||
write_json_atomic(DRAFT_FILE, read_json_body());
|
||||
reply(200, ['ok' => true]);
|
||||
case 'save':
|
||||
write_json_atomic(CONFIG_FILE, read_json_body());
|
||||
@unlink(DRAFT_FILE);
|
||||
reply(200, ['ok' => true]);
|
||||
case 'discard':
|
||||
@unlink(DRAFT_FILE);
|
||||
reply(200, ['ok' => true]);
|
||||
}
|
||||
}
|
||||
|
||||
reply(404, ['error' => "Action inconnue : $action"]);
|
||||
@@ -0,0 +1,464 @@
|
||||
:root {
|
||||
--purple: #4c2b8f;
|
||||
--purple-dark: #3a2070;
|
||||
--bg: #ffffff;
|
||||
--panel-bg: #f6f6f6;
|
||||
--tile-bg: #efefef;
|
||||
--tile-hover: #e2e2e2;
|
||||
--text: #1a1a1a;
|
||||
--muted: #6b6b6b;
|
||||
--border: #dcdcdc;
|
||||
--danger: #c0392b;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.editor-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 24px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--bg);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.editor-topbar h1 {
|
||||
font-size: 18px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.editor-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.status {
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
min-width: 90px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.status.saved { color: #2f855a; }
|
||||
.status.error { color: var(--danger); }
|
||||
|
||||
.btn {
|
||||
display: inline-block;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
border: 2px solid transparent;
|
||||
background: none;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--purple);
|
||||
color: #fff;
|
||||
}
|
||||
.btn-primary:hover { background: var(--purple-dark); }
|
||||
|
||||
.btn-outline {
|
||||
background: transparent;
|
||||
color: var(--purple);
|
||||
border-color: var(--purple);
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
#editor-root {
|
||||
max-width: 1500px;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.editor-layout {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.editor-center {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.catalog-column {
|
||||
width: 200px;
|
||||
flex-shrink: 0;
|
||||
position: sticky;
|
||||
top: 88px;
|
||||
max-height: calc(100vh - 112px);
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.catalog-column h2 {
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
margin: 0 0 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.catalog-message {
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.catalog-error {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.catalog-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(88px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.catalog-tile {
|
||||
cursor: grab;
|
||||
background: var(--panel-bg);
|
||||
border: 1px dashed var(--border);
|
||||
}
|
||||
|
||||
.catalog-tile:hover {
|
||||
border-color: var(--purple);
|
||||
}
|
||||
|
||||
.catalog-tile .tile-icon {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.catalog-tile .tile-name {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.catalog-column {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.group-card {
|
||||
background: var(--panel-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
margin-bottom: 20px;
|
||||
padding: 14px 16px 16px;
|
||||
}
|
||||
|
||||
.group-card.drag-over {
|
||||
outline: 2px dashed var(--purple);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
|
||||
.group-card.dragging {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.group-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.drag-handle {
|
||||
cursor: grab;
|
||||
color: var(--muted);
|
||||
font-size: 18px;
|
||||
user-select: none;
|
||||
padding: 2px 4px;
|
||||
}
|
||||
|
||||
.group-name-input {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.group-name-input:hover,
|
||||
.group-name-input:focus {
|
||||
border-color: var(--border);
|
||||
background: #fff;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.group-collapsed-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
border: none;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
color: var(--muted);
|
||||
font-size: 16px;
|
||||
padding: 4px 6px;
|
||||
border-radius: 6px;
|
||||
line-height: 1;
|
||||
}
|
||||
.icon-btn:hover {
|
||||
background: var(--tile-hover);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.tile-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
|
||||
gap: 14px;
|
||||
min-height: 96px;
|
||||
}
|
||||
|
||||
.tile-grid.drag-over {
|
||||
background: rgba(76, 43, 143, 0.06);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.app-tile {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 14px 8px 10px;
|
||||
border-radius: 12px;
|
||||
background: var(--tile-bg);
|
||||
cursor: grab;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.app-tile.dragging {
|
||||
opacity: 0.35;
|
||||
}
|
||||
|
||||
.app-tile .remove-btn {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 2px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
border: none;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.app-tile .remove-btn:hover { background: var(--danger); }
|
||||
|
||||
.tile-icon {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
border-radius: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 700;
|
||||
font-size: 18px;
|
||||
color: #fff;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.tile-icon img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.tile-name {
|
||||
font-size: 12px;
|
||||
line-height: 1.25;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.add-tile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 12px;
|
||||
border: 2px dashed var(--border);
|
||||
min-height: 96px;
|
||||
cursor: pointer;
|
||||
color: var(--muted);
|
||||
font-size: 28px;
|
||||
background: transparent;
|
||||
}
|
||||
.add-tile:hover {
|
||||
border-color: var(--purple);
|
||||
color: var(--purple);
|
||||
}
|
||||
|
||||
.ungrouped-section {
|
||||
margin-top: 32px;
|
||||
padding-top: 16px;
|
||||
border-top: 2px solid var(--border);
|
||||
}
|
||||
|
||||
.ungrouped-section h2 {
|
||||
font-size: 15px;
|
||||
color: var(--muted);
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.pinned-section {
|
||||
margin-bottom: 24px;
|
||||
padding-bottom: 16px;
|
||||
border-bottom: 2px solid var(--border);
|
||||
}
|
||||
|
||||
.pinned-section h2 {
|
||||
font-size: 15px;
|
||||
color: var(--muted);
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.add-group-btn {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 14px;
|
||||
border-radius: 12px;
|
||||
border: 2px dashed var(--border);
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.add-group-btn:hover {
|
||||
border-color: var(--purple);
|
||||
color: var(--purple);
|
||||
}
|
||||
|
||||
.app-form-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.35);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.app-form {
|
||||
background: #fff;
|
||||
border-radius: 14px;
|
||||
padding: 24px;
|
||||
width: 100%;
|
||||
max-width: 380px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.app-form h3 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.app-form label {
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.app-form input {
|
||||
font-family: inherit;
|
||||
font-size: 14px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.app-form-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* --- Apercu en direct (iframe en bas d'ecran) --- */
|
||||
.preview-drawer {
|
||||
display: none;
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
height: 45vh;
|
||||
flex-direction: column;
|
||||
border-top: 2px solid var(--purple);
|
||||
background: var(--bg);
|
||||
z-index: 20;
|
||||
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
body[data-preview="open"] .preview-drawer { display: flex; }
|
||||
body[data-preview="open"] #editor-root { padding-bottom: 46vh; }
|
||||
#preview-toggle[aria-pressed="true"] { background: var(--purple); color: #fff; }
|
||||
|
||||
.preview-bar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 6px 16px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
background: var(--panel-bg);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.preview-bar a { color: var(--purple); text-decoration: none; white-space: nowrap; }
|
||||
|
||||
#preview-frame {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.access-denied {
|
||||
max-width: 560px;
|
||||
margin: 64px auto;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
background: var(--panel-bg);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
[hidden] { display: none !important; }
|
||||
@@ -0,0 +1,709 @@
|
||||
let state = null;
|
||||
let dirty = false;
|
||||
let dragSource = null; // { appId }, { groupId } or { catalogApp } currently being dragged
|
||||
let catalog = []; // apps visibles par l'utilisateur connecte (/yunohost/portalapi/me)
|
||||
let catalogError = null;
|
||||
let env = { user: "", canEdit: false }; // voir api.php?action=whoami
|
||||
|
||||
// Backend : api.php, dans ce meme dossier /edit/ (protege par la permission
|
||||
// YunoHost <app>.editor : SSOwat bloque les autres comptes avant PHP).
|
||||
function api(action) {
|
||||
return `api.php?action=${action}`;
|
||||
}
|
||||
|
||||
function apiPost(action, body, extra = {}) {
|
||||
const headers = { "X-Homepage-Editor": "1" };
|
||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||
return fetch(api(action), { method: "POST", headers, body, credentials: "same-origin", ...extra });
|
||||
}
|
||||
|
||||
const PALETTE = [
|
||||
"#1db9c3", "#ff5a1f", "#2094f3", "#ffc230", "#00a651", "#e6721a",
|
||||
"#b71c1c", "#f39c12", "#0d3b66", "#3b8a8c", "#568d34", "#609926",
|
||||
"#d24939", "#0066cc", "#8e44ad", "#16a085", "#c0392b", "#2c3e50",
|
||||
];
|
||||
|
||||
function uid(prefix) {
|
||||
return `${prefix}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
function initialsOf(name) {
|
||||
const words = name.trim().split(/\s+/);
|
||||
if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
|
||||
return (words[0][0] + words[1][0]).toUpperCase();
|
||||
}
|
||||
|
||||
function colorOf(name) {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) >>> 0;
|
||||
return PALETTE[hash % PALETTE.length];
|
||||
}
|
||||
|
||||
function setStatus(text, kind) {
|
||||
const el = document.getElementById("status");
|
||||
el.textContent = text;
|
||||
el.className = "status" + (kind ? " " + kind : "");
|
||||
}
|
||||
|
||||
// Les modifications sont ecrites dans un brouillon (.config.draft.json) que
|
||||
// l'apercu utilise ; config.json ne change qu'au clic sur Publier.
|
||||
let draftTimer = null;
|
||||
let draftWrite = Promise.resolve();
|
||||
|
||||
function setDirty(value) {
|
||||
dirty = value;
|
||||
document.getElementById("revert-btn").disabled = !value;
|
||||
if (value) setStatus("Brouillon non enregistré");
|
||||
}
|
||||
|
||||
function writeDraft() {
|
||||
draftTimer = null;
|
||||
const body = JSON.stringify(state, null, 2);
|
||||
draftWrite = draftWrite
|
||||
.then(() => apiPost("draft", body))
|
||||
.then((res) => { if (!res.ok) throw new Error(res.statusText); })
|
||||
.catch((err) => {
|
||||
setStatus("Erreur d'écriture du brouillon", "error");
|
||||
console.error(err);
|
||||
});
|
||||
return draftWrite;
|
||||
}
|
||||
|
||||
function cancelPendingDraft() {
|
||||
if (draftTimer) clearTimeout(draftTimer);
|
||||
draftTimer = null;
|
||||
}
|
||||
|
||||
function markDirty() {
|
||||
setDirty(true);
|
||||
cancelPendingDraft();
|
||||
draftTimer = setTimeout(writeDraft, 300);
|
||||
}
|
||||
|
||||
function normalizeUrl(url) {
|
||||
return (url || "").replace(/^https?:\/\//, "").replace(/\/+$/, "").toLowerCase();
|
||||
}
|
||||
|
||||
// Apps du catalogue YunoHost pas encore presentes dans le portail. Calcule
|
||||
// a chaque rendu depuis l'etat courant : une app supprimee avec la croix
|
||||
// y reapparait aussitot, une app ajoutee en disparait.
|
||||
function availableCatalog() {
|
||||
const used = new Set();
|
||||
const all = [...(state.pinned || []), ...state.ungrouped, ...state.groups.flatMap((g) => g.apps)];
|
||||
all.forEach((a) => used.add(normalizeUrl(a.url)));
|
||||
return catalog.filter((a) => !used.has(normalizeUrl(a.url)));
|
||||
}
|
||||
|
||||
function findAppLocation(appId) {
|
||||
const pinnedIdx = (state.pinned || []).findIndex((a) => a.id === appId);
|
||||
if (pinnedIdx !== -1) return { list: state.pinned, index: pinnedIdx };
|
||||
for (const group of state.groups) {
|
||||
const idx = group.apps.findIndex((a) => a.id === appId);
|
||||
if (idx !== -1) return { list: group.apps, index: idx };
|
||||
}
|
||||
const idx = state.ungrouped.findIndex((a) => a.id === appId);
|
||||
if (idx !== -1) return { list: state.ungrouped, index: idx };
|
||||
return null;
|
||||
}
|
||||
|
||||
function computeDropIndexGrid(containerEl, clientX, clientY) {
|
||||
const items = Array.from(containerEl.querySelectorAll(":scope > .app-tile"));
|
||||
if (items.length === 0) return 0;
|
||||
let closestIndex = items.length;
|
||||
let closestDist = Infinity;
|
||||
items.forEach((item, i) => {
|
||||
const rect = item.getBoundingClientRect();
|
||||
const cx = rect.left + rect.width / 2;
|
||||
const cy = rect.top + rect.height / 2;
|
||||
const dist = Math.hypot(clientX - cx, clientY - cy);
|
||||
if (dist < closestDist) {
|
||||
closestDist = dist;
|
||||
closestIndex = clientX < cx ? i : i + 1;
|
||||
}
|
||||
});
|
||||
return closestIndex;
|
||||
}
|
||||
|
||||
function computeDropIndexList(containerEl, selector, clientY) {
|
||||
const items = Array.from(containerEl.querySelectorAll(selector));
|
||||
if (items.length === 0) return 0;
|
||||
let closestIndex = items.length;
|
||||
let closestDist = Infinity;
|
||||
items.forEach((item, i) => {
|
||||
const rect = item.getBoundingClientRect();
|
||||
const cy = rect.top + rect.height / 2;
|
||||
const dist = Math.abs(clientY - cy);
|
||||
if (dist < closestDist) {
|
||||
closestDist = dist;
|
||||
closestIndex = clientY < cy ? i : i + 1;
|
||||
}
|
||||
});
|
||||
return closestIndex;
|
||||
}
|
||||
|
||||
function renderTile(app) {
|
||||
const tile = document.createElement("div");
|
||||
tile.className = "app-tile";
|
||||
tile.draggable = true;
|
||||
tile.dataset.appId = app.id;
|
||||
|
||||
tile.addEventListener("dragstart", (e) => {
|
||||
e.stopPropagation();
|
||||
dragSource = { appId: app.id };
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
e.dataTransfer.setData("text/plain", app.id);
|
||||
tile.classList.add("dragging");
|
||||
});
|
||||
tile.addEventListener("dragend", (e) => {
|
||||
e.stopPropagation();
|
||||
tile.classList.remove("dragging");
|
||||
dragSource = null;
|
||||
});
|
||||
|
||||
const removeBtn = document.createElement("button");
|
||||
removeBtn.className = "remove-btn";
|
||||
removeBtn.textContent = "✕";
|
||||
removeBtn.title = "Supprimer cette application";
|
||||
removeBtn.addEventListener("click", () => {
|
||||
if (!confirm(`Retirer "${app.name}" de la page ?`)) return;
|
||||
const loc = findAppLocation(app.id);
|
||||
if (loc) loc.list.splice(loc.index, 1);
|
||||
markDirty();
|
||||
render();
|
||||
});
|
||||
|
||||
const icon = document.createElement("div");
|
||||
icon.className = "tile-icon";
|
||||
if (app.icon) {
|
||||
const img = document.createElement("img");
|
||||
img.src = app.icon;
|
||||
img.alt = "";
|
||||
icon.appendChild(img);
|
||||
} else {
|
||||
icon.style.background = app.color || "#8e8e8e";
|
||||
icon.textContent = app.initials || initialsOf(app.name);
|
||||
}
|
||||
|
||||
const name = document.createElement("div");
|
||||
name.className = "tile-name";
|
||||
name.textContent = app.name;
|
||||
|
||||
tile.appendChild(removeBtn);
|
||||
tile.appendChild(icon);
|
||||
tile.appendChild(name);
|
||||
return tile;
|
||||
}
|
||||
|
||||
function renderAddTile(onAdd) {
|
||||
const add = document.createElement("button");
|
||||
add.className = "add-tile";
|
||||
add.type = "button";
|
||||
add.textContent = "+";
|
||||
add.title = "Ajouter une application";
|
||||
add.addEventListener("click", onAdd);
|
||||
return add;
|
||||
}
|
||||
|
||||
function attachGridDropzone(gridEl, targetListGetter) {
|
||||
gridEl.addEventListener("dragover", (e) => {
|
||||
if (!dragSource || (!dragSource.appId && !dragSource.catalogApp)) return;
|
||||
e.preventDefault();
|
||||
gridEl.classList.add("drag-over");
|
||||
});
|
||||
gridEl.addEventListener("dragleave", () => {
|
||||
gridEl.classList.remove("drag-over");
|
||||
});
|
||||
gridEl.addEventListener("drop", (e) => {
|
||||
e.preventDefault();
|
||||
gridEl.classList.remove("drag-over");
|
||||
if (!dragSource) return;
|
||||
const targetList = targetListGetter();
|
||||
const dropIndex = computeDropIndexGrid(gridEl, e.clientX, e.clientY);
|
||||
|
||||
if (dragSource.catalogApp) {
|
||||
const app = { ...dragSource.catalogApp };
|
||||
targetList.splice(Math.min(dropIndex, targetList.length), 0, app);
|
||||
markDirty();
|
||||
render();
|
||||
return;
|
||||
}
|
||||
|
||||
if (dragSource.appId) {
|
||||
const loc = findAppLocation(dragSource.appId);
|
||||
if (!loc) return;
|
||||
const [app] = loc.list.splice(loc.index, 1);
|
||||
targetList.splice(Math.min(dropIndex, targetList.length), 0, app);
|
||||
markDirty();
|
||||
render();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function addCatalogAppTo(app, targetList) {
|
||||
targetList.push({ ...app });
|
||||
markDirty();
|
||||
render();
|
||||
}
|
||||
|
||||
function renderCatalogTile(app) {
|
||||
const tile = document.createElement("div");
|
||||
tile.className = "app-tile catalog-tile";
|
||||
tile.draggable = true;
|
||||
tile.title = "Glisser dans le portail, ou cliquer pour ajouter dans \"Sans groupe\"";
|
||||
|
||||
tile.addEventListener("dragstart", (e) => {
|
||||
e.stopPropagation();
|
||||
dragSource = { catalogApp: app };
|
||||
e.dataTransfer.effectAllowed = "copy";
|
||||
e.dataTransfer.setData("text/plain", app.id);
|
||||
tile.classList.add("dragging");
|
||||
});
|
||||
tile.addEventListener("dragend", (e) => {
|
||||
e.stopPropagation();
|
||||
tile.classList.remove("dragging");
|
||||
dragSource = null;
|
||||
});
|
||||
tile.addEventListener("click", () => {
|
||||
state.ungrouped = state.ungrouped || [];
|
||||
addCatalogAppTo(app, state.ungrouped);
|
||||
});
|
||||
|
||||
const icon = document.createElement("div");
|
||||
icon.className = "tile-icon";
|
||||
if (app.icon) {
|
||||
const img = document.createElement("img");
|
||||
img.src = app.icon;
|
||||
img.alt = "";
|
||||
icon.appendChild(img);
|
||||
} else {
|
||||
icon.style.background = app.color || "#8e8e8e";
|
||||
icon.textContent = app.initials || initialsOf(app.name);
|
||||
}
|
||||
|
||||
const name = document.createElement("div");
|
||||
name.className = "tile-name";
|
||||
name.textContent = app.name;
|
||||
|
||||
tile.appendChild(icon);
|
||||
tile.appendChild(name);
|
||||
return tile;
|
||||
}
|
||||
|
||||
function renderCatalogColumn(title, apps) {
|
||||
const column = document.createElement("aside");
|
||||
column.className = "catalog-column";
|
||||
|
||||
const heading = document.createElement("h2");
|
||||
heading.textContent = title;
|
||||
column.appendChild(heading);
|
||||
|
||||
if (catalogError) {
|
||||
const msg = document.createElement("p");
|
||||
msg.className = "catalog-message catalog-error";
|
||||
msg.textContent = catalogError;
|
||||
column.appendChild(msg);
|
||||
return column;
|
||||
}
|
||||
|
||||
if (apps.length === 0) {
|
||||
const msg = document.createElement("p");
|
||||
msg.className = "catalog-message";
|
||||
msg.textContent = "Aucune app à ajouter.";
|
||||
column.appendChild(msg);
|
||||
return column;
|
||||
}
|
||||
|
||||
const list = document.createElement("div");
|
||||
list.className = "catalog-list";
|
||||
apps.forEach((app) => list.appendChild(renderCatalogTile(app)));
|
||||
column.appendChild(list);
|
||||
return column;
|
||||
}
|
||||
|
||||
function openAppForm(onSubmit) {
|
||||
const backdrop = document.createElement("div");
|
||||
backdrop.className = "app-form-backdrop";
|
||||
|
||||
const form = document.createElement("form");
|
||||
form.className = "app-form";
|
||||
form.innerHTML = `
|
||||
<h3>Nouvelle application</h3>
|
||||
<label>Nom
|
||||
<input type="text" name="name" required placeholder="Ex: Navidrome" />
|
||||
</label>
|
||||
<label>URL
|
||||
<input type="url" name="url" required placeholder="https://sous-domaine.tondomaine.exemple/" />
|
||||
</label>
|
||||
<label>Icône (optionnel, sinon détection auto)
|
||||
<input type="url" name="icon" placeholder="https://..." />
|
||||
</label>
|
||||
<div class="app-form-actions">
|
||||
<button type="button" class="btn btn-outline" data-cancel>Annuler</button>
|
||||
<button type="submit" class="btn btn-primary">Ajouter</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
backdrop.appendChild(form);
|
||||
document.body.appendChild(backdrop);
|
||||
form.querySelector('input[name="name"]').focus();
|
||||
|
||||
backdrop.addEventListener("click", (e) => {
|
||||
if (e.target === backdrop) backdrop.remove();
|
||||
});
|
||||
form.querySelector("[data-cancel]").addEventListener("click", () => backdrop.remove());
|
||||
|
||||
form.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
const data = new FormData(form);
|
||||
const name = data.get("name").trim();
|
||||
const url = data.get("url").trim();
|
||||
const icon = data.get("icon").trim();
|
||||
if (!name || !url) return;
|
||||
const app = {
|
||||
id: uid("app"),
|
||||
name,
|
||||
url,
|
||||
color: colorOf(name),
|
||||
initials: initialsOf(name),
|
||||
};
|
||||
if (icon) app.icon = icon;
|
||||
onSubmit(app);
|
||||
backdrop.remove();
|
||||
});
|
||||
}
|
||||
|
||||
function renderGroup(group, index) {
|
||||
const card = document.createElement("section");
|
||||
card.className = "group-card";
|
||||
card.draggable = true;
|
||||
card.dataset.groupId = group.id;
|
||||
|
||||
card.addEventListener("dragstart", (e) => {
|
||||
dragSource = { groupId: group.id };
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
e.dataTransfer.setData("text/plain", group.id);
|
||||
card.classList.add("dragging");
|
||||
});
|
||||
card.addEventListener("dragend", () => {
|
||||
card.classList.remove("dragging");
|
||||
dragSource = null;
|
||||
});
|
||||
|
||||
const header = document.createElement("div");
|
||||
header.className = "group-header";
|
||||
|
||||
const handle = document.createElement("span");
|
||||
handle.className = "drag-handle";
|
||||
handle.textContent = "⠿";
|
||||
handle.title = "Glisser pour réordonner les groupes";
|
||||
|
||||
const nameInput = document.createElement("input");
|
||||
nameInput.className = "group-name-input";
|
||||
nameInput.value = group.name;
|
||||
nameInput.draggable = false;
|
||||
nameInput.addEventListener("input", () => {
|
||||
group.name = nameInput.value;
|
||||
markDirty();
|
||||
});
|
||||
nameInput.addEventListener("mousedown", (e) => e.stopPropagation());
|
||||
|
||||
const collapsedLabel = document.createElement("label");
|
||||
collapsedLabel.className = "group-collapsed-label";
|
||||
const collapsedCheckbox = document.createElement("input");
|
||||
collapsedCheckbox.type = "checkbox";
|
||||
collapsedCheckbox.checked = !!group.collapsed;
|
||||
collapsedCheckbox.addEventListener("change", () => {
|
||||
group.collapsed = collapsedCheckbox.checked;
|
||||
markDirty();
|
||||
});
|
||||
collapsedLabel.appendChild(collapsedCheckbox);
|
||||
collapsedLabel.appendChild(document.createTextNode("replié par défaut"));
|
||||
|
||||
const deleteBtn = document.createElement("button");
|
||||
deleteBtn.className = "icon-btn";
|
||||
deleteBtn.textContent = "✕";
|
||||
deleteBtn.title = "Supprimer le groupe (les apps repassent en \"Sans groupe\")";
|
||||
deleteBtn.addEventListener("click", () => {
|
||||
if (!confirm(`Supprimer le groupe "${group.name}" ? Les apps repasseront en "Sans groupe".`)) return;
|
||||
state.ungrouped.push(...group.apps);
|
||||
state.groups.splice(index, 1);
|
||||
markDirty();
|
||||
render();
|
||||
});
|
||||
|
||||
header.appendChild(handle);
|
||||
header.appendChild(nameInput);
|
||||
header.appendChild(collapsedLabel);
|
||||
header.appendChild(deleteBtn);
|
||||
|
||||
const grid = document.createElement("div");
|
||||
grid.className = "tile-grid";
|
||||
group.apps.forEach((app) => grid.appendChild(renderTile(app)));
|
||||
grid.appendChild(renderAddTile(() => {
|
||||
openAppForm((app) => {
|
||||
group.apps.push(app);
|
||||
markDirty();
|
||||
render();
|
||||
});
|
||||
}));
|
||||
attachGridDropzone(grid, () => group.apps);
|
||||
|
||||
card.appendChild(header);
|
||||
card.appendChild(grid);
|
||||
return card;
|
||||
}
|
||||
|
||||
function attachGroupsDropzone(containerEl) {
|
||||
containerEl.addEventListener("dragover", (e) => {
|
||||
if (!dragSource || !dragSource.groupId) return;
|
||||
e.preventDefault();
|
||||
});
|
||||
containerEl.addEventListener("drop", (e) => {
|
||||
if (!dragSource || !dragSource.groupId) return;
|
||||
e.preventDefault();
|
||||
const groupId = dragSource.groupId;
|
||||
const fromIndex = state.groups.findIndex((g) => g.id === groupId);
|
||||
if (fromIndex === -1) return;
|
||||
const [group] = state.groups.splice(fromIndex, 1);
|
||||
const dropIndex = computeDropIndexList(containerEl, ".group-card", e.clientY);
|
||||
state.groups.splice(Math.min(dropIndex, state.groups.length), 0, group);
|
||||
markDirty();
|
||||
render();
|
||||
});
|
||||
}
|
||||
|
||||
function render() {
|
||||
const root = document.getElementById("editor-root");
|
||||
root.innerHTML = "";
|
||||
|
||||
const layout = document.createElement("div");
|
||||
layout.className = "editor-layout";
|
||||
|
||||
const available = availableCatalog();
|
||||
const half = Math.ceil(available.length / 2);
|
||||
const leftCatalog = renderCatalogColumn("Catalogue YunoHost", available.slice(0, half));
|
||||
const rightCatalog = renderCatalogColumn("Catalogue YunoHost", available.slice(half));
|
||||
|
||||
const center = document.createElement("div");
|
||||
center.className = "editor-center";
|
||||
|
||||
layout.appendChild(leftCatalog);
|
||||
layout.appendChild(center);
|
||||
layout.appendChild(rightCatalog);
|
||||
root.appendChild(layout);
|
||||
|
||||
const pinnedSection = document.createElement("section");
|
||||
pinnedSection.className = "pinned-section";
|
||||
const pinnedHeading = document.createElement("h2");
|
||||
pinnedHeading.textContent = "Épinglées (en haut de la page)";
|
||||
pinnedSection.appendChild(pinnedHeading);
|
||||
|
||||
const pinnedGrid = document.createElement("div");
|
||||
pinnedGrid.className = "tile-grid";
|
||||
(state.pinned || []).forEach((app) => pinnedGrid.appendChild(renderTile(app)));
|
||||
pinnedGrid.appendChild(renderAddTile(() => {
|
||||
openAppForm((app) => {
|
||||
state.pinned = state.pinned || [];
|
||||
state.pinned.push(app);
|
||||
markDirty();
|
||||
render();
|
||||
});
|
||||
}));
|
||||
attachGridDropzone(pinnedGrid, () => (state.pinned = state.pinned || []));
|
||||
pinnedSection.appendChild(pinnedGrid);
|
||||
center.appendChild(pinnedSection);
|
||||
|
||||
const groupsList = document.createElement("div");
|
||||
groupsList.id = "groups-list";
|
||||
state.groups.forEach((group, i) => groupsList.appendChild(renderGroup(group, i)));
|
||||
attachGroupsDropzone(groupsList);
|
||||
center.appendChild(groupsList);
|
||||
|
||||
const addGroupBtn = document.createElement("button");
|
||||
addGroupBtn.className = "add-group-btn";
|
||||
addGroupBtn.type = "button";
|
||||
addGroupBtn.textContent = "+ Nouveau groupe";
|
||||
addGroupBtn.addEventListener("click", () => {
|
||||
state.groups.push({ id: uid("group"), name: "Nouveau groupe", collapsed: false, apps: [] });
|
||||
markDirty();
|
||||
render();
|
||||
});
|
||||
center.appendChild(addGroupBtn);
|
||||
|
||||
const ungroupedSection = document.createElement("section");
|
||||
ungroupedSection.className = "ungrouped-section";
|
||||
const heading = document.createElement("h2");
|
||||
heading.textContent = "Sans groupe";
|
||||
ungroupedSection.appendChild(heading);
|
||||
|
||||
const ungroupedGrid = document.createElement("div");
|
||||
ungroupedGrid.className = "tile-grid";
|
||||
state.ungrouped.forEach((app) => ungroupedGrid.appendChild(renderTile(app)));
|
||||
ungroupedGrid.appendChild(renderAddTile(() => {
|
||||
openAppForm((app) => {
|
||||
state.ungrouped.push(app);
|
||||
markDirty();
|
||||
render();
|
||||
});
|
||||
}));
|
||||
attachGridDropzone(ungroupedGrid, () => state.ungrouped);
|
||||
ungroupedSection.appendChild(ungroupedGrid);
|
||||
|
||||
center.appendChild(ungroupedSection);
|
||||
pushPreview();
|
||||
}
|
||||
|
||||
// On demande au portail YunoHost les apps visibles par l'utilisateur
|
||||
// connecte (PHP n'a pas acces au fichier du portail, lisible par root seul).
|
||||
async function fetchPortalCatalog() {
|
||||
const res = await fetch("/yunohost/portalapi/me", { credentials: "same-origin", cache: "no-store" });
|
||||
if (!res.ok) throw new Error(`portalapi/me : HTTP ${res.status}`);
|
||||
const me = await res.json();
|
||||
const ownPath = new URL("..", window.location.href).pathname.replace(/\/+$/, "");
|
||||
const apps = [];
|
||||
Object.entries(me.apps || {}).forEach(([permKey, info]) => {
|
||||
if (!permKey.endsWith(".main") || !info.url) return;
|
||||
let url = info.url.startsWith("http") ? info.url : `https://${info.url}`;
|
||||
if (!url.endsWith("/")) url += "/";
|
||||
if (ownPath && new URL(url).pathname.replace(/\/+$/, "") === ownPath) return; // cette page elle-meme
|
||||
const name = info.label || permKey.slice(0, -".main".length);
|
||||
const app = { id: permKey.slice(0, -".main".length), name, url, color: colorOf(name), initials: initialsOf(name) };
|
||||
if (info.logo) app.icon = info.logo.startsWith("http") ? info.logo : `${window.location.origin}${info.logo}`;
|
||||
apps.push(app);
|
||||
});
|
||||
apps.sort((a, b) => a.name.localeCompare(b.name, "fr", { sensitivity: "base" }));
|
||||
return { apps };
|
||||
}
|
||||
|
||||
async function loadCatalog() {
|
||||
try {
|
||||
catalog = (await fetchPortalCatalog()).apps;
|
||||
catalogError = null;
|
||||
} catch (err) {
|
||||
catalog = [];
|
||||
catalogError = "Catalogue YunoHost indisponible.";
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
function showAccessDenied(message) {
|
||||
document.querySelector(".editor-actions").hidden = true;
|
||||
const root = document.getElementById("editor-root");
|
||||
root.innerHTML = "";
|
||||
const box = document.createElement("p");
|
||||
box.className = "access-denied";
|
||||
box.textContent = message;
|
||||
root.appendChild(box);
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
env = await (await fetch(api("whoami"), { cache: "no-store" })).json();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
showAccessDenied("Impossible de joindre le backend de l'éditeur (api.php).");
|
||||
return;
|
||||
}
|
||||
if (!env.canEdit) {
|
||||
showAccessDenied(env.user
|
||||
? `« ${env.user} » n'est pas autorisé à modifier la page d'accueil.`
|
||||
: "Connecte-toi au portail YunoHost pour modifier la page d'accueil.");
|
||||
return;
|
||||
}
|
||||
const res = await fetch(api("config"), { cache: "no-store" });
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
state = await res.json();
|
||||
setDirty(res.headers.get("X-Homepage-Draft") === "1");
|
||||
await loadCatalog();
|
||||
render();
|
||||
}
|
||||
|
||||
async function revert() {
|
||||
if (!confirm("Abandonner toutes les modifications non enregistrées et revenir à la dernière version enregistrée ?")) return;
|
||||
cancelPendingDraft();
|
||||
try {
|
||||
await draftWrite;
|
||||
const res = await apiPost("discard");
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
const orig = await fetch(api("original"), { cache: "no-store" });
|
||||
state = await orig.json();
|
||||
setDirty(false);
|
||||
render();
|
||||
setStatus("Original rétabli ✓", "saved");
|
||||
setTimeout(() => setStatus(""), 2000);
|
||||
} catch (err) {
|
||||
setStatus("Erreur lors du rétablissement", "error");
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
cancelPendingDraft();
|
||||
await draftWrite;
|
||||
try {
|
||||
const res = await apiPost("save", JSON.stringify(state, null, 2));
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
setDirty(false);
|
||||
setStatus("Publié ✓", "saved");
|
||||
setTimeout(() => setStatus(""), 2000);
|
||||
} catch (err) {
|
||||
setStatus("Erreur d'enregistrement", "error");
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById("save-btn").addEventListener("click", save);
|
||||
document.getElementById("revert-btn").addEventListener("click", revert);
|
||||
|
||||
// Le brouillon est sur disque : fermer ou recharger l'editeur ne perd rien,
|
||||
// il suffit d'envoyer la derniere modification si elle est encore en attente.
|
||||
window.addEventListener("pagehide", () => {
|
||||
if (!draftTimer) return;
|
||||
cancelPendingDraft();
|
||||
apiPost("draft", JSON.stringify(state), { keepalive: true });
|
||||
});
|
||||
|
||||
// --- Apercu en direct -------------------------------------------------------
|
||||
// index.html charge dans une iframe ; a chaque rendu, l'editeur lui envoie
|
||||
// l'etat courant (postMessage) et app.js le re-affiche sans aller-retour
|
||||
// serveur. L'iframe signale "ready" a chaque chargement pour recevoir l'etat.
|
||||
const PREVIEW_STORAGE_KEY = "homepage-editor-preview-open";
|
||||
|
||||
function previewFrame() {
|
||||
return document.getElementById("preview-frame");
|
||||
}
|
||||
|
||||
function pushPreview() {
|
||||
const frame = previewFrame();
|
||||
if (!state || !frame || !frame.contentWindow || document.body.dataset.preview !== "open") return;
|
||||
frame.contentWindow.postMessage({ type: "homepage-config", config: state }, window.location.origin);
|
||||
}
|
||||
|
||||
function setPreviewOpen(open) {
|
||||
document.body.dataset.preview = open ? "open" : "closed";
|
||||
document.getElementById("preview-toggle").setAttribute("aria-pressed", String(open));
|
||||
const frame = previewFrame();
|
||||
if (open && !frame.src) frame.src = "../index.html?preview=1";
|
||||
else pushPreview();
|
||||
try { localStorage.setItem(PREVIEW_STORAGE_KEY, open ? "1" : "0"); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
window.addEventListener("message", (e) => {
|
||||
if (e.origin !== window.location.origin || e.source !== previewFrame().contentWindow) return;
|
||||
if (e.data && e.data.type === "homepage-preview-ready") pushPreview();
|
||||
});
|
||||
|
||||
document.getElementById("preview-toggle").addEventListener("click", () => {
|
||||
setPreviewOpen(document.body.dataset.preview !== "open");
|
||||
});
|
||||
|
||||
(function initPreview() {
|
||||
let open = true;
|
||||
try { open = localStorage.getItem(PREVIEW_STORAGE_KEY) !== "0"; } catch (e) { /* ignore */ }
|
||||
setPreviewOpen(open);
|
||||
})();
|
||||
|
||||
load().catch((err) => {
|
||||
setStatus("Erreur de chargement de la configuration", "error");
|
||||
console.error(err);
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Éditeur du portail</title>
|
||||
<link rel="stylesheet" href="editor.css" />
|
||||
<script src="../favicon.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="editor-topbar">
|
||||
<h1>Éditeur du portail</h1>
|
||||
<div class="editor-actions">
|
||||
<span id="status" class="status"></span>
|
||||
<a href="../" class="btn btn-outline" title="Revenir à la page d'accueil">← Accueil</a>
|
||||
<button id="preview-toggle" class="btn btn-outline" aria-pressed="true" title="Afficher/masquer l'aperçu en direct">Aperçu</button>
|
||||
<button id="revert-btn" class="btn btn-outline" disabled title="Abandonner le brouillon et revenir à la dernière version enregistrée">Rétablir l'original</button>
|
||||
<button id="save-btn" class="btn btn-primary">Publier</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="editor-root"></main>
|
||||
|
||||
<aside class="preview-drawer" aria-label="Aperçu en direct">
|
||||
<div class="preview-bar">
|
||||
<span>Aperçu en direct — non publié tant que tu n'as pas cliqué sur Publier</span>
|
||||
<a href="../" target="_blank" rel="noopener">Ouvrir la page ↗</a>
|
||||
</div>
|
||||
<iframe id="preview-frame" title="Aperçu de la page d'accueil"></iframe>
|
||||
</aside>
|
||||
|
||||
<script src="editor.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user