Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb6d95d867 | ||
|
|
1fe6a1bad0 | ||
|
|
6143d62f99 | ||
|
|
fdc7626ef0 | ||
|
|
865aff1957 | ||
|
|
3de4363f36 | ||
|
|
eecabeb273 | ||
|
|
f7d71bae41 | ||
|
|
0887458b24 | ||
|
|
68aa0463eb | ||
|
|
8aba7100a4 | ||
|
|
17f4787b35 | ||
|
|
b0f9842aa5 | ||
|
|
a674fe2a7b | ||
|
|
b5e84948d0 | ||
|
|
b11a68f7c6 |
+23
-1
@@ -6,7 +6,7 @@ Format basé sur [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/),
|
||||
et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
> **En cours de développement** : les changements à venir sont listés dans la section
|
||||
> [Unreleased](#unreleased). La dernière version livrée est **2.97.0**.
|
||||
> [Unreleased](#unreleased). La dernière version livrée est **2.99.0**.
|
||||
|
||||
---
|
||||
|
||||
@@ -14,6 +14,28 @@ et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
---
|
||||
|
||||
## [2.99.0] — 2026-12-01
|
||||
|
||||
### Ajouté
|
||||
|
||||
- **Mes vaults, recherches sauvées et personnalisation de l'Accueil (#249)** : cartes des vaults (clic = onglet de navigation du vault, vault personnel en premier), recherches sauvées relançables en un clic, bloc Raccourcis & Astuces compact, et panneaux de l'Accueil masquables/réaffichables avec choix persisté par utilisateur (localStorage — pas de préférences serveur pour le dashboard, repli documenté dans la fiche #246).
|
||||
- **Panneau « À traiter » dans l'Accueil (#248)** : conflits de synchronisation (widget existant, alimenté par `/api/conflicts`), partages reçus non encore ouverts et partages expirant sous 7 jours (via `/api/shares`), chaque élément ouvrable en un clic ; le panneau est entièrement masqué quand il n'y a rien à traiter.
|
||||
- **Page d'accueil « Reprendre » (#247, épopée #246)** : nouvel onglet **Accueil**, premier et actif par défaut dans le dashboard — bandeau statistiques en une ligne, recherche héros (focus sur la recherche globale), actions rapides (Nouveau fichier, Téléverser, Palette de fichiers) et section **Reprendre** (bookmarks/épinglés en tête, puis les 6 derniers fichiers ouverts). Les onglets Statistiques, Bookmarks, Récents et Partagés sont inchangés.
|
||||
|
||||
---
|
||||
|
||||
## [2.98.0] — 2026-11-30
|
||||
|
||||
### Ajouté
|
||||
|
||||
- **Audit de chargement versionné (#241, épopée perf #240)** : `scripts/audit_chargement.py` (stdlib seule) mesure TTFB/total médians, en-têtes de cache et graphe de modules ES statiques (mode distant ou `--local`) ; budget de chargement figé dans `docs/features/perf-chargement-240.md` (affichage utile ÷3, JS initial −50 %, `/api/dashboard` répété < 50 ms).
|
||||
- **Bootstrap rapide des liens profonds (#244)** : à l'arrivée sur un lien `#file=` (y compris au retour d'un SSO), le fichier cible s'ouvre dès l'authentification faite, avant le chargement des réglages des vaults, de la liste des vaults et des tags ; le chargement complet suit sans recouvrir la cible. `#folder=` inchangé (il a besoin de l'arborescence chargée).
|
||||
- **Cache mémoire de `/api/dashboard` (#245)** : résultat mis en cache 60 s par utilisateur et invalidé dès que le watcher signale un changement d'index — les appels répétés ne parcourent plus les 10 987 fichiers à chaque fois.
|
||||
- **Chargement paresseux des modules lourds et des CDN (#243)** : Mermaid, vue graphe, Excalidraw, now-playing, plugins, push et l'éditeur mobile sont chargés par `import()` dynamique à la première utilisation (ou en tâche de fond) au lieu du graphe statique initial (41 → 34 modules, −12,5 % en octets bruts — le cœur couplé viewer/ui reste statique, voir fiche #240) ; les 13 scripts CDN du `<head>` (Mermaid 745 Ko, highlight.js + 10 langages, Lucide) sont retirés : highlight arrive au premier bloc de code (base + langage détecté), Lucide au premier appel d'icônes, Mermaid au premier diagramme.
|
||||
- **Cache versionné des statiques (#242)** : les URL `/static/…` de `index.html` et les imports des modules ES sont réécrits au service avec `?v=<VERSION>` (`backend/static_versioning.py`, serveur `VersionedStaticFiles`) ; `Cache-Control: immutable` (1 an) uniquement pour les URL à la version courante, `no-cache` sinon — le cache long ne peut plus servir un build périmé. Le service worker porte un nom de cache à la version courante (ancien cache abandonné à l'activation). La règle Cloudflare « HIT » sur les statiques versionnées reste une action d'exploitation hors code.
|
||||
|
||||
---
|
||||
|
||||
## [2.97.0] — 2026-11-30
|
||||
|
||||
### Ajouté
|
||||
|
||||
+3
-3
@@ -4,7 +4,7 @@
|
||||
|
||||
**Porte d'entrée web ultra-léger pour vos vaults Obsidian** — Accédez, naviguez et recherchez dans toutes vos notes Obsidian depuis n'importe quel appareil via une interface web moderne et responsive.
|
||||
|
||||
[]()
|
||||
[]()
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://www.docker.com/)
|
||||
[](https://www.python.org/)
|
||||
@@ -981,8 +981,8 @@ Ce projet est sous licence **MIT** — voir le fichier [LICENSE](LICENSE) pour l
|
||||
|
||||
## 📝 Changelog
|
||||
|
||||
Consultez le [CHANGELOG.md](./CHANGELOG.md) pour l'historique complet de toutes les versions (v1.0.0 → v2.97.0).
|
||||
Consultez le [CHANGELOG.md](./CHANGELOG.md) pour l'historique complet de toutes les versions (v1.0.0 → v2.99.0).
|
||||
|
||||
---
|
||||
|
||||
*Projet : ObsiGate | Version : 2.97.0 | Dernière mise à jour : Septembre 2026*
|
||||
*Projet : ObsiGate | Version : 2.99.0 | Dernière mise à jour : Septembre 2026*
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Ultra-light web gateway for your Obsidian vaults** — Access, browse, and search all your Obsidian notes from any device via a modern, responsive web interface.
|
||||
|
||||
[]()
|
||||
[]()
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://www.docker.com/)
|
||||
[](https://www.python.org/)
|
||||
@@ -1156,8 +1156,8 @@ This project is licensed under the **MIT License** - see the [LICENSE](LICENSE)
|
||||
|
||||
## 📝 Changelog
|
||||
|
||||
See [CHANGELOG.md](./CHANGELOG.md) for the complete version history (v1.0.0 → v2.97.0).
|
||||
See [CHANGELOG.md](./CHANGELOG.md) for the complete version history (v1.0.0 → v2.99.0).
|
||||
|
||||
---
|
||||
|
||||
*Project: ObsiGate | Version: 2.97.0 | Last updated: September 2026*
|
||||
*Project: ObsiGate | Version: 2.99.0 | Last updated: September 2026*
|
||||
|
||||
+65
-10
@@ -70,6 +70,11 @@ async def _on_vault_change(events: list):
|
||||
Processes each event (create/modify/delete/move) and updates the index
|
||||
incrementally, then broadcasts SSE notifications.
|
||||
"""
|
||||
# #245 : tout changement d'index invalide le cache du dashboard.
|
||||
from backend.routers.config import invalidate_dashboard_cache
|
||||
|
||||
invalidate_dashboard_cache()
|
||||
|
||||
updated_vaults = set()
|
||||
changes = []
|
||||
|
||||
@@ -245,12 +250,17 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
|
||||
yield patched
|
||||
|
||||
response.body_iterator = _docs_body()
|
||||
# Static assets are NOT content-hashed, so they must revalidate:
|
||||
# ``immutable``/long max-age made Cloudflare and mobile browsers serve
|
||||
# a stale build for a year (the service worker cache compounded it).
|
||||
# ``no-cache`` keeps caching but forces revalidation (ETag/Last-Modified).
|
||||
# Cache des statiques (#242) : ``immutable`` UNIQUEMENT pour les
|
||||
# URL versionnées ``?v=<VERSION courante>`` (voir
|
||||
# backend.static_versioning) — une nouvelle version change toutes
|
||||
# les URL, donc le piège historique (cache long sans versionnage
|
||||
# → build périmé servi un an) ne peut pas se reproduire. Sans
|
||||
# ``?v=`` valide : ``no-cache`` (revalidation ETag/Last-Modified).
|
||||
if request.url.path.startswith("/static/"):
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
from backend.static_versioning import cache_control_for
|
||||
|
||||
response.headers["Cache-Control"] = cache_control_for(
|
||||
request.url.path, request.url.query)
|
||||
return response
|
||||
|
||||
|
||||
@@ -927,6 +937,10 @@ def _index_html(request: Request) -> str:
|
||||
from backend.draco_config import urls_publiques
|
||||
|
||||
html = (FRONTEND_DIR / "index.html").read_text(encoding="utf-8")
|
||||
# #242 : URL statiques versionnées (?v=<VERSION>) — cache long sûr.
|
||||
from backend.static_versioning import rewrite_static_urls
|
||||
|
||||
html = rewrite_static_urls(html)
|
||||
script = (
|
||||
"<script>window.DRACO_URLS = "
|
||||
+ _json.dumps(urls_publiques()).replace("<", "\\u003c")
|
||||
@@ -947,17 +961,58 @@ def _index_html(request: Request) -> str:
|
||||
html = html.replace("</header>", "</header>" + fragment, 1)
|
||||
return inject_csp_nonce(html, request.state.csp_nonce)
|
||||
|
||||
class VersionedStaticFiles(StaticFiles):
|
||||
"""Statiques dont les modules ES sont réécrits au service (#242).
|
||||
|
||||
Les spécificateurs d'import relatifs des fichiers ``.js`` reçoivent
|
||||
``?v=<VERSION>`` : le navigateur ne demande donc que des URL
|
||||
versionnées, de proche en proche dans le graphe de modules.
|
||||
``Cache-Control`` reste posé par ``SecurityHeadersMiddleware``.
|
||||
"""
|
||||
|
||||
async def get_response(self, path, scope): # type: ignore[override]
|
||||
if path.endswith(".js"):
|
||||
from backend.static_versioning import rewrite_js_imports
|
||||
|
||||
full = Path(self.directory) / path
|
||||
try:
|
||||
resolved = full.resolve()
|
||||
root = Path(self.directory).resolve()
|
||||
if resolved.is_file() and resolved.is_relative_to(root):
|
||||
source = resolved.read_text(encoding="utf-8", errors="replace")
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
return PlainTextResponse(
|
||||
rewrite_js_imports(source),
|
||||
media_type="application/javascript",
|
||||
)
|
||||
except OSError:
|
||||
pass # repli : service statique standard (404 propre inclus)
|
||||
return await super().get_response(path, scope)
|
||||
|
||||
|
||||
if FRONTEND_DIR.exists():
|
||||
# ``Cache-Control`` for /static is set by SecurityHeadersMiddleware (no-cache).
|
||||
app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR)), name="static")
|
||||
# ``Cache-Control`` for /static is set by SecurityHeadersMiddleware (#242).
|
||||
app.mount("/static", VersionedStaticFiles(directory=str(FRONTEND_DIR)), name="static")
|
||||
|
||||
@app.get("/sw.js")
|
||||
async def serve_service_worker():
|
||||
"""Serve the service worker for PWA support."""
|
||||
"""Serve the service worker for PWA support.
|
||||
|
||||
#242 : le nom de cache du SW embarque la version courante
|
||||
(``__OBSIGATE_SW_VERSION__`` remplacé ici) — à chaque release,
|
||||
l'ancien cache est abandonné à l'activation.
|
||||
"""
|
||||
sw_file = FRONTEND_DIR / "sw.js"
|
||||
if sw_file.exists():
|
||||
return FileResponse(
|
||||
sw_file,
|
||||
from backend.version import get_version
|
||||
|
||||
content = sw_file.read_text(encoding="utf-8").replace(
|
||||
"__OBSIGATE_SW_VERSION__", f"v{get_version()}")
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
return PlainTextResponse(
|
||||
content,
|
||||
media_type="application/javascript",
|
||||
headers={
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
|
||||
@@ -233,9 +233,45 @@ async def api_diagnostics(current_user=Depends(require_admin)):
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cache mémoire du dashboard (#245, épopée perf #240)
|
||||
#
|
||||
# ``GET /api/dashboard`` parcourait tous les fichiers de tous les vaults
|
||||
# à chaque appel (10 987 fichiers en prod). Le résultat est mis en cache
|
||||
# 60 s par utilisateur (l'accès aux vaults dépend de l'utilisateur) et
|
||||
# invalidé dès que le watcher signale un changement (voir
|
||||
# ``_on_vault_change`` dans ``backend.main``) ou après modification de
|
||||
# l'index par les routes d'écriture via ``invalidate_dashboard_cache``.
|
||||
# ---------------------------------------------------------------------------
|
||||
import time as _time
|
||||
|
||||
_DASHBOARD_TTL_SECONDS = 60.0
|
||||
_dashboard_cache: dict[str, tuple[float, dict]] = {}
|
||||
|
||||
|
||||
def invalidate_dashboard_cache() -> None:
|
||||
"""Vider le cache du dashboard (changement d'index signalé)."""
|
||||
_dashboard_cache.clear()
|
||||
|
||||
|
||||
def _dashboard_cache_key(current_user) -> str:
|
||||
return str(getattr(current_user, "username", None) or getattr(current_user, "id", "") or "anon")
|
||||
|
||||
|
||||
@router.get("/api/dashboard", response_model=DashboardResponse)
|
||||
async def api_dashboard(current_user=Depends(require_auth)):
|
||||
"""Aggregated dashboard statistics across all accessible vaults."""
|
||||
key = _dashboard_cache_key(current_user)
|
||||
cached = _dashboard_cache.get(key)
|
||||
if cached and (_time.monotonic() - cached[0]) < _DASHBOARD_TTL_SECONDS:
|
||||
return cached[1]
|
||||
result = _compute_dashboard(current_user)
|
||||
_dashboard_cache[key] = (_time.monotonic(), result)
|
||||
return result
|
||||
|
||||
|
||||
def _compute_dashboard(current_user) -> dict:
|
||||
"""Calcul effectif des statistiques du dashboard (sans cache)."""
|
||||
vault_stats = []
|
||||
total_files = 0
|
||||
total_tags = set()
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Cache versionné des statiques (#242, épopée perf #240).
|
||||
|
||||
Mécanisme sans étape de build (règle du dépôt) :
|
||||
|
||||
- les URL ``/static/…`` référencées par ``index.html`` sont réécrites
|
||||
au service avec ``?v=<VERSION>`` (:func:`rewrite_static_urls`) ;
|
||||
- les spécificateurs d'import relatifs des modules ES servis sont
|
||||
réécrits de la même façon (:func:`rewrite_js_imports`), donc tout le
|
||||
graphe de modules est demandé en URL versionnées, de proche en
|
||||
proche ;
|
||||
- l'en-tête ``Cache-Control`` n'autorise le cache long
|
||||
(``immutable``) **que** pour une requête dont le ``?v=`` vaut la
|
||||
version courante (:func:`cache_control_for`) — une nouvelle version
|
||||
change toutes les URL, donc un cache long ne peut plus jamais
|
||||
servir un build périmé (l'incident historique du ``max-age`` sans
|
||||
versionnage).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from backend.version import get_version
|
||||
|
||||
IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable"
|
||||
NO_CACHE = "no-cache"
|
||||
|
||||
_STATIC_URL_RE = re.compile(r"((?:src|href)=[\"'])(/static/[^\"'?#]+)([\"'])")
|
||||
_JS_SPEC_RE = re.compile(
|
||||
r"((?:from\s+|import\s*\(\s*|import\s+)['\"])(\.{1,2}/[^'\"]+?\.js)(['\"])"
|
||||
)
|
||||
|
||||
|
||||
def current_version() -> str:
|
||||
"""Version courante (source unique : fichier ``VERSION``)."""
|
||||
return get_version()
|
||||
|
||||
|
||||
def rewrite_static_urls(html: str, version: str | None = None) -> str:
|
||||
"""Ajouter ``?v=<version>`` aux URL ``/static/…`` d'un document HTML."""
|
||||
v = version if version is not None else current_version()
|
||||
return _STATIC_URL_RE.sub(
|
||||
lambda m: f"{m.group(1)}{m.group(2)}?v={v}{m.group(3)}", html)
|
||||
|
||||
|
||||
def rewrite_js_imports(source: str, version: str | None = None) -> str:
|
||||
"""Ajouter ``?v=<version>`` aux imports relatifs ``.js`` d'un module ES.
|
||||
|
||||
Couvre ``import … from '…'``, ``import '…'`` et ``import('…')``.
|
||||
Les spécificateurs déjà pourvus d'une query string sont laissés
|
||||
intacts.
|
||||
"""
|
||||
v = version if version is not None else current_version()
|
||||
return _JS_SPEC_RE.sub(
|
||||
lambda m: f"{m.group(1)}{m.group(2)}?v={v}{m.group(3)}", source)
|
||||
|
||||
|
||||
def cache_control_for(path: str, query_string: str = "") -> str | None:
|
||||
"""En-tête ``Cache-Control`` pour un chemin, selon la query string.
|
||||
|
||||
Retourne ``None`` hors des statiques (l'appelant ne touche alors
|
||||
à rien). ``immutable`` seulement si ``v`` vaut la version
|
||||
courante ; ``no-cache`` dans tous les autres cas.
|
||||
"""
|
||||
if not path.startswith("/static/"):
|
||||
return None
|
||||
params = {}
|
||||
for pair in query_string.split("&"):
|
||||
if "=" in pair:
|
||||
key, value = pair.split("=", 1)
|
||||
params[key] = value
|
||||
if params.get("v") and params["v"] == current_version():
|
||||
return IMMUTABLE_CACHE_CONTROL
|
||||
return NO_CACHE
|
||||
Generated
+1
-1
@@ -2626,7 +2626,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "obsigate-desktop"
|
||||
version = "2.97.0"
|
||||
version = "2.99.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"env_logger",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "obsigate-desktop"
|
||||
version = "2.97.0"
|
||||
version = "2.99.0"
|
||||
description = "ObsiGate Desktop — Porte d'entrée native pour vos vaults Obsidian"
|
||||
authors = ["Bruno Charest"]
|
||||
edition = "2021"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/nicedoc/obsigate/main/desktop/tauri.conf.schema.json",
|
||||
"productName": "ObsiGate",
|
||||
"version": "2.97.0",
|
||||
"version": "2.99.0",
|
||||
"identifier": "com.obsigate.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../frontend",
|
||||
|
||||
+22
-1
@@ -1,6 +1,6 @@
|
||||
# ObsiGate — Roadmap
|
||||
|
||||
> **Version :** 2.97.0 | **Dernière mise à jour :** 2026-11-30
|
||||
> **Version :** 2.99.0 | **Dernière mise à jour :** 2026-12-01
|
||||
> **Ce fichier ne contient que le travail à venir** (🔵 En cours + ⚪ Backlog) et un index compact
|
||||
> vers les fonctionnalités livrées.
|
||||
> - **Méthode de livraison à appliquer pour toute tâche : [DELIVERY_WORKFLOW.md](./DELIVERY_WORKFLOW.md)**
|
||||
@@ -30,6 +30,27 @@
|
||||
|
||||
## 🔵 En cours
|
||||
|
||||
### 240. Épopée — Performance du chargement initial
|
||||
|
||||
- **Effort :** ~3 jours | **Impact :** 🔴 | **Ouvert :** 2026-11-30 | **Statut :** ✅ livré en 2.98.0 — PR #116 fusionnée dans main (issue Gitea #106)
|
||||
- **Fiche :** [features/perf-chargement-240.md](./features/perf-chargement-240.md)
|
||||
- **Description :** demande de Bruno (2026-11-30) — diviser par ~3 le premier affichage utile d'og.dracodev.net au bénéfice du retour SSO, des liens profonds `#file=`/`#folder=` et de l'accès de base. Baseline : TTFB 0,36–0,67 s, graphe ES statique 41 modules / 1 420 963 o, Mermaid CDN 745 Ko chargé d'emblée, statiques sans URL versionnées, `/api/dashboard` sans cache.
|
||||
- **Sous-tâches :**
|
||||
- [x] **#241 P0** — script d'audit versionné (`scripts/audit_chargement.py`) + budget figé (fiche) — Gitea #107
|
||||
- [x] **#242 P1** — cache versionné `?v=<VERSION>` + `immutable` conditionnel + SW versionné — Gitea #108
|
||||
- [x] **#243 P2** — `import()` dynamique des modules lourds + retrait des CDN du `<head>` — Gitea #109 (graphe −10,8 %, CDN retirés ; −50 % non atteint, voir fiche)
|
||||
- [x] **#244 P3** — bootstrap : lien profond ouvert avant le chargement complet — Gitea #110
|
||||
- [x] **#245 P4** — cache 60 s de `/api/dashboard` invalidé par le watcher — Gitea #111
|
||||
### 246. Épopée — Page d'accueil « Reprendre »
|
||||
|
||||
- **Effort :** ~2 jours | **Impact :** 🟡 | **Ouvert :** 2026-11-30 | **Statut :** 🔵 en cours — branche `feat/accueil-reprendre-246` livrée, PR à fusionner (issue Gitea #112)
|
||||
- **Fiche :** [features/accueil-reprendre-246.md](./features/accueil-reprendre-246.md)
|
||||
- **Description :** demande de Bruno (2026-11-30) — la page principale était la section Statistiques. Nouvel onglet Accueil par défaut, orienté « reprendre / à traiter » ; les onglets Statistiques, Bookmarks, Récents et Partagés restent inchangés.
|
||||
- **Sous-tâches :**
|
||||
- [x] **#247 A1** — onglet Accueil par défaut : bandeau stats, recherche héros, actions rapides, Reprendre — Gitea #113
|
||||
- [x] **#248 A2** — panneau « À traiter » (conflits existants, partages reçus non ouverts, expirations) — Gitea #114
|
||||
- [x] **#249 A3** — Mes vaults, recherches sauvées, raccourcis, personnalisation persistée — Gitea #115
|
||||
|
||||
### 239. Lien profond « dossier » `#folder=` (console Spark)
|
||||
|
||||
- **Effort :** ~0,5 jour | **Impact :** 🟢 | **Ouvert :** 2026-11-30 | **Statut :** 🔵 en cours — PR sur `feat/lien-dossier-239` (fusion = geste de Bruno)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# Page d'accueil « Reprendre » — épopée #246
|
||||
|
||||
> Demande de Bruno (2026-11-30). Issues Gitea : épopée #112, lots
|
||||
> #113 à #115. La page principale était la section Statistiques —
|
||||
> informative une fois, inutile au quotidien.
|
||||
|
||||
## Principe
|
||||
|
||||
Un nouvel onglet **Accueil** (`data-tab="home"`), premier et actif
|
||||
par défaut, dans le dashboard existant. Les onglets **Statistiques /
|
||||
Bookmarks / Récents / Partagés sont inchangés** (mêmes panneaux, mêmes
|
||||
widgets, mêmes appels). L'Accueil répond à « qu'est-ce que je
|
||||
reprends, qu'est-ce qui m'attend » et réutilise les données et les
|
||||
cartes existantes — aucun nouvel endpoint.
|
||||
|
||||
Le balisage vit aux deux endroits où le dashboard est construit :
|
||||
`frontend/index.html` (page initiale) et le gabarit de `showWelcome()`
|
||||
(`frontend/js/viewer.js`, reconstruction). Le widget est
|
||||
`DashboardHomeWidget` (`frontend/js/dashboard.js`), chargé par
|
||||
`showWelcome()` comme les autres widgets.
|
||||
|
||||
## Lots
|
||||
|
||||
- **#247 A1 — socle.** Bandeau stats en une ligne (les 4 chiffres de
|
||||
`/api/dashboard` : fichiers, tags, taille, vaults), recherche héros
|
||||
(le focus bascule sur le champ de recherche global existant, avec le
|
||||
texte saisi), actions rapides — **Nouveau fichier** (palette de
|
||||
commandes, où vit la commande existante), **Téléverser** (sélecteur
|
||||
de fichiers → `handleVaultDropUpload` existant, avec choix du
|
||||
dossier cible), **Palette de fichiers** (`palette.open('')`) — et
|
||||
section **Reprendre** : bookmarks/épinglés en tête
|
||||
(`/api/bookmarks`), puis les 6 derniers fichiers ouverts
|
||||
(`/api/recent?mode=opened`), rendus avec les cartes existantes
|
||||
(`DashboardRecentWidget._createCard`).
|
||||
- **#248 A2 — À traiter.** Conflits de synchronisation rendus par le
|
||||
widget existant `DashboardConflictsWidget.render()` alimenté par
|
||||
`/api/conflicts` (il était noyé dans la vue Statistiques) ; partages
|
||||
reçus non ouverts (`access_count` nul) et partages expirant sous
|
||||
7 jours, depuis `/api/shares`. **Le panneau est absent du DOM
|
||||
visible quand il n'y a rien à traiter** (`display:none` posé par le
|
||||
widget, pas un panneau vide).
|
||||
- **#249 A3 — vaults, recherches, personnalisation.** Cartes **Mes
|
||||
vaults** (nom, fichiers, taille depuis `/api/dashboard`, vault
|
||||
personnel `home-<user>` en premier ; clic = `TabManager.openNav`,
|
||||
l'onglet de navigation #158), **Recherches sauvées**
|
||||
(`/api/saved-searches`, clic = recherche relancée dans le champ
|
||||
global), bloc **Raccourcis & Astuces** compact (le bloc complet
|
||||
reste dans la vue Statistiques), et **personnalisation** : chaque
|
||||
panneau de l'Accueil peut être masqué/réaffiché (cases dans le bloc
|
||||
« Personnaliser »), choix persisté **par utilisateur dans
|
||||
localStorage** (clé `obsigate-home-hidden-panels-<user>`).
|
||||
⚠️ Repli documenté : il n'existe pas de mécanisme de préférences
|
||||
serveur pour le dashboard (les préférences serveur existantes sont
|
||||
celles des vaults/thème) — la personnalisation est donc propre à
|
||||
l'appareil, pas synchronisée entre appareils.
|
||||
|
||||
## i18n
|
||||
|
||||
Toutes les chaînes passent par les locales (`dashboard.home_*`,
|
||||
FR + EN, parité vérifiée par `tests/test_i18n_parity.py`).
|
||||
|
||||
## Tests
|
||||
|
||||
`tests/frontend/dashboard-home.test.mjs` (JSDOM sur le vrai
|
||||
`index.html` + formes des sources) : onglet par défaut, sections,
|
||||
branchements API, reconstruction par `showWelcome`.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Performance du chargement initial — épopée #240
|
||||
|
||||
> Demande de Bruno (2026-11-30). Audit complet : rapport du 2026-11-30
|
||||
> (mesures en direct sur la prod 2.97.0). Issues Gitea : épopée #106,
|
||||
> lots #107 à #111.
|
||||
|
||||
## Baseline (2026-11-30, prod 2.97.0 + fichiers du dépôt)
|
||||
|
||||
- TTFB médian 0,36–0,67 s ; `/`, `/sso/login` et `/healthz` servent la
|
||||
même SPA de 333 809 o.
|
||||
- Graphe ES statique depuis `frontend/js/app.js` : **41 modules,
|
||||
1 420 963 o bruts** (mesure locale, `scripts/audit_chargement.py
|
||||
--local` ; la mesure prod donnait 1 406 497 o), zéro `import()`
|
||||
dynamique dans le point d'entrée.
|
||||
- Mermaid (CDN jsdelivr) : 745 043 o au fil, chargé d'emblée ;
|
||||
highlight.js + 11 langages (cdnjs) et Lucide (unpkg) aussi dans le
|
||||
`<head>`.
|
||||
- Statiques sans URL versionnées : `cf-cache-status` MISS/DYNAMIC,
|
||||
`Cache-Control: max-age=30` constaté en prod.
|
||||
- Démarrage : `Promise.all([loadVaultSettings, loadVaults, loadTags])`
|
||||
avant l'ouverture du fichier d'un lien profond `#file=`/`#folder=`.
|
||||
- `GET /api/dashboard` recalcule les totaux (10 987 fichiers) à chaque
|
||||
appel, sans cache.
|
||||
|
||||
## Budget figé (#241)
|
||||
|
||||
| Indicateur | Cible |
|
||||
|---|---|
|
||||
| Premier affichage utile (connexion initiale) | ÷ ~3 vs baseline |
|
||||
| JS initial parsé (graphe statique local) | −50 % au moins |
|
||||
| 2ᵉ visite | zéro re-téléchargement des statiques versionnées (`?v=`) |
|
||||
| `/api/dashboard` répété | < 50 ms à chaud (cache) |
|
||||
| Lien profond `#file=`/`#folder=` | cible lisible avant la fin du chargement complet |
|
||||
|
||||
## Mécanisme du cache versionné (#242)
|
||||
|
||||
Sans étape de build (règle du dépôt) :
|
||||
|
||||
1. **HTML** : `_index_html()` réécrit au service les URL
|
||||
`/static/…` de `index.html` en `/static/…?v=<VERSION>`
|
||||
(`backend/static_versioning.py`, VERSION = source unique).
|
||||
2. **Modules ES** : le serveur de statiques (`VersionedStaticFiles`)
|
||||
réécrit au service les spécificateurs d'import relatifs des
|
||||
fichiers `.js` en y ajoutant `?v=<VERSION>` — le navigateur ne
|
||||
connaît donc que des URL versionnées, de proche en proche.
|
||||
3. **En-têtes** : `Cache-Control: public, max-age=31536000, immutable`
|
||||
**uniquement** quand la requête porte `?v=<VERSION courante>` ;
|
||||
`no-cache` sinon, et toujours `no-cache` sur le HTML. Le piège
|
||||
historique (cache long sans versionnage → build périmé servi un an)
|
||||
est impossible : une nouvelle version change toutes les URL.
|
||||
4. **Service worker** : le nom de cache embarque la version servie
|
||||
(`__OBSIGATE_SW_VERSION__` remplacé par le backend à la route
|
||||
`/sw.js`) ; à l'activation, tout cache d'un autre nom est supprimé.
|
||||
|
||||
⚠️ **Hors code** : la règle Cloudflare qui ferait passer les statiques
|
||||
versionnées en `cf-cache-status: HIT` est une action d'exploitation
|
||||
(à faire au tableau de bord Cloudflare), elle n'est pas livrée par
|
||||
cette branche.
|
||||
|
||||
## Lots
|
||||
|
||||
- **#241 P0** — script d'audit versionné + ce budget. ✅
|
||||
- **#242 P1** — cache versionné (ci-dessus) + tests d'en-têtes et de
|
||||
non-régression « nouvelle version servie ». ✅
|
||||
- **#243 P2** — `import()` dynamique à la première utilisation
|
||||
(Mermaid, graphe, Excalidraw, now-playing, plugins, push, mobile-editor) et
|
||||
retrait des scripts CDN du `<head>` (highlight chargé au premier
|
||||
bloc de code, par langage ; Lucide chargé en différé non bloquant
|
||||
par `safeCreateIcons` ; Mermaid au premier diagramme).
|
||||
**Résultat mesuré (script --local)** : graphe statique 41 → **34 modules**,
|
||||
1 420 963 → **1 243 303 o (−12,5 %)** ; les **13 scripts CDN du `<head>`
|
||||
sont retirés** (Mermaid 745 Ko au fil, highlight + langages, Lucide),
|
||||
chargés à la demande — c'est le gain principal du lot sur le fil.
|
||||
Le budget « −50 % du graphe statique » n'est **pas** atteint : le cœur
|
||||
(viewer/ui/config/auth/sidebar, fortement couplés et circulaires)
|
||||
reste statique, de même que les modules XLSX de `viewer.js` et
|
||||
`filechat.js` (chat latéral câblé au démarrage par sidebar/config) —
|
||||
leur extraction exigerait de découper viewer.js lui-même, chantier
|
||||
séparé à ouvrir si Bruno le souhaite.
|
||||
- **#244 P3** — bootstrap : lien profond ouvert avant le chargement
|
||||
complet des vaults/tags/réglages. ✅ (`#file=` ouvert dès l'auth ;
|
||||
`#folder=` reste après `loadVaults`, son arborescence en dépend.)
|
||||
- **#245 P4** — cache mémoire 60 s de `/api/dashboard`, invalidé par
|
||||
le watcher ; GZip inchangé (SSE toujours exclu). ✅
|
||||
+80
-14
@@ -63,20 +63,7 @@
|
||||
disabled
|
||||
/>
|
||||
<!-- defer: ne bloque pas le premier paint -->
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
||||
<!-- Langues highlight.js hors bundle "common" (enregistrement auto apres le core) -->
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/dockerfile.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/powershell.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/dos.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/cmake.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/dart.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/elixir.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/haskell.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/nginx.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/http.min.js"></script>
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/plaintext.min.js"></script>
|
||||
<script defer src="https://unpkg.com/[email protected]/dist/umd/lucide.min.js"></script>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
|
||||
<script type="importmap">
|
||||
{
|
||||
"imports": {
|
||||
@@ -1296,6 +1283,16 @@
|
||||
<div class="dashboard-tabs">
|
||||
<button
|
||||
class="dashboard-tab active"
|
||||
data-tab="home"
|
||||
>
|
||||
<i
|
||||
data-lucide="home"
|
||||
style="width: 14px; height: 14px"
|
||||
></i>
|
||||
<span data-i18n="dashboard.home_tab">Accueil</span>
|
||||
</button>
|
||||
<button
|
||||
class="dashboard-tab"
|
||||
data-tab="stats"
|
||||
>
|
||||
<i
|
||||
@@ -1330,10 +1327,79 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Home Panel — Accueil « Reprendre » (#247-#249) -->
|
||||
<div
|
||||
id="dashboard-panel-home"
|
||||
class="dashboard-panel active"
|
||||
>
|
||||
<div id="home-stats-strip" class="home-stats-strip"></div>
|
||||
<div class="home-hero">
|
||||
<input
|
||||
id="home-search-input"
|
||||
class="home-search-input"
|
||||
type="text"
|
||||
data-i18n-placeholder="dashboard.home_search_placeholder"
|
||||
placeholder="Rechercher dans vos vaults…"
|
||||
/>
|
||||
<div class="home-actions">
|
||||
<button id="home-action-new" class="home-action-btn">
|
||||
<i data-lucide="file-plus-2" style="width: 14px; height: 14px"></i>
|
||||
<span data-i18n="dashboard.home_new_file">Nouveau fichier</span>
|
||||
</button>
|
||||
<button id="home-action-upload" class="home-action-btn">
|
||||
<i data-lucide="upload" style="width: 14px; height: 14px"></i>
|
||||
<span data-i18n="dashboard.home_upload">Téléverser</span>
|
||||
</button>
|
||||
<button id="home-action-palette" class="home-action-btn">
|
||||
<i data-lucide="layout-grid" style="width: 14px; height: 14px"></i>
|
||||
<span data-i18n="dashboard.home_palette">Palette de fichiers</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<section id="home-section-todo" data-home-panel="todo" class="home-section" style="display: none">
|
||||
<h2 class="home-section-title" data-i18n="dashboard.home_todo">À traiter</h2>
|
||||
<div id="home-conflicts-container"></div>
|
||||
<div id="home-todo-list"></div>
|
||||
</section>
|
||||
<section id="home-section-resume" data-home-panel="resume" class="home-section">
|
||||
<h2 class="home-section-title" data-i18n="dashboard.home_resume">Reprendre</h2>
|
||||
<div id="home-resume-grid" class="dashboard-recent-grid"></div>
|
||||
<div id="home-resume-empty" class="dashboard-recent-empty" style="display: none">
|
||||
<span data-i18n="dashboard.home_no_resume">Rien à reprendre pour le moment</span>
|
||||
</div>
|
||||
</section>
|
||||
<section id="home-section-vaults" data-home-panel="vaults" class="home-section">
|
||||
<h2 class="home-section-title" data-i18n="dashboard.home_vaults">Mes vaults</h2>
|
||||
<div id="home-vaults-grid" class="home-vaults-grid"></div>
|
||||
</section>
|
||||
<section id="home-section-searches" data-home-panel="searches" class="home-section">
|
||||
<h2 class="home-section-title" data-i18n="dashboard.home_saved_searches">Recherches sauvées</h2>
|
||||
<div id="home-searches-list" class="home-searches-list"></div>
|
||||
<div id="home-searches-empty" class="dashboard-recent-empty" style="display: none">
|
||||
<span data-i18n="dashboard.home_no_saved_searches">Aucune recherche sauvée</span>
|
||||
</div>
|
||||
</section>
|
||||
<section id="home-section-help" data-home-panel="help" class="home-section">
|
||||
<h2 class="home-section-title" data-i18n="help.shortcuts_title">Raccourcis & Astuces</h2>
|
||||
<div class="qh-row"><span class="qh-kbd">Ctrl+Shift+Space</span> <span data-i18n="dashboard.home_sc_palette">Palette de fichiers (nav. rapide)</span></div>
|
||||
<div class="qh-row"><span class="qh-kbd">Ctrl+K</span> <span data-i18n="dashboard.home_sc_search">Focus barre de recherche</span></div>
|
||||
<div class="qh-row"><span class="qh-kbd">Ctrl+S</span> <span data-i18n="dashboard.home_sc_save">Sauvegarder le fichier ouvert</span></div>
|
||||
<div class="qh-row"><span class="qh-kbd">Esc</span> <span data-i18n="dashboard.home_sc_close">Fermer l'éditeur / modale</span></div>
|
||||
</section>
|
||||
<details class="home-customize">
|
||||
<summary data-i18n="dashboard.home_customize">Personnaliser</summary>
|
||||
<label><input type="checkbox" data-home-toggle="resume" checked /> <span data-i18n="dashboard.home_resume">Reprendre</span></label>
|
||||
<label><input type="checkbox" data-home-toggle="todo" checked /> <span data-i18n="dashboard.home_todo">À traiter</span></label>
|
||||
<label><input type="checkbox" data-home-toggle="vaults" checked /> <span data-i18n="dashboard.home_vaults">Mes vaults</span></label>
|
||||
<label><input type="checkbox" data-home-toggle="searches" checked /> <span data-i18n="dashboard.home_saved_searches">Recherches sauvées</span></label>
|
||||
<label><input type="checkbox" data-home-toggle="help" checked /> <span data-i18n="help.shortcuts_title">Raccourcis & Astuces</span></label>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<!-- Stats Panel -->
|
||||
<div
|
||||
id="dashboard-panel-stats"
|
||||
class="dashboard-panel active"
|
||||
class="dashboard-panel"
|
||||
>
|
||||
<div
|
||||
id="dashboard-stats-grid"
|
||||
|
||||
+34
-19
@@ -5,7 +5,11 @@
|
||||
import * as UI from './ui.js';
|
||||
import * as Utils from './utils.js';
|
||||
import { initI18n, t } from './i18n.js';
|
||||
import { initNowPlaying } from './now-playing.js';
|
||||
|
||||
// #243 : modules chargés paresseusement (import dynamique) à la première
|
||||
// utilisation ou en tâche de fond : graph, mermaid-viewer, now-playing,
|
||||
// mobile-editor, push, plugins — ils ne font plus partie du graphe statique.
|
||||
const _idle = window.requestIdleCallback || ((f) => setTimeout(f, 1200));
|
||||
|
||||
// Wire up AI toolbar toast (avoids circular import in utils.js)
|
||||
window._obsigateShowToast = UI.showToast;
|
||||
@@ -13,17 +17,12 @@ import * as Sidebar from './sidebar.js';
|
||||
import * as Auth from './auth.js';
|
||||
import * as Viewer from './viewer.js';
|
||||
import * as Sync from './sync.js';
|
||||
import { initGraphView } from './graph.js';
|
||||
import * as Legacy from './legacy.js';
|
||||
import { initCommandPalette } from './palette.js';
|
||||
import { initMobileToolbar } from './mobile-toolbar.js';
|
||||
import { initMobileEditor } from './mobile-editor.js';
|
||||
import { initDragDrop } from './dragdrop.js';
|
||||
import { initMermaid, setupFocusMode } from './mermaid-viewer.js';
|
||||
import PaneManager from './pane-manager.js';
|
||||
import { initDesktopIntegration, isTauriEnv } from './desktop.js';
|
||||
import { initPush } from './push.js';
|
||||
import { initPlugins } from './plugins.js';
|
||||
import { populateVersions } from './config.js';
|
||||
import { initSidebarChat } from './filechat.js';
|
||||
|
||||
@@ -74,25 +73,28 @@ async function init() {
|
||||
PaneManager.init();
|
||||
initCommandPalette();
|
||||
initMobileToolbar();
|
||||
initMobileEditor();
|
||||
initPush();
|
||||
initPlugins();
|
||||
import('./mobile-editor.js').then((m) => m.initMobileEditor()).catch(() => {});
|
||||
import('./push.js').then((m) => m.initPush()).catch(() => {});
|
||||
import('./plugins.js').then((m) => m.initPlugins()).catch(() => {});
|
||||
|
||||
if (authOk) {
|
||||
Legacy.initSyncStatus();
|
||||
|
||||
try {
|
||||
await Promise.all([Legacy.loadVaultSettings(), Sidebar.loadVaults(), Sidebar.loadTags()]);
|
||||
|
||||
initDragDrop();
|
||||
|
||||
Legacy.DashboardRecentWidget.init();
|
||||
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
if (urlParams.get("popup") === "true") {
|
||||
document.body.classList.add("popup-mode");
|
||||
}
|
||||
|
||||
// #244 (P3) : bootstrap rapide des liens profonds — un lien
|
||||
// ``#file=`` (y compris à l'arrivée d'un retour SSO) est ouvert
|
||||
// AVANT le chargement complet (réglages des vaults, liste des
|
||||
// vaults, tags) : ``openFile`` ne dépend que de l'auth, déjà
|
||||
// faite. Le reste charge ensuite, sans rouvrir ni écraser la
|
||||
// cible (``fichierOuvert`` garde la suite). ``#folder=`` reste
|
||||
// après le chargement : ``focusPathInSidebar`` a besoin de
|
||||
// l'arborescence rendue par ``loadVaults``.
|
||||
let fichierOuvert = false;
|
||||
if (window.location.hash && window.location.hash.startsWith("#file=")) {
|
||||
const hashVal = window.location.hash.substring(6);
|
||||
const sepIndex = hashVal.indexOf(":");
|
||||
@@ -100,7 +102,19 @@ async function init() {
|
||||
const vault = decodeURIComponent(hashVal.substring(0, sepIndex));
|
||||
const path = decodeURIComponent(hashVal.substring(sepIndex + 1));
|
||||
Viewer.openFile(vault, path);
|
||||
fichierOuvert = true;
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all([Legacy.loadVaultSettings(), Sidebar.loadVaults(), Sidebar.loadTags()]);
|
||||
|
||||
initDragDrop();
|
||||
|
||||
Legacy.DashboardRecentWidget.init();
|
||||
|
||||
if (fichierOuvert) {
|
||||
// Cible déjà ouverte par le bootstrap rapide : ne pas la
|
||||
// recouvrir par l'accueil.
|
||||
} else if (window.location.hash && window.location.hash.startsWith("#folder=")) {
|
||||
// #239 : lien profond « dossier » (émis par la console Spark,
|
||||
// forme sœur de #file= : « #folder=<vault>:<chemin> »). Un
|
||||
@@ -134,11 +148,12 @@ async function init() {
|
||||
}
|
||||
}
|
||||
|
||||
initGraphView();
|
||||
initMermaid();
|
||||
setupFocusMode();
|
||||
// #243 : graphe, mermaid (mode focus) et lecteur média en différé —
|
||||
// aucun de ces modules n'est nécessaire au premier affichage.
|
||||
_idle(() => { import('./graph.js').then((m) => m.initGraphView()).catch(() => {}); });
|
||||
_idle(() => { import('./mermaid-viewer.js').then((m) => m.setupFocusMode()).catch(() => {}); });
|
||||
Utils.safeCreateIcons();
|
||||
initNowPlaying();
|
||||
_idle(() => { import('./now-playing.js').then((m) => m.initNowPlaying()).catch(() => {}); });
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
|
||||
+256
-1
@@ -493,4 +493,259 @@ const DashboardBookmarkWidget = {
|
||||
}
|
||||
};
|
||||
|
||||
export { DashboardRecentWidget, DashboardStatsWidget, DashboardBookmarkWidget, DashboardSharedWidget, DashboardConflictsWidget };
|
||||
|
||||
// ── Dashboard Home Widget — Accueil « Reprendre » (#247-#249) ─────────────
|
||||
// Nouvel onglet par défaut du dashboard. Les onglets Statistiques /
|
||||
// Bookmarks / Récents / Partagés sont inchangés ; l'Accueil réutilise
|
||||
// leurs données et leurs cartes :
|
||||
// - #247 : bandeau stats (une ligne, /api/dashboard), recherche héros
|
||||
// (focus sur le champ de recherche existant), actions rapides
|
||||
// (Nouveau fichier via la palette de commandes, Téléverser via le
|
||||
// flux d'upload existant, Palette de fichiers), section Reprendre
|
||||
// (bookmarks/épinglés en tête + 6 derniers fichiers ouverts).
|
||||
// - #248 : panneau « À traiter » (conflits via DashboardConflictsWidget,
|
||||
// partages reçus non ouverts et expirations < 7 j via /api/shares) ;
|
||||
// le panneau est masqué quand il n'y a rien à traiter.
|
||||
// - #249 : cartes Mes vaults (clic = onglet de navigation du vault),
|
||||
// Recherches sauvées, Raccourcis & Astuces compact, et
|
||||
// personnalisation (panneaux masquables, choix persisté par
|
||||
// utilisateur dans localStorage — aucun mécanisme de préférences
|
||||
// serveur n'existe pour le dashboard, repli documenté dans la fiche).
|
||||
const DashboardHomeWidget = {
|
||||
_vaults: [],
|
||||
|
||||
_prefsKey() {
|
||||
const user = (AuthManager.getUser() || {}).username || "anon";
|
||||
return `obsigate-home-hidden-panels-${user}`;
|
||||
},
|
||||
|
||||
_hiddenPanels() {
|
||||
try {
|
||||
return new Set(JSON.parse(localStorage.getItem(this._prefsKey()) || "[]"));
|
||||
} catch { return new Set(); }
|
||||
},
|
||||
|
||||
applyPrefs() {
|
||||
const hidden = this._hiddenPanels();
|
||||
// Le panneau « À traiter » est piloté par les données (loadTodo) :
|
||||
// la personnalisation ne fait que l'autoriser, jamais l'afficher vide.
|
||||
document.querySelectorAll('[data-home-panel]:not([data-home-panel="todo"])').forEach((section) => {
|
||||
section.style.display = hidden.has(section.dataset.homePanel) ? "none" : "";
|
||||
});
|
||||
document.querySelectorAll("[data-home-toggle]").forEach((box) => {
|
||||
box.checked = !hidden.has(box.dataset.homeToggle);
|
||||
});
|
||||
},
|
||||
|
||||
bindActions(panel) {
|
||||
if (panel.dataset.homeBound) return;
|
||||
panel.dataset.homeBound = "1";
|
||||
|
||||
const hero = document.getElementById("home-search-input");
|
||||
if (hero) {
|
||||
hero.addEventListener("focus", () => {
|
||||
const input = document.getElementById("search-input");
|
||||
if (input) { input.value = hero.value; input.focus(); input.dispatchEvent(new Event("input")); }
|
||||
});
|
||||
}
|
||||
const newBtn = document.getElementById("home-action-new");
|
||||
if (newBtn) newBtn.addEventListener("click", () => {
|
||||
import("./palette.js").then((m) => m.open("> ")).catch(() => {});
|
||||
});
|
||||
const paletteBtn = document.getElementById("home-action-palette");
|
||||
if (paletteBtn) paletteBtn.addEventListener("click", () => {
|
||||
import("./palette.js").then((m) => m.open("")).catch(() => {});
|
||||
});
|
||||
const uploadBtn = document.getElementById("home-action-upload");
|
||||
if (uploadBtn) uploadBtn.addEventListener("click", () => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.multiple = true;
|
||||
input.style.display = "none";
|
||||
document.body.appendChild(input);
|
||||
input.addEventListener("change", async () => {
|
||||
const items = Array.from(input.files || []).map((f) => ({ path: f.name, file: f, isDir: false }));
|
||||
input.remove();
|
||||
if (!items.length) return;
|
||||
const vault = (state.selectedContextVault && state.selectedContextVault !== "all")
|
||||
? state.selectedContextVault
|
||||
: (this._vaults[0] && this._vaults[0].name);
|
||||
if (!vault) return;
|
||||
const m = await import("./upload.js");
|
||||
await m.handleVaultDropUpload(vault, null, items);
|
||||
this.load();
|
||||
});
|
||||
input.click();
|
||||
});
|
||||
panel.querySelectorAll("[data-home-toggle]").forEach((box) => {
|
||||
box.addEventListener("change", () => {
|
||||
const hidden = this._hiddenPanels();
|
||||
if (box.checked) hidden.delete(box.dataset.homeToggle);
|
||||
else hidden.add(box.dataset.homeToggle);
|
||||
try { localStorage.setItem(this._prefsKey(), JSON.stringify([...hidden])); } catch {}
|
||||
this.applyPrefs();
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
async load() {
|
||||
const panel = document.getElementById("dashboard-panel-home");
|
||||
if (!panel) return;
|
||||
this.bindActions(panel);
|
||||
this.applyPrefs();
|
||||
await Promise.allSettled([
|
||||
this.loadStatsAndVaults(),
|
||||
this.loadResume(),
|
||||
this.loadTodo(),
|
||||
this.loadSavedSearches(),
|
||||
]);
|
||||
this.applyPrefs();
|
||||
safeCreateIcons();
|
||||
},
|
||||
|
||||
async loadStatsAndVaults() {
|
||||
const strip = document.getElementById("home-stats-strip");
|
||||
const grid = document.getElementById("home-vaults-grid");
|
||||
try {
|
||||
const data = await api("/api/dashboard");
|
||||
this._vaults = data.vaults || [];
|
||||
const fmtSize = (bytes) => bytes < 1024 ? `${bytes}${t('dashboard.size_bytes')}` : bytes < 1048576 ? `${(bytes/1024).toFixed(1)}${t('dashboard.size_kb')}` : bytes < 1073741824 ? `${(bytes/1048576).toFixed(1)}${t('dashboard.size_mb')}` : `${(bytes/1073741824).toFixed(1)}${t('dashboard.size_gb')}`;
|
||||
if (strip) {
|
||||
strip.innerHTML = `
|
||||
<span><i data-lucide="files"></i> ${data.total_files.toLocaleString()} ${t('dashboard.stats_files')}</span>
|
||||
<span><i data-lucide="tags"></i> ${data.total_tags.toLocaleString()} ${t('dashboard.stats_tags')}</span>
|
||||
<span><i data-lucide="hard-drive"></i> ${fmtSize(data.total_size_bytes)}</span>
|
||||
<span><i data-lucide="folder-open"></i> ${data.vaults.length} ${t('dashboard.stats_vaults')}</span>`;
|
||||
}
|
||||
if (grid) {
|
||||
grid.innerHTML = "";
|
||||
// Le vault personnel (home-<user>) d'abord, comme dans l'arborescence (#194).
|
||||
const me = (AuthManager.getUser() || {}).username;
|
||||
const sorted = [...this._vaults].sort((a, b) =>
|
||||
(b.name === `home-${me}`) - (a.name === `home-${me}`) || a.name.localeCompare(b.name));
|
||||
sorted.forEach((v) => {
|
||||
const card = document.createElement("button");
|
||||
card.className = "home-vault-card";
|
||||
card.innerHTML = `<i data-lucide="folder-open"></i>
|
||||
<span class="home-vault-name">${escapeHtml(v.name)}</span>
|
||||
<span class="home-vault-meta">${v.file_count.toLocaleString()} ${t('dashboard.count_files_plural')} · ${fmtSize(v.total_size_bytes)}</span>`;
|
||||
card.addEventListener("click", () => TabManager.openNav(v.name));
|
||||
grid.appendChild(card);
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
if (strip) strip.innerHTML = "";
|
||||
}
|
||||
},
|
||||
|
||||
async loadResume() {
|
||||
const grid = document.getElementById("home-resume-grid");
|
||||
const empty = document.getElementById("home-resume-empty");
|
||||
if (!grid) return;
|
||||
try {
|
||||
const [bookmarks, recent] = await Promise.all([
|
||||
api("/api/bookmarks").catch(() => ({ files: [] })),
|
||||
api("/api/recent?mode=opened").catch(() => ({ files: [] })),
|
||||
]);
|
||||
const pinned = (bookmarks.files || []).map((f) => ({ ...f, bookmarked: true }));
|
||||
const seen = new Set(pinned.map((f) => `${f.vault}:${f.path}`));
|
||||
const fresh = (recent.files || []).filter((f) => !seen.has(`${f.vault}:${f.path}`)).slice(0, 6);
|
||||
const files = [...pinned.slice(0, 6), ...fresh];
|
||||
grid.innerHTML = "";
|
||||
files.forEach((f, idx) => grid.appendChild(DashboardRecentWidget._createCard(f, idx)));
|
||||
if (empty) empty.style.display = files.length ? "none" : "";
|
||||
safeCreateIcons();
|
||||
} catch (err) {
|
||||
if (empty) empty.style.display = "";
|
||||
}
|
||||
},
|
||||
|
||||
async loadTodo() {
|
||||
const section = document.getElementById("home-section-todo");
|
||||
const list = document.getElementById("home-todo-list");
|
||||
const conflictsHost = document.getElementById("home-conflicts-container");
|
||||
if (!section) return;
|
||||
let has = false;
|
||||
|
||||
try {
|
||||
const data = await api("/api/conflicts");
|
||||
if (data && data.total > 0 && conflictsHost) {
|
||||
DashboardConflictsWidget.render(data.conflicts, conflictsHost);
|
||||
has = true;
|
||||
} else if (conflictsHost) {
|
||||
conflictsHost.innerHTML = "";
|
||||
}
|
||||
} catch { /* pas de conflits exposables */ }
|
||||
|
||||
try {
|
||||
const shares = await api("/api/shares");
|
||||
const me = (AuthManager.getUser() || {}).username;
|
||||
const now = Date.now();
|
||||
const week = 7 * 24 * 3600 * 1000;
|
||||
const items = [];
|
||||
(shares || []).forEach((sh) => {
|
||||
const received = me && sh.created_by && sh.created_by !== me
|
||||
&& Array.isArray(sh.shared_with) && sh.shared_with.includes(me);
|
||||
const expiresSoon = sh.expires_at && (new Date(sh.expires_at).getTime() - now) > 0
|
||||
&& (new Date(sh.expires_at).getTime() - now) < week;
|
||||
if (received && !sh.access_count) {
|
||||
items.push({ share: sh, received, label: t('dashboard.home_received_unopened') });
|
||||
} else if (expiresSoon) {
|
||||
items.push({ share: sh, received, label: t('dashboard.home_expiring_soon') });
|
||||
}
|
||||
});
|
||||
if (list) {
|
||||
list.innerHTML = "";
|
||||
items.forEach(({ share: sh, received, label }) => {
|
||||
const row = document.createElement("div");
|
||||
row.className = "home-todo-item";
|
||||
const name = (sh.path || "").split("/").pop().replace(/\.md$/i, "");
|
||||
row.innerHTML = `<i data-lucide="share-2"></i>
|
||||
<span class="home-todo-label">${escapeHtml(label)}</span>
|
||||
<span class="home-todo-name">${escapeHtml(name)}</span>
|
||||
<span class="home-todo-vault">${escapeHtml(sh.vault)}</span>`;
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "shared-open-btn";
|
||||
btn.textContent = t('dashboard.open_btn');
|
||||
btn.addEventListener("click", () => {
|
||||
if (received) TabManager.openPreview(`home-${me}`, `Partage/${(sh.path || "").split("/").pop()}`);
|
||||
else TabManager.openPreview(sh.vault, sh.path);
|
||||
});
|
||||
row.appendChild(btn);
|
||||
list.appendChild(row);
|
||||
});
|
||||
}
|
||||
if (items.length) has = true;
|
||||
} catch { /* pas de partages exposables */ }
|
||||
|
||||
section.style.display = (has && !this._hiddenPanels().has("todo")) ? "" : "none";
|
||||
if (has) safeCreateIcons();
|
||||
},
|
||||
|
||||
async loadSavedSearches() {
|
||||
const list = document.getElementById("home-searches-list");
|
||||
const empty = document.getElementById("home-searches-empty");
|
||||
if (!list) return;
|
||||
try {
|
||||
const searches = await api("/api/saved-searches");
|
||||
list.innerHTML = "";
|
||||
(searches || []).forEach((srch) => {
|
||||
const isDir = (!srch.query || srch.query.trim() === "") && srch.include_paths;
|
||||
const item = document.createElement("button");
|
||||
item.className = "home-search-item";
|
||||
item.innerHTML = `<i data-lucide="${isDir ? "folder-search" : "search"}"></i> ${escapeHtml(isDir ? srch.include_paths : srch.query)}`;
|
||||
item.addEventListener("click", () => {
|
||||
const input = document.getElementById("search-input");
|
||||
if (input) { input.value = srch.query || ""; input.focus(); input.dispatchEvent(new Event("input")); }
|
||||
});
|
||||
list.appendChild(item);
|
||||
});
|
||||
if (empty) empty.style.display = (searches && searches.length) ? "none" : "";
|
||||
safeCreateIcons();
|
||||
} catch {
|
||||
if (empty) empty.style.display = "";
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export { DashboardRecentWidget, DashboardStatsWidget, DashboardBookmarkWidget, DashboardSharedWidget, DashboardConflictsWidget, DashboardHomeWidget };
|
||||
|
||||
@@ -15,9 +15,26 @@ import { safeCreateIcons } from './utils.js';
|
||||
var _mermaidReady = false;
|
||||
var _currentTheme = 'default';
|
||||
|
||||
let _mermaidLoadPromise = null;
|
||||
export function ensureMermaid() {
|
||||
// #243 : Mermaid (745 Ko au fil) n'est plus chargé dans le <head> ;
|
||||
// il arrive au premier diagramme rencontré.
|
||||
if (typeof mermaid !== 'undefined') return Promise.resolve(true);
|
||||
if (!_mermaidLoadPromise) {
|
||||
_mermaidLoadPromise = new Promise((resolve) => {
|
||||
const el = document.createElement('script');
|
||||
el.src = 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js';
|
||||
el.onload = () => resolve(typeof mermaid !== 'undefined');
|
||||
el.onerror = () => resolve(false);
|
||||
document.head.appendChild(el);
|
||||
});
|
||||
}
|
||||
return _mermaidLoadPromise;
|
||||
}
|
||||
|
||||
export function initMermaid() {
|
||||
if (typeof mermaid === 'undefined') {
|
||||
console.warn('[Mermaid] library not loaded');
|
||||
ensureMermaid().then((ok) => { if (ok) initMermaid(); });
|
||||
return;
|
||||
}
|
||||
mermaid.initialize(_getMermaidConfig(_currentTheme === 'dark'));
|
||||
@@ -235,7 +252,12 @@ export var MERMAID_TEMPLATES = {
|
||||
var _renderCounter = 0;
|
||||
|
||||
export async function renderMermaidBlocks(container) {
|
||||
if (!_mermaidReady || typeof mermaid === 'undefined') return;
|
||||
if (typeof mermaid === 'undefined') {
|
||||
const ok = await ensureMermaid();
|
||||
if (!ok) return;
|
||||
}
|
||||
if (!_mermaidReady) initMermaid();
|
||||
if (!_mermaidReady) return;
|
||||
|
||||
var blocks = container.querySelectorAll('pre code.language-mermaid, .mermaid-code');
|
||||
if (blocks.length === 0) return;
|
||||
|
||||
@@ -8,7 +8,6 @@ import { _getEffective } from './config.js';
|
||||
import { TabManager, showToast } from './ui.js';
|
||||
import { addTagFilter, buildSearchResultsHeader, shouldDisplayPath, removeTagFilter, TagFilterService } from './sidebar.js';
|
||||
import { t } from './i18n.js';
|
||||
import { onSearchFilter } from './plugins.js';
|
||||
// ---------------------------------------------------------------------------
|
||||
// Search History Service (localStorage, LIFO, max 50, dedup)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -826,6 +825,7 @@ export async function performAdvancedSearch(query, vaultFilter, tagFilter, offse
|
||||
semBtn.classList.toggle("active", state.semanticSearch);
|
||||
}
|
||||
// Plugin hook: filter search results
|
||||
const { onSearchFilter } = await import('./plugins.js'); // #243 paresseux
|
||||
data.results = await onSearchFilter(state.vault || "default", query, data.results);
|
||||
renderAdvancedSearchResults(data, query, tagFilter);
|
||||
} catch (err) {
|
||||
|
||||
+1
-2
@@ -4,7 +4,6 @@ import { state } from './state.js';
|
||||
import { openFile, showWelcome, renderFile, renderImageViewer, el } from './viewer.js';
|
||||
import { safeCreateIcons, getFileIcon, escapeHtml, detachInlineEditor } from './utils.js';
|
||||
import { syncActiveFileTreeItem, refreshSidebarTreePreservingState } from './sidebar.js';
|
||||
import { GraphViewManager } from './graph.js';
|
||||
import { DashboardConflictsWidget } from './dashboard.js';
|
||||
import { t, tr } from './i18n.js';
|
||||
import { toggleThemeMode } from './themes.js';
|
||||
@@ -1799,7 +1798,7 @@ export const ContextMenuManager = {
|
||||
|
||||
// Graph view — available for all types
|
||||
const graphPath = type === 'vault' ? '' : path;
|
||||
this._addItem('git-graph', 'Vue Graphique', () => GraphViewManager.open(vault, graphPath, type), false);
|
||||
this._addItem('git-graph', 'Vue Graphique', () => { import('./graph.js').then((m) => m.GraphViewManager.open(vault, graphPath, type)).catch(() => {}); }, false); // #243 graphe paresseux
|
||||
|
||||
this._addSeparator();
|
||||
|
||||
|
||||
+49
-1
@@ -290,8 +290,48 @@ let _iconDebounceTimer = null;
|
||||
* Debounced icon creation — batches multiple rapid calls into one
|
||||
* DOM scan to avoid excessive reflows when building large trees.
|
||||
*/
|
||||
// ---------------------------------------------------------------------------
|
||||
// Chargement paresseux des CDN (#243) : Lucide et highlight.js ne sont plus
|
||||
// chargés dans le <head> — ils arrivent à la première utilisation.
|
||||
// ---------------------------------------------------------------------------
|
||||
const _scriptPromises = {};
|
||||
function _loadScriptOnce(src) {
|
||||
if (!_scriptPromises[src]) {
|
||||
_scriptPromises[src] = new Promise((resolve) => {
|
||||
const el = document.createElement("script");
|
||||
el.src = src;
|
||||
el.onload = () => resolve(true);
|
||||
el.onerror = () => resolve(false);
|
||||
document.head.appendChild(el);
|
||||
});
|
||||
}
|
||||
return _scriptPromises[src];
|
||||
}
|
||||
|
||||
function ensureLucide() {
|
||||
if (typeof lucide !== "undefined" && lucide.createIcons) return Promise.resolve(true);
|
||||
return _loadScriptOnce("https://unpkg.com/[email protected]/dist/umd/lucide.min.js")
|
||||
.then((ok) => ok && typeof lucide !== "undefined" && !!lucide.createIcons);
|
||||
}
|
||||
|
||||
const HLJS_BASE = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0";
|
||||
function ensureHighlight(lang) {
|
||||
if (typeof hljs !== "undefined" && hljs.highlightElement) return Promise.resolve(true);
|
||||
return _loadScriptOnce(`${HLJS_BASE}/highlight.min.js`).then(async (ok) => {
|
||||
if (!ok || typeof hljs === "undefined") return false;
|
||||
if (lang && hljs.getLanguage && !hljs.getLanguage(lang)) {
|
||||
await _loadScriptOnce(`${HLJS_BASE}/languages/${lang}.min.js`);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function safeCreateIcons() {
|
||||
if (typeof lucide === "undefined" || !lucide.createIcons) return;
|
||||
if (typeof lucide === "undefined" || !lucide.createIcons) {
|
||||
// #243 : charger Lucide en différé, puis rejouer la création d'icônes.
|
||||
ensureLucide().then((ok) => { if (ok) safeCreateIcons(); });
|
||||
return;
|
||||
}
|
||||
if (state._iconDebounceTimer) return; // already scheduled
|
||||
state._iconDebounceTimer = requestAnimationFrame(() => {
|
||||
state._iconDebounceTimer = null;
|
||||
@@ -321,6 +361,12 @@ function flushIcons() {
|
||||
function safeHighlight(block) {
|
||||
// Skip mermaid blocks — they're rendered by Mermaid.js, not highlighted
|
||||
if (block.className && block.className.indexOf('language-mermaid') !== -1) return;
|
||||
if (typeof hljs === "undefined" || !hljs.highlightElement) {
|
||||
// #243 : charger highlight.js (base + langage détecté) puis recolorer.
|
||||
const mLang = /\blanguage-([\w-]+)/.exec(block.className || "");
|
||||
ensureHighlight(mLang ? mLang[1] : null).then((ok) => { if (ok) safeHighlight(block); });
|
||||
return;
|
||||
}
|
||||
if (typeof hljs !== "undefined" && hljs.highlightElement) {
|
||||
try {
|
||||
// Alias pour les extensions que highlight.js (bundle common) ne connaît pas
|
||||
@@ -965,6 +1011,8 @@ function copyToClipboard(text) {
|
||||
export {
|
||||
getFileIcon,
|
||||
safeCreateIcons,
|
||||
ensureLucide,
|
||||
ensureHighlight,
|
||||
flushIcons,
|
||||
safeHighlight,
|
||||
escapeHtml,
|
||||
|
||||
+75
-20
@@ -7,15 +7,10 @@ import { TabManager, closeMobileSidebar, ContextMenuManager, RightSidebarManager
|
||||
import { syncActiveFileTreeItem, searchByTag, TagFilterService, refreshSidebarTreePreservingState, focusPathInSidebar } from './sidebar.js';
|
||||
import { AutocompleteDropdown, performAdvancedSearch } from './search.js';
|
||||
import { initDashboardTabs } from './sync.js';
|
||||
import { renderMermaidBlocks } from './mermaid-viewer.js';
|
||||
import { renderExcalidraw } from './excalidraw-viewer.js';
|
||||
import { DashboardStatsWidget, DashboardRecentWidget, DashboardBookmarkWidget, DashboardSharedWidget, DashboardConflictsWidget } from './dashboard.js';
|
||||
import { DashboardStatsWidget, DashboardRecentWidget, DashboardBookmarkWidget, DashboardSharedWidget, DashboardConflictsWidget, DashboardHomeWidget } from './dashboard.js';
|
||||
import { openShareDialog } from './config.js';
|
||||
import { cacheViewedFile, getCachedFile } from './offline.js';
|
||||
import { t, getLocale } from './i18n.js';
|
||||
import { onFileRender } from './plugins.js';
|
||||
import { NowPlaying } from './now-playing.js';
|
||||
import { toggleFileChat, followFileChat } from './filechat.js';
|
||||
import { parseRef, columnName, findTd, invalidateCellIndex, sheetOfRef, firstCellOfRange } from './xlsx/refs.js';
|
||||
import { createColourPicker } from './xlsx/color-picker.js';
|
||||
import { buildCommandBar } from './xlsx/command-bar.js';
|
||||
@@ -27,6 +22,13 @@ import {
|
||||
colToIndex, indexToCol,
|
||||
} from './xlsx/formula.js';
|
||||
|
||||
// #243 : modules lourds chargés à la première utilisation (le graphe
|
||||
// statique initial ne les contient plus) : mermaid, excalidraw, plugins,
|
||||
// now-playing (média), filechat.
|
||||
function _withNowPlaying(fn) {
|
||||
import('./now-playing.js').then((m) => { try { fn(m.NowPlaying); } catch (e) {} }).catch(() => {});
|
||||
}
|
||||
|
||||
// ── Multi-format export ────────────────────────────────────────────────────
|
||||
// Downloads a file export (HTML / MD bundle / ePub) via the authenticated
|
||||
// export endpoints, showing a loading toast while the request is in flight.
|
||||
@@ -1135,16 +1137,15 @@ export function renderImageViewer(area, data) {
|
||||
// between this inline view and a body-level dock, so playback survives tab,
|
||||
// pane and page navigation. The inline branches below just hand over the
|
||||
// surface; the legacy "stop on re-render" cleanup no longer applies.
|
||||
export { formatMediaDuration, buildMediaUrl, renderFallback as renderMediaFallback } from "./now-playing.js";
|
||||
|
||||
/** Audio viewer (roadmap #109-B, made persistent by #110). */
|
||||
export function renderAudioViewer(area, data) {
|
||||
NowPlaying.attachInline(area, data);
|
||||
_withNowPlaying((np) => np.attachInline(area, data));
|
||||
}
|
||||
|
||||
/** Video viewer (roadmap #109-C, made persistent by #110). */
|
||||
export function renderVideoViewer(area, data) {
|
||||
NowPlaying.attachInline(area, data);
|
||||
_withNowPlaying((np) => np.attachInline(area, data));
|
||||
}
|
||||
|
||||
|
||||
@@ -6951,7 +6952,7 @@ export function renderFile(data) {
|
||||
// instead of being wiped mid-session by a tab switch / sidebar click.
|
||||
if (isInlineEditorActive()) detachInlineEditor();
|
||||
// #190 A — an open chat panel follows the document being rendered.
|
||||
followFileChat(data.vault, data.path, data.title);
|
||||
import('./filechat.js').then((m) => m.followFileChat(data.vault, data.path, data.title)).catch(() => {}); // #243
|
||||
// #108 — release the image viewer's document-level shortcuts before swapping
|
||||
// the content area (otherwise they leak on every re-render).
|
||||
if (_imageViewerCleanup) { _imageViewerCleanup(); _imageViewerCleanup = null; }
|
||||
@@ -6965,7 +6966,7 @@ export function renderFile(data) {
|
||||
const area = getContentArea();
|
||||
// #110 — if this render is about to replace the surface that currently hosts
|
||||
// the shared media element, hand it back to the persistent dock first.
|
||||
NowPlaying.handleRender(area, data);
|
||||
_withNowPlaying((np) => np.handleRender(area, data));
|
||||
|
||||
// Handle PDF files — render in iframe with TOC sidebar
|
||||
if (data.is_pdf) {
|
||||
@@ -7029,7 +7030,7 @@ export function renderFile(data) {
|
||||
|
||||
// Handle Excalidraw — render in iframe editor
|
||||
if (data.is_excalidraw) {
|
||||
renderExcalidraw(area, data, data.vault, data.path);
|
||||
import('./excalidraw-viewer.js').then((m) => m.renderExcalidraw(area, data, data.vault, data.path)).catch(() => {}); // #243
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -7257,7 +7258,7 @@ export function renderFile(data) {
|
||||
// #169 — Chat intégré par fichier (panneau latéral)
|
||||
const chatBtn = el("button", { class: "btn-action btn-chat", title: t("chat.button_title") }, [icon("message-square", 14), document.createTextNode(t("chat.button"))]);
|
||||
chatBtn.addEventListener("click", () => {
|
||||
toggleFileChat(data.vault, data.path, data.title);
|
||||
import('./filechat.js').then((m) => m.toggleFileChat(data.vault, data.path, data.title)).catch(() => {}); // #243
|
||||
});
|
||||
// Check bookmark status and color the button
|
||||
(async () => {
|
||||
@@ -7419,7 +7420,7 @@ export function renderFile(data) {
|
||||
});
|
||||
|
||||
// Render Mermaid diagrams
|
||||
renderMermaidBlocks(area);
|
||||
import('./mermaid-viewer.js').then((m) => m.renderMermaidBlocks(area)).catch(() => {}); // #243
|
||||
|
||||
// Wire up wikilinks
|
||||
area.querySelectorAll(".wikilink").forEach((link) => {
|
||||
@@ -7458,7 +7459,7 @@ export function renderFile(data) {
|
||||
// content or append custom widgets beneath it. Async + non-blocking so a
|
||||
// slow/failed plugin never delays the normal file render.
|
||||
if (data.content && data.is_markdown) {
|
||||
onFileRender(data.vault, data.content, data.path).then((fr) => {
|
||||
import('./plugins.js').then((m) => m.onFileRender(data.vault, data.content, data.path)).then((fr) => { // #243
|
||||
if (!fr) return;
|
||||
if (typeof fr.replace === 'string' && fr.replace !== data.content) {
|
||||
const rendered = document.getElementById('file-rendered-content');
|
||||
@@ -7752,7 +7753,7 @@ export function showWelcome() {
|
||||
// Restore or rebuild the dashboard with tabbed sections
|
||||
const area = getContentArea();
|
||||
// #110 — keep playing media alive if the dashboard replaces its surface.
|
||||
NowPlaying.handleRender(area, null);
|
||||
_withNowPlaying((np) => np.handleRender(area, null));
|
||||
const home = document.getElementById("dashboard-home");
|
||||
|
||||
if (area && !home) {
|
||||
@@ -7760,7 +7761,10 @@ export function showWelcome() {
|
||||
<div id="dashboard-home" class="dashboard-home" role="region" aria-label="Tableau de bord">
|
||||
<!-- Dashboard Tabs -->
|
||||
<div class="dashboard-tabs">
|
||||
<button class="dashboard-tab active" data-tab="stats" data-i18n="dashboard.stats">
|
||||
<button class="dashboard-tab active" data-tab="home" data-i18n="dashboard.home_tab">
|
||||
<i data-lucide="home" style="width:14px;height:14px"></i> ${t('dashboard.home_tab')}
|
||||
</button>
|
||||
<button class="dashboard-tab" data-tab="stats" data-i18n="dashboard.stats">
|
||||
<i data-lucide="bar-chart-3" style="width:14px;height:14px"></i> ${t('dashboard.stats')}
|
||||
</button>
|
||||
<button class="dashboard-tab" data-tab="bookmarks" data-i18n="dashboard.bookmarks">
|
||||
@@ -7774,8 +7778,56 @@ export function showWelcome() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- Home Panel — Accueil « Reprendre » (#247-#249) -->
|
||||
<div id="dashboard-panel-home" class="dashboard-panel active">
|
||||
<div id="home-stats-strip" class="home-stats-strip"></div>
|
||||
<div class="home-hero">
|
||||
<input id="home-search-input" class="home-search-input" type="text" placeholder="${t('dashboard.home_search_placeholder')}" />
|
||||
<div class="home-actions">
|
||||
<button id="home-action-new" class="home-action-btn"><i data-lucide="file-plus-2" style="width:14px;height:14px"></i> ${t('dashboard.home_new_file')}</button>
|
||||
<button id="home-action-upload" class="home-action-btn"><i data-lucide="upload" style="width:14px;height:14px"></i> ${t('dashboard.home_upload')}</button>
|
||||
<button id="home-action-palette" class="home-action-btn"><i data-lucide="layout-grid" style="width:14px;height:14px"></i> ${t('dashboard.home_palette')}</button>
|
||||
</div>
|
||||
</div>
|
||||
<section id="home-section-todo" data-home-panel="todo" class="home-section" style="display:none">
|
||||
<h2 class="home-section-title"><i data-lucide="bell-ring" style="width:16px;height:16px"></i> ${t('dashboard.home_todo')}</h2>
|
||||
<div id="home-conflicts-container"></div>
|
||||
<div id="home-todo-list"></div>
|
||||
</section>
|
||||
<section id="home-section-resume" data-home-panel="resume" class="home-section">
|
||||
<h2 class="home-section-title"><i data-lucide="history" style="width:16px;height:16px"></i> ${t('dashboard.home_resume')}</h2>
|
||||
<div id="home-resume-grid" class="dashboard-recent-grid"></div>
|
||||
<div id="home-resume-empty" class="dashboard-recent-empty" style="display:none"><span>${t('dashboard.home_no_resume')}</span></div>
|
||||
</section>
|
||||
<section id="home-section-vaults" data-home-panel="vaults" class="home-section">
|
||||
<h2 class="home-section-title"><i data-lucide="folder-open" style="width:16px;height:16px"></i> ${t('dashboard.home_vaults')}</h2>
|
||||
<div id="home-vaults-grid" class="home-vaults-grid"></div>
|
||||
</section>
|
||||
<section id="home-section-searches" data-home-panel="searches" class="home-section">
|
||||
<h2 class="home-section-title"><i data-lucide="search" style="width:16px;height:16px"></i> ${t('dashboard.home_saved_searches')}</h2>
|
||||
<div id="home-searches-list" class="home-searches-list"></div>
|
||||
<div id="home-searches-empty" class="dashboard-recent-empty" style="display:none"><span>${t('dashboard.home_no_saved_searches')}</span></div>
|
||||
</section>
|
||||
<section id="home-section-help" data-home-panel="help" class="home-section">
|
||||
<h2 class="home-section-title"><i data-lucide="keyboard" style="width:16px;height:16px"></i> ${t('help.shortcuts_title')}</h2>
|
||||
<div class="qh-row"><span class="qh-kbd">Ctrl+Shift+Space</span> <span>${t('dashboard.home_sc_palette')}</span></div>
|
||||
<div class="qh-row"><span class="qh-kbd">Ctrl+K</span> <span>${t('dashboard.home_sc_search')}</span></div>
|
||||
<div class="qh-row"><span class="qh-kbd">Ctrl+S</span> <span>${t('dashboard.home_sc_save')}</span></div>
|
||||
<div class="qh-row"><span class="qh-kbd">Esc</span> <span>${t('dashboard.home_sc_close')}</span></div>
|
||||
</section>
|
||||
<details class="home-customize">
|
||||
<summary>${t('dashboard.home_customize')}</summary>
|
||||
<label><input type="checkbox" data-home-toggle="resume" checked /> ${t('dashboard.home_resume')}</label>
|
||||
<label><input type="checkbox" data-home-toggle="todo" checked /> ${t('dashboard.home_todo')}</label>
|
||||
<label><input type="checkbox" data-home-toggle="vaults" checked /> ${t('dashboard.home_vaults')}</label>
|
||||
<label><input type="checkbox" data-home-toggle="searches" checked /> ${t('dashboard.home_saved_searches')}</label>
|
||||
<label><input type="checkbox" data-home-toggle="help" checked /> ${t('help.shortcuts_title')}</label>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<!-- Stats Panel -->
|
||||
<div id="dashboard-panel-stats" class="dashboard-panel active">
|
||||
<div id="dashboard-panel-stats" class="dashboard-panel">
|
||||
<div id="dashboard-stats-grid" class="dashboard-stats-grid">
|
||||
<div class="dashboard-stats-loading" data-i18n="common.loading">${t('common.loading')}</div>
|
||||
</div>
|
||||
@@ -7835,13 +7887,16 @@ export function showWelcome() {
|
||||
// Reset tabs to default
|
||||
document.querySelectorAll(".dashboard-tab").forEach(t => t.classList.remove("active"));
|
||||
document.querySelectorAll(".dashboard-panel").forEach(p => p.classList.remove("active"));
|
||||
const defaultTab = document.querySelector('.dashboard-tab[data-tab="stats"]');
|
||||
const defaultPanel = document.getElementById("dashboard-panel-stats");
|
||||
const defaultTab = document.querySelector('.dashboard-tab[data-tab="home"]');
|
||||
const defaultPanel = document.getElementById("dashboard-panel-home");
|
||||
if (defaultTab) defaultTab.classList.add("active");
|
||||
if (defaultPanel) defaultPanel.classList.add("active");
|
||||
}
|
||||
|
||||
// Load all widgets (they handle missing elements gracefully)
|
||||
if (typeof DashboardHomeWidget !== "undefined") {
|
||||
DashboardHomeWidget.load();
|
||||
}
|
||||
if (typeof DashboardStatsWidget !== "undefined") {
|
||||
DashboardStatsWidget.load();
|
||||
}
|
||||
|
||||
@@ -601,6 +601,24 @@
|
||||
"dashboard.size_gb": " GB",
|
||||
"dashboard.size_kb": " KB",
|
||||
"dashboard.size_mb": " MB",
|
||||
"dashboard.home_tab": "Home",
|
||||
"dashboard.home_resume": "Resume",
|
||||
"dashboard.home_todo": "Needs attention",
|
||||
"dashboard.home_vaults": "My vaults",
|
||||
"dashboard.home_search_placeholder": "Search your vaults…",
|
||||
"dashboard.home_new_file": "New file",
|
||||
"dashboard.home_upload": "Upload",
|
||||
"dashboard.home_palette": "File palette",
|
||||
"dashboard.home_saved_searches": "Saved searches",
|
||||
"dashboard.home_no_saved_searches": "No saved searches",
|
||||
"dashboard.home_customize": "Customize",
|
||||
"dashboard.home_no_resume": "Nothing to resume yet",
|
||||
"dashboard.home_received_unopened": "Received share not opened yet",
|
||||
"dashboard.home_expiring_soon": "Share expiring soon",
|
||||
"dashboard.home_sc_palette": "File palette (quick nav)",
|
||||
"dashboard.home_sc_search": "Focus the search bar",
|
||||
"dashboard.home_sc_save": "Save the open file",
|
||||
"dashboard.home_sc_close": "Close the editor / modal",
|
||||
"dashboard.stats": "Statistics",
|
||||
"dashboard.stats_files": "Files",
|
||||
"dashboard.stats_size": "Total size",
|
||||
|
||||
@@ -601,6 +601,24 @@
|
||||
"dashboard.size_gb": " Go",
|
||||
"dashboard.size_kb": " Ko",
|
||||
"dashboard.size_mb": " Mo",
|
||||
"dashboard.home_tab": "Accueil",
|
||||
"dashboard.home_resume": "Reprendre",
|
||||
"dashboard.home_todo": "À traiter",
|
||||
"dashboard.home_vaults": "Mes vaults",
|
||||
"dashboard.home_search_placeholder": "Rechercher dans vos vaults…",
|
||||
"dashboard.home_new_file": "Nouveau fichier",
|
||||
"dashboard.home_upload": "Téléverser",
|
||||
"dashboard.home_palette": "Palette de fichiers",
|
||||
"dashboard.home_saved_searches": "Recherches sauvées",
|
||||
"dashboard.home_no_saved_searches": "Aucune recherche sauvée",
|
||||
"dashboard.home_customize": "Personnaliser",
|
||||
"dashboard.home_no_resume": "Rien à reprendre pour le moment",
|
||||
"dashboard.home_received_unopened": "Partage reçu non ouvert",
|
||||
"dashboard.home_expiring_soon": "Partage qui expire bientôt",
|
||||
"dashboard.home_sc_palette": "Palette de fichiers (nav. rapide)",
|
||||
"dashboard.home_sc_search": "Focus barre de recherche",
|
||||
"dashboard.home_sc_save": "Sauvegarder le fichier ouvert",
|
||||
"dashboard.home_sc_close": "Fermer l'éditeur / modale",
|
||||
"dashboard.stats": "Statistiques",
|
||||
"dashboard.stats_files": "Fichiers",
|
||||
"dashboard.stats_size": "Taille totale",
|
||||
|
||||
@@ -13676,3 +13676,56 @@ body.has-draco-bar .app-container { height: calc(100vh - 60px); }
|
||||
.banniere-hub-texte { flex: 1; overflow-wrap: anywhere; }
|
||||
.banniere-hub-fermer { flex: none; background: transparent; border: none; color: inherit; font-size: 15px; line-height: 1; padding: 4px 6px; cursor: pointer; border-radius: 6px; }
|
||||
.banniere-hub-fermer:hover { background: rgba(255, 255, 255, 0.18); }
|
||||
|
||||
/* ── Accueil « Reprendre » (#247-#249) ─────────────────────────────── */
|
||||
.home-stats-strip {
|
||||
display: flex; flex-wrap: wrap; gap: 8px 20px; align-items: center;
|
||||
padding: 10px 14px; margin-bottom: 14px;
|
||||
background: var(--bg-secondary, var(--surface)); border: 1px solid var(--border);
|
||||
border-radius: 10px; color: var(--text-muted); font-size: 0.85rem;
|
||||
}
|
||||
.home-stats-strip span { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.home-stats-strip svg { width: 14px; height: 14px; }
|
||||
.home-hero { margin-bottom: 18px; }
|
||||
.home-search-input {
|
||||
width: 100%; box-sizing: border-box; padding: 12px 16px; font-size: 1rem;
|
||||
background: var(--bg-secondary, var(--surface)); color: var(--text);
|
||||
border: 1px solid var(--border); border-radius: 10px;
|
||||
}
|
||||
.home-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
|
||||
.home-action-btn {
|
||||
display: inline-flex; align-items: center; gap: 6px; padding: 8px 14px;
|
||||
background: var(--bg-secondary, var(--surface)); color: var(--text);
|
||||
border: 1px solid var(--border); border-radius: 8px; cursor: pointer;
|
||||
}
|
||||
.home-action-btn:hover { border-color: var(--accent); }
|
||||
.home-section { margin-bottom: 22px; }
|
||||
.home-section-title {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
font-size: 1rem; margin: 0 0 10px 0; color: var(--text);
|
||||
}
|
||||
.home-vaults-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; }
|
||||
.home-vault-card {
|
||||
display: flex; flex-direction: column; align-items: flex-start; gap: 4px;
|
||||
padding: 12px 14px; text-align: left; cursor: pointer;
|
||||
background: var(--bg-secondary, var(--surface)); color: var(--text);
|
||||
border: 1px solid var(--border); border-radius: 10px;
|
||||
}
|
||||
.home-vault-card:hover { border-color: var(--accent); }
|
||||
.home-vault-name { font-weight: 600; }
|
||||
.home-vault-meta { color: var(--text-muted); font-size: 0.8rem; }
|
||||
.home-todo-item {
|
||||
display: flex; align-items: center; gap: 10px; padding: 8px 12px; margin-bottom: 8px;
|
||||
background: var(--bg-secondary, var(--surface)); border: 1px solid var(--border); border-radius: 8px;
|
||||
}
|
||||
.home-todo-label { color: var(--accent-orange, var(--accent)); font-size: 0.8rem; }
|
||||
.home-todo-name { font-weight: 600; }
|
||||
.home-todo-vault { color: var(--text-muted); font-size: 0.8rem; margin-right: auto; }
|
||||
.home-searches-list { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.home-search-item {
|
||||
display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; cursor: pointer;
|
||||
background: var(--bg-secondary, var(--surface)); color: var(--text);
|
||||
border: 1px solid var(--border); border-radius: 999px;
|
||||
}
|
||||
.home-customize { color: var(--text-muted); font-size: 0.85rem; }
|
||||
.home-customize label { display: inline-flex; align-items: center; gap: 5px; margin: 6px 14px 0 0; cursor: pointer; }
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
* cache or Cloudflare does NOT clear the Service Worker Cache Storage, which is
|
||||
* a separate store. Bumping SW_VERSION invalidates it on every release.
|
||||
*/
|
||||
const SW_VERSION = 'v29';
|
||||
const SW_VERSION = '__OBSIGATE_SW_VERSION__'; // remplacé au service par le backend (#242) ; repli statique : 'dev'
|
||||
const CODE_CACHE = `obsigate-code-${SW_VERSION}`;
|
||||
const RUNTIME_CACHE = `obsigate-runtime-${SW_VERSION}`;
|
||||
const API_CACHE = `obsigate-api-${SW_VERSION}`;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "obsigate",
|
||||
"version": "2.97.0",
|
||||
"version": "2.99.0",
|
||||
"description": "**Porte d'entrée web ultra-léger pour vos vaults Obsidian** — Accédez, naviguez et recherchez dans toutes vos notes Obsidian depuis n'importe quel appareil via une interface web moderne et responsive.",
|
||||
"main": "patch.js",
|
||||
"directories": {
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Audit de chargement d'ObsiGate (#241, épopée perf #240).
|
||||
|
||||
Mesure, sans dépendance externe (stdlib seule) :
|
||||
|
||||
- en mode distant (défaut) : TTFB et temps total médians de ``/``,
|
||||
``/sso/login`` et des statiques clés, plus les en-têtes de cache
|
||||
(``Cache-Control``, ``cf-cache-status``, ``ETag``) ;
|
||||
- en mode ``--local`` : la baseline calculée depuis les fichiers du
|
||||
dépôt — graphe des modules ES **statiques** atteint depuis
|
||||
``frontend/js/app.js`` (nombre de modules + octets bruts, plus gros
|
||||
modules), taille de ``index.html`` / ``style.css`` et des statiques
|
||||
référencées par ``index.html``.
|
||||
|
||||
Le graphe local ne suit que les imports statiques (``import … from``,
|
||||
``export … from``, ``import '…'``) : un module chargé par ``import()``
|
||||
dynamique n'y compte pas — c'est exactement ce que le lot #243 cherche
|
||||
à réduire.
|
||||
|
||||
Usage :
|
||||
python3 scripts/audit_chargement.py [--base-url https://og.dracodev.net]
|
||||
python3 scripts/audit_chargement.py --local [RACINE_DU_DEPOT]
|
||||
python3 scripts/audit_chargement.py --local --json sortie.json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Graphe de modules ES (mode local)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_STATIC_IMPORT_RE = re.compile(
|
||||
r"(?:^|[\n;])\s*(?:import\s+(?!\(\s*['\"])(?:[^'\"]*?\sfrom\s+)?|export\s+[^'\"]*?\sfrom\s+)['\"]([^'\"]+)['\"]"
|
||||
)
|
||||
|
||||
|
||||
def static_imports(source: str) -> list[str]:
|
||||
"""Spécificateurs relatifs importés statiquement par un module ES."""
|
||||
return [m.group(1) for m in _STATIC_IMPORT_RE.finditer(source)
|
||||
if m.group(1).startswith(".")]
|
||||
|
||||
|
||||
def resolve_spec(importer: Path, spec: str, root: Path) -> Path:
|
||||
"""Résoudre un spécificateur relatif par rapport à son importeur."""
|
||||
return (importer.parent / spec).resolve()
|
||||
|
||||
|
||||
def local_module_graph(frontend_dir: Path) -> dict:
|
||||
"""Graphe statique depuis ``js/app.js`` : compte + octets bruts."""
|
||||
entry = frontend_dir / "js" / "app.js"
|
||||
seen: dict[str, int] = {}
|
||||
queue: list[Path] = [entry]
|
||||
while queue:
|
||||
module = queue.pop()
|
||||
try:
|
||||
key = str(module.relative_to(frontend_dir))
|
||||
except ValueError:
|
||||
continue
|
||||
if key in seen or not module.is_file():
|
||||
continue
|
||||
source = module.read_text(encoding="utf-8", errors="replace")
|
||||
seen[key] = len(source.encode("utf-8"))
|
||||
for spec in static_imports(source):
|
||||
target = resolve_spec(module, spec, frontend_dir)
|
||||
if target.suffix == ".js":
|
||||
queue.append(target)
|
||||
top = sorted(seen.items(), key=lambda kv: -kv[1])[:10]
|
||||
return {
|
||||
"entry": "js/app.js",
|
||||
"module_count": len(seen),
|
||||
"raw_bytes": sum(seen.values()),
|
||||
"top_modules": [{"module": k, "bytes": v} for k, v in top],
|
||||
"modules": seen,
|
||||
}
|
||||
|
||||
|
||||
_STATIC_REF_RE = re.compile(r"(?:src|href)=\"(/static/[^\"]+)\"")
|
||||
_CDN_REF_RE = re.compile(
|
||||
r"(?:src|href)=\"(https://(?:cdnjs\.cloudflare\.com|unpkg\.com|cdn\.jsdelivr\.net)/[^\" ]+)\"")
|
||||
|
||||
|
||||
def local_baseline(repo_root: Path) -> dict:
|
||||
"""Baseline locale : graphe ES + poids des fichiers de la page."""
|
||||
frontend = repo_root / "frontend"
|
||||
index_html = (frontend / "index.html").read_text(encoding="utf-8", errors="replace")
|
||||
refs: dict[str, int] = {}
|
||||
for ref in _STATIC_REF_RE.findall(index_html):
|
||||
path = frontend / ref.removeprefix("/static/")
|
||||
if path.is_file():
|
||||
refs[ref] = path.stat().st_size
|
||||
return {
|
||||
"mode": "local",
|
||||
"index_html_bytes": (frontend / "index.html").stat().st_size,
|
||||
"style_css_bytes": (frontend / "style.css").stat().st_size,
|
||||
"module_graph": local_module_graph(frontend),
|
||||
"index_static_refs": refs,
|
||||
"index_static_refs_bytes": sum(refs.values()),
|
||||
"index_cdn_refs": sorted(set(_CDN_REF_RE.findall(index_html))),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Mesures distantes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def measure_once(url: str) -> dict:
|
||||
"""Une mesure : TTFB (en-têtes reçus) et temps total (corps lu)."""
|
||||
parsed = urlparse(url)
|
||||
conn_cls = (http.client.HTTPSConnection if parsed.scheme == "https"
|
||||
else http.client.HTTPConnection)
|
||||
conn = conn_cls(parsed.netloc, timeout=30)
|
||||
path = parsed.path or "/"
|
||||
if parsed.query:
|
||||
path += "?" + parsed.query
|
||||
start = time.perf_counter()
|
||||
conn.request("GET", path, headers={"Accept-Encoding": "identity"})
|
||||
response = conn.getresponse()
|
||||
ttfb = time.perf_counter() - start
|
||||
body = response.read()
|
||||
total = time.perf_counter() - start
|
||||
headers = {k.lower(): v for k, v in response.getheaders()}
|
||||
conn.close()
|
||||
return {
|
||||
"status": response.status,
|
||||
"ttfb_s": round(ttfb, 3),
|
||||
"total_s": round(total, 3),
|
||||
"bytes": len(body),
|
||||
"cache_control": headers.get("cache-control"),
|
||||
"cf_cache_status": headers.get("cf-cache-status"),
|
||||
"etag": headers.get("etag"),
|
||||
}
|
||||
|
||||
|
||||
def measure(url: str, runs: int = 3) -> dict:
|
||||
"""Médianes de ``runs`` mesures d'une URL."""
|
||||
samples = [measure_once(url) for _ in range(runs)]
|
||||
return {
|
||||
"url": url,
|
||||
"runs": runs,
|
||||
"status": samples[0]["status"],
|
||||
"ttfb_median_s": statistics.median(s["ttfb_s"] for s in samples),
|
||||
"total_median_s": statistics.median(s["total_s"] for s in samples),
|
||||
"bytes": samples[0]["bytes"],
|
||||
"cache_control": samples[0]["cache_control"],
|
||||
"cf_cache_status": samples[0]["cf_cache_status"],
|
||||
"etag": samples[0]["etag"],
|
||||
"samples": samples,
|
||||
}
|
||||
|
||||
|
||||
DEFAULT_PATHS = ["/", "/sso/login", "/static/style.css", "/static/js/app.js", "/sw.js"]
|
||||
|
||||
|
||||
def remote_audit(base_url: str, runs: int = 3) -> dict:
|
||||
base = base_url.rstrip("/")
|
||||
return {
|
||||
"mode": "remote",
|
||||
"base_url": base,
|
||||
"paths": {p: measure(base + p, runs) for p in DEFAULT_PATHS},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _print_local(report: dict) -> None:
|
||||
graph = report["module_graph"]
|
||||
print("=== Audit chargement ObsiGate — baseline locale ===")
|
||||
print(f"index.html : {report['index_html_bytes']} o")
|
||||
print(f"style.css : {report['style_css_bytes']} o")
|
||||
print(f"Graphe ES statique depuis {graph['entry']} : "
|
||||
f"{graph['module_count']} modules, {graph['raw_bytes']} o bruts")
|
||||
for item in graph["top_modules"][:5]:
|
||||
print(f" {item['bytes']:>8} {item['module']}")
|
||||
print(f"Statiques référencées par index.html : "
|
||||
f"{len(report['index_static_refs'])} fichiers, "
|
||||
f"{report['index_static_refs_bytes']} o")
|
||||
print(f"CDN référencées : {len(report['index_cdn_refs'])}")
|
||||
for cdn in report["index_cdn_refs"]:
|
||||
print(f" {cdn}")
|
||||
|
||||
|
||||
def _print_remote(report: dict) -> None:
|
||||
print(f"=== Audit chargement ObsiGate — {report['base_url']} ===")
|
||||
for path, m in report["paths"].items():
|
||||
print(f"{path:<24} TTFB médian {m['ttfb_median_s']:.3f} s | "
|
||||
f"total {m['total_median_s']:.3f} s | {m['bytes']} o | "
|
||||
f"cache: {m['cache_control']} | cf: {m['cf_cache_status']}")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="https://og.dracodev.net",
|
||||
help="URL de base à mesurer (mode distant)")
|
||||
parser.add_argument("--local", nargs="?", const=".", default=None,
|
||||
metavar="RACINE", help="Baseline depuis les fichiers du dépôt")
|
||||
parser.add_argument("--runs", type=int, default=3, help="Mesures par URL (défaut 3)")
|
||||
parser.add_argument("--json", metavar="FICHIER", help="Écrire le rapport JSON")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.local is not None:
|
||||
report = local_baseline(Path(args.local).resolve())
|
||||
_print_local(report)
|
||||
else:
|
||||
report = remote_audit(args.base_url, args.runs)
|
||||
_print_remote(report)
|
||||
|
||||
if args.json:
|
||||
Path(args.json).write_text(json.dumps(report, indent=2), encoding="utf-8")
|
||||
print(f"JSON écrit : {args.json}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -48,12 +48,16 @@ test.describe('Dashboard & Navigation', () => {
|
||||
|
||||
test('should show Quick Help section', async ({ page }) => {
|
||||
await goHome(page);
|
||||
// Depuis #247, l'onglet par défaut est Accueil ; l'aide rapide vit dans
|
||||
// le panneau Statistiques, il faut donc l'ouvrir explicitement.
|
||||
await page.locator('.dashboard-tab[data-tab="stats"]').click();
|
||||
await expect(page.locator('#quick-help')).toBeVisible();
|
||||
await expect(page.locator('#quick-help .qh-header')).toContainText('Raccourcis');
|
||||
});
|
||||
|
||||
test('should toggle Quick Help collapsed state', async ({ page }) => {
|
||||
await goHome(page);
|
||||
await page.locator('.dashboard-tab[data-tab="stats"]').click();
|
||||
// Wait for JS to initialize
|
||||
await page.waitForTimeout(500);
|
||||
const toggle = page.locator('#qh-toggle');
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Bootstrap rapide des liens profonds (#244, épopée perf #240).
|
||||
*
|
||||
* Vérifie la structure de `init()` dans app.js : un lien `#file=` est
|
||||
* ouvert AVANT le `Promise.all(loadVaultSettings, loadVaults,
|
||||
* loadTags)`, et la suite du démarrage ne recouvre pas la cible
|
||||
* (garde `fichierOuvert`). `#folder=` reste après le chargement
|
||||
* (l'arborescence doit exister pour `focusPathInSidebar`).
|
||||
*
|
||||
* Usage: node tests/frontend/bootstrap-244.test.mjs
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const app = readFileSync(join(here, '../../frontend/js/app.js'), 'utf8');
|
||||
|
||||
let passed = 0;
|
||||
function check(name, cond) {
|
||||
if (!cond) {
|
||||
console.error(`✗ ${name}`);
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
console.log(`✓ ${name}`);
|
||||
passed++;
|
||||
}
|
||||
}
|
||||
|
||||
const idxOpen = app.indexOf('Viewer.openFile(vault, path)');
|
||||
const idxAll = app.indexOf('Promise.all([Legacy.loadVaultSettings(), Sidebar.loadVaults(), Sidebar.loadTags()])');
|
||||
const idxFolder = app.indexOf('focusPathInSidebar(vault, path');
|
||||
|
||||
check('#file= ouvert dans app.js', idxOpen !== -1);
|
||||
check('chargement complet présent', idxAll !== -1);
|
||||
check('#file= ouvert AVANT le chargement complet (#244)', idxOpen !== -1 && idxAll !== -1 && idxOpen < idxAll);
|
||||
check('garde fichierOuvert contre le recouvrement par l\'accueil', app.includes('fichierOuvert'));
|
||||
check('#folder= toujours après le chargement complet', idxFolder !== -1 && idxAll !== -1 && idxFolder > idxAll);
|
||||
|
||||
console.log(`\n${passed} checks passed`);
|
||||
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Accueil « Reprendre » (#247-#249) — structure et branchements.
|
||||
*
|
||||
* Vérifie, sur le DOM réel d'index.html (JSDOM) et les sources :
|
||||
* - l'onglet Accueil existe, premier et actif par défaut ; les onglets
|
||||
* Statistiques / Bookmarks / Récents / Partagés sont toujours là ;
|
||||
* - le panneau Accueil porte toutes les sections (#247 bandeau +
|
||||
* recherche héros + actions, Reprendre ; #248 À traiter ; #249
|
||||
* vaults, recherches sauvées, raccourcis, personnalisation) ;
|
||||
* - le widget DashboardHomeWidget est exporté, chargé par
|
||||
* showWelcome, et branché sur les API existantes ;
|
||||
* - le gabarit de showWelcome (viewer.js) reconstruit le même accueil.
|
||||
*
|
||||
* Usage: node tests/frontend/dashboard-home.test.mjs
|
||||
*/
|
||||
|
||||
import { strict as assert } from "node:assert";
|
||||
import { JSDOM } from "jsdom";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(__dirname, "..", "..");
|
||||
const read = (rel) => readFileSync(path.join(ROOT, rel), "utf8");
|
||||
|
||||
let passed = 0;
|
||||
function test(name, fn) {
|
||||
try { fn(); console.log(` ✓ ${name}`); passed++; }
|
||||
catch (e) { console.error(` ✗ ${name}\n ${e.message}`); process.exitCode = 1; }
|
||||
}
|
||||
|
||||
const indexHtml = read("frontend/index.html");
|
||||
const dom = new JSDOM(indexHtml, { url: "http://localhost/" });
|
||||
const doc = dom.window.document;
|
||||
|
||||
test("onglet Accueil premier et actif par défaut", () => {
|
||||
const tabs = [...doc.querySelectorAll(".dashboard-tab")];
|
||||
assert.ok(tabs.length >= 5, "au moins 5 onglets");
|
||||
assert.equal(tabs[0].dataset.tab, "home");
|
||||
assert.ok(tabs[0].classList.contains("active"));
|
||||
const names = tabs.map((t) => t.dataset.tab);
|
||||
for (const kept of ["stats", "bookmarks", "recent", "shared"]) {
|
||||
assert.ok(names.includes(kept), `onglet ${kept} conservé`);
|
||||
}
|
||||
const statsTab = tabs.find((t) => t.dataset.tab === "stats");
|
||||
assert.ok(!statsTab.classList.contains("active"), "stats n'est plus l'onglet actif");
|
||||
});
|
||||
|
||||
test("panneau Accueil actif, statistiques conservé mais inactif", () => {
|
||||
const home = doc.getElementById("dashboard-panel-home");
|
||||
assert.ok(home && home.classList.contains("active"));
|
||||
const stats = doc.getElementById("dashboard-panel-stats");
|
||||
assert.ok(stats && !stats.classList.contains("active"));
|
||||
assert.ok(doc.getElementById("dashboard-stats-grid"), "grille stats intacte");
|
||||
assert.ok(doc.getElementById("quick-help"), "raccourcis de la vue stats intacts");
|
||||
});
|
||||
|
||||
test("sections de l'Accueil présentes (#247-#249)", () => {
|
||||
for (const id of [
|
||||
"home-stats-strip", "home-search-input",
|
||||
"home-action-new", "home-action-upload", "home-action-palette",
|
||||
"home-section-todo", "home-conflicts-container", "home-todo-list",
|
||||
"home-section-resume", "home-resume-grid",
|
||||
"home-section-vaults", "home-vaults-grid",
|
||||
"home-section-searches", "home-searches-list",
|
||||
"home-section-help",
|
||||
]) {
|
||||
assert.ok(doc.getElementById(id), `#${id} présent`);
|
||||
}
|
||||
assert.ok(doc.querySelectorAll("[data-home-toggle]").length >= 5, "personnalisation présente");
|
||||
});
|
||||
|
||||
const dashboard = read("frontend/js/dashboard.js");
|
||||
|
||||
test("DashboardHomeWidget exporté et branché sur les API existantes", () => {
|
||||
assert.match(dashboard, /DashboardHomeWidget/);
|
||||
assert.match(dashboard, /export \{[^}]*DashboardHomeWidget/);
|
||||
for (const endpoint of ["/api/dashboard", "/api/recent?mode=opened", "/api/bookmarks", "/api/conflicts", "/api/shares", "/api/saved-searches"]) {
|
||||
assert.ok(dashboard.includes(endpoint), `endpoint ${endpoint}`);
|
||||
}
|
||||
assert.match(dashboard, /DashboardConflictsWidget\.render\(data\.conflicts/);
|
||||
assert.match(dashboard, /TabManager\.openNav\(v\.name\)/);
|
||||
assert.match(dashboard, /localStorage/);
|
||||
});
|
||||
|
||||
const viewer = read("frontend/js/viewer.js");
|
||||
|
||||
test("showWelcome reconstruit l'Accueil et le charge", () => {
|
||||
assert.ok(viewer.includes('data-tab="home"'), "onglet home dans le gabarit");
|
||||
assert.ok(viewer.includes('id="dashboard-panel-home"'), "panneau home dans le gabarit");
|
||||
assert.match(viewer, /DashboardHomeWidget\.load\(\)/);
|
||||
assert.ok(viewer.includes("dashboard-panel-stats"), "panneau stats toujours reconstruit");
|
||||
});
|
||||
|
||||
console.log(`\n${passed} dashboard-home tests passed`);
|
||||
@@ -87,11 +87,11 @@ test("viewer delegates inline rendering to NowPlaying.attachInline", () => {
|
||||
const stop = viewer.indexOf("export function renderFile");
|
||||
assert.ok(start !== -1 && stop > start, "renderAudioViewer block not found");
|
||||
const block = viewer.slice(start, stop);
|
||||
assert.match(block, /NowPlaying\.attachInline\(area, data\)/);
|
||||
assert.match(block, /np\.attachInline\(area, data\)/); // #243 : délégation paresseuse via _withNowPlaying
|
||||
});
|
||||
|
||||
test("renderFile hands the shared element to the dock before a re-render", () => {
|
||||
assert.match(viewer, /NowPlaying\.handleRender\(area, data\)/);
|
||||
assert.match(viewer, /np\.handleRender\(area, data\)/); // #243 : idem
|
||||
assert.doesNotMatch(viewer, /_mediaViewerCleanup/);
|
||||
});
|
||||
|
||||
|
||||
@@ -313,12 +313,18 @@ test("reading button only shows while a file is open", () => {
|
||||
test("reading button is hidden while the assistant panel is open", () => {
|
||||
const btn = w.document.getElementById("me-reading-btn");
|
||||
const panel = w.document.createElement("div");
|
||||
panel.className = "bookslm-panel open";
|
||||
// Depuis la transition Spark (D5), le panneau assistant est le panneau
|
||||
// Spark `.draco-panneau` (l'ancien `.bookslm-panel` a été retiré) et
|
||||
// isAssistantOpen() s'appuie sur checkVisibility() — absent du rendu
|
||||
// JSDOM, on le simule donc explicitement sur l'élément.
|
||||
panel.className = "draco-panneau";
|
||||
let panelVisible = true;
|
||||
panel.checkVisibility = () => panelVisible;
|
||||
w.document.body.appendChild(panel);
|
||||
state.currentPath = "Notes/note.md";
|
||||
updateReadingButtonVisibility();
|
||||
assert.ok(btn.hidden, "hidden while the assistant is expanded");
|
||||
panel.classList.add("hidden");
|
||||
panelVisible = false;
|
||||
updateReadingButtonVisibility();
|
||||
assert.ok(!btn.hidden, "shown again once the assistant is collapsed");
|
||||
panel.remove();
|
||||
|
||||
@@ -42,7 +42,7 @@ test("viewer.js — group nav: TOC markdown-only, then pop-out, bookmark", () =>
|
||||
assert.ok(m[1].includes("navBtns.push(openNewWindowBtn, bookmarkBtn, chatBtn);"), "navBtns group order");
|
||||
});
|
||||
|
||||
test("viewer.js — group edit = [edit, source, .ext, forge?, pretty?] in order", () => {
|
||||
test("viewer.js — group edit = [edit, source, .ext, spark?, pretty?] in order", () => {
|
||||
const m = viewer.match(
|
||||
/const editBtns = \[\];([\s\S]*?)const exportBtns/,
|
||||
);
|
||||
@@ -52,11 +52,13 @@ test("viewer.js — group edit = [edit, source, .ext, forge?, pretty?] in order"
|
||||
const re = /editBtns\.push\((\w+)\)/g;
|
||||
let g;
|
||||
while ((g = re.exec(block))) order.push(g[1]);
|
||||
// editBtn conditional, then sourceBtn, then ext-download conditional, then forge conditional
|
||||
assert.deepEqual(order, ["editBtn", "sourceBtn", "mdBtn", "forgeBtn", "prettyBtn"]);
|
||||
// editBtn conditional, then sourceBtn, then ext-download conditional, then
|
||||
// Spark conditional (depuis la transition D5, sparkBtn remplace forgeBtn,
|
||||
// proposé pour tout fichier supporté non-image)
|
||||
assert.deepEqual(order, ["editBtn", "sourceBtn", "mdBtn", "sparkBtn", "prettyBtn"]);
|
||||
assert.ok(block.includes("if (!data.unsupported) editBtns.push(editBtn)"));
|
||||
assert.ok(block.includes("if (!data.is_image) editBtns.push(mdBtn)"));
|
||||
assert.ok(block.includes("if (data.is_markdown) editBtns.push(forgeBtn)"));
|
||||
assert.ok(block.includes("if (!data.unsupported && !data.is_image) editBtns.push(sparkBtn)"));
|
||||
// Pretty (text files) must land in the EDIT group, after the extension button
|
||||
assert.ok(block.indexOf("editBtns.push(prettyBtn)") > block.indexOf("editBtns.push(mdBtn)"));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Tests du script d'audit de chargement (#241, épopée perf #240).
|
||||
|
||||
Le script est stdlib seule et versionné dans ``scripts/`` ; on teste
|
||||
son mode local (graphe de modules ES statiques) sur un mini-frontend
|
||||
synthétique, pour que la mesure reste honnête : un module chargé par
|
||||
``import()`` dynamique ne doit PAS compter dans le graphe statique.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
_SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "audit_chargement.py"
|
||||
_spec = importlib.util.spec_from_file_location("audit_chargement", _SCRIPT)
|
||||
assert _spec and _spec.loader
|
||||
audit = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(audit)
|
||||
|
||||
|
||||
def _write(root: Path, rel: str, content: str) -> None:
|
||||
path = root / rel
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
|
||||
|
||||
def test_static_imports_ignore_dynamic_imports():
|
||||
source = (
|
||||
"import * as A from './a.js';\n"
|
||||
"import './side.js';\n"
|
||||
"export { x } from './re.js';\n"
|
||||
"const m = await import('./lazy.js');\n"
|
||||
"import('https://cdn.example.com/x.js');\n"
|
||||
)
|
||||
assert audit.static_imports(source) == ["./a.js", "./side.js", "./re.js"]
|
||||
|
||||
|
||||
def test_local_module_graph_counts_only_static_chain(tmp_path):
|
||||
frontend = tmp_path / "frontend"
|
||||
_write(frontend, "js/app.js",
|
||||
"import { a } from './a.js';\nconst l = await import('./lazy.js');\n")
|
||||
_write(frontend, "js/a.js", "import { b } from './sub/b.js';\nexport const a = b;\n")
|
||||
_write(frontend, "js/sub/b.js", "export const b = 1;\n")
|
||||
_write(frontend, "js/lazy.js", "export const lazy = 'x'.repeat(5000);\n")
|
||||
|
||||
graph = audit.local_module_graph(frontend)
|
||||
|
||||
assert graph["module_count"] == 3 # app + a + sub/b, pas lazy
|
||||
assert "js/lazy.js" not in graph["modules"]
|
||||
assert graph["raw_bytes"] == sum(graph["modules"].values())
|
||||
|
||||
|
||||
def test_local_baseline_on_real_repo():
|
||||
repo = Path(__file__).resolve().parent.parent
|
||||
baseline = audit.local_baseline(repo)
|
||||
graph = baseline["module_graph"]
|
||||
# La baseline du dépôt réel au moment du lot #241 : 41 modules,
|
||||
# ~1,42 Mo bruts. On vérifie des bornes larges (le graphe bouge
|
||||
# avec les lots suivants, #243 doit le faire BAISSER).
|
||||
assert graph["module_count"] >= 10
|
||||
assert graph["raw_bytes"] > 100_000
|
||||
assert baseline["index_html_bytes"] > 100_000
|
||||
assert any("mermaid" in url or "lucide" in url or "highlight" in url
|
||||
for url in baseline["index_cdn_refs"]) or graph["raw_bytes"] < 1_000_000
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Cache mémoire de GET /api/dashboard (#245, épopée perf #240)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.routers import config as config_router
|
||||
|
||||
|
||||
def _count_calls(monkeypatch):
|
||||
calls = {"n": 0}
|
||||
original = config_router._compute_dashboard
|
||||
|
||||
def counting(user):
|
||||
calls["n"] += 1
|
||||
return original(user)
|
||||
|
||||
monkeypatch.setattr(config_router, "_compute_dashboard", counting)
|
||||
return calls
|
||||
|
||||
|
||||
def test_dashboard_second_call_served_from_cache(client, monkeypatch):
|
||||
config_router.invalidate_dashboard_cache()
|
||||
calls = _count_calls(monkeypatch)
|
||||
|
||||
first = client.get("/api/dashboard")
|
||||
second = client.get("/api/dashboard")
|
||||
|
||||
assert first.status_code == 200
|
||||
assert second.status_code == 200
|
||||
assert second.json() == first.json()
|
||||
assert calls["n"] == 1 # un seul calcul pour deux appels
|
||||
|
||||
|
||||
def test_dashboard_cache_invalidation_recomputes(client, monkeypatch):
|
||||
config_router.invalidate_dashboard_cache()
|
||||
calls = _count_calls(monkeypatch)
|
||||
|
||||
assert client.get("/api/dashboard").status_code == 200
|
||||
config_router.invalidate_dashboard_cache()
|
||||
assert client.get("/api/dashboard").status_code == 200
|
||||
assert calls["n"] == 2
|
||||
|
||||
|
||||
def test_dashboard_cache_ttl_expiry(client, monkeypatch):
|
||||
import time
|
||||
|
||||
config_router.invalidate_dashboard_cache()
|
||||
calls = _count_calls(monkeypatch)
|
||||
assert client.get("/api/dashboard").status_code == 200
|
||||
# Vieillir artificiellement l'entrée au-delà du TTL.
|
||||
for key, (ts, value) in list(config_router._dashboard_cache.items()):
|
||||
config_router._dashboard_cache[key] = (ts - config_router._DASHBOARD_TTL_SECONDS - 1, value)
|
||||
assert client.get("/api/dashboard").status_code == 200
|
||||
assert calls["n"] == 2
|
||||
_ = time # (garde-fou d'import)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Cache versionné des statiques (#242, épopée perf #240).
|
||||
|
||||
Non-régression clé : une nouvelle version doit être servie
|
||||
immédiatement — le cache long (``immutable``) n'est accordé qu'aux
|
||||
URL portant ``?v=<version courante>``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from backend import static_versioning as sv
|
||||
|
||||
|
||||
def test_rewrite_static_urls_adds_version():
|
||||
html = '<link rel="stylesheet" href="/static/style.css" />' \
|
||||
'<script type="module" src="/static/js/app.js"></script>' \
|
||||
'<a href="https://example.com/static/nope.css">x</a>'
|
||||
out = sv.rewrite_static_urls(html, version="9.9.9")
|
||||
assert "/static/style.css?v=9.9.9" in out
|
||||
assert "/static/js/app.js?v=9.9.9" in out
|
||||
assert "example.com/static/nope.css?v=" not in out
|
||||
|
||||
|
||||
def test_rewrite_js_imports_adds_version():
|
||||
source = (
|
||||
"import * as UI from './ui.js';\n"
|
||||
"import './side.js';\n"
|
||||
"export { x } from '../shared.js';\n"
|
||||
"const m = await import('./lazy.js');\n"
|
||||
"const s = 'pas un import ./faux.js';\n"
|
||||
)
|
||||
out = sv.rewrite_js_imports(source, version="9.9.9")
|
||||
assert "'./ui.js?v=9.9.9'" in out
|
||||
assert "'./side.js?v=9.9.9'" in out
|
||||
assert "'../shared.js?v=9.9.9'" in out
|
||||
assert "'./lazy.js?v=9.9.9'" in out
|
||||
|
||||
|
||||
def test_cache_control_only_immutable_for_current_version():
|
||||
current = sv.current_version()
|
||||
assert sv.cache_control_for("/static/js/app.js", f"v={current}") == sv.IMMUTABLE_CACHE_CONTROL
|
||||
# Ancienne version / absence de version : jamais de cache long.
|
||||
assert sv.cache_control_for("/static/js/app.js", "v=0.0.1") == sv.NO_CACHE
|
||||
assert sv.cache_control_for("/static/js/app.js", "") == sv.NO_CACHE
|
||||
assert sv.cache_control_for("/api/dashboard", f"v={current}") is None
|
||||
|
||||
|
||||
def test_served_headers_and_rewriting(client):
|
||||
"""Via l'application : en-têtes selon ?v= et corps JS réécrit."""
|
||||
current = sv.current_version()
|
||||
|
||||
versioned = client.get(f"/static/js/app.js?v={current}")
|
||||
assert versioned.status_code == 200
|
||||
assert "immutable" in versioned.headers.get("cache-control", "")
|
||||
assert f"?v={current}" in versioned.text # imports réécrits au service
|
||||
|
||||
plain = client.get("/static/js/app.js")
|
||||
assert plain.status_code == 200
|
||||
assert plain.headers.get("cache-control") == "no-cache"
|
||||
|
||||
stale = client.get("/static/js/app.js?v=0.0.1")
|
||||
assert stale.headers.get("cache-control") == "no-cache"
|
||||
|
||||
index = client.get("/")
|
||||
assert index.status_code == 200
|
||||
assert index.headers.get("cache-control") == "no-cache"
|
||||
assert f"/static/style.css?v={current}" in index.text
|
||||
assert f"/static/js/app.js?v={current}" in index.text
|
||||
|
||||
|
||||
def test_service_worker_carries_current_version(client):
|
||||
current = sv.current_version()
|
||||
sw = client.get("/sw.js")
|
||||
assert sw.status_code == 200
|
||||
assert "__OBSIGATE_SW_VERSION__" not in sw.text
|
||||
assert f"v{current}" in sw.text
|
||||
Reference in New Issue
Block a user