feat: focus of the upsell windows, and ProfileFormModal as a named dialog (#494) #511

Merged
maximus merged 3 commits from issue-494-upsell-dialog-focus into main 2026-10-28 01:44:53 +00:00
16 changed files with 1016 additions and 34 deletions

View file

@ -13,7 +13,7 @@
- Transactions : sur un profil sans aucune transaction, la carte « Aucune transaction pour l'instant » s'affiche dès que l'application sait que le profil est vide, au lieu des filtres, des totaux et de « Chargement... » jusqu'au retour de la première page de la liste (#384).
- Textes d'aide : l'aide de la page Rapports nomme désormais les rapports par leurs cartes, « Tendances » et « Analyse par catégorie », au lieu de « Tendances mensuelles » et « Catégories dans le temps », des onglets qui n'existent plus. La section Tableau de bord du guide d'utilisation nomme désormais les huit étapes de démarrage et dit comment elles se cochent : selon vos données, ou par « J'ai compris » (ou, pour les rapports, un clic sur la carte Tendances entourée) pour les visites (#446).
- Guide d'utilisation : la procédure BMO de « Exporter un CSV depuis votre banque » est désormais confirmée sur un compte réel (2026-10-22). Le bouton s'appelle « Télécharger » sur le site français, sans l'ancien « ou Exporter », et les trois points qui n'ont pas pu être vérifiés (l'historique de la Mastercard, les prêts qui ne s'exportent pas, les colonnes des comptes de dépôt) sont marqués comme non vérifiés. La note dit désormais que la détection générique lit les exports BMO, des comptes de dépôt comme de la Mastercard, en retenant pour la Mastercard la date de la transaction plutôt que celle de l'inscription au relevé, et qu'un fichier dont les vingt premières lignes comptent plus d'entrées que de sorties sort inversé à l'aperçu jusqu'à « Inverser les signes » (#371).
- L'écran de déverrouillage qui s'ouvre dans une fenêtre en édition Gratuite, depuis un profil verrouillé du sélecteur de profil ou depuis le bouton Répartition de la page Transactions, se ferme désormais avec Échap. Les lecteurs d'écran reconnaissent désormais la fenêtre du sélecteur de profil comme une boîte de dialogue, nommée d'après l'édition requise (par exemple « Fonctionnalité Base »), avec un bouton « Fermer », comme celle du bouton Répartition (#451).
- L'écran de déverrouillage qui s'ouvre dans une fenêtre en édition Gratuite, depuis un profil verrouillé du sélecteur de profil ou depuis le bouton Répartition de la page Transactions, se ferme désormais avec Échap. Les lecteurs d'écran reconnaissent désormais la fenêtre du sélecteur de profil comme une boîte de dialogue, nommée d'après l'édition requise (par exemple « Fonctionnalité Base »), avec un bouton « Fermer », comme celle du bouton Répartition. Ces fenêtres, et la fenêtre « Gérer les profils », s'ouvrent désormais avec le focus sur leur bouton « Fermer », gardent Tab et Maj+Tab à l'intérieur et rendent le focus quand elles se ferment : au bouton du sélecteur de profil pour les fenêtres ouvertes depuis son menu, sinon au bouton qui les a ouvertes. La fenêtre « Gérer les profils » se ferme aussi avec Échap, sauf pendant l'enregistrement d'un profil ; les lecteurs d'écran la reconnaissent comme une boîte de dialogue nommée d'après son titre, avec un bouton « Fermer », et le bouton du sélecteur de profil dit désormais si sa liste est ouverte. Dans « Gérer les profils », le focus revient sur « Créer un profil » après « Annuler » ou après l'enregistrement des modifications d'un profil (#451, #494).
### Corrigé

View file

@ -13,7 +13,7 @@
- Transactions: on a profile without any transaction, the “No transactions yet” card now shows as soon as the app knows the profile is empty, instead of the filters, the totals and “Loading...” until the first page of the list comes back (#384).
- Help texts: the help of the Reports page now names the reports by their cards, “Trends” and “Category Analysis”, instead of “Monthly Trends” and “Category Over Time”, tabs that no longer exist. The Dashboard section of the user guide now names the eight getting-started steps and says how they get checked: from your data, or with “Got it” (or, for the reports, a click on the outlined Trends card) for the visit steps (#446).
- User guide: the BMO procedure of “Export a CSV from your bank” is now confirmed on a real account (2026-10-22). The button is named “Télécharger” on the French site, without the former “or Export”, and the three points that could not be checked (the Mastercard history, loans that cannot be exported, the columns of deposit accounts) are marked as not verified. The note now says that generic detection reads BMO exports, deposit accounts and Mastercard alike, keeping the transaction date rather than the posting date for the Mastercard, and that a file whose first twenty rows hold more inflows than outflows comes out reversed in the preview until “Flip the signs” (#371).
- The unlock screen that opens in a window on the Free edition, from a locked profile of the profile switcher or from the Split button of the Transactions page, now closes with Escape. Screen readers now identify the profile switcher's window as a dialog, named after the edition it needs (such as “Base feature”), with a “Close” button, like the Split button's (#451).
- The unlock screen that opens in a window on the Free edition, from a locked profile of the profile switcher or from the Split button of the Transactions page, now closes with Escape. Screen readers now identify the profile switcher's window as a dialog, named after the edition it needs (such as “Base feature”), with a “Close” button, like the Split button's. These windows, and the “Manage Profiles” window, now open with the focus on their “Close” button, keep Tab and Shift+Tab inside them, and give the focus back when they close: to the profile switcher's button for the windows opened from its menu, otherwise to the button that opened them. The “Manage Profiles” window also closes with Escape, except while a profile is being saved; screen readers identify it as a dialog named after its title, with a “Close” button, and the profile switcher's button now tells whether its list is open. In “Manage Profiles”, the focus goes back to “Create Profile” after “Cancel” or after saving a profile's changes (#451, #494).
### Fixed

View file

@ -54,7 +54,7 @@ src/
│ ├── shared/ # Composants réutilisables
│ └── transactions/ # Transactions
├── contexts/ # ProfileContext (état global profil)
├── hooks/ # 29 hooks custom (useReducer)
├── hooks/ # 30 hooks custom (useReducer)
├── pages/ # 11 pages
├── services/ # 14 services métier
├── shared/ # Types et constantes partagés

View file

@ -200,8 +200,9 @@ Côté site, la demande « merger et déployer après la publication » pour l'
- Import : carte Transactions d'un profil vide, trois erreurs du dossier d'exemple traduites, bandeau effacé par « Actualiser » ;
- aide du tableau de bord à huit étapes, textes FR/EN de #475, point du bandeau, avertissement des fichiers à la racine après un changement de dossier ;
- aide d'import (#371, PR #489) : bloc BMO en FR et en EN, statut confirmé, bouton « Télécharger », trois points « Non vérifié ».
- Écran de déverrouillage en fenêtre (#451, PR #493), en édition Gratuite, en FR et en EN, thèmes clair et sombre : Transactions → bouton Répartition verrouillé → la fenêtre se ferme avec Échap ; sélecteur de profil → profil verrouillé → la même fenêtre (titre « Fonctionnalité Base », le X la ferme, Échap aussi, « J'ai déjà une clé » la ferme et ouvre la carte Licence, « Obtenir Base » la laisse ouverte, un clic sur le voile ne fait rien) ; lecteur d'écran (Orca, Narrateur), une fois la fenêtre atteinte (le focus n'y entre pas à l'ouverture, hors périmètre) : lue comme une boîte de dialogue avec son nom, le X lu « Fermer » ; en Base, le sélecteur change toujours de profil.
- Écran de déverrouillage en fenêtre (#451, PR #493), en édition Gratuite, en FR et en EN, thèmes clair et sombre : Transactions → bouton Répartition verrouillé → la fenêtre se ferme avec Échap ; sélecteur de profil → profil verrouillé → la même fenêtre (titre « Fonctionnalité Base », le X la ferme, Échap aussi, « J'ai déjà une clé » la ferme et ouvre la carte Licence, « Obtenir Base » la laisse ouverte, un clic sur le voile ne fait rien) ; lecteur d'écran (Orca, Narrateur), une fois la fenêtre atteinte (depuis #494, le focus y entre à l'ouverture : sous-puce de #494 ci-dessous) : lue comme une boîte de dialogue avec son nom, le X lu « Fermer » ; en Base, le sélecteur change toujours de profil.
- Procédure `/release` revue par la pile #499 → #506 (dossiers 28630 et 28647) : à l'étape 0, lancer les deux commandes de report de la matrice des éditions et lire chaque commit trouvé, la PR du site n'étant mergée et déployée qu'après le `VERDICT : OK` ; à l'étape 3, la sous-étape « Vérifier les en-têtes » doit mener au vert sans toucher à la version des autres fichiers ; à l'étape 10, si seul l'endpoint de mise à jour change, `curl … | jq -r .version` doit rendre la nouvelle version.
- Focus des fenêtres d'incitation (#494, PR #511), en édition Gratuite sauf mention, en FR et en EN, thèmes clair et sombre, sous Linux et sous Windows : Transactions → bouton Répartition verrouillé (à la souris, puis par Tab et Entrée), et sélecteur de profil → profil verrouillé : anneau de focus visible sur le X à l'ouverture, Tab et Maj+Tab font le tour de la fenêtre sans passer derrière le voile, X et Échap rendent le focus au bouton Répartition de la ligne, ou au bouton du sélecteur pour la fenêtre ouverte depuis son menu, comme « J'ai déjà une clé » depuis le sélecteur (depuis Transactions, la page change et le focus n'est nulle part, comme après toute navigation) ; « Gérer les profils » : focus sur le X à l'ouverture, Tab qui boucle dans chaque mode, « Créer un profil » verrouillé → focus sur le X, « Annuler » → focus sur « Créer un profil », en Base « Créer un profil » et « Modifier » → champ Nom, « Annuler » ou « Enregistrer » d'une modification → « Créer un profil », Échap qui ferme la fenêtre (depuis le champ Nom aussi) sauf pendant un enregistrement, X et Échap qui rendent le focus au bouton du sélecteur ; la même fenêtre ouverte depuis l'écran de choix du profil (aucun profil actif, hors routeur), le focus rendu à sa tuile « Créer un profil » ; lecteur d'écran (Orca, Narrateur) : chaque fenêtre annoncée à l'ouverture comme une boîte de dialogue avec son nom, le X lu « Fermer », le bouton du sélecteur annoncé déplié ou replié ; en Base, le sélecteur change toujours de profil et Répartition ouvre la fenêtre de répartition. Après la suppression d'un profil, la fenêtre se ferme le temps du rechargement des profils, comme avant : le focus ne va pas sur « Créer un profil » (attendu, PR #511).
- **Le paiement est live : « aucun tag avant le go-live » n'a plus de raison d'être, et la release desktop qu'attendait le go-live est publiée (v0.16.0, 2026-10-03).** Bascule live le 2026-09-29 (Product et Price live à 19 $ CAD, webhook, variables Stripe de production, redeploy `3673d09` de maximus-api, URL `cs_live_` vérifiée), puis achat réel de contrôle le 2026-09-30 : clé sur `/merci` et par courriel, activation dans l'app, remboursement complet et licence révoquée par `charge.refunded`. **Volet serveur clos le 2026-10-03** (derniers commentaires relus le 2026-10-04) : maximus-api#62 fermée, tous critères cochés (maximus-api 0.4.2 en prod, secrets en runtime seul), avec la milestone `spec-paiements` de maximus-api (12/12) ; la-compagnie-maximus#150 (Link dans les textes légaux) livrée et fermée le 2026-10-01. **Go-live clos : la-compagnie-maximus#141** fermée le 2026-10-10 sur décision de Max, l'updater vérifié (Free refuse et invite à acheter, Base accepte ; confirmé le même jour). Restent pour mémoire, sans issue : le Dashboard Stripe (logo, paramètres Checkout, reçus automatiques, alertes d'échec de webhook) et les relevés du commentaire de fermeture. la-compagnie-maximus#184 (politique de confidentialité : données d'activation, contrôle au démarrage) est en `status:review` ; sa PR reste en brouillon jusqu'au déploiement de maximus-api#85 (commentaire du 2026-10-03). Les deux textes des suites de licence (contrôle à la saisie, retrait de la clé) y sont postés depuis le 2026-10-05 (commentaire 19724). **Vérifications manuelles sur la release publiée, toutes faites** : #365 le 2026-10-03, #346 et #350 le 2026-10-04 (voir Décisions). L'étape 10 sous Windows est faite (Michel, confirmée le 2026-10-10).
- Backlog ouvert : **vague `planned-2026-09-24-paiements` close 3/3** (milestone fermée le 2026-09-30) : #270 (PR #359) et #346 (PR #362) mergées le 2026-09-27, #347 (PR #364, ferme aussi #360) mergée le 2026-09-30 ; volet site **clos** (maximus/la-compagnie-maximus#153, redirection de `/simpl-resultat` en prod). **#365 fermée le 2026-10-03** après sa vérification manuelle. **Milestone `planned-2026-10-03-suites-licence` fermée 3/3 le 2026-10-05** (#373, #370, #367 mergées, voir Décisions ; suivi #389 en `status:triage`). Hors milestone : **#369** (réserver le fractionnement de transactions à l'édition Base) **fermée le 2026-10-17** (PR #452, voir Décisions) ; **#372** (la liste complète des versions repousse le Journal en bas de Paramètres → Systèmes) reste en `status:ready`. **#350 fermée le 2026-10-04** (étape 3 vérifiée en production, voir Décisions) ; #363 fermée le 2026-10-10 sur décision de Max (ses tests, absorbés par #347, sont livrés dans la v0.16.0) ; réglés côté serveur et site : maximus-api#63 (clés de 100 ans) et maximus-api#70 (réactivation d'une machine désactivée), fermées et contenues dans `3673d09`, le commit déployé à la bascule du 2026-09-29, et la-compagnie-maximus#157, fermée, dont les CGV sont publiées en tronc commun plus annexe Simpl-Résultat (annexe relue en production le 2026-09-30, plus aucune durée de 10 ans) ; côté serveur, `/v1/prices` ne vérifie pas qu'une machine est encore active (une machine désactivée garde les cours jusqu'à l'expiration de son jeton), issue maximus-api à ouvrir ; suites de #350 ouvertes le 2026-10-01 : maximus-api#82 (`status:triage` : identifiants machine bruts déjà stockés, lignes désactivées comprises ; à rehacher avant l'expiration des premiers jetons bruts, sinon une réactivation crée une seconde ligne) et la-compagnie-maximus#184 (`status:review`, voir ci-dessus) ; go-live clos (la-compagnie-maximus#141 fermée le 2026-10-10, maximus-api#62 le 2026-10-03) ; `spec-paiements` fermée ici 5/5 ; onboarding phase 2 (parcours guidé) **mergée** : milestone `planned-2026-10-06-onboarding-parcours-guide` fermée 6/6 le 2026-10-08 (#396 à #401, `ee17f31`), suivis **#408** et **#409** (`status:triage`) ; onboarding phase 1 **livrée** : milestone `planned-2026-10-03-onboarding-phase1` fermée 7/7 le 2026-10-04 (#351 à #357, mergées en avance rapide, `667e058`) ; suivis ouverts : **#384** (`status:ready`, suivis non bloquants des revues) ; **#371** fermée le 2026-10-23 (PR #489, bloc BMO confirmé sur compte réel), la signature d'import BMO suit en **#488** (`status:blocked` : lignes aux valeurs fictives, préambule éventuel et en-tête d'un compte de dépôt à fournir par Max) ; analyse d'origine dans `docs/analyse-onboarding-2026-09.md`, plan détaillé dans les `spec-*-onboarding-phase1.md` locaux, ignorés par git ; #271 absorbé par #301, livré ; `spec-ci-build-optimization` **fermée 4/4** le 2026-10-05 (#232 livrée le 2026-07-27 ; #234 close le 2026-10-05 avec ses quatre preuves : dispatch run 464, PR #386 run 480, run planifié 488, `actcache` à 999 Mo) ; **#376** fermée le 2026-10-12 (Node 24, PR #414). Le suivi « glob `src-tauri/**` non prouvé » ouvert avec #232 est **levé** : la PR #344 est le cas test isolé attendu (`Cargo.lock` + 2 `.md` seulement) — `check-rust` a bien tourné, `check-frontend` a bien été sauté par sa denylist.
- Suivis des advisories : **#312, #313 et #315 fermées le 2026-08-15** (PRs #321/#322 mergées). **#314 fermée le 2026-08-15, prémisse infirmée** — elle affirmait « zéro run `schedule` », or `audit.yml` tire tous les jours à 06:00 UTC (**19 runs `schedule` verts** du 07-28 au 08-15, sans trou) ; elle a été écrite le 07-27 vers 23:56Z, ~6 h avant le premier tir programmé possible, et décrivait donc une fenêtre trop courte, pas un scheduler en panne. Ces 19 runs confirment au passage que `.cargo/audit.toml` est bien lu en conteneur **sur `main`** — l'ADR 0018 ne l'avait vérifié que par un `workflow_dispatch` sur une branche. **#343 fermée le 2026-09-04** (PR #344) — RUSTSEC-2026-0258 sur `h2`, la seule vulnérabilité qui rougissait l'audit depuis le 08-19 ; l'audit est de nouveau vert sur `main`, prouvé par `workflow_dispatch` (run 393) et non déduit du run de PR. **#348 fermée le 2026-09-21** (PR #349) — RUSTSEC-2026-0285 sur `rustls`, seule vulnérabilité rougissant l'audit depuis le 09-15 (7 runs, 405→411) ; vert reprouvé par `workflow_dispatch` sur `main` (run 414 : 666 paquets, zéro vulnérabilité, 12 warnings autorisés). Deux advisories en cinq semaines sur le même chemin, celui de la mise à jour automatique. **#447 fermée le 2026-10-16** (PR #448, run 556 vert), quatre avis `rustls` sur ce même chemin ; le Défenseur n'audite pas le Rust (agent-defenseurs#186), `audit.yml` reste le seul canal pour les avis RustSec. **#455 fermée le 2026-10-18** (PR #459, run 564 vert), trois avis `zip` sur ce même chemin, retirés avec la feature `zip` de l'updater plutôt que supprimés. **#317** fermée le 2026-10-12 par la PR #417 (#358). Reste **#319** (déclencheur de retrait pour `rsa`, désormais **seule** entrée de `.cargo/audit.toml` — le garde-fou est passé à 2 vérifications). **#345** fermée le 2026-10-12 (PR #415) : garde `Verify windows-sys pinning` dans `check-rust.yml` et ADR 0023, qui portent la mesure, le coût (3 contre 5 versions compilées pour Windows) et la condition de sortie. Côté npm, **#358** fermée le 2026-10-12 (PR #417) : lock régénéré par `npm@11.21.0` dans les bornes de `package.json`, `npm audit` 8 → 0 au 2026-10-10.

View file

@ -42,7 +42,7 @@ simpl-resultat/
│ │ ├── shared/ # 14 composants réutilisables (dont RequireFeature, UpsellGate, UpsellDialog, PurchaseButton, EmptyState)
│ │ └── transactions/ # 6 composants (dont SplitButton, #369)
│ ├── contexts/ # LicenseContext (licence machine) + ProfileContext (état global profil) + OnboardingContext (parcours de démarrage, #396)
│ ├── hooks/ # 29 hooks custom (useReducer, 5 hooks rapports par domaine)
│ ├── hooks/ # 30 hooks custom (useReducer, 5 hooks rapports par domaine)
│ ├── pages/ # 14 pages (dont 4 sous-pages rapports)
│ ├── services/ # 27 services métier (21 détaillés dans la section « Services TypeScript »)
│ ├── shared/ # Types, constantes, matrice d'entitlements (entitlements.ts), gate profils (profileGate.ts), gate de la Répartition (splitGate.ts), CTA d'upsell (upsellCta.ts), URL d'achat (purchaseUrl.ts), échéance de licence (licenseExpiry.ts)
@ -232,9 +232,9 @@ Un seul service par convention projet (1 service par domaine, splitter seulement
Le CRUD passe par `getDb()` + `tauri-plugin-sql` direct, **jamais** via une commande Tauri — convention projet. Les commandes Rust sont réservées au filesystem, OAuth, license, profils, feedback, aux cours (`fetch_price`, appel réseau qui porte le jeton d'activation) et au seul calcul Modified Dietz (qui a besoin d'arithmétique de dates `chrono`).
## Hooks (29)
## Hooks (30)
Les 29 fichiers `.ts` de `src/hooks/`, hors tests (`ls src/hooks/*.ts | grep -v '\.test\.ts$' | wc -l`, #384) : les 28 du tableau et `useCollapsibleGroups`, décrit plus bas. Chaque hook de domaine encapsule la logique d'état via `useReducer` :
Les 30 fichiers `.ts` de `src/hooks/`, hors tests (`ls src/hooks/*.ts | grep -v '\.test\.ts$' | wc -l`, #384) : les 28 du tableau, puis `useCollapsibleGroups` et `useDialogFocus` (#494), décrits plus bas. Chaque hook de domaine encapsule la logique d'état via `useReducer` :
| Hook | Domaine |
|------|---------|
@ -275,6 +275,17 @@ Les 29 fichiers `.ts` de `src/hooks/`, hors tests (`ls src/hooks/*.ts | grep -v
- `storageKey === null` → état **purement en mémoire**, réinitialisé à chaque montage (les 2 arbres de catégories : navigation éphémère, rien à conserver ni à révéler).
- L'historique des versions de Paramètres → Système (`ChangelogContent`, #372) n'utilise pas ce hook : c'est une liste plate dont une seule version s'ouvre au départ, choisie par une règle, alors que le hook n'a qu'un `defaultExpanded` global, sans amorce par clé. Son état est un `Set` local, en mémoire, amorcé à chaque lecture du fichier par `initiallyExpandedVersions` (`src/utils/changelog.ts`, pur, avec `parseChangelog`) : la version installée, ou la première version publiée quand la version installée est inconnue ou absente du fichier.
### Hook transverse — `useDialogFocus`
`useDialogFocus({ dialog, initialFocus, returnFocusTo })` (#494) est un hook **utilitaire de fenêtre** (un seul `useEffect`, hors convention `useReducer` par domaine), partagé par `UpsellDialog` et `ProfileFormModal`, qui rend `{ onKeyDown }`. Ses trois arguments sont des refs : l'élément `role="dialog"`, le bouton X de la fenêtre, et, en option, l'élément où rendre le focus.
- **Ouverture** — l'effet, joué au montage seulement, mémorise `document.activeElement` et met le focus sur `initialFocus`, le X : premier élément focalisable dans l'ordre du DOM, où Entrée ne déclenche rien d'irréversible, et le lecteur d'écran annonce d'abord le nom de la fenêtre (décision de Max du 2026-10-24).
- **Fermeture** — le nettoyage de l'effet rend le focus à `returnFocusTo.current` quand l'hôte passe cette ref et qu'elle tient un élément (elle l'emporte), sinon à l'élément mémorisé, ignoré s'il vaut `body` ou n'est plus dans le document (`isConnected`). Le nettoyage joue à toute disparition : X, Échap, « J'ai déjà une clé », et la fenêtre que son hôte démonte sans `onClose` (l'incitation de `TransactionTable` quand l'accès devient `open`). `ProfileSwitcher` passe son déclencheur : le bouton du menu qui a ouvert la fenêtre est démonté dans la même mise à jour qu'elle se monte, et `activeElement` vaut alors `body`. Après « J'ai déjà une clé » depuis `TransactionTable`, la navigation démonte le bouton Répartition mémorisé, et le focus ne va nulle part, comme après toute navigation de l'application.
- **Tab** — `onKeyDown`, posé sur l'élément de la fenêtre et jamais sur `document` (où les fenêtres écoutent Échap), fait passer Tab du dernier élément focalisable au premier et Maj+Tab du premier au dernier, parmi ceux que `FOCUSABLE_SELECTOR` désigne (`button:not([disabled])`, `[href]`, `input:not([disabled])`, `select`, `textarea`, `[tabindex]:not([tabindex="-1"])`), relus à chaque frappe ; ailleurs, le navigateur fait le reste. Écartés : `inert` sur le reste de la page, les fenêtres n'étant pas en portail, et l'absence de piège, qui laissait Tab parcourir la page derrière le voile.
- **`ProfileFormModal`** ajoute un effet sur `mode` : à l'entrée en mode `upsell`, le focus va sur le X (le bouton « Créer » qui l'a ouvert est démonté) ; à tout retour en `list`, sur « Créer ». Il ne joue ni au montage ni au second passage de StrictMode, la ref du dernier mode traité partant du mode du premier rendu. Les formulaires `create` et `edit` gardent l'`autoFocus` de leur champ Nom. La suppression d'un profil met aussi le focus sur « Créer », mais elle démonte aujourd'hui la fenêtre, comme la création : `deleteProfile` et `createProfile` passent les profils en chargement, et `App` rend son écran de chargement à la place de tout l'arbre. Le retour sur « Créer » ne joue donc qu'après « Annuler » et l'enregistrement d'une modification.
Les autres fenêtres de l'application (`PinDialog`, `SplitAdjustmentModal`, `TransactionDetailModal`, `AddKeywordDialog`, `ImportConfirmModal`, les confirmations d'`ImportHistoryPanel`, de `CategoriesPage` et de `SnapshotEditPage`) n'ont ni focus initial ni retour : le hook les attend, hors périmètre de #494.
## Hiérarchie des catégories (#393)
Un `parent_id` en boucle (A sous B, B sous A, ou une catégorie sous elle-même) cache la boucle et tout ce qui pend dessous partout où l'on part des racines : arbre, sélecteurs de catégorie, budget, rapports. Les données restent intactes ; seul `parent_id` est en cause.
@ -429,9 +440,9 @@ Depuis le chantier #297-#301, l'accès aux modules est gaté par l'édition de l
| CTA partagés | `src/components/shared/PurchaseButton.tsx`, `DownloadLatestButton.tsx`, `HaveKeyButton.tsx` | « Obtenir Base » et « Télécharger la dernière version » ouvrent `purchaseUrl` dans le navigateur, sans routeur ; ils servent aussi la carte Mises à jour et `ErrorPage` en édition Gratuite, sans aucune vérification de mise à jour. « J'ai déjà une clé » ne rend rien hors `BrowserRouter` (#346) |
| Règle du CTA | `src/shared/upsellCta.ts` | `upsellCtaFor(tier)` → `{ purchasable, noteKey }` : Base achetable, Premium désactivé avec `upsell.premiumNotForSale` ; testée sur toute la matrice (#346) |
| Cadenas navigation | `Sidebar.tsx` (`NavLock`) + `ReportsPage` (tuiles du hub) | Badge verrou affiché si `ready && !allowed` ; les items restent **cliquables** (la route montre l'upsell — verrouillé visible, jamais masqué). `NAV_ITEMS[].feature?` porté par `budget` / `adjustments` / `balance` uniquement (invariant testé : `reports` n'est jamais gaté, le hub est Free) |
| Gate multi-profils | `src/shared/profileGate.ts` | Prédicats purs `isProfileSwitchLocked` / `isProfileCreationLocked` (`multi-profile`, Base+) : le profil **actif** n'est jamais verrouillé, la création est gatée au point unique `ProfileFormModal` (mode upsell, qui réutilise `UpsellGate`) ; `ProfileSelectionPage` marque l'entrée « Créer » sans verrouiller les tuiles. Non destructif : aucune donnée supprimée, un upgrade fait tout réapparaître |
| Gate multi-profils | `src/shared/profileGate.ts` | Prédicats purs `isProfileSwitchLocked` / `isProfileCreationLocked` (`multi-profile`, Base+) : le profil **actif** n'est jamais verrouillé, la création est gatée au point unique `ProfileFormModal` (mode upsell, qui réutilise `UpsellGate` ; fenêtre nommée par son titre, `role="dialog"`, `aria-modal` et `aria-labelledby`, fermée par Échap hors sauvegarde, au focus d'`UpsellDialog`, #494) ; `ProfileSelectionPage` marque l'entrée « Créer » sans verrouiller les tuiles. Non destructif : aucune donnée supprimée, un upgrade fait tout réapparaître |
| Gate de la Répartition | `src/shared/splitGate.ts`, `src/components/transactions/SplitButton.tsx` | `splitAccessFor(gate)` → `open` / `locked` / `pending` sur `useEntitlement("adjustments")`, lu par `TransactionsPage` et passé à `TransactionTable` en prop obligatoire (#369). `locked` : cadenas sur le bouton et `UpsellDialog` au lieu de la fenêtre de répartition, pour toute ligne ; `pending` (licence pas `ready`, chargement ou erreur) : ni cadenas ni fenêtre, bouton inactif, `allowed` ne court-circuitant pas `ready`. La fenêtre de répartition n'est rendue que hors `locked`, l'incitation que hors `open`. Non destructif : les répartitions existantes restent comptées et gardent leur icône orange |
| `UpsellDialog` | `src/components/shared/UpsellDialog.tsx` | `UpsellGate` dans une fenêtre (`role="dialog"`, `aria-modal`, nom accessible `upsell.title`), pour une action gatée hors d'une route verrouillée : l'ouvrent le bouton Répartition de `TransactionTable` (#369) et un profil verrouillé de `ProfileSwitcher` (#451). `onNavigate` ferme la fenêtre après « J'ai déjà une clé » ; le bouton X et Échap la ferment aussi (écouteur `keydown` sur `document`, posé au montage, retiré au démontage et remplacé quand `onClose` change, #451), un clic sur le voile non ; le bouton d'achat la laisse ouverte. Elle ne prend pas le focus à l'ouverture (suivi #494) |
| `UpsellDialog` | `src/components/shared/UpsellDialog.tsx` | `UpsellGate` dans une fenêtre (`role="dialog"`, `aria-modal`, nom accessible `upsell.title`), pour une action gatée hors d'une route verrouillée : l'ouvrent le bouton Répartition de `TransactionTable` (#369) et un profil verrouillé de `ProfileSwitcher` (#451). `onNavigate` ferme la fenêtre après « J'ai déjà une clé » ; le bouton X et Échap la ferment aussi (écouteur `keydown` sur `document`, posé au montage, retiré au démontage et remplacé quand `onClose` change, #451), un clic sur le voile non ; le bouton d'achat la laisse ouverte. Focus par `useDialogFocus` (#494) : sur le X à l'ouverture, Tab et Maj+Tab gardés dans la fenêtre, et rendu à sa disparition, quelle qu'elle soit, au déclencheur de `ProfileSwitcher` (`returnFocusTo`) ou à l'élément actif à l'ouverture (le bouton Répartition), sauf s'il vaut `body` ou n'est plus dans le document. `TransactionTable` remet son état d'ouverture à faux quand l'accès devient `open` : la fenêtre ne revient pas d'elle-même si l'accès redevient `locked` |
| Rust | `src-tauri/src/commands/entitlements.rs` | `FEATURE_TIERS` réduit à `auto-update` → Base+ (la matrice UI vit en TS) ; `check_entitlement` = matrice OU `features[]` signés avec court-circuit Free (même CWE-863), entitlements résolus par `license_commands::current_entitlements` |
Modules Free — jamais gatés, aucune `FeatureKey` : Dashboard, Import, Transactions, Catégories, hub `/reports` + `/reports/trends`, Export/Import, Paramètres, Changelog, docs. Seule exception à l'intérieur d'une page Free : le bouton Répartition de la page Transactions, gaté par `adjustments` (#369). Le déclassement d'édition est **non destructif** : les données des modules verrouillés restent en base et redeviennent accessibles avec une clé valide.
@ -635,7 +646,7 @@ Page spéciale : `ProfileSelectionPage` (affichée quand aucun profil n'est acti
## Tests (vitest sans jsdom)
Le dépôt n'a pas de jsdom : les tests rendent les composants par `renderToStaticMarkup`, ou appellent hooks et composants comme des fonctions pour lire l'arbre rendu et les props. Un rendu statique ne lance aucun effet et aucun clic ; ce qu'un composant fait avec React entre deux rendus passe par un faux module `react`.
Le dépôt n'a pas de jsdom : les tests rendent les composants par `renderToStaticMarkup`, ou appellent hooks et composants comme des fonctions pour lire l'arbre rendu et les props. Un rendu statique ne lance aucun effet, aucun clic et ne pose aucun focus ; ce qu'un composant fait avec React entre deux rendus passe par un faux module `react`.
### Harnais de hooks — `src/test/hookHarness.ts` (#409)
@ -657,13 +668,15 @@ Sémantique simulée, chaque point prouvé par `src/test/hookHarness.test.ts` :
- `useRef` : un objet par emplacement, gardé d'un rendu à l'autre ;
- `useMemo` / `useCallback` : recalculés seulement quand une dépendance change (`Object.is`) ;
- `useEffect` : capturé pendant le rendu, joué seulement par `commit()` s'il a une dépendance changée, nettoyages d'abord ; `replayEffects()` joue le double passage de StrictMode au montage, `unmount()` les nettoyages ;
- tout autre hook (`useContext`, `useLayoutEffect`, `useSyncExternalStore`, `useId`, `use`…) **lève** : un test rougit sur son assertion, jamais par « Invalid hook call ». Mocker le module qui l'appelle (`useOnboarding`, `useLocation`, `useTranslation`…).
- tout autre hook (`useContext`, `useLayoutEffect`, `useSyncExternalStore`, `useId`, `use`…) **lève** : un test rougit sur son assertion, jamais par « Invalid hook call ». Mocker le module qui l'appelle (`useOnboarding`, `useLocation`, `useTranslation`…). C'est pourquoi `useDialogFocus` s'en tient à `useEffect`, et `ProfileFormModal` nomme sa fenêtre par un id statique plutôt que par `useId` (#494).
Non simulé : le nouveau rendu après un setter ou un dispatch, les enfants (un composant dans l'arbre rendu reste un élément), le DOM, le concurrent, la boucle de mises à jour pendant le rendu (le `render()` suivant la lit), et un reducer qui change d'un rendu à l'autre : le `dispatch` d'un `useReducer` garde le reducer du premier rendu (il est créé une fois, avec l'emplacement), là où React applique celui du dernier rendu. Un reducer défini au niveau du module, seul cas utilisé, n'est pas touché.
Utilisateurs : 27 fichiers de test au 2026-10-23, que `grep -rl "test/hookHarness" src --include='*.test.*'` liste (sans le filtre, la commande nomme aussi le harnais) ; d'abord ceux de #389 (`useOnboardingChecklist.wiring.test.ts`, `UsersSettingsPage.test.tsx`, `BudgetTable.wiring.test.ts`, `BudgetPage.wiring.test.ts`, `AppShell.slot.test.tsx`, `OnboardingStepCard.test.tsx`, `PriceFetchConsentToggle.test.tsx`), puis les tests de câblage et de hooks venus après (`PriceFetchControl.test.tsx` en #437, `TransactionTable.wiring.test.ts`, `useCategories.test.ts`…), dont les quatre tests de suppression de #467 (`CategoryDetailPanel.delete.test.ts`, `AdjustmentDetailPanel.delete.test.ts`, `TemplateActions.delete.test.ts`, `AccountsPage.delete.test.ts`) : ce qu'un gestionnaire fait de la réponse de `confirmAction`, que `native-dialog-guard.test.ts` ne voit pas. #451 y ajoute `UpsellDialog.render.test.tsx` (l'écouteur d'Échap, sur un `document` factice) et `ProfileSwitcher.wiring.test.ts`. `CategoryCombobox.placement.test.ts` y fait passer `useLayoutEffect` pour `useEffect` et `useId` pour une constante, dans ce seul fichier (#429). Hors périmètre de #409, `useImportWizard.mount.test.ts` et `useImportWizard.executeImport.test.ts` gardent leurs faux non persistants ; `useImportWizard.samples.test.ts` (« Créer un dossier d'exemple », #384) passe par le harnais partagé.
Faute de DOM, un test qui a besoin d'un élément, pour le focus de `useDialogFocus` par exemple (#494), pose un faux (un objet qui porte un espion `focus` et `isConnected`) dans la ref de l'élément rendu, par ses props : `(el.props.ref as { current: unknown }).current = fake`, React 19 gardant `ref` dans les props (motif de `CategoryCombobox.placement.test.ts`), puis joue `commit()`. Jamais par un emplacement préréglé : un hook partagé ajouté au composant décale les emplacements (« Limites connues », plus bas). `document` est alors un faux posé par `vi.stubGlobal` (`activeElement`, `body`, `addEventListener`), et la boucle de Tab lit un `querySelectorAll` factice posé sur l'élément de la fenêtre. Le harnais ne vide jamais une ref, là où React la vide au démontage de son élément : un faux reste dans la ref d'un bouton que le rendu suivant n'affiche plus.
Lecture de l'arbre rendu — `src/test/elementTree.ts` (#467, #495). `find(node, pred)` rend tous les éléments que garde le prédicat, en profondeur (un élément avant ce qu'il contient), à travers les tableaux, à toute profondeur, et les fragments ; `find(tree, (el) => el.type === CategoryForm)` rend les éléments d'un type. `holding(node, type)` rend les éléments dont un enfant direct est un élément de ce type, chacun une fois : le bouton qui porte un `Trash2`, ni l'icône ni la ligne autour du bouton ; un tableau de `props.children` n'y est lu que sur un niveau. `texts(node)` rend les chaînes de l'arbre, en profondeur, donc dans l'ordre où la page les montre, à travers les tableaux et les fragments, chacune telle quelle (ni rognée ni jointe à sa voisine) ; un nombre n'est pas une chaîne : `texts` le laisse de côté et ne le rend jamais, comme `null`, `undefined` et les booléens. Les trois ne lisent que `props.children`, et un composant enfant reste un élément : son bouton s'atteint par les props de son élément (`props.onDelete()` de `CategoryForm`). Chaque point est prouvé par `src/test/elementTree.test.ts`. L'utilisent 23 fichiers de test au 2026-10-26, que `grep -rl "test/elementTree" src --include='*.test.*'` liste, dont sept qui importent aussi `texts` (`grep -rlE '\btexts\b.*test/elementTree' src --include='*.test.*'`). Les constantes `texts` de `CategoryDetailPanel.delete.test.ts` et `AccountsPage.delete.test.ts` ont un autre sens, les chaînes qui forment tout le contenu d'un élément, et restent dans leur fichier.
Utilisateurs : 29 fichiers de test au 2026-10-26, que `grep -rl "test/hookHarness" src --include='*.test.*'` liste (sans le filtre, la commande nomme aussi le harnais) ; d'abord ceux de #389 (`useOnboardingChecklist.wiring.test.ts`, `UsersSettingsPage.test.tsx`, `BudgetTable.wiring.test.ts`, `BudgetPage.wiring.test.ts`, `AppShell.slot.test.tsx`, `OnboardingStepCard.test.tsx`, `PriceFetchConsentToggle.test.tsx`), puis les tests de câblage et de hooks venus après (`PriceFetchControl.test.tsx` en #437, `TransactionTable.wiring.test.ts`, `useCategories.test.ts`…), dont les quatre tests de suppression de #467 (`CategoryDetailPanel.delete.test.ts`, `AdjustmentDetailPanel.delete.test.ts`, `TemplateActions.delete.test.ts`, `AccountsPage.delete.test.ts`) : ce qu'un gestionnaire fait de la réponse de `confirmAction`, que `native-dialog-guard.test.ts` ne voit pas. #451 y ajoute `UpsellDialog.render.test.tsx` (l'écouteur d'Échap, sur un `document` factice) et `ProfileSwitcher.wiring.test.ts`, #494 `useDialogFocus.test.ts` et `ProfileFormModal.render.test.tsx` (le focus, par des faux posés dans les refs). `CategoryCombobox.placement.test.ts` y fait passer `useLayoutEffect` pour `useEffect` et `useId` pour une constante, dans ce seul fichier (#429). Hors périmètre de #409, `useImportWizard.mount.test.ts` et `useImportWizard.executeImport.test.ts` gardent leurs faux non persistants ; `useImportWizard.samples.test.ts` (« Créer un dossier d'exemple », #384) passe par le harnais partagé.
Lecture de l'arbre rendu — `src/test/elementTree.ts` (#467, #495). `find(node, pred)` rend tous les éléments que garde le prédicat, en profondeur (un élément avant ce qu'il contient), à travers les tableaux, à toute profondeur, et les fragments ; `find(tree, (el) => el.type === CategoryForm)` rend les éléments d'un type. `holding(node, type)` rend les éléments dont un enfant direct est un élément de ce type, chacun une fois : le bouton qui porte un `Trash2`, ni l'icône ni la ligne autour du bouton ; un tableau de `props.children` n'y est lu que sur un niveau. `texts(node)` rend les chaînes de l'arbre, en profondeur, donc dans l'ordre où la page les montre, à travers les tableaux et les fragments, chacune telle quelle (ni rognée ni jointe à sa voisine) ; un nombre n'est pas une chaîne : `texts` le laisse de côté et ne le rend jamais, comme `null`, `undefined` et les booléens. Les trois ne lisent que `props.children`, et un composant enfant reste un élément : son bouton s'atteint par les props de son élément (`props.onDelete()` de `CategoryForm`). Chaque point est prouvé par `src/test/elementTree.test.ts`. L'utilisent 24 fichiers de test au 2026-10-26, que `grep -rl "test/elementTree" src --include='*.test.*'` liste, dont neuf qui importent aussi `texts` (`grep -rlE '\btexts\b.*test/elementTree' src --include='*.test.*'`). Les constantes `texts` de `CategoryDetailPanel.delete.test.ts` et `AccountsPage.delete.test.ts` ont un autre sens, les chaînes qui forment tout le contenu d'un élément, et restent dans leur fichier.
### Faux `t` marqué — `src/test/i18nMock.ts` (#389)

View file

@ -1,10 +1,15 @@
// ProfileFormModal — deleting a secondary profile waits for the confirmation (#421).
// ProfileFormModal — deleting a secondary profile waits for the confirmation (#421), then
// puts the focus on « Create » (#494).
//
// Before #421 the dialog plugin's async `window.confirm` returned a Promise, always truthy:
// the profile and its database were deleted before the user answered, and "Cancel" stopped
// nothing. The modal runs as a plain function under the shared hook harness (#409); the test
// clicks the delete button of the secondary profile through its props, the confirmation
// answered by a mocked `confirmAction`.
// answered by a mocked `confirmAction`. The deleted row takes its delete button, which had
// the focus, with it: the handler puts the focus on « Create », whose ref gets a fake element
// through its `props.ref` (React 19 keeps `ref` in the props), as React would attach it. In the
// app, `deleteProfile` also unmounts the window today (App shows its loading screen while the
// profiles reload), and React empties that ref first.
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
@ -33,16 +38,22 @@ vi.mock("../../contexts/ProfileContext", () => ({
import { Trash2 } from "lucide-react";
import { hookHarness } from "../../test/hookHarness";
import { holding, type TreeProps } from "../../test/elementTree";
import { find, holding, texts, type TreeProps } from "../../test/elementTree";
import ProfileFormModal from "./ProfileFormModal";
const harness = hookHarness();
type Props = TreeProps & { onClick?: () => Promise<void> };
/** The element the ref of « Create » holds: a focus spy. */
const create = { focus: vi.fn() };
/** Clicks the only delete button, the secondary profile's, and waits for its handler. */
async function clickDelete() {
const tree = harness.render(() => ProfileFormModal({ onClose: vi.fn() }));
const creates = find(tree, (el) => el.type === "button" && texts(el).includes("t(profile.create)"));
expect(creates).toHaveLength(1);
(creates[0].props.ref as { current: unknown }).current = create;
const buttons = holding<Props>(tree, Trash2);
expect(buttons).toHaveLength(1);
await buttons[0].props.onClick?.();
@ -52,6 +63,7 @@ beforeEach(() => {
harness.clear();
mocks.confirmAction.mockReset();
mocks.deleteProfile.mockClear();
create.focus.mockReset();
});
describe("ProfileFormModal deletion (#421)", () => {
@ -72,3 +84,22 @@ describe("ProfileFormModal deletion (#421)", () => {
expect(mocks.deleteProfile).toHaveBeenCalledWith("second");
});
});
describe("ProfileFormModal deletion — focus (#494)", () => {
it("puts the focus on « Create » once the profile is deleted, not before", async () => {
mocks.confirmAction.mockResolvedValue(true);
await clickDelete();
expect(create.focus).toHaveBeenCalledTimes(1);
expect(mocks.deleteProfile.mock.invocationCallOrder[0]).toBeLessThan(create.focus.mock.invocationCallOrder[0]);
});
it("leaves the focus alone when the confirmation is refused: the row and its button stay", async () => {
mocks.confirmAction.mockResolvedValue(false);
await clickDelete();
expect(create.focus).not.toHaveBeenCalled();
});
});

View file

@ -0,0 +1,323 @@
// ProfileFormModal — a named modal dialog, closed on Escape except while a save
// runs, whose focus goes to its X at the opening and follows its mode (#494).
//
// No jsdom: react-dom/server renders the markup in vitest's node environment.
// React's hooks come from the shared harness (src/test/hookHarness.ts, #409):
// the window runs as a plain function inside `harness.render`, the test clicks
// through the props of the rendered tree, renders again to read the new mode,
// and `commit()` runs the effects against a stubbed `document` (the node
// environment has none). The fake elements of the X, of « Create » and of the
// dialog element reach their refs through `props.ref` (React 19 keeps `ref` in
// the props), as React would attach them, never through a preset slot of the
// harness: a shared hook moves the slots. The harness never detaches a ref,
// so the fake of « Create » stays in its ref while the list is not rendered.
// UpsellGate stays an element, never called.
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import type { KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from "react";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
const ctx = vi.hoisted(() => ({
/** What `useEntitlement("multi-profile")` returns: Base by default, creation open. */
gate: { allowed: true, ready: true },
createProfile: vi.fn<(name: string, color: string, pin?: string) => Promise<void>>(),
updateProfile: vi.fn<(id: string, updates: unknown) => Promise<void>>(),
}));
vi.mock("../../services/confirmService", () => ({ confirmAction: vi.fn() }));
vi.mock("../../hooks/useEntitlement", () => ({ useEntitlement: () => ctx.gate }));
vi.mock("../../contexts/ProfileContext", () => ({
useProfile: () => ({
profiles: [
{ id: "default", name: "Principal", color: "#4A90A4", pin_hash: null, db_filename: "simpl_resultat.db", created_at: "" },
{ id: "second", name: "Second", color: "#C17767", pin_hash: null, db_filename: "profile_second.db", created_at: "" },
],
createProfile: ctx.createProfile,
updateProfile: ctx.updateProfile,
deleteProfile: vi.fn(),
setPin: vi.fn(),
}),
}));
import { hookHarness } from "../../test/hookHarness";
import { find, texts, type TreeElement } from "../../test/elementTree";
import ProfileFormModal, { PROFILE_FORM_TITLE_ID } from "./ProfileFormModal";
import UpsellGate from "../shared/UpsellGate";
const harness = hookHarness();
interface FakeElement {
focus: ReturnType<typeof vi.fn>;
isConnected: boolean;
}
const element = (): FakeElement => ({ focus: vi.fn(), isConnected: true });
type KeyListener = (e: Pick<KeyboardEvent, "key">) => void;
const doc = {
activeElement: null as FakeElement | null,
body: element(),
addEventListener: vi.fn<(type: string, listener: KeyListener) => void>(),
removeEventListener: vi.fn<(type: string, listener: KeyListener) => void>(),
};
/** The buttons whose text is the marked `key`, in tree order. */
const buttonsSaying = (tree: ReactNode, key: string) =>
find(tree, (el) => el.type === "button" && texts(el).includes(`t(${key})`));
const closeButtons = (tree: ReactNode) =>
find(tree, (el) => el.type === "button" && el.props["aria-label"] === "t(common.close)");
const dialogElements = (tree: ReactNode) => find(tree, (el) => el.props.role === "dialog");
/** Calls the click handler of the one button of `buttons`, and returns what it returns. */
function click(buttons: TreeElement[]): unknown {
expect(buttons).toHaveLength(1);
return (buttons[0].props.onClick as () => unknown)();
}
const setRef = (el: TreeElement, fake: unknown) => {
(el.props.ref as { current: unknown }).current = fake;
};
beforeEach(() => {
harness.clear();
ctx.gate = { allowed: true, ready: true };
ctx.createProfile.mockReset();
ctx.updateProfile.mockReset();
ctx.createProfile.mockResolvedValue(undefined);
ctx.updateProfile.mockResolvedValue(undefined);
doc.activeElement = null;
doc.addEventListener.mockReset();
doc.removeEventListener.mockReset();
vi.stubGlobal("document", doc);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("ProfileFormModal — a named modal dialog (#494)", () => {
it("is a modal dialog named by its title, with a Close button", () => {
vi.unstubAllGlobals(); // the static render runs no effect, and needs no document
const html = renderToStaticMarkup(<ProfileFormModal onClose={vi.fn()} />);
expect(html).toContain('role="dialog"');
expect(html).toContain('aria-modal="true"');
expect(html).toContain(`aria-labelledby="${PROFILE_FORM_TITLE_ID}"`);
expect(html).toMatch(new RegExp(`<h2 id="${PROFILE_FORM_TITLE_ID}"[^>]*>t\\(profile\\.manageProfiles\\)</h2>`));
expect(html).toContain('<button type="button" aria-label="t(common.close)"');
});
it("keeps its role, its name and its X in every mode, the title following the mode", () => {
const seen: Array<[string, string[]]> = [];
const read = (tree: ReactNode) => {
const [dialog] = dialogElements(tree);
expect(dialog.props).toMatchObject({ "aria-modal": "true", "aria-labelledby": PROFILE_FORM_TITLE_ID });
const titles = find(tree, (el) => el.type === "h2");
expect(titles).toHaveLength(1);
expect(titles[0].props.id).toBe(PROFILE_FORM_TITLE_ID);
const [x] = closeButtons(tree);
expect(x.props.type).toBe("button");
return texts(titles[0]);
};
const list = harness.render(() => ProfileFormModal({ onClose: vi.fn() }));
seen.push(["list", read(list)]);
click(buttonsSaying(list, "common.edit").slice(1));
const edit = harness.render(() => ProfileFormModal({ onClose: vi.fn() }));
seen.push(["edit", read(edit)]);
click(buttonsSaying(edit, "common.cancel"));
ctx.gate = { allowed: false, ready: true };
click(buttonsSaying(harness.render(() => ProfileFormModal({ onClose: vi.fn() })), "profile.create"));
const upsell = harness.render(() => ProfileFormModal({ onClose: vi.fn() }));
expect(find(upsell, (el) => el.type === UpsellGate)).toHaveLength(1);
seen.push(["upsell", read(upsell)]);
expect(seen).toEqual([
["list", ["t(profile.manageProfiles)"]],
["edit", ["t(profile.edit)"]],
["upsell", ["t(profile.create)"]],
]);
});
});
describe("ProfileFormModal — Escape (#494)", () => {
/** The keydown listener the window added last. */
function latestListener(): KeyListener {
const added = doc.addEventListener.mock.calls.filter(([type]) => type === "keydown");
expect(added.length).toBeGreaterThan(0);
return added[added.length - 1][1];
}
/** One render of the mounted window, then its effects. */
function renderAndCommit(onClose: () => void) {
const tree = harness.render(() => ProfileFormModal({ onClose }));
harness.commit();
return tree;
}
it("Escape closes it, like its X", () => {
const onClose = vi.fn();
const tree = renderAndCommit(onClose);
latestListener()({ key: "Escape" });
expect(onClose).toHaveBeenCalledTimes(1);
click(closeButtons(tree));
expect(onClose).toHaveBeenCalledTimes(2);
});
it("another key leaves it open", () => {
const onClose = vi.fn();
renderAndCommit(onClose);
const listener = latestListener();
for (const key of ["Enter", " ", "Tab", "a"]) listener({ key });
expect(onClose).not.toHaveBeenCalled();
});
it("Escape does nothing while a save runs, and closes it again once the save is over", async () => {
let finish: (() => void) | undefined;
ctx.updateProfile.mockImplementation(
() =>
new Promise<void>((resolve) => {
finish = () => resolve();
}),
);
const onClose = vi.fn();
const list = renderAndCommit(onClose);
click(buttonsSaying(list, "common.edit").slice(1));
const edit = renderAndCommit(onClose);
const saving = click(buttonsSaying(edit, "common.save")) as Promise<void>;
renderAndCommit(onClose);
latestListener()({ key: "Escape" });
expect(onClose).not.toHaveBeenCalled();
expect(finish).toBeDefined();
finish?.();
await saving;
renderAndCommit(onClose);
latestListener()({ key: "Escape" });
expect(onClose).toHaveBeenCalledTimes(1);
});
it("removes its listener when it goes away", () => {
renderAndCommit(vi.fn());
const listener = latestListener();
harness.unmount();
expect(doc.removeEventListener).toHaveBeenCalledWith("keydown", listener);
});
});
describe("ProfileFormModal — focus (#494)", () => {
const close = element();
const create = element();
beforeEach(() => {
close.focus.mockReset();
create.focus.mockReset();
});
/**
* One render of the mounted window: hands the refs of the X and of
* « Create », when they are in the tree, their fakes, then runs the effects.
*/
function show(options: { returnFocusTo?: RefObject<HTMLElement | null>; dialog?: object } = {}) {
const tree = harness.render(() => ProfileFormModal({ onClose: vi.fn(), returnFocusTo: options.returnFocusTo }));
for (const x of closeButtons(tree)) setRef(x, close);
for (const button of buttonsSaying(tree, "profile.create")) setRef(button, create);
if (options.dialog) setRef(dialogElements(tree)[0], options.dialog);
harness.commit();
return tree;
}
it("puts the focus on its X once mounted, never on « Create »", () => {
show();
expect(close.focus).toHaveBeenCalledTimes(1);
expect(create.focus).not.toHaveBeenCalled();
});
it("StrictMode's second run at mount leaves it on the X", () => {
show();
harness.replayEffects();
expect(create.focus).not.toHaveBeenCalled();
expect(close.focus).toHaveBeenCalledTimes(2);
});
it("entering the upsell puts it on the X, and Cancel back on « Create »", () => {
ctx.gate = { allowed: false, ready: true };
const list = show();
expect(close.focus).toHaveBeenCalledTimes(1);
click(buttonsSaying(list, "profile.create"));
const upsell = show();
expect(find(upsell, (el) => el.type === UpsellGate)).toHaveLength(1);
expect(close.focus).toHaveBeenCalledTimes(2);
expect(create.focus).not.toHaveBeenCalled();
click(buttonsSaying(upsell, "common.cancel"));
show();
expect(create.focus).toHaveBeenCalledTimes(1);
expect(close.focus).toHaveBeenCalledTimes(2);
});
it("the create and edit forms keep the autoFocus of their name field, and Cancel brings the focus back on « Create »", () => {
for (const [mode, enter] of [
["create", (tree: ReactNode) => buttonsSaying(tree, "profile.create")],
["edit", (tree: ReactNode) => buttonsSaying(tree, "common.edit").slice(1)],
] as const) {
harness.clear();
close.focus.mockReset();
create.focus.mockReset();
click(enter(show()));
const form = show();
const names = find(form, (el) => el.type === "input" && el.props.type === "text");
expect(names, mode).toHaveLength(1);
expect(names[0].props.autoFocus, mode).toBe(true);
expect(close.focus, mode).toHaveBeenCalledTimes(1); // the mount only
expect(create.focus, mode).not.toHaveBeenCalled();
click(buttonsSaying(form, "common.cancel"));
show();
expect(create.focus, mode).toHaveBeenCalledTimes(1);
}
});
it("a save brings the focus back on « Create »", async () => {
for (const mode of ["edit", "create"] as const) {
harness.clear();
create.focus.mockReset();
const list = show();
if (mode === "edit") {
click(buttonsSaying(list, "common.edit").slice(1));
} else {
click(buttonsSaying(list, "profile.create"));
const [name] = find(show(), (el) => el.type === "input" && el.props.type === "text");
(name.props.onChange as (e: { target: { value: string } }) => void)({ target: { value: "Vacances" } });
}
const form = show();
expect(create.focus, mode).not.toHaveBeenCalled();
await click(buttonsSaying(form, "common.save"));
show();
expect(create.focus, mode).toHaveBeenCalledTimes(1);
}
expect(ctx.updateProfile).toHaveBeenCalledWith("second", { name: "Second", color: "#C17767" });
expect(ctx.createProfile).toHaveBeenCalledWith("Vacances", expect.any(String), undefined);
});
it("gives the focus back to returnFocusTo when it goes away, else to the element active at the opening", () => {
const opener = element();
const trigger = element();
doc.activeElement = opener;
show({ returnFocusTo: { current: trigger } as unknown as RefObject<HTMLElement | null> });
harness.unmount();
expect(trigger.focus).toHaveBeenCalledTimes(1);
expect(opener.focus).not.toHaveBeenCalled();
harness.clear();
show();
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(1);
});
it("Tab on « Create », its last button, goes back to the X, through the handler of the dialog element", () => {
const pin = element();
const tree = show({ dialog: { querySelectorAll: () => [close, pin, create] } });
close.focus.mockReset();
const preventDefault = vi.fn();
const onKeyDown = dialogElements(tree)[0].props.onKeyDown as (event: ReactKeyboardEvent<HTMLElement>) => void;
onKeyDown({ key: "Tab", shiftKey: false, target: create, preventDefault } as unknown as ReactKeyboardEvent<HTMLElement>);
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(close.focus).toHaveBeenCalledTimes(1);
});
});

View file

@ -1,8 +1,9 @@
import { useState } from "react";
import { useEffect, useRef, useState, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import { X, Trash2, Lock, LockOpen, Plus } from "lucide-react";
import { useProfile } from "../../contexts/ProfileContext";
import { useEntitlement } from "../../hooks/useEntitlement";
import { useDialogFocus } from "../../hooks/useDialogFocus";
import { requiredTierFor } from "../../shared/entitlements";
import { isProfileCreationLocked } from "../../shared/profileGate";
import { confirmAction } from "../../services/confirmService";
@ -13,12 +14,26 @@ const PRESET_COLORS = [
"#ec4899", "#06b6d4", "#f97316", "#6366f1", "#14b8a6",
];
/**
* The id of the window's title, its accessible name (#494). A static id: two
* instances never coexist, ProfileSelectionPage rendering only without an
* active profile (as in StarterAccountsModal); a generated id would make the
* hook harness of the tests throw.
*/
export const PROFILE_FORM_TITLE_ID = "profile-form-title";
interface Props {
onClose: () => void;
editProfileId?: string;
/**
* Where the focus goes back when the window closes, when the button that
* opened it is gone by then: ProfileSwitcher passes its trigger (#494).
* Without it, the focus goes back to the element active at the opening.
*/
returnFocusTo?: RefObject<HTMLElement | null>;
}
export default function ProfileFormModal({ onClose, editProfileId }: Props) {
export default function ProfileFormModal({ onClose, editProfileId, returnFocusTo }: Props) {
const { t } = useTranslation();
const { profiles, createProfile, updateProfile, deleteProfile, setPin } = useProfile();
// Multi-profile gate (Base+, #300) — this modal is the SINGLE creation
@ -41,6 +56,36 @@ export default function ProfileFormModal({ onClose, editProfileId }: Props) {
const [color, setColor] = useState(editProfile?.color ?? PRESET_COLORS[0]);
const [pin, setPin_] = useState("");
const [saving, setSaving] = useState(false);
const dialogRef = useRef<HTMLDivElement>(null);
const closeRef = useRef<HTMLButtonElement>(null);
const createRef = useRef<HTMLButtonElement>(null);
// Focus (#494): on the X once mounted, in every mode; Tab and Shift+Tab kept
// inside; given back when the window goes away.
const { onKeyDown } = useDialogFocus({ dialog: dialogRef, initialFocus: closeRef, returnFocusTo });
// Escape closes the window like its X, except while a save is running (as
// in FeedbackDialog). The listener follows the latest onClose and `saving`.
useEffect(() => {
function handleEscape(e: KeyboardEvent) {
if (e.key === "Escape" && !saving) onClose();
}
document.addEventListener("keydown", handleEscape);
return () => document.removeEventListener("keydown", handleEscape);
}, [onClose, saving]);
// A change of mode unmounts the button that had the focus (Create, Cancel,
// Save): entering the upsell puts the focus on the X, every return to the
// list on « Create ». The create and edit forms keep the autoFocus of their
// name field. Never at mount, where the initial focus goes to the X: the
// mode last acted on starts as the mode of the first render, so StrictMode's
// second run of the effect at mount does nothing either.
const focusedMode = useRef(mode);
useEffect(() => {
if (focusedMode.current === mode) return;
focusedMode.current = mode;
if (mode === "upsell") closeRef.current?.focus();
else if (mode === "list") createRef.current?.focus();
}, [mode]);
const handleCreate = () => {
if (creationLocked) {
@ -91,6 +136,11 @@ export default function ProfileFormModal({ onClose, editProfileId }: Props) {
if (!profile || profile.db_filename === "simpl_resultat.db") return;
if (!(await confirmAction(t("profile.deleteConfirm")))) return;
await deleteProfile(id);
// The deleted row takes its delete button, which had the focus, with it:
// the focus goes to « Create », as on every return to the list (#494).
// Today `deleteProfile` also unmounts the window (App shows its loading
// screen while the profiles reload), and the ref is empty by then.
createRef.current?.focus();
};
const handleTogglePin = async (id: string) => {
@ -109,16 +159,29 @@ export default function ProfileFormModal({ onClose, editProfileId }: Props) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div className="bg-[var(--card)] rounded-xl shadow-xl w-full max-w-md border border-[var(--border)]">
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={PROFILE_FORM_TITLE_ID}
onKeyDown={onKeyDown}
className="bg-[var(--card)] rounded-xl shadow-xl w-full max-w-md border border-[var(--border)]"
>
<div className="flex items-center justify-between p-4 border-b border-[var(--border)]">
<h2 className="font-semibold text-[var(--foreground)]">
<h2 id={PROFILE_FORM_TITLE_ID} className="font-semibold text-[var(--foreground)]">
{mode === "create" || mode === "upsell"
? t("profile.create")
: mode === "edit"
? t("profile.edit")
: t("profile.manageProfiles")}
</h2>
<button onClick={onClose} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
<button
ref={closeRef}
type="button"
onClick={onClose}
aria-label={t("common.close")}
className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
>
<X size={18} />
</button>
</div>
@ -164,6 +227,7 @@ export default function ProfileFormModal({ onClose, editProfileId }: Props) {
</div>
))}
<button
ref={createRef}
onClick={handleCreate}
title={creationLocked ? t("nav.locked") : undefined}
className={`flex items-center gap-2 w-full p-3 rounded-lg border-2 border-dashed border-[var(--border)] hover:border-[var(--primary)] text-[var(--muted-foreground)] text-sm transition-colors ${

View file

@ -21,6 +21,10 @@ export default function ProfileSwitcher() {
const [showManage, setShowManage] = useState(false);
const [showUpsell, setShowUpsell] = useState(false);
const ref = useRef<HTMLDivElement>(null);
// The windows opened from the menu give the focus back to this button when
// they close (#494): the menu item that opened them is unmounted with the
// menu, in the same update as the window mounts.
const triggerRef = useRef<HTMLButtonElement>(null);
// Close on outside click
useEffect(() => {
@ -69,7 +73,11 @@ export default function ProfileSwitcher() {
return (
<>
<div ref={ref} className="relative px-3 pb-2">
{/* No aria-haspopup: the list is not a role="menu" (#494). */}
<button
ref={triggerRef}
type="button"
aria-expanded={open}
onClick={() => setOpen(!open)}
className="flex items-center gap-2 w-full px-3 py-2 rounded-lg text-sm hover:bg-[var(--sidebar-hover)] transition-colors"
>
@ -135,10 +143,16 @@ export default function ProfileSwitcher() {
)}
{showManage && (
<ProfileFormModal onClose={() => setShowManage(false)} />
<ProfileFormModal onClose={() => setShowManage(false)} returnFocusTo={triggerRef} />
)}
{showUpsell && <UpsellDialog feature="multi-profile" onClose={() => setShowUpsell(false)} />}
{showUpsell && (
<UpsellDialog
feature="multi-profile"
onClose={() => setShowUpsell(false)}
returnFocusTo={triggerRef}
/>
)}
</>
);
}

View file

@ -12,7 +12,10 @@
// UpsellDialog stays an element, never called: what it renders (UpsellGate,
// Escape) is proved by UpsellDialog.render.test.tsx. A locked profile that has
// a PIN opens the dialog, never the PIN entry: the lock is checked first, or
// the right PIN would switch to a locked profile.
// the right PIN would switch to a locked profile. The windows opened from the
// menu give the focus back to the switcher's trigger (#494): the test reads the
// ref each window element receives, what the window does with it being proved
// by UpsellDialog.render.test.tsx and ProfileFormModal.render.test.tsx.
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { ReactNode } from "react";
@ -39,11 +42,12 @@ vi.mock("../../contexts/ProfileContext", () => ({
}),
}));
import { ChevronDown } from "lucide-react";
import { ChevronDown, Settings } from "lucide-react";
import { hookHarness } from "../../test/hookHarness";
import { find, holding } from "../../test/elementTree";
import ProfileSwitcher from "./ProfileSwitcher";
import PinDialog from "./PinDialog";
import ProfileFormModal from "./ProfileFormModal";
import UpsellDialog from "../shared/UpsellDialog";
import UpsellGate from "../shared/UpsellGate";
@ -137,3 +141,55 @@ describe("ProfileSwitcher — the upsell of a locked profile (#451)", () => {
expect(ctx.switchProfile).not.toHaveBeenCalled();
});
});
describe("ProfileSwitcher — the trigger and the focus of its windows (#494)", () => {
/** The trigger: the button that holds the chevron. */
function trigger(tree: ReactNode) {
const toggles = holding(tree, ChevronDown);
expect(toggles).toHaveLength(1);
return toggles[0];
}
/** The trigger's ref: a ref object, the one React fills with the button. */
function triggerRef(tree: ReactNode) {
const ref = trigger(tree).props.ref;
expect(ref).toHaveProperty("current");
return ref;
}
it("is a plain button whose aria-expanded follows the menu, without aria-haspopup", () => {
const closed = trigger(render());
expect(closed.props.type).toBe("button");
expect(closed.props["aria-expanded"]).toBe(false);
// The list is not a role="menu": announcing a menu would be wrong (Max, 2026-10-25).
expect(closed.props).not.toHaveProperty("aria-haspopup");
(closed.props.onClick as () => void)();
const opened = trigger(render());
expect(opened.props["aria-expanded"]).toBe(true);
expect(opened.props).not.toHaveProperty("aria-haspopup");
(opened.props.onClick as () => void)();
expect(trigger(render()).props["aria-expanded"]).toBe(false);
});
it("a locked profile's window gives the focus back to the trigger: the menu item is gone by then", () => {
openMenu();
(profileButtons(render(), "second")[0].props.onClick as () => void)();
const opened = render();
const shown = dialogs(opened);
expect(shown).toHaveLength(1);
expect(shown[0].props.returnFocusTo).toBe(triggerRef(opened));
});
it("« Manage profiles » gives the focus back to the trigger too", () => {
openMenu();
const manage = holding(render(), Settings);
expect(manage).toHaveLength(1);
(manage[0].props.onClick as () => void)();
const opened = render();
const forms = find(opened, (el) => el.type === ProfileFormModal);
expect(forms).toHaveLength(1);
expect(forms[0].props.returnFocusTo).toBe(triggerRef(opened));
expect(dialogs(opened)).toHaveLength(0);
});
});

View file

@ -1,13 +1,18 @@
// UpsellDialog — the locked screen in a modal (#369), closed on Escape (#451).
// UpsellDialog — the locked screen in a modal (#369), closed on Escape (#451),
// with the focus on its X and kept inside (#494).
// No jsdom: react-dom/server renders the markup in vitest's node environment.
// React's hooks come from the shared harness (src/test/hookHarness.ts, #409):
// the dialog runs as a plain function inside `harness.render`, which exposes
// the props it hands to UpsellGate and to its close button, and `commit()`
// runs its Escape effect against a stubbed `document` (the node environment
// has none), whose listener the test then calls with a key.
// has none), whose listener the test then calls with a key. For the focus,
// the test hands fake elements to the refs of the X and of the dialog element
// through their `props.ref` (React 19 keeps `ref` in the props), as React
// would attach them, never through a preset slot of the harness.
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import type { KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from "react";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
vi.mock("@tauri-apps/plugin-opener", () => ({ openUrl: vi.fn(() => Promise.resolve()) }));
@ -133,3 +138,98 @@ describe("UpsellDialog — Escape (#451)", () => {
expect(first).not.toHaveBeenCalled();
});
});
describe("UpsellDialog — focus (#494)", () => {
interface FakeElement {
focus: ReturnType<typeof vi.fn>;
isConnected: boolean;
}
const element = (): FakeElement => ({ focus: vi.fn(), isConnected: true });
const doc = {
activeElement: null as FakeElement | null,
body: element(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
};
const refTo = (current: FakeElement) => ({ current }) as unknown as RefObject<HTMLElement | null>;
beforeEach(() => {
doc.activeElement = null;
doc.addEventListener.mockReset();
doc.removeEventListener.mockReset();
vi.stubGlobal("document", doc);
});
afterEach(() => {
vi.unstubAllGlobals();
});
const closeButtons = (tree: ReactNode) =>
find(tree, (el) => el.type === "button" && el.props["aria-label"] === "t(common.close)");
const dialogElements = (tree: ReactNode) => find(tree, (el) => el.props.role === "dialog");
/**
* Renders the dialog, hands the refs of its X and of its dialog element the
* fakes, then runs its effects: the dialog as React mounts it.
*/
function mount(close: FakeElement, options: { dialog?: object; returnFocusTo?: RefObject<HTMLElement | null> } = {}) {
const tree = harness.render(() =>
UpsellDialog({ feature: "adjustments", onClose: vi.fn(), returnFocusTo: options.returnFocusTo }),
);
const [x] = closeButtons(tree);
(x.props.ref as { current: unknown }).current = close;
const [dialog] = dialogElements(tree);
if (options.dialog) (dialog.props.ref as { current: unknown }).current = options.dialog;
harness.commit();
return dialog;
}
it("puts the focus on its X once mounted, not during the render", () => {
const close = element();
const tree = harness.render(() => UpsellDialog({ feature: "adjustments", onClose: vi.fn() }));
(closeButtons(tree)[0].props.ref as { current: unknown }).current = close;
expect(close.focus).not.toHaveBeenCalled();
harness.commit();
expect(close.focus).toHaveBeenCalledTimes(1);
});
it("gives the focus back to the element active at the opening when it goes away (the Répartition button)", () => {
const opener = element();
doc.activeElement = opener;
mount(element());
expect(opener.focus).not.toHaveBeenCalled();
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(1);
});
it("gives it to returnFocusTo instead when the host passes it (the profile switcher's trigger)", () => {
const opener = element();
const trigger = element();
doc.activeElement = opener;
mount(element(), { returnFocusTo: refTo(trigger) });
harness.unmount();
expect(trigger.focus).toHaveBeenCalledTimes(1);
expect(opener.focus).not.toHaveBeenCalled();
});
it("Tab on its last button goes back to the X, through the handler of the dialog element", () => {
const close = element();
const purchase = element();
const haveKey = element();
const dialog = mount(close, { dialog: { querySelectorAll: () => [close, purchase, haveKey] } });
close.focus.mockClear();
const preventDefault = vi.fn();
const onKeyDown = dialog.props.onKeyDown as (event: ReactKeyboardEvent<HTMLElement>) => void;
onKeyDown({ key: "Tab", shiftKey: false, target: haveKey, preventDefault } as unknown as ReactKeyboardEvent<HTMLElement>);
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(close.focus).toHaveBeenCalledTimes(1);
onKeyDown({ key: "Tab", shiftKey: true, target: close, preventDefault } as unknown as ReactKeyboardEvent<HTMLElement>);
expect(haveKey.focus).toHaveBeenCalledTimes(1);
});
it("adds no listener of its own to the document: Escape stays the only one", () => {
mount(element());
expect(doc.addEventListener).toHaveBeenCalledTimes(1);
expect(doc.addEventListener).toHaveBeenCalledWith("keydown", expect.any(Function));
});
});

View file

@ -1,12 +1,19 @@
import { useEffect } from "react";
import { useEffect, useRef, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import { X } from "lucide-react";
import { requiredTierFor, type FeatureKey } from "../../shared/entitlements";
import { useDialogFocus } from "../../hooks/useDialogFocus";
import UpsellGate from "./UpsellGate";
interface UpsellDialogProps {
feature: FeatureKey;
onClose: () => void;
/**
* Where the focus goes back when the dialog goes away, when the button that
* opened it is gone by then: ProfileSwitcher passes its trigger (#494).
* Without it, the focus goes back to the element active at the opening.
*/
returnFocusTo?: RefObject<HTMLElement | null>;
}
/**
@ -19,10 +26,16 @@ interface UpsellDialogProps {
* page; the purchase button leaves it open (the product page opens in the
* browser). The X button and Escape close it too; a click on the backdrop does
* not.
*
* Focus (#494, `useDialogFocus`): on the X once mounted, Tab and Shift+Tab
* kept inside, and given back when the dialog goes away, however it goes.
*/
export default function UpsellDialog({ feature, onClose }: UpsellDialogProps) {
export default function UpsellDialog({ feature, onClose, returnFocusTo }: UpsellDialogProps) {
const { t } = useTranslation();
const requiredTier = requiredTierFor(feature);
const dialogRef = useRef<HTMLDivElement>(null);
const closeRef = useRef<HTMLButtonElement>(null);
const { onKeyDown } = useDialogFocus({ dialog: dialogRef, initialFocus: closeRef, returnFocusTo });
// Escape closes the dialog, as in TransactionDetailModal. The listener
// follows the latest onClose: hosts pass an inline arrow.
@ -37,13 +50,16 @@ export default function UpsellDialog({ feature, onClose }: UpsellDialogProps) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-label={t("upsell.title", { tier: t(`license.editions.${requiredTier}`) })}
onKeyDown={onKeyDown}
className="bg-[var(--card)] rounded-xl shadow-xl w-full max-w-md border border-[var(--border)]"
>
<div className="flex justify-end p-3 pb-0">
<button
ref={closeRef}
type="button"
onClick={onClose}
aria-label={t("common.close")}

View file

@ -1,4 +1,4 @@
import { Fragment, useState, useMemo } from "react";
import { Fragment, useState, useMemo, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { ChevronUp, ChevronDown, MessageSquare, Tag, Link2 } from "lucide-react";
import type {
@ -95,6 +95,14 @@ export default function TransactionTable({
() => [{ value: "", label: t("transactions.table.noCategory") }],
[t]
);
// The upsell goes away without onClose once the edition resolves to Base or
// Premium (see its render below): clear its flag then, or the dialog would
// come back on its own, and take the focus, if the access went back to
// locked (#494). Before the early return: no hook may come after it, or the
// number of hooks would change when the list goes from no row to some.
useEffect(() => {
if (splitAccess === "open") setShowSplitUpsell(false);
}, [splitAccess]);
if (rows.length === 0) {
return (

View file

@ -7,7 +7,8 @@
// state survives from one call to the next as between two renders of a mounted
// component, and the test clicks through the props the table hands to each
// SplitButton (or to a row's notes button), then renders again to read what
// opened.
// opened. `commit()` runs the table's one effect, which clears the upsell's
// flag once the edition is Base (#494); it touches no `document`.
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Fragment, type ReactNode } from "react";
@ -52,11 +53,11 @@ const row = (id: number, isSplit: boolean): TransactionRow => ({
/** A split row and a plain one: the button must behave the same on both. */
const ROWS = [row(1, true), row(2, false)];
/** One render of the mounted table, under the given access. */
const render = (splitAccess: SplitAccess) =>
/** One render of the mounted table, under the given access, with the given rows (the two of ROWS by default). */
const render = (splitAccess: SplitAccess, rows: TransactionRow[] = ROWS) =>
harness.render(() =>
TransactionTable({
rows: ROWS,
rows,
sort: { column: "date", direction: "desc" },
categories: [GROCERIES],
onSort: vi.fn(),
@ -135,6 +136,40 @@ describe("TransactionTable — the Répartition button's wiring (#369)", () => {
});
});
// The upsell goes away without onClose once the edition is Base: its flag must
// go too, or the dialog would come back on its own, and take the focus, if the
// access went back to locked (#494).
describe("TransactionTable — an upsell gone with the edition stays gone (#494)", () => {
it("does not come back on its own when the access turns locked again", () => {
render("locked");
harness.commit();
(splitButtons(render("locked"))[0].props.onOpenUpsell as () => void)();
// A refresh keeps it open: only an edition that resolves to Base or Premium clears it.
expect(upsells(render("pending"))).toHaveLength(1);
harness.commit();
expect(upsells(render("locked"))).toHaveLength(1);
harness.commit();
expect(upsells(render("open"))).toHaveLength(0);
harness.commit();
expect(upsells(render("locked"))).toHaveLength(0);
// A click opens it again, as before.
(splitButtons(render("locked"))[0].props.onOpenUpsell as () => void)();
expect(upsells(render("locked"))).toHaveLength(1);
});
// The effect sits before the early return of an empty table: a hook after it
// would change the number of hooks when the list goes from no row to some
// (React throws), and would not run while the table is empty.
it("clears it even while the table has no row", () => {
(splitButtons(render("locked"))[0].props.onOpenUpsell as () => void)();
render("locked", []);
harness.commit();
render("open", []);
harness.commit();
expect(upsells(render("locked"))).toHaveLength(0);
});
});
describe("TransactionTable — the notes row (#437)", () => {
/** The rows' notes buttons, named by their title (pinned in TransactionTable.render.test.tsx). */
const notesButtons = (tree: ReactNode) =>

View file

@ -0,0 +1,247 @@
// useDialogFocus — the focus of a modal window (#494).
//
// No jsdom: React's hooks come from the shared harness (src/test/hookHarness.ts,
// #409), the hook runs as a plain function inside `harness.render`, `commit()`
// runs its effect and `unmount()` its cleanup. The DOM is faked: `document` is a
// stub (`vi.stubGlobal`) whose `activeElement` and `body` the test sets, the
// elements are objects with a `focus` spy and an `isConnected` flag, and the
// dialog's `querySelectorAll` returns the elements the test lists. The refs are
// plain `{ current }` objects: the hook is called directly, not through the
// tree of a component (UpsellDialog.render.test.tsx and
// ProfileFormModal.render.test.tsx prove that wiring through `props.ref`).
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { KeyboardEvent as ReactKeyboardEvent, RefObject } from "react";
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
import { hookHarness } from "../test/hookHarness";
import { FOCUSABLE_SELECTOR, useDialogFocus } from "./useDialogFocus";
const harness = hookHarness();
interface FakeElement {
focus: ReturnType<typeof vi.fn>;
isConnected: boolean;
}
/** An element of the fake DOM: a focus spy, in the document unless told otherwise. */
const element = (isConnected = true): FakeElement => ({ focus: vi.fn(), isConnected });
const doc: { activeElement: FakeElement | null; body: FakeElement } = { activeElement: null, body: element() };
/** A ref holding a fake element, typed as the hook takes it. */
const refTo = (current: FakeElement | object | null) => ({ current }) as unknown as RefObject<HTMLElement | null>;
/** The dialog element: `querySelectorAll` returns `items`, the focusable elements in DOM order. */
function dialogOf(items: FakeElement[]) {
return { querySelectorAll: vi.fn((_selector: string) => items) };
}
/** A keydown on `target`, with the spy React's `preventDefault` stands for. */
function keydown(key: string, target: FakeElement, shiftKey = false) {
const preventDefault = vi.fn();
const event = { key, shiftKey, target, preventDefault } as unknown as ReactKeyboardEvent<HTMLElement>;
return { event, preventDefault };
}
beforeEach(() => {
harness.clear();
doc.activeElement = null;
doc.body = element();
vi.stubGlobal("document", doc);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("useDialogFocus — focus at the opening (#494)", () => {
it("puts the focus on the initial element once mounted, not during the render", () => {
const close = element();
harness.render(() => useDialogFocus({ dialog: refTo(null), initialFocus: refTo(close) }));
expect(close.focus).not.toHaveBeenCalled();
harness.commit();
expect(close.focus).toHaveBeenCalledTimes(1);
});
it("does it once: a later render with the same refs leaves the focus where it is", () => {
const close = element();
const refs = { dialog: refTo(null), initialFocus: refTo(close) };
harness.render(() => useDialogFocus(refs));
harness.commit();
harness.render(() => useDialogFocus(refs));
harness.commit();
expect(close.focus).toHaveBeenCalledTimes(1);
});
it("an empty initial ref focuses nothing and does not throw", () => {
harness.render(() => useDialogFocus({ dialog: refTo(null), initialFocus: refTo(null) }));
expect(() => harness.commit()).not.toThrow();
});
});
describe("useDialogFocus — focus given back when the dialog goes away (#494)", () => {
/** Mounts the hook with the opener active, then unmounts it. */
function openThenClose(opener: FakeElement | null, returnFocusTo?: RefObject<HTMLElement | null>) {
doc.activeElement = opener;
harness.render(() => useDialogFocus({ dialog: refTo(null), initialFocus: refTo(element()), returnFocusTo }));
harness.commit();
}
it("gives it back to the element active at the opening, on unmount only", () => {
const opener = element();
openThenClose(opener);
expect(opener.focus).not.toHaveBeenCalled();
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(1);
});
it("returnFocusTo wins over the element active at the opening", () => {
const opener = element();
const trigger = element();
openThenClose(opener, refTo(trigger));
harness.unmount();
expect(trigger.focus).toHaveBeenCalledTimes(1);
expect(opener.focus).not.toHaveBeenCalled();
});
it("an empty returnFocusTo leaves the element active at the opening", () => {
const opener = element();
openThenClose(opener, refTo(null));
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(1);
});
it("never gives it to body", () => {
openThenClose(doc.body);
harness.unmount();
expect(doc.body.focus).not.toHaveBeenCalled();
});
it("never to an element no longer in the document", () => {
const opener = element();
openThenClose(opener);
// The opener is unmounted along with the dialog (a navigation, a row that goes away).
opener.isConnected = false;
harness.unmount();
expect(opener.focus).not.toHaveBeenCalled();
});
it("with nothing active at the opening, gives the focus to nothing", () => {
openThenClose(null);
expect(() => harness.unmount()).not.toThrow();
});
it("StrictMode's double run at mount ends with the focus on the initial element, the opener still remembered", () => {
const opener = element();
const close = element();
doc.activeElement = opener;
harness.render(() => useDialogFocus({ dialog: refTo(null), initialFocus: refTo(close) }));
harness.commit();
harness.replayEffects();
const calls = (spy: FakeElement) => spy.focus.mock.invocationCallOrder;
expect(calls(close)).toHaveLength(2);
expect(calls(opener)).toHaveLength(1);
// The X, the opener (the simulated unmount), then the X again.
expect(calls(close)[0]).toBeLessThan(calls(opener)[0]);
expect(calls(opener)[0]).toBeLessThan(calls(close)[1]);
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(2);
});
});
describe("useDialogFocus — Tab stays inside the dialog (#494)", () => {
const first = element();
const middle = element();
const last = element();
beforeEach(() => {
for (const el of [first, middle, last]) el.focus.mockReset();
});
/** The keydown handler of a mounted dialog whose focusable elements are `items`. */
function handler(items: FakeElement[] = [first, middle, last]) {
const dialog = dialogOf(items);
const { onKeyDown } = harness.render(() =>
useDialogFocus({ dialog: refTo(dialog), initialFocus: refTo(null) }),
);
return { onKeyDown, dialog };
}
it("Tab on the last element goes to the first, instead of leaving the dialog", () => {
const { onKeyDown, dialog } = handler();
const { event, preventDefault } = keydown("Tab", last);
onKeyDown(event);
expect(dialog.querySelectorAll).toHaveBeenCalledWith(FOCUSABLE_SELECTOR);
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(first.focus).toHaveBeenCalledTimes(1);
expect(last.focus).not.toHaveBeenCalled();
});
it("Shift+Tab on the first element goes to the last", () => {
const { onKeyDown } = handler();
const { event, preventDefault } = keydown("Tab", first, true);
onKeyDown(event);
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(last.focus).toHaveBeenCalledTimes(1);
expect(first.focus).not.toHaveBeenCalled();
});
it("anywhere else, Tab and Shift+Tab are left to the browser", () => {
const { onKeyDown } = handler();
for (const [target, shift] of [
[middle, false],
[middle, true],
[first, false],
[last, true],
] as const) {
const { event, preventDefault } = keydown("Tab", target, shift);
onKeyDown(event);
expect(preventDefault).not.toHaveBeenCalled();
}
for (const el of [first, middle, last]) expect(el.focus).not.toHaveBeenCalled();
});
it("another key does nothing, even on the last element", () => {
const { onKeyDown, dialog } = handler();
for (const key of ["Enter", "Escape", " ", "ArrowDown", "a"]) {
const { event, preventDefault } = keydown(key, last);
onKeyDown(event);
expect(preventDefault).not.toHaveBeenCalled();
}
expect(dialog.querySelectorAll).not.toHaveBeenCalled();
expect(first.focus).not.toHaveBeenCalled();
});
it("one focusable element only: Tab and Shift+Tab keep the focus on it", () => {
const { onKeyDown } = handler([middle]);
onKeyDown(keydown("Tab", middle).event);
onKeyDown(keydown("Tab", middle, true).event);
expect(middle.focus).toHaveBeenCalledTimes(2);
});
it("no focusable element, or no dialog element: Tab is left to the browser, without an error", () => {
const { onKeyDown } = handler([]);
const empty = keydown("Tab", last);
onKeyDown(empty.event);
expect(empty.preventDefault).not.toHaveBeenCalled();
harness.clear();
const { onKeyDown: unmounted } = harness.render(() =>
useDialogFocus({ dialog: refTo(null), initialFocus: refTo(null) }),
);
const none = keydown("Tab", last);
expect(() => unmounted(none.event)).not.toThrow();
expect(none.preventDefault).not.toHaveBeenCalled();
});
it("counts what the issue lists as focusable, and leaves out what is disabled", () => {
expect(FOCUSABLE_SELECTOR.split(", ")).toEqual([
"button:not([disabled])",
"[href]",
"input:not([disabled])",
"select",
"textarea",
'[tabindex]:not([tabindex="-1"])',
]);
});
});

View file

@ -0,0 +1,74 @@
import { useEffect, type KeyboardEvent as ReactKeyboardEvent, type RefObject } from "react";
/**
* What can take the focus inside a dialog, for the Tab loop (#494): a disabled
* button or field is left out, as the browser leaves it out of the Tab order.
*/
export const FOCUSABLE_SELECTOR =
'button:not([disabled]), [href], input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])';
export interface DialogFocusRefs {
/** The `role="dialog"` element: Tab and Shift+Tab loop through its focusable elements. */
dialog: RefObject<HTMLElement | null>;
/** What takes the focus once the dialog is mounted: its close button. */
initialFocus: RefObject<HTMLElement | null>;
/**
* What takes the focus back when the dialog goes away, when the host has it:
* it wins over the element that was active at mount. ProfileSwitcher passes
* its trigger, since the menu item that opened the dialog is gone by then.
*/
returnFocusTo?: RefObject<HTMLElement | null>;
}
/** The element active at mount, if the focus can go back to it: neither `body` nor out of the document. */
function returnable(element: Element | null): HTMLElement | null {
if (!element || element === document.body || !element.isConnected) return null;
return element as HTMLElement;
}
/**
* The focus of a modal window (#494), shared by UpsellDialog and
* ProfileFormModal.
*
* - Once mounted, the dialog remembers the active element and puts the focus
* on `initialFocus`.
* - When it goes away, the focus goes to `returnFocusTo` when the host passed
* it and it holds an element, otherwise to the element remembered at mount,
* unless that one is `body` or no longer in the document. This runs in the
* effect's cleanup, so it also covers a dialog its host unmounts without
* calling `onClose` (the split upsell once the edition is Base).
* - The returned `onKeyDown`, set on the dialog element (never on `document`,
* where the dialogs listen for Escape), makes Tab on the last focusable
* element go to the first, and Shift+Tab on the first go to the last.
*
* `useEffect` is its only hook: the hook harness of the tests throws on a
* generated id or a layout effect (src/test/hookHarness.ts). The refs are
* stable objects, read when the effect runs and when it is cleaned up, hence
* the empty dependency list: mount and unmount only.
*/
export function useDialogFocus({ dialog, initialFocus, returnFocusTo }: DialogFocusRefs) {
useEffect(() => {
const opener = document.activeElement;
initialFocus.current?.focus();
return () => {
(returnFocusTo?.current ?? returnable(opener))?.focus();
};
}, []);
const onKeyDown = (event: ReactKeyboardEvent<HTMLElement>) => {
if (event.key !== "Tab") return;
const focusable = dialog.current?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);
if (!focusable || focusable.length === 0) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (event.shiftKey && event.target === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && event.target === last) {
event.preventDefault();
first.focus();
}
};
return { onKeyDown };
}