From 4a855575eb071a4ec9f605a5b3aa2bfbfbecd050 Mon Sep 17 00:00:00 2001 From: Dave Liu <7david12liu@gmail.com> Date: Thu, 13 Aug 2026 18:45:13 -0700 Subject: [PATCH] Preserve deliberate focus after photo changes (#645) --- IMPLEMENTATION_PLAN.md | 2 + SECURITY.md | 1 + SYSTEM_DESIGN.md | 2 + docs/officers/EVENTS_SHOP_MEMBERS.md | 107 +++- .../account/MemberDirectoryProfile.test.tsx | 599 +++++++++++++++++- src/pages/account/MemberDirectoryProfile.tsx | 89 ++- 6 files changed, 772 insertions(+), 28 deletions(-) diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index e2893e2..c54f632 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -189,6 +189,8 @@ Exit gate: **MEMBERS-DIRECTORY-001M current source boundary:** [#643](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/643) changes only rejected-removal keyboard focus in the preserved connected Account branch. A pending focus intent is created only when request-ID creation and `startMutation('remove')` admit the exact current operation into `pending` while **Remove current saved photo** owns focus, and it contains only the mounted application-and-account lifetime and exact operation symbol. After a definitive rejection and successful current authoritative readback, that matching pending intent transfers to the result ref and the matching ready render chooses a surviving Remove action, otherwise an enabled **Save profile photo** for the exact current ready draft, otherwise the persistent Add/Replace file input for no, reading, or not-yet-ready draft. The already-focused target is left alone; body, document-root, absent, or disconnected focus returns to that target; and another connected element deliberately focused during pending keeps focus. A surviving Remove alone describes the fixed rejection. If Remove disappears, the alert remains standalone and does not become an error for Save or the file input; destination focus does not claim success or deletion proof. Programmatic or outside-focused invocation, request-ID failure, failed mutation admission, confirmed success, unknown outcome, failed confirming read, application or account change, unmount, and stale completion create no intent or clear or fail the guards. Existing confirmed-success focus, #637 Reload recovery, draft identity/bytes/render/revision behavior, mutation/read/render/context fences, and error truth remain unchanged. Focus creates no request ID, callable, retry, mutation, draft, data URL, confirmation, audit, provider action, or data action. Availability stays `false`, so the default branch and live #623 preview remain inert. #643 changes no data movement, page structure, Account wiring, service contract, Function, Rule, index, package, workflow, backend, provider, account, sign-in, production data, deployment, biometric processing, or connected/live behavior. #507 still owns privacy approval, scoped authorization, isolated staging, backend-first deployment/readback, the reviewed availability flip, connected publication, and live proof. +**MEMBERS-DIRECTORY-001N current source boundary:** [#645](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/645) changes only confirmed upload and removal keyboard focus in the preserved connected Account branch. A pending confirmed-photo intent is created only after request-ID creation and `startMutation('upload'|'remove')` admit the exact current operation into `pending`, and only while the exact **Save profile photo** or **Remove current saved photo** initiating action owns focus. It contains only the mounted application-and-account lifetime, exact operation symbol, and upload-or-remove action. A successful mutation plus current successful authoritative readback transfers only the matching lifetime, operation, and action to the result ref for one ready render. Upload keeps the persistent Add/Replace file input as its destination; removal keeps the existing surviving Remove, exact current ready Save, then persistent file-input priority. The already-focused destination is left alone; body, document-root, absent, or disconnected focus returns to that destination; and any other connected focus deliberately chosen during mutation or readback keeps focus. Programmatic or outside-focused invocation, request-ID failure, failed mutation admission, definitive rejection, unknown outcome, failed readback, application or account change, unmount, and stale completion create no intent or clear or fail the guards. #643 rejected-removal behavior, #637 Reload recovery, confirmations, exact calls, bytes, revisions, draft behavior, and existing fences remain unchanged. Focus creates no request ID, callable, retry, mutation, draft, data URL, confirmation, audit, provider action, or data action. Availability stays `false`, so the default branch and live #623 preview remain inert. #645 changes no data movement, page structure, Account wiring, People finder, visibility setting, service contract, Function, Rule, index, schema, package, workflow, backend, provider, account, sign-in, production data, deployment, biometric processing, or connected/live behavior. #507 still owns privacy approval, scoped authorization, isolated staging, backend-first deployment/readback, the reviewed availability flip, connected publication, and live proof. + ### Phase 5 — End-to-end qualification **Issue:** TEST-001 plus final closure evidence from all prior phases diff --git a/SECURITY.md b/SECURITY.md index 0e12690..bed357b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -109,6 +109,7 @@ These entries are implementation evidence, not a production risk-acceptance deci | Source-only saved-photo response containment for RISK-042 | MEMBERS-DIRECTORY-001K [#639](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/639) makes the preserved connected Account service admit an inbound returned saved photo only when the existing exact object, `image/webp`, 256×256 dimensions, and UUID version contract contains canonical base64 that decodes to 12 through 65,536 bytes with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11. Any failure returns only **Invalid member directory response.** without rendering or logging raw bytes, a provider value, or caught detail. A real Account component-to-real-service test with only `firebase/functions` mocked proves mislabeled bytes stop before a saved-thumbnail image or data URL. Structurally admitted but browser-undecodable bytes retain the version-scoped, byte-free **Photo unavailable** fallback and enabled **Remove current saved photo** action without another callable. Outbound JPG, PNG, and WebP admission and exact bytes remain unchanged. | RIFF/WEBP markers are structural admission, not full decoding, safe image proof, authenticity, server-state proof, authorization, or provider acknowledgement; header-shaped hostile bytes can still reach the browser decoder, so the byte-free render fallback remains required. The source-controlled availability value stays `false`, and live #623 remains inert. No Function, Rule, index, schema, package, workflow, photo query, facial recognition, matching, embedding, similarity, biometric processing, Firebase or provider configuration, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use only generated non-face test bytes; do not inspect or upload a real photo. | | Source-only search-focus containment for RISK-042 | MEMBERS-DIRECTORY-001L [#641](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/641) gives the preserved connected People finder one exact-operation focus intent after a valid query and request ID admit `pending`, and only when the persistent name input or Search button owns focus. Current result-card, empty-result, and fixed-failure settlement consumes the intent after render. The already-focused origin is left alone; body, root, absent, or disconnected focus returns to the same now-enabled origin; and another connected element focused during the request retains focus. Programmatic or outside-focused submit creates no intent. Editing, Clear, local validation failure, request-ID failure, application or administrator change, unmount, and stale resolution or rejection clear or fail the guards. Generated-only tests cover both origins and all three outcomes, deliberate outside focus, retained-origin focus, local failures, Clear, context changes, unmount, one exact request, and the unavailable default. | Programmatic focus is accessibility state, not authorization, search correctness, provider acknowledgement, audit proof, membership evidence, or live behavior. It stores no query, name, result, photo, account ID, request ID, or service value and creates no request ID, search, retry, Clear action, result, audit, service call, or data URL. Existing response/privacy bounds and name-only search plus human comparison of voluntary thumbnails remain unchanged; never add a photo query, face recognition, matching, embedding, similarity, biometric processing, totals, export, or roster authority. The source-controlled availability value stays `false`, and live #623 remains inert. No data movement, page structure, service/server contract, Function, Rule, index, Firebase or provider configuration, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use no real name or photo. | | Source-only rejected-removal focus containment for RISK-042 | MEMBERS-DIRECTORY-001M [#643](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/643) gives the preserved connected Account branch one exact-operation pending focus intent only after request-ID creation and admitted `pending` removal, and only when **Remove current saved photo** owns focus. A definitive rejection plus current successful authoritative readback transfers the matching pending intent to the result ref for one ready render. The destination is a surviving Remove action, otherwise the enabled Save action for the exact current ready draft, otherwise the persistent file input for no, reading, or not-yet-ready draft. Body, document-root, absent, or disconnected focus returns to that current destination; an already-focused destination is left alone; any other connected focus selected during pending is preserved. A surviving Remove alone describes the fixed rejection. If Remove disappears, the fixed alert stays standalone and is not attached to Save or the input. Generated-only tests cover all destinations, native focus eviction, retained and deliberate outside focus, request-ID failure, both readback-failure classes, application/account changes, unmount, zero extra calls, and the unavailable default. | Programmatic focus is current-interface accessibility state, not provider acknowledgement, deletion proof, reconciliation, authorization, audit evidence, or proof that the rejected removal succeeded. The focus intent contains only the mounted application-and-account lifetime and exact mutation-operation symbol, with no photo bytes, profile, request ID, revision, provider value, or error, and creates no request ID, callable, retry, mutation, draft, data URL, confirmation, audit, provider action, or data action. Existing confirmed-success and #637 Reload focus behavior remains. The source-controlled availability value stays `false`, and live #623 remains inert. No data movement, page structure, service/server contract, Function, Rule, index, Firebase or provider configuration, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use no real name or photo. | +| Source-only confirmed-photo focus containment for RISK-042 | MEMBERS-DIRECTORY-001N [#645](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/645) gives the preserved connected Account branch separate pending and result confirmed-photo focus refs. Only a successful request-ID creation followed by admitted `pending` upload or removal may record an intent, and only while the exact **Save profile photo** or **Remove current saved photo** initiating control owns focus. The intent contains only the mounted application-and-account lifetime, exact operation symbol, and upload-or-remove action. A successful mutation and current successful authoritative readback transfer only a matching lifetime, operation, and action for one ready render. Confirmed upload targets the persistent file input. Confirmed removal retains the existing surviving Remove, exact current render-ready Save, then persistent file-input priority. Body, document-root, absent, or disconnected focus returns to the current destination; an already-focused destination is left alone; every other connected focus selected during mutation or readback is preserved. Generated-only tests cover both actions, all removal destinations, native focus eviction, redundant-focus avoidance, deliberate outside and in-profile focus, programmatic invocation, request-ID failure, definitive rejection, unknown and readback failure, application/account changes, unmount, one-shot consumption, exact call/byte/revision behavior, and the unavailable default. | Programmatic focus is current-interface accessibility state, not provider acknowledgement, upload or deletion proof, reconciliation, authorization, audit evidence, or connected-live proof. The focus intent stores no name, profile, revision, request ID, photo bytes, data URL, provider value, response, or error and creates no request ID, callable, retry, mutation, draft, data URL, confirmation, audit, provider action, or data action. #643 rejected-removal focus/error ownership and #637 Reload recovery remain separate. The source-controlled availability value stays `false`, and live #623 remains inert. No data movement, page structure, People finder, visibility behavior, service/server contract, Function, Rule, index, schema, Firebase or provider configuration, account, sign-in, production data, deployment, biometric processing, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use only generated non-face test images; never add a photo query, facial recognition, matching, embedding, similarity, biometric processing, roster authority, or membership proof. | | Immediate Product-binding containment part of RISK-031 | PAY-PRODUCT-001A is tracked in live [#353](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/353). One dependency-free projection is used by the paid race and Shop checkout paths. A present stored Product link must be an own primitive non-empty string from 1 through 255 JavaScript code units and is copied without trimming, conversion, character restrictions, or `prod_` inference. Only a genuinely missing own field retains the compatibility Product-create path. Before any mapping write, a resolved Product must provide a bounded custom ID, exact Product kind, expected declared mode, and an installed-SDK 2xx response marker. Malformed stored links stop before token, registration/order identifier, Product-link or business-record write, or Stripe work; earlier access and request-count checks and their safety-counter writes may already have run. Malformed created results stop after at most one Product attempt but before mapping, Checkout Session, or business-record writes. | This structural containment does not prove provider origin, Stripe account ownership, intended catalog identity, metadata binding, Product status, price, dispatch, delivery, or reconciliation. A rejected create result may leave an orphaned Product; do not retry automatically. Anonymous clean-missing creation remains concurrency-prone and reachable from public traffic. Complete #113 inventory/disposition, authenticated idempotent catalog synchronization, Product-specific plan/pre-send/result/lost-acknowledgement/reconciliation controls, isolated staging, protected Firebase deployment, and provider proof before live commerce. | | Immediate current-handler containment part of RISK-003 | PAY-SESSION-001A is tracked in live [#357](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/357). The current paid race and Shop handlers build one immutable expectation before the Session call, catch rejection without opening it, and immediately project only a closed installed-SDK result. A result must match declared test/live mode, payment/open/unpaid state, exact cents, USD, buyer email, exact closed metadata, exact callbacks, a mode-compatible bounded Session ID, one canonical HTTPS capability at the hard-coded default `checkout.stripe.com` origin, and an installed-SDK 200 marker. Only copied ID/URL values continue; records store the ID but never the URL. Invalid results create no registration/order record and return one fixed unknown-result message. The website makes rejection or a missing paid URL terminal for that page visit, retains the form, and blocks a second direct handler call. | This is a narrow legacy compatibility stop, not trusted provider/account origin, deterministic business idempotency, dispatch/delivery proof, durable result evidence, payment proof, or adoption of the unused C4 chain. The Session call occurs first, so a rejected result may leave a payable orphan; earlier rate-counter, token/identifier, and lazy Product-mapping effects may remain. Reload, another tab/device, or a scripted caller bypasses the page lock. A configured Stripe custom checkout domain is blocked until #113 and a protected configuration boundary approve it. Complete PAY-002C/D persistence-first sagas, trusted C4 controller/result persistence, reconciliation, protected staging/deployment, provider readback, and exact website/Firebase/live proof. | | Immediate pre-render browser containment part of RISK-003 | PAY-SESSION-001B is tracked in live [#503](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/503). Each current public race and Shop page now keeps one component-local in-memory marker. After existing local checks admit a request, the handler sets that marker synchronously before analytics or its first Checkout promise can settle. A same-action or later submission on that mounted page is inert, including the gap before React renders the existing pending disabled button. Focused actual-route tests prove one service/analytics attempt across same-action and post-render repeats; preserve free-participant, volunteer-without-price-tier, and both paid-link navigation branches; and prove local waiver/native-disabled paths do not consume an attempt. | This browser marker is not a server boundary, durable idempotency key, provider dispatch/result record, business-state lock, payment proof, or reconciliation. It never releases during the mounted page visit because the admitted result must navigate or enter #357's terminal unknown-result state. Existing form controls other than the submit button remain editable. Reload, a remount, another tab/device, a script, or a direct service caller can bypass it. A same-mounted route change instead stays locked, and this slice does not fence an older pending result from that changed route. Complete PAY-002C/D persistence-first deterministic commands, durable replay/reconciliation, protected deployment, and exact website/Firebase/Stripe/live proof. | diff --git a/SYSTEM_DESIGN.md b/SYSTEM_DESIGN.md index 9f18618..630afe8 100644 --- a/SYSTEM_DESIGN.md +++ b/SYSTEM_DESIGN.md @@ -705,6 +705,8 @@ WEB-002C [#623](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/623) publi **MEMBERS-DIRECTORY-001M rejected-removal focus — SOURCE ONLY:** [#643](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/643) changes only keyboard-focus recovery in the preserved connected Account photo controls. After request-ID creation and `startMutation('remove')` admit an exact current removal into `pending`, the component records a focus intent only if **Remove current saved photo** owns focus. The pending intent stores only the mounted application-and-account lifetime and exact mutation-operation symbol; it stores no photo bytes, profile value, request ID, revision, provider value, or error. A definitive rejection transfers the matching pending intent to the result ref only after a current authoritative profile read succeeds, then the ready render consumes it. The current destination is a surviving Remove action, otherwise the enabled **Save profile photo** action for the exact current ready draft, otherwise the persistent Add/Replace file input for no draft or a reading or not-yet-ready draft. An already-focused destination is left alone; focus at the document body, document root element, no active element, or a disconnected element returns to the current destination; any other connected focus chosen during the mutation is preserved. A surviving Remove alone keeps the fixed rejection description. If Remove disappears, the fixed `role="alert"` remains standalone and is not associated with Save or the file input; moving focus identifies only the current available control and does not imply that removal succeeded or that the rejection belongs to that destination. Programmatic or outside-focused invocation, request-ID failure, rejected mutation admission, confirmed success, unknown outcome, failed confirming read, application or account change, unmount, and obsolete completion create no intent or clear or fail its guards. Existing confirmed-removal focus, #637 Reload recovery, draft identity/bytes/render/revision rules, mutation/read/render/context fences, and fixed errors remain unchanged. The handoff creates no request ID, callable, retry, mutation, draft, data URL, confirmation, audit, provider action, or data action. This adds no data movement, page structure, service contract, Function, Rule, index, package, workflow, backend, provider, account, sign-in state, production-data action, deployment, photo query, face recognition, matching, embedding, similarity, biometric processing, or connected/live behavior. Availability remains byte-for-byte `false`; the default branch and live #623 preview remain inert, and #507 retains every privacy, authorization, staging, backend-first deployment/readback, availability-flip, publication, and live-proof gate. +**MEMBERS-DIRECTORY-001N confirmed-photo focus containment — SOURCE ONLY:** [#645](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/645) changes only confirmed upload and removal keyboard-focus settlement in the preserved connected Account photo controls. After request-ID creation and `startMutation('upload'|'remove')` admit the exact current operation into `pending`, the component records a pending confirmed-photo intent only if **Save profile photo** owns focus for upload or **Remove current saved photo** owns focus for removal. The intent stores only the mounted application-and-account lifetime, exact operation symbol, and `upload` or `remove` action; it stores no name, profile, revision, request ID, photo bytes, data URL, provider value, response, or error. A successful mutation transfers only a matching current lifetime, operation, and action to the result ref after a current authoritative profile read also succeeds, then the matching ready render consumes the result once. Confirmed upload retains the persistent Add/Replace file input as its destination. Confirmed removal retains the existing priority: a surviving Remove action, otherwise enabled Save for the exact current render-ready draft, otherwise the persistent file input. An already-focused destination is left alone; focus at the document body, document root element, no active element, or a disconnected element returns to the current destination; any other connected focus deliberately chosen during the mutation or readback is preserved. Programmatic or outside-focused invocation, request-ID failure, rejected mutation admission, definitive rejection, unknown outcome, failed readback, application or account change, unmount, and obsolete completion create no intent or clear or fail its guards. #643's separate rejected-removal focus and error ownership, #637 Reload recovery, confirmation copy, draft identity/bytes/render/revision rules, and mutation/read/render/context fences remain unchanged. The handoff creates no request ID, callable, retry, mutation, draft, data URL, confirmation, audit, provider action, or data action. This adds no data movement, page structure, service contract, Function, Rule, index, schema, package, workflow, backend, provider, account, sign-in state, production-data action, deployment, photo query, facial recognition, matching, embedding, similarity, biometric processing, roster authority, membership proof, or connected/live behavior. Availability remains byte-for-byte `false`; the default branch and live #623 preview remain inert, and #507 retains every privacy, authorization, staging, backend-first deployment/readback, availability-flip, publication, and live-proof gate. + ### 8.0a Provider-neutral membership authority and entitlement — SOURCE ONLY, UNUSED MEMBERS-IDENTITY-001A [#208](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/208), with its command-order correction in MEMBERS-IDENTITY-001H [#451](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/451), defines one unused pure contract that keeps a stable MPRC membership separate from the Firebase account used to sign in. A membership record can exist and receive monotonic term decisions without a UID. Such a record grants no website entitlement. Google, WhatsApp, Strava, email equality, a profile role, and any browser field remain projections or inputs to future reviewed workflows; none is membership authority. diff --git a/docs/officers/EVENTS_SHOP_MEMBERS.md b/docs/officers/EVENTS_SHOP_MEMBERS.md index d145260..f09bcd9 100644 --- a/docs/officers/EVENTS_SHOP_MEMBERS.md +++ b/docs/officers/EVENTS_SHOP_MEMBERS.md @@ -2472,7 +2472,7 @@ flowchart TD Connected -. "never photo search or proof" .-> Official["Membership, role, payment, or official records"] ``` -Text alternative: the published #623 artifact keeps the Account and administrator-guarded People-finder controls disabled; source-only #627 preserves the accessible connected layouts behind the unchanged false availability value; source-only #629 adds local photo review where Cancel sends nothing, Save alone sends the existing upload command, and the current saved photo remains authoritative with a version-reset unavailable fallback; source-only #631 distinguishes a `null` **No photo** result from an unrenderable supplied **Photo unavailable** result, retries a different later photo version, and lets completed local states clear the query, messages, cards, names, and images with an announcement, input focus, and no new request or service call; that Clear action does not cancel work, erase memory or cache, roll back an audit, or recall a seen result; source-only #633 makes **Remove current saved photo** preserve the same local reading or ready replacement through a confirmed authoritative remove, use the refreshed revision only when the person later chooses Save, focus a remaining Remove action before a ready Save action before the persistent file input, keep the draft after a definitive rejection with successful readback, and after an unknown outcome or failed readback discard its bytes, hide photo and finder mutation controls, and retain only the existing Reload settings recovery with no Save retry; source-only #635 keeps that uncertain-change warning through failed Reload settings attempts until one authoritative profile read succeeds, while generic load failures make no global no-change promise and reload sends no mutation; source-only #637 focuses the recovery action after user-initiated mutation or readback failure, binds a Reload focus intent to the exact current load before focusing a replacement after failure, never steals focus on an initial load failure, and keeps stale application, account, and unmounted completions focus-inert; source-only #639 admits a returned saved photo only when its canonical decoded bytes total 12 through 65,536 with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11, maps every other returned byte shape to one fixed byte-free failure before the Account image path, preserves the version-scoped **Photo unavailable** fallback and Remove action for structurally admitted bytes the browser cannot display, and leaves outbound uploads unchanged; source-only #641 records only the exact current input-or-Search focus origin after a valid search enters pending, restores that same now-enabled origin after cards, empty, or fixed failure only when native disablement left no meaningful focus, and preserves any other connected focus the user chose during the request; source-only #643 records only the exact current lifetime and removal operation when focused Remove enters pending, and after definitive rejection plus successful authoritative readback restores otherwise-lost focus to surviving Remove, a current ready Save, or the persistent file input without stealing deliberately moved connected focus or attaching the standalone rejection alert to a replacement target; and only #507 may later connect name search plus voluntary thumbnails after privacy, authorization, staging, and backend-first readback, without photo search, face recognition, or official-record authority. +Text alternative: the published #623 artifact keeps the Account and administrator-guarded People-finder controls disabled; source-only #627 preserves the accessible connected layouts behind the unchanged false availability value; source-only #629 adds local photo review where Cancel sends nothing, Save alone sends the existing upload command, and the current saved photo remains authoritative with a version-reset unavailable fallback; source-only #631 distinguishes a `null` **No photo** result from an unrenderable supplied **Photo unavailable** result, retries a different later photo version, and lets completed local states clear the query, messages, cards, names, and images with an announcement, input focus, and no new request or service call; that Clear action does not cancel work, erase memory or cache, roll back an audit, or recall a seen result; source-only #633 makes **Remove current saved photo** preserve the same local reading or ready replacement through a confirmed authoritative remove, use the refreshed revision only when the person later chooses Save, focus a remaining Remove action before a ready Save action before the persistent file input, keep the draft after a definitive rejection with successful readback, and after an unknown outcome or failed readback discard its bytes, hide photo and finder mutation controls, and retain only the existing Reload settings recovery with no Save retry; source-only #635 keeps that uncertain-change warning through failed Reload settings attempts until one authoritative profile read succeeds, while generic load failures make no global no-change promise and reload sends no mutation; source-only #637 focuses the recovery action after user-initiated mutation or readback failure, binds a Reload focus intent to the exact current load before focusing a replacement after failure, never steals focus on an initial load failure, and keeps stale application, account, and unmounted completions focus-inert; source-only #639 admits a returned saved photo only when its canonical decoded bytes total 12 through 65,536 with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11, maps every other returned byte shape to one fixed byte-free failure before the Account image path, preserves the version-scoped **Photo unavailable** fallback and Remove action for structurally admitted bytes the browser cannot display, and leaves outbound uploads unchanged; source-only #641 records only the exact current input-or-Search focus origin after a valid search enters pending, restores that same now-enabled origin after cards, empty, or fixed failure only when native disablement left no meaningful focus, and preserves any other connected focus the user chose during the request; source-only #643 records only the exact current lifetime and removal operation when focused Remove enters pending, and after definitive rejection plus successful authoritative readback restores otherwise-lost focus to surviving Remove, a current ready Save, or the persistent file input without stealing deliberately moved connected focus or attaching the standalone rejection alert to a replacement target; source-only #645 records only the exact current lifetime, operation, and upload-or-remove action when focused Save or Remove enters pending, transfers it only after confirmed success plus current authoritative readback, restores otherwise-lost upload focus to the persistent file input or removal focus by the existing Remove, ready Save, then file-input priority, and preserves any other connected focus deliberately chosen during the mutation or readback; and only #507 may later connect name search plus voluntary thumbnails after privacy, authorization, staging, and backend-first readback, without photo search, face recognition, or official-record authority. Officer review steps for the #621 frontend preview: @@ -3346,6 +3346,111 @@ Officer source-review procedure for MEMBERS-DIRECTORY-001M [#643] rejected-remov **Escalation:** membership lead plus privacy and platform/security owners. Use the private incident path if a real name or photo appeared, focus moved across applications or accounts, settlement stole deliberately moved focus, a standalone rejection was attached to the wrong control, a focus handoff created a request or service call, or connected behavior became available. +Officer source-review procedure for MEMBERS-DIRECTORY-001N [#645] confirmed-photo focus containment — connected source only, **NOT LIVE**: + +**Purpose:** let a backup officer verify from specialist-prepared evidence that the preserved connected Account interface restores keyboard focus displaced from the exact focused Save or Remove action after confirmed success and authoritative readback, while preserving any other connected focus deliberately chosen during that work, without connecting the feature, using a real person, or changing production. + +**Approvers:** membership lead, privacy owner, and platform/security owner. + +**Prerequisites:** #643 is reviewed and merged. Ask the platform owner or testing specialist for the exact #645 source candidate, the named synthetic-only test output, the trustworthy old-source failure, and a redacted written behavior report. The specialist runs the tests and records the evidence. The backup officer reviews that written evidence without a terminal or test harness. Keep the source-controlled availability value `false`. Do not sign in to production, choose a real photo, call production Firebase, or change production data. + +1. Keep the complete profile-photo and People-finder feature marked **NOT AVAILABLE YET**. +2. Ask the platform owner for the exact #645 issue. +3. Ask the platform owner for the reviewed pull request. +4. Ask the platform owner for the candidate or merge commit. +5. Ask the testing specialist for the named MEMBERS-DIRECTORY-001N test output. +6. Ask the testing specialist for the trustworthy old-source failure. +7. Ask the testing specialist for the redacted written synthetic-behavior report. +8. Confirm the report names the specialist who ran the tests. +9. Confirm every image fixture is generated non-face data. +10. Confirm the source-controlled availability value remains byte-for-byte `false`. +11. Confirm the last verified production deployment remains inert #623 deploy `6a7e072f8f346b0008510d29`. +12. Confirm request-number creation must succeed before a confirmed-photo focus intent can exist. +13. Confirm the exact upload or removal operation must enter `pending` before the intent can exist. +14. Confirm **Save profile photo** must own focus when an upload operation enters `pending`. +15. Confirm **Remove current saved photo** must own focus when a removal operation enters `pending`. +16. Confirm an outside-focused or programmatic invocation creates no confirmed-photo focus intent. +17. Confirm the intent records only the current mounted application-and-account lifetime. +18. Confirm the intent records only the exact mutation-operation identity. +19. Confirm the intent records only the `upload` or `remove` action. +20. Confirm the intent records no name or profile value. +21. Confirm the intent records no request number or revision. +22. Confirm the intent records no photo bytes or data URL. +23. Confirm the intent records no provider value, response, or caught error. +24. Confirm the mutation must succeed before the intent can advance. +25. Confirm a current successful authoritative profile read is required before the intent can advance. +26. Confirm lifetime, operation, and action must all match before transfer. +27. Confirm only that matching pending intent transfers to result ownership. +28. Confirm one matching ready render consumes the result exactly once. +29. Confirm a confirmed upload selects the persistent Add/Replace file input. +30. Confirm a confirmed removal with a current saved photo selects the surviving Remove action. +31. Confirm a confirmed removal with no saved photo and an exact current ready draft selects enabled **Save profile photo**. +32. Confirm a confirmed removal with no saved photo and no draft selects the persistent Add profile photo input. +33. Confirm a confirmed removal with no saved photo and a reading draft selects the persistent Add profile photo input. +34. Confirm a confirmed removal with no saved photo and a not-yet-ready preview selects the persistent Add profile photo input. +35. Confirm destination choice uses the current authoritative profile and exact current draft state. +36. Confirm a destination that already owns focus is not focused again. +37. Confirm document-body focus returns to the current destination. +38. Confirm document-root focus returns to the current destination. +39. Confirm absent focus returns to the current destination. +40. Confirm disconnected focus returns to the current destination. +41. Confirm another connected outside control deliberately focused during pending keeps focus. +42. Confirm another connected in-profile control deliberately focused during pending keeps focus. +43. Confirm connected focus deliberately selected while authoritative readback is pending keeps focus. +44. Confirm consuming a handoff cannot move focus during a later unrelated draft render. +45. Confirm request-number failure creates no focus intent and sends no photo mutation. +46. Confirm failed mutation admission creates no focus intent. +47. Confirm a definitive upload rejection does not use confirmed-success focus. +48. Confirm a definitive removal rejection retains the separate #643 focus and error behavior. +49. Confirm an unknown mutation outcome retains the existing #637 **Reload settings** recovery. +50. Confirm a failed authoritative readback retains the existing #637 **Reload settings** recovery. +51. Confirm an application change makes an older confirmed-photo intent focus-inert. +52. Confirm an account change makes an older confirmed-photo intent focus-inert. +53. Confirm unmount makes an older confirmed-photo intent focus-inert. +54. Confirm an obsolete mutation completion cannot move focus. +55. Confirm an obsolete readback completion cannot move focus. +56. Confirm existing upload and removal confirmation wording remains unchanged. +57. Confirm upload content type and exact bytes remain unchanged. +58. Confirm upload and removal expected revisions remain unchanged. +59. Confirm draft retention, disposal, identity, and render rules remain unchanged. +60. Confirm request-number, mutation-call, and profile-read counts remain unchanged. +61. Confirm the focus handoff creates no second request number. +62. Confirm the focus handoff creates no second callable. +63. Confirm the focus handoff starts no retry or automatic mutation. +64. Confirm the focus handoff creates no draft, data URL, or confirmation. +65. Confirm the focus handoff creates no audit, provider action, or data action. +66. Confirm the source diff changes no People-finder behavior or administrator guard. +67. Confirm the source diff changes no finder-visibility setting behavior. +68. Confirm the source diff changes no service contract, Function, Rule, index, or schema. +69. Confirm the source diff changes no package, workflow, or release control. +70. Confirm the source diff adds no photo query or facial recognition. +71. Confirm the source diff adds no image matching, embedding, or similarity score. +72. Confirm the source diff adds no biometric processing, roster authority, or membership proof. +73. Confirm the default Account branch obtains no directory-service context. +74. Confirm the default Account branch creates no directory request number. +75. Confirm the default Account branch calls no directory service. +76. Record the source change as its own state. +77. Record the named test results as their own state. +78. Record whether the change merged as its own state. +79. Record whether any website artifact was published as its own state. +80. Record the exact `runmprc.com` revision as its own state. +81. Record whether Firebase was deployed as its own state. +82. Record whether an outside provider was configured as its own state. +83. Record whether an account or sign-in state changed as its own state. +84. Record whether production data changed as its own state. +85. Record whether connected or live profile-photo behavior became available as its own state. +86. Stop before changing availability, Firebase, a provider, an account, production data, or the live website. + +**Expected result:** the reviewed connected source records one pending confirmed-photo focus intent only after request-number creation and admitted pending upload or removal while the exact Save or Remove initiating action owns focus. The intent contains only the current mounted application-and-account lifetime, exact operation identity, and upload-or-remove action. Successful mutation plus a current successful authoritative profile read transfers only the matching intent to one ready render. Confirmed upload selects the persistent file input. Confirmed removal selects surviving Remove first, exact current ready Save second, or the persistent file input otherwise. Focus returns from the document body, document root, no active element, or a disconnected element, but an already-focused destination is left alone and any other connected focus deliberately chosen during mutation or readback is preserved. The result is consumed once. Programmatic or outside-focused invocation, request-number failure, failed mutation admission, definitive rejection, unknown outcome, failed readback, application or account change, unmount, and obsolete completion create no intent or clear or fail its guards. #643 rejected-removal behavior and #637 Reload recovery remain separate. Focus creates no request number, callable, retry, mutation, draft, data URL, confirmation, audit, provider action, or data action. Availability remains `false`; the default branch obtains no directory context, creates no request number, and calls no directory service; and live #623 remains inert. The backend and connected behavior remain **NOT AVAILABLE YET**. + +**Stop conditions:** a real account, name, or photo; production sign-in; direct production Firebase access; a focused current Save or Remove action that is displaced while confirmed work settles but never yields its current destination; settlement that moves focus away from another connected control; an outside-focused or programmatic invocation that creates an intent; an intent that records a profile, revision, request number, photo byte, data URL, provider value, response, or error; a transfer before successful current authoritative readback; changed upload or removal destination order; delayed focus during an unrelated later render; a definitive rejection that uses confirmed-success focus; an unknown outcome or failed readback that bypasses Reload recovery; an application, account, unmounted, or obsolete completion that moves focus; an extra request number, callable, retry, mutation, draft, data URL, confirmation, audit, provider action, or data action caused by focus; changed calls, bytes, revisions, confirmation copy, draft behavior, #643 behavior, or #637 behavior; a photo query; facial recognition, matching, embedding, similarity scoring, biometric processing, roster authority, or membership proof; a People-finder, visibility, service-contract, Function, Rule, index, schema, package, workflow, provider, account, sign-in, production-data, or website change; an availability flip; use of a terminal or test harness by the backup officer; or a claim that source, tests, merge, or a preview means the feature is live. + +**Success proof:** record the exact #645 issue, reviewed pull request and commit; trustworthy old-source failure; green separately named MEMBERS-DIRECTORY-001N focused tests; green full frontend tests; type-checking; scoped lint; diagnostic production build; unchanged lint baseline; repository Node tests; workflow checks; diff-check; independent privacy/security, frontend/accessibility, focus/race, and backup-officer reviews; and exact-main CI if merged. Record source, tests, merge, website publication, exact `runmprc.com` revision, Firebase deployment, provider configuration, account/sign-in change, production-data action, and connected/live behavior separately. Record the unchanged `false` availability value and unchanged #623 deploy separately. Source and tests do not prove merge; merge does not prove publication; publication does not prove `runmprc.com`, Firebase, provider, account, data, or connected-live behavior. Final connection and live proof remain #507 work. + +**Undo:** use one reviewed frontend-and-documentation revert or safe roll-forward. Confirm the default disabled branch still makes zero directory calls. No Firebase, provider, account, or production-data undo is needed because #645 changes source only. Undo must not restore unconditional confirmed-photo focus or weaken #643 rejected-removal focus and #637 Reload recovery. + +**Escalation:** membership lead plus privacy and platform/security owners. Use the private incident path if a real name or photo appeared, focus moved across applications or accounts, settlement stole deliberately moved focus, a focus intent retained private or service data, a focus handoff created a request or service call, or connected behavior became available. + ## Admin screens — NOT AVAILABLE YET Admin event and product editors exist in source, but their live permissions, backup, preview, and rollback behavior have not been approved. Saving can write directly to production Firestore. Officers must not use these screens as a continuity procedure yet. diff --git a/src/pages/account/MemberDirectoryProfile.test.tsx b/src/pages/account/MemberDirectoryProfile.test.tsx index 3f7270c..8ffdf01 100644 --- a/src/pages/account/MemberDirectoryProfile.test.tsx +++ b/src/pages/account/MemberDirectoryProfile.test.tsx @@ -335,7 +335,9 @@ describe('My Account member directory profile', () => { expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(1); expect(document.body).not.toHaveTextContent('fixture-002.png'); - fireEvent.click(screen.getByRole('button', { name: 'Save profile photo' })); + const save = screen.getByRole('button', { name: 'Save profile photo' }); + save.focus(); + fireEvent.click(save); await waitFor(() => expect(setMyMemberDirectoryPhoto).toHaveBeenCalledWith(app, { requestId: REQUEST_ID, @@ -997,7 +999,9 @@ describe('My Account member directory profile', () => { renderProfile(); await selectReadyReplacement('preserved replacement', 'fixture-001h-001.png'); - fireEvent.click(screen.getByRole('button', { name: 'Remove current saved photo' })); + const remove = screen.getByRole('button', { name: 'Remove current saved photo' }); + remove.focus(); + fireEvent.click(remove); expect(await screen.findByRole('img', { name: 'No profile photo' })) .toBeInTheDocument(); @@ -1052,9 +1056,11 @@ describe('My Account member directory profile', () => { expect(screen.getByText('Preparing selected photo preview...')) .toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { + const remove = screen.getByRole('button', { name: 'Remove current saved photo', - })); + }); + remove.focus(); + fireEvent.click(remove); expect(await screen.findByRole('img', { name: 'No profile photo' })) .toBeInTheDocument(); @@ -1216,6 +1222,7 @@ describe('My Account member directory profile', () => { name: 'Remove current saved photo', }); + remove.focus(); fireEvent.click(remove); await waitFor(() => expect(removeMyMemberDirectoryPhoto).toHaveBeenCalledWith(app, { @@ -1246,9 +1253,11 @@ describe('My Account member directory profile', () => { renderProfile(); await selectReadyReplacement('concurrent replacement', 'fixture-001h-007.png'); - fireEvent.click(await screen.findByRole('button', { + const remove = await screen.findByRole('button', { name: 'Remove current saved photo', - })); + }); + remove.focus(); + fireEvent.click(remove); expect(await screen.findByText( 'Profile photo changed again elsewhere. The preview shows the current photo.', @@ -1745,6 +1754,584 @@ describe('My Account member directory profile', () => { }); }); + describe('MEMBERS-DIRECTORY-001N confirmed-photo focus containment', () => { + const WITHOUT_PHOTO: MemberDirectoryProfileData = { + ...PROFILE_WITH_PHOTO, + revision: 5, + hasPhoto: false, + photo: null, + }; + const UPDATED_WITH_PHOTO: MemberDirectoryProfileData = { + ...DEFAULT_PROFILE, + revision: 1, + hasPhoto: true, + photo: PHOTO, + }; + + async function selectReadyUpload( + bytes = '001n upload bytes', + inputLabel = 'Add profile photo', + ) { + const input = await screen.findByLabelText(inputLabel); + fireEvent.change(input, { + target: { + files: [new File([bytes], 'fixture-001n.png', { type: 'image/png' })], + }, + }); + const preview = await screen.findByRole('img', { + name: 'Selected profile photo preview', + }); + fireEvent.load(preview); + return screen.getByRole('button', { name: 'Save profile photo' }); + } + + function arrangeConfirmedUpload( + current: MemberDirectoryProfileData = UPDATED_WITH_PHOTO, + ) { + const mutation = deferred(); + const readback = deferred(); + (setMyMemberDirectoryPhoto as jest.Mock).mockReturnValueOnce(mutation.promise); + (getMyMemberDirectoryProfile as jest.Mock) + .mockResolvedValueOnce(DEFAULT_PROFILE) + .mockReturnValueOnce(readback.promise); + return { + settle: async () => { + await act(async () => mutation.resolve({})); + await waitFor(() => expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2)); + await act(async () => readback.resolve(current)); + }, + }; + } + + function arrangeConfirmedRemoval( + current: MemberDirectoryProfileData = WITHOUT_PHOTO, + ) { + const mutation = deferred(); + const readback = deferred(); + (removeMyMemberDirectoryPhoto as jest.Mock).mockReturnValueOnce(mutation.promise); + (getMyMemberDirectoryProfile as jest.Mock) + .mockResolvedValueOnce(PROFILE_WITH_PHOTO) + .mockReturnValueOnce(readback.promise); + return { + settle: async () => { + await act(async () => mutation.resolve({})); + await waitFor(() => expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2)); + await act(async () => readback.resolve(current)); + }, + }; + } + + function modelDisabledControlFocusEviction(control: HTMLElement) { + control.blur(); + const disposable = document.createElement('button'); + document.body.appendChild(disposable); + disposable.focus(); + expect(disposable).toHaveFocus(); + disposable.remove(); + expect(document.body).toHaveFocus(); + } + + test('preserves deliberately selected connected outside focus after confirmed upload', async () => { + const attempt = arrangeConfirmedUpload(); + render( + <> + + + , + ); + const save = await selectReadyUpload(); + const outside = screen.getByRole('button', { name: 'Outside control' }); + save.focus(); + fireEvent.click(save); + outside.focus(); + + await attempt.settle(); + + expect(outside).toHaveFocus(); + expect(screen.getByLabelText('Replace profile photo')).not.toHaveFocus(); + }); + + test('preserves deliberately selected connected in-profile focus after confirmed upload', async () => { + const attempt = arrangeConfirmedUpload(); + renderProfile(); + const save = await selectReadyUpload(); + save.focus(); + fireEvent.click(save); + const heading = screen.getByRole('heading', { + name: 'Profile photo and officer finder', + }); + heading.tabIndex = -1; + heading.focus(); + + await attempt.settle(); + + expect(heading).toHaveFocus(); + expect(screen.getByLabelText('Replace profile photo')).not.toHaveFocus(); + }); + + test('preserves deliberately selected connected outside focus after confirmed removal', async () => { + const attempt = arrangeConfirmedRemoval(); + render( + <> + + + , + ); + const remove = await screen.findByRole('button', { + name: 'Remove current saved photo', + }); + const outside = screen.getByRole('button', { name: 'Outside control' }); + remove.focus(); + fireEvent.click(remove); + outside.focus(); + + await attempt.settle(); + + expect(outside).toHaveFocus(); + expect(screen.getByLabelText('Add profile photo')).not.toHaveFocus(); + }); + + test('preserves deliberately selected connected in-profile focus after confirmed removal', async () => { + const attempt = arrangeConfirmedRemoval(); + renderProfile(); + const remove = await screen.findByRole('button', { + name: 'Remove current saved photo', + }); + remove.focus(); + fireEvent.click(remove); + const heading = screen.getByRole('heading', { + name: 'Profile photo and officer finder', + }); + heading.tabIndex = -1; + heading.focus(); + + await attempt.settle(); + + expect(heading).toHaveFocus(); + expect(screen.getByLabelText('Add profile photo')).not.toHaveFocus(); + }); + + test('restores the persistent file input after focused Save is natively evicted', async () => { + const attempt = arrangeConfirmedUpload(); + renderProfile(); + const save = await selectReadyUpload('focused upload bytes'); + save.focus(); + + fireEvent.click(save); + modelDisabledControlFocusEviction(save); + await attempt.settle(); + + expect(screen.getByLabelText('Replace profile photo')).toHaveFocus(); + expect(screen.getByRole('status')).toHaveTextContent( + 'Profile photo saved. Your officer finder setting did not change.', + ); + expect(createMemberDirectoryRequestId).toHaveBeenCalledTimes(1); + expect(setMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(setMyMemberDirectoryPhoto).toHaveBeenCalledWith(app, { + requestId: REQUEST_ID, + expectedRevision: 0, + contentType: 'image/png', + base64Data: btoa('focused upload bytes'), + }); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2); + expect(removeMyMemberDirectoryPhoto).not.toHaveBeenCalled(); + expect(setMyMemberDirectoryVisibility).not.toHaveBeenCalled(); + expect(document.body).not.toHaveTextContent('fixture-001n.png'); + }); + + test('restores the file input after focused Remove is evicted and no draft remains', async () => { + const attempt = arrangeConfirmedRemoval(); + renderProfile(); + const remove = await screen.findByRole('button', { + name: 'Remove current saved photo', + }); + remove.focus(); + + fireEvent.click(remove); + modelDisabledControlFocusEviction(remove); + await attempt.settle(); + + expect(screen.getByLabelText('Add profile photo')).toHaveFocus(); + expect(screen.getByRole('status')).toHaveTextContent( + 'Profile photo removed. Your officer finder setting did not change.', + ); + expect(createMemberDirectoryRequestId).toHaveBeenCalledTimes(1); + expect(removeMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(removeMyMemberDirectoryPhoto).toHaveBeenCalledWith(app, { + requestId: REQUEST_ID, + expectedRevision: 4, + }); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2); + expect(setMyMemberDirectoryPhoto).not.toHaveBeenCalled(); + expect(setMyMemberDirectoryVisibility).not.toHaveBeenCalled(); + }); + + test('restores the exact current ready Save after focused Remove is evicted', async () => { + const attempt = arrangeConfirmedRemoval(); + renderProfile(); + await selectReadyUpload('retained 001n draft', 'Replace profile photo'); + const remove = screen.getByRole('button', { + name: 'Remove current saved photo', + }); + remove.focus(); + + fireEvent.click(remove); + modelDisabledControlFocusEviction(remove); + await attempt.settle(); + + const save = screen.getByRole('button', { name: 'Save profile photo' }); + expect(save).toHaveFocus(); + expect(save).toBeEnabled(); + expect(screen.getByRole('img', { name: 'Selected profile photo preview' })) + .toHaveAttribute( + 'src', + `data:image/png;base64,${btoa('retained 001n draft')}`, + ); + expect(removeMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(setMyMemberDirectoryPhoto).not.toHaveBeenCalled(); + expect(createMemberDirectoryRequestId).toHaveBeenCalledTimes(1); + }); + + test('restores a surviving Remove after focused Remove is evicted', async () => { + const changedAgain: MemberDirectoryProfileData = { + ...PROFILE_WITH_PHOTO, + revision: 6, + photo: { + ...PHOTO, + version: '22222222-2222-4222-8222-222222222222', + }, + }; + const attempt = arrangeConfirmedRemoval(changedAgain); + renderProfile(); + const remove = await screen.findByRole('button', { + name: 'Remove current saved photo', + }); + remove.focus(); + + fireEvent.click(remove); + modelDisabledControlFocusEviction(remove); + await attempt.settle(); + + expect(screen.getByRole('button', { name: 'Remove current saved photo' })) + .toHaveFocus(); + expect(screen.getByRole('status')).toHaveTextContent( + 'Profile photo changed again elsewhere. The preview shows the current photo.', + ); + expect(removeMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2); + }); + + test('does not redundantly focus an already-focused surviving Remove', async () => { + const current: MemberDirectoryProfileData = { + ...PROFILE_WITH_PHOTO, + revision: 6, + }; + const attempt = arrangeConfirmedRemoval(current); + renderProfile(); + const remove = await screen.findByRole('button', { + name: 'Remove current saved photo', + }); + remove.focus(); + const focus = jest.spyOn(remove, 'focus'); + + fireEvent.click(remove); + expect(remove).toHaveFocus(); + await attempt.settle(); + + expect(remove).toHaveFocus(); + expect(focus).not.toHaveBeenCalled(); + focus.mockRestore(); + }); + + test('creates no confirmed handoff for an outside-focused programmatic Save invocation', async () => { + const attempt = arrangeConfirmedUpload(); + renderProfile(); + const save = await selectReadyUpload('programmatic upload bytes'); + const outside = document.createElement('button'); + document.body.appendChild(outside); + outside.focus(); + + fireEvent.click(save); + outside.remove(); + expect(document.body).toHaveFocus(); + await attempt.settle(); + + expect(document.body).toHaveFocus(); + expect(screen.getByLabelText('Replace profile photo')).not.toHaveFocus(); + expect(createMemberDirectoryRequestId).toHaveBeenCalledTimes(1); + expect(setMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + }); + + test('creates no confirmed handoff for an outside-focused programmatic Remove invocation', async () => { + const attempt = arrangeConfirmedRemoval(); + renderProfile(); + const remove = await screen.findByRole('button', { + name: 'Remove current saved photo', + }); + const outside = document.createElement('button'); + document.body.appendChild(outside); + outside.focus(); + + fireEvent.click(remove); + outside.remove(); + expect(document.body).toHaveFocus(); + await attempt.settle(); + + expect(document.body).toHaveFocus(); + expect(screen.getByLabelText('Add profile photo')).not.toHaveFocus(); + expect(createMemberDirectoryRequestId).toHaveBeenCalledTimes(1); + expect(removeMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + }); + + test('a request-ID failure creates no upload focus intent or service call', async () => { + (createMemberDirectoryRequestId as jest.Mock).mockImplementationOnce(() => { + throw new Error('synthetic private request-id detail'); + }); + renderProfile(); + const save = await selectReadyUpload('request failure bytes'); + save.focus(); + + fireEvent.click(save); + + expect(save).toHaveFocus(); + expect(save).toBeEnabled(); + expect(createMemberDirectoryRequestId).toHaveBeenCalledTimes(1); + expect(setMyMemberDirectoryPhoto).not.toHaveBeenCalled(); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(1); + expect(screen.getByRole('alert')).toHaveTextContent( + 'This browser could not safely start that change. No setting was changed.', + ); + expect(document.body).not.toHaveTextContent('synthetic private'); + }); + + test('a request-ID failure creates no removal focus intent or service call', async () => { + (createMemberDirectoryRequestId as jest.Mock).mockImplementationOnce(() => { + throw new Error('synthetic private request-id detail'); + }); + (getMyMemberDirectoryProfile as jest.Mock).mockResolvedValueOnce(PROFILE_WITH_PHOTO); + renderProfile(); + const remove = await screen.findByRole('button', { + name: 'Remove current saved photo', + }); + remove.focus(); + + fireEvent.click(remove); + + expect(remove).toHaveFocus(); + expect(remove).toBeEnabled(); + expect(createMemberDirectoryRequestId).toHaveBeenCalledTimes(1); + expect(removeMyMemberDirectoryPhoto).not.toHaveBeenCalled(); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(1); + expect(document.body).not.toHaveTextContent('synthetic private'); + }); + + test('a definitive upload rejection does not use confirmed-success focus', async () => { + const rejected = { code: 'functions/failed-precondition' }; + (setMyMemberDirectoryPhoto as jest.Mock).mockRejectedValueOnce(rejected); + (isDefinitiveMemberDirectoryRejection as jest.Mock).mockImplementation( + (error) => error === rejected, + ); + (getMyMemberDirectoryProfile as jest.Mock) + .mockResolvedValueOnce(DEFAULT_PROFILE) + .mockResolvedValueOnce(DEFAULT_PROFILE); + renderProfile(); + const save = await selectReadyUpload('rejected upload bytes'); + save.focus(); + + fireEvent.click(save); + modelDisabledControlFocusEviction(save); + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'That change was rejected before it was saved.', + ); + expect(document.body).toHaveFocus(); + expect(screen.getByLabelText('Add profile photo')).not.toHaveFocus(); + expect(screen.getByRole('button', { name: 'Save profile photo' })) + .not.toHaveFocus(); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2); + expect(setMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(document.body).not.toHaveTextContent('synthetic private'); + }); + + test('an unknown removal outcome uses Reload recovery, not confirmed-success focus', async () => { + (getMyMemberDirectoryProfile as jest.Mock).mockResolvedValueOnce(PROFILE_WITH_PHOTO); + (removeMyMemberDirectoryPhoto as jest.Mock) + .mockRejectedValueOnce(new Error('synthetic private outcome detail')); + renderProfile(); + const remove = await screen.findByRole('button', { + name: 'Remove current saved photo', + }); + remove.focus(); + + fireEvent.click(remove); + modelDisabledControlFocusEviction(remove); + + expect(await screen.findByRole('button', { name: 'Reload settings' })) + .toHaveFocus(); + expect(screen.queryByLabelText('Add profile photo')).not.toBeInTheDocument(); + expect(removeMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(1); + expect(document.body).not.toHaveTextContent('synthetic private'); + }); + + test('a failed upload readback uses Reload recovery, not confirmed-success focus', async () => { + (getMyMemberDirectoryProfile as jest.Mock) + .mockResolvedValueOnce(DEFAULT_PROFILE) + .mockRejectedValueOnce(new Error('synthetic private readback detail')); + renderProfile(); + const save = await selectReadyUpload('failed readback bytes'); + save.focus(); + + fireEvent.click(save); + modelDisabledControlFocusEviction(save); + + expect(await screen.findByRole('button', { name: 'Reload settings' })) + .toHaveFocus(); + expect(screen.queryByLabelText('Add profile photo')).not.toBeInTheDocument(); + expect(setMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2); + expect(document.body.innerHTML).not.toContain(btoa('failed readback bytes')); + expect(document.body).not.toHaveTextContent('synthetic private'); + }); + + test('makes an old confirmed upload mutation focus-inert after the application changes', async () => { + const mutation = deferred(); + (setMyMemberDirectoryPhoto as jest.Mock).mockReturnValueOnce(mutation.promise); + (getMyMemberDirectoryProfile as jest.Mock) + .mockResolvedValueOnce(DEFAULT_PROFILE) + .mockResolvedValueOnce(DEFAULT_PROFILE); + const view = renderProfile(); + const save = await selectReadyUpload('old application bytes'); + save.focus(); + fireEvent.click(save); + modelDisabledControlFocusEviction(save); + + view.rerender( + , + ); + const currentInput = await screen.findByLabelText('Add profile photo'); + currentInput.focus(); + await act(async () => mutation.resolve({})); + + expect(currentInput).toHaveFocus(); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2); + expect(setMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(document.body.innerHTML).not.toContain(btoa('old application bytes')); + }); + + test('makes an old confirmed upload readback focus-inert after the account changes', async () => { + const oldReadback = deferred(); + (getMyMemberDirectoryProfile as jest.Mock) + .mockResolvedValueOnce(DEFAULT_PROFILE) + .mockReturnValueOnce(oldReadback.promise) + .mockResolvedValueOnce(DEFAULT_PROFILE); + const view = renderProfile(); + const save = await selectReadyUpload('old account bytes'); + save.focus(); + fireEvent.click(save); + modelDisabledControlFocusEviction(save); + await waitFor(() => expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2)); + + view.rerender( + , + ); + const currentInput = await screen.findByLabelText('Add profile photo'); + currentInput.focus(); + await act(async () => oldReadback.resolve(UPDATED_WITH_PHOTO)); + + expect(currentInput).toHaveFocus(); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(3); + expect(setMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(document.body.innerHTML).not.toContain(btoa('old account bytes')); + }); + + test('makes an old confirmed upload readback focus-inert after unmount', async () => { + const oldReadback = deferred(); + (getMyMemberDirectoryProfile as jest.Mock) + .mockResolvedValueOnce(DEFAULT_PROFILE) + .mockReturnValueOnce(oldReadback.promise); + const view = renderProfile(); + const save = await selectReadyUpload('unmounted upload bytes'); + save.focus(); + fireEvent.click(save); + modelDisabledControlFocusEviction(save); + await waitFor(() => expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2)); + view.unmount(); + const outside = document.createElement('button'); + document.body.appendChild(outside); + try { + outside.focus(); + await act(async () => oldReadback.resolve(UPDATED_WITH_PHOTO)); + + expect(outside).toHaveFocus(); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2); + expect(setMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + } finally { + outside.remove(); + } + }); + + test('consumes a confirmed upload focus handoff exactly once', async () => { + const attempt = arrangeConfirmedUpload(); + render( + <> + + + , + ); + const save = await selectReadyUpload('one-shot upload bytes'); + save.focus(); + fireEvent.click(save); + modelDisabledControlFocusEviction(save); + await attempt.settle(); + const input = screen.getByLabelText('Replace profile photo'); + expect(input).toHaveFocus(); + const outside = screen.getByRole('button', { name: 'Outside control' }); + outside.focus(); + + fireEvent.change(input, { + target: { + files: [new File(['next local bytes'], 'next-local.png', { + type: 'image/png', + })], + }, + }); + await screen.findByRole('img', { name: 'Selected profile photo preview' }); + + expect(outside).toHaveFocus(); + expect(input).not.toHaveFocus(); + expect(createMemberDirectoryRequestId).toHaveBeenCalledTimes(1); + expect(setMyMemberDirectoryPhoto).toHaveBeenCalledTimes(1); + expect(getMyMemberDirectoryProfile).toHaveBeenCalledTimes(2); + expect(document.body).not.toHaveTextContent('next-local.png'); + }); + }); + test('MEMBERS-DIRECTORY-001F falls back when a saved thumbnail cannot decode and resets for a new version', async () => { const newPhoto = { ...PHOTO, diff --git a/src/pages/account/MemberDirectoryProfile.tsx b/src/pages/account/MemberDirectoryProfile.tsx index 737ef33..fc6e6a4 100644 --- a/src/pages/account/MemberDirectoryProfile.tsx +++ b/src/pages/account/MemberDirectoryProfile.tsx @@ -232,6 +232,12 @@ type RemoveFocusIntent = { operation: symbol; }; +type ConfirmedPhotoFocusIntent = { + lifetime: symbol; + operation: symbol; + action: 'upload' | 'remove'; +}; + function visibilityConfirmation( requested: boolean, ): MutationConfirmation { @@ -334,12 +340,13 @@ function MemberDirectoryProfileAttempt({ const recoveryFocusIntentRef = useRef(null); const pendingRemoveFocusIntentRef = useRef(null); const rejectedRemoveResultFocusIntentRef = useRef(null); + const pendingConfirmedPhotoFocusIntentRef = useRef(null); + const confirmedPhotoResultFocusIntentRef = useRef(null); const photoReadRef = useRef(null); const photoInputRef = useRef(null); const removePhotoButtonRef = useRef(null); const reloadButtonRef = useRef(null); const savePhotoButtonRef = useRef(null); - const postMutationFocusRef = useRef<'photo-input' | 'remove-result' | null>(null); useEffect(() => { const lifetime = Symbol('member-directory-lifetime'); @@ -352,8 +359,9 @@ function MemberDirectoryProfileAttempt({ recoveryFocusIntentRef.current = null; pendingRemoveFocusIntentRef.current = null; rejectedRemoveResultFocusIntentRef.current = null; + pendingConfirmedPhotoFocusIntentRef.current = null; + confirmedPhotoResultFocusIntentRef.current = null; photoReadRef.current = null; - postMutationFocusRef.current = null; }; }, []); @@ -403,26 +411,35 @@ function MemberDirectoryProfileAttempt({ }, [photoDraft, state]); useEffect(() => { - if (state.phase !== 'ready' || postMutationFocusRef.current === null) return; - const focusIntent = postMutationFocusRef.current; - postMutationFocusRef.current = null; - if (focusIntent === 'photo-input') { - photoInputRef.current?.focus(); - return; - } - if (state.profile.hasPhoto) { - removePhotoButtonRef.current?.focus(); - return; - } - if ( + const intent = confirmedPhotoResultFocusIntentRef.current; + if (state.phase !== 'ready' || intent === null) return; + confirmedPhotoResultFocusIntentRef.current = null; + if (intent.lifetime !== lifetimeRef.current) return; + + let target: HTMLElement | null = null; + if (intent.action === 'upload') { + target = photoInputRef.current; + } else if (state.profile.hasPhoto) { + target = removePhotoButtonRef.current; + } else if ( photoDraft?.phase === 'preview' && photoDraft.renderState === 'ready' && photoReadRef.current === photoDraft.identity ) { - savePhotoButtonRef.current?.focus(); - return; + target = savePhotoButtonRef.current; + } else { + target = photoInputRef.current; } - photoInputRef.current?.focus(); + if (target === null) return; + + const active = document.activeElement; + if (active === target) return; + if ( + active === null + || active === document.body + || active === document.documentElement + || !active.isConnected + ) target.focus(); }, [photoDraft, state]); useEffect(() => { @@ -443,8 +460,9 @@ function MemberDirectoryProfileAttempt({ mutationRef.current = null; pendingRemoveFocusIntentRef.current = null; rejectedRemoveResultFocusIntentRef.current = null; + pendingConfirmedPhotoFocusIntentRef.current = null; + confirmedPhotoResultFocusIntentRef.current = null; photoReadRef.current = null; - postMutationFocusRef.current = null; setActionError(null); setPhotoDraft(null); setState({ phase: 'loading' }); @@ -517,6 +535,8 @@ function MemberDirectoryProfileAttempt({ } catch (error) { if (!mutationIsCurrent(start)) return; if (isDefinitiveMemberDirectoryRejection(error)) { + pendingConfirmedPhotoFocusIntentRef.current = null; + confirmedPhotoResultFocusIntentRef.current = null; try { const profile = await getMyMemberDirectoryProfile(app); if (!mutationIsCurrent(start)) return; @@ -541,6 +561,8 @@ function MemberDirectoryProfileAttempt({ mutationRef.current = null; pendingRemoveFocusIntentRef.current = null; rejectedRemoveResultFocusIntentRef.current = null; + pendingConfirmedPhotoFocusIntentRef.current = null; + confirmedPhotoResultFocusIntentRef.current = null; photoReadRef.current = null; setPhotoDraft(null); setActionError(null); @@ -556,6 +578,8 @@ function MemberDirectoryProfileAttempt({ mutationRef.current = null; pendingRemoveFocusIntentRef.current = null; rejectedRemoveResultFocusIntentRef.current = null; + pendingConfirmedPhotoFocusIntentRef.current = null; + confirmedPhotoResultFocusIntentRef.current = null; photoReadRef.current = null; setPhotoDraft(null); setActionError(null); @@ -572,16 +596,23 @@ function MemberDirectoryProfileAttempt({ if (!mutationIsCurrent(start)) return; pendingRemoveFocusIntentRef.current = null; rejectedRemoveResultFocusIntentRef.current = null; + confirmedPhotoResultFocusIntentRef.current = null; try { const profile = await getMyMemberDirectoryProfile(app); if (!mutationIsCurrent(start)) return; + const focusIntent = pendingConfirmedPhotoFocusIntentRef.current; + pendingConfirmedPhotoFocusIntentRef.current = null; + confirmedPhotoResultFocusIntentRef.current = focusIntent !== null + && focusIntent.lifetime === start.lifetime + && focusIntent.operation === start.operation + && focusIntent.action === start.action + && (start.action === 'upload' || start.action === 'remove') + ? focusIntent + : null; mutationRef.current = null; if (start.action === 'upload') { photoReadRef.current = null; setPhotoDraft(null); - postMutationFocusRef.current = 'photo-input'; - } else if (start.action === 'remove') { - postMutationFocusRef.current = 'remove-result'; } uncertainChangeRef.current = false; recoveryFocusIntentRef.current = null; @@ -589,6 +620,8 @@ function MemberDirectoryProfileAttempt({ } catch { if (!mutationIsCurrent(start)) return; mutationRef.current = null; + pendingConfirmedPhotoFocusIntentRef.current = null; + confirmedPhotoResultFocusIntentRef.current = null; photoReadRef.current = null; setPhotoDraft(null); setActionError(null); @@ -648,6 +681,13 @@ function MemberDirectoryProfileAttempt({ operation: start.operation, }; } + if (document.activeElement === removePhotoButtonRef.current) { + pendingConfirmedPhotoFocusIntentRef.current = { + lifetime: start.lifetime, + operation: start.operation, + action: 'remove', + }; + } finishMutation( start, () => removeMyMemberDirectoryPhoto(app, { @@ -785,6 +825,13 @@ function MemberDirectoryProfileAttempt({ const start = startMutation('upload'); if (start === null) return; + if (document.activeElement === savePhotoButtonRef.current) { + pendingConfirmedPhotoFocusIntentRef.current = { + lifetime: start.lifetime, + operation: start.operation, + action: 'upload', + }; + } const { contentType, base64Data } = photoDraft; finishMutation(