From c73934b84e2da5d05e2ac7773bc8b15f35a7598a Mon Sep 17 00:00:00 2001 From: "platform-localization-pr-bot[bot]" <294853593+platform-localization-pr-bot[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:30:54 -0600 Subject: [PATCH 01/75] chore: sync react localization from platform-localization (#478) chore: sync react localization Co-authored-by: camrun91 <16566029+camrun91@users.noreply.github.com> --- .changeset/sync-localization-react-4bb808c.md | 5 + packages/ui/src/i18n/locales/en.json | 18 ++- packages/ui/src/i18n/locales/it.json | 127 ++++++++++++++++++ packages/ui/src/i18n/locales/ko.json | 45 ++++++- packages/ui/src/i18n/locales/nl.json | 7 +- packages/ui/src/i18n/locales/ro.json | 127 ++++++++++++++++++ packages/ui/src/i18n/locales/ru.json | 7 +- packages/ui/src/i18n/locales/sr.json | 9 +- packages/ui/src/i18n/locales/sv.json | 127 ++++++++++++++++++ packages/ui/src/i18n/locales/tr.json | 11 +- packages/ui/src/i18n/locales/uk.json | 7 +- packages/ui/src/i18n/resources.generated.ts | 46 ++++--- 12 files changed, 500 insertions(+), 36 deletions(-) create mode 100644 .changeset/sync-localization-react-4bb808c.md create mode 100644 packages/ui/src/i18n/locales/it.json create mode 100644 packages/ui/src/i18n/locales/ro.json create mode 100644 packages/ui/src/i18n/locales/sv.json diff --git a/.changeset/sync-localization-react-4bb808c.md b/.changeset/sync-localization-react-4bb808c.md new file mode 100644 index 000000000..dbb826ef0 --- /dev/null +++ b/.changeset/sync-localization-react-4bb808c.md @@ -0,0 +1,5 @@ +--- +'@youversion/platform-react-ui': patch +--- + +Sync localization from platform-localization (4bb808c): add Italian (it), Romanian (ro), Swedish (sv); update 81 keys in en, ko, nl, ru, sr, tr, uk. diff --git a/packages/ui/src/i18n/locales/en.json b/packages/ui/src/i18n/locales/en.json index 6de04814d..27e0ded28 100644 --- a/packages/ui/src/i18n/locales/en.json +++ b/packages/ui/src/i18n/locales/en.json @@ -124,5 +124,21 @@ "bibleSearchTrendingHeading": "Trending Searches", "bibleLanguagesHeading": "Bible Languages", "languageVersionsHeading": "{{language}} Versions", - "versionsStatistics": "{{versionsCount}} Versions in {{languagesCount}} Languages" + "versionsStatistics": "{{versionsCount}} Versions in {{languagesCount}} Languages", + "notesPreviouslySaved": "Previously Saved", + "notesAddedNoteOn": "You added a note on {{date}}", + "notesReplaceTitle": "Replace unsaved changes?", + "notesReplaceMessage": "Your unsaved changes will be discarded when you open this saved note.", + "notesReplace": "Replace", + "notesDelete": "Delete", + "notesDeleteTitle": "Delete saved note?", + "notesDeleteMessage": "This note will be permanently deleted. Your unsaved note text will be kept.", + "notesSave": "Save", + "notesPrivate": "Private", + "notesPublic": "Public", + "notesPlaceholder": "Add Note…", + "notesDiscardTitle": "Discard note?", + "notesDiscardMessage": "Your note hasn’t been saved. Discard your changes?", + "notesDiscard": "Discard", + "notesVerseIndicatorAccessibilityLabel": "Notes {{verse}}" } diff --git a/packages/ui/src/i18n/locales/it.json b/packages/ui/src/i18n/locales/it.json new file mode 100644 index 000000000..2af1609aa --- /dev/null +++ b/packages/ui/src/i18n/locales/it.json @@ -0,0 +1,127 @@ +{ + "verseOfTheDay": "Versetto del giorno", + "shareAriaLabel": "Condividi", + "languageSearchAriaLabel": "Cerca lingue", + "loadingVerseAriaLabel": "Caricamento versetto", + "loadingPassageAriaLabel": "Caricamento brano", + "loadingBibleVersionAriaLabel": "Caricamento versione della Bibbia", + "loading": "Caricamento", + "loadingEllipsis": "Caricamento in corso...", + "footnotesHeading": "Note a piè di pagina", + "unableToShare": "Impossibile condividere. Riprova.", + "signIn": "Accedi", + "signOut": "Disconnetti", + "signInWithYouVersion": "Accedi con {{brandName}}", + "signOutOfYouVersion": "Esci da {{brandName}}", + "signInAppNameFallback": "Questa app", + "previousChapterAriaLabel": "Capitolo precedente", + "nextChapterAriaLabel": "Capitolo successivo", + "changeBibleBookAndChapterAriaLabel": "Cambia libro e capitolo della Bibbia", + "changeBibleVersionAriaLabel": "Cambia versione della Bibbia", + "settingsAriaLabel": "Impostazioni", + "readerSettingsHeading": "Impostazioni del lettore", + "fontLabel": "Carattere", + "sourceSerifFontName": "Source Serif", + "closeAriaLabel": "Chiudi", + "searchPlaceholder": "Scopri di più", + "selectLanguageHeading": "Seleziona una lingua", + "bibleLanguagesHeading": "Lingue della Bibbia", + "languageVersionsHeading": "{{language}} Versioni", + "versionsStatistics": "{{versionsCount}} Versioni in {{languagesCount}} lingue", + "selectLanguageAriaLabel": "Seleziona una lingua", + "regionalHeading": "Regionale", + "selectVersion": "Seleziona versione", + "select": "Seleziona", + "selectChapter": "Seleziona un capitolo", + "learnMore": "Scopri di più", + "userAvatarAlt": "Immagine profilo utente", + "chapterUnavailable": "Questo capitolo non è disponibile in questa versione. Scegli un capitolo o una versione diversa.", + "noBibleSearchResults": "Siamo spiacenti, non sono stati trovati risultati relativi alla Bibbia per questa ricerca.", + "noVersionsFound": "Nessuna versione trovata", + "suggestedTab": "Suggerito", + "errorHeading": "Errore", + "verseLabel": "Versetto {{verseNum}}", + "bibleAppTitle": "App della Bibbia", + "sunIconTitle": "Luce", + "passageNotFoundError": "Questo brano non è disponibile nella versione della Bibbia selezionata.", + "invalidAppKeyError": "Impossibile caricare questo contenuto biblico perché la chiave dell'app è mancante o non valida.", + "forbiddenError": "Questa app non è autorizzata ad accedere a questo contenuto biblico.", + "unreachableServerError": "Il server della Bibbia non è raggiungibile. Controlla la connessione e riprova.", + "rateLimitedError": "Il nostro servizio della Bibbia sta ricevendo troppe richieste in questo momento. Ti preghiamo di attendere qualche istante e riprovare.", + "serverError": "Il servizio dell'app Bibbia sta riscontrando dei problemi in questo momento. Riprova tra un momento.", + "genericPassageError": "Non è stato possibile caricare questo brano biblico. Riprova.", + "copy": "Copia", + "share": "Condividi", + "verseActionsAriaLabel": "Azioni del versetto", + "highlightColorsAriaLabel": "Colori di evidenziazione", + "applyHighlightAriaLabel": "Applica evidenziazione", + "clearHighlightAriaLabel": "Rimuovi evidenziazione", + "dataExchangeHighlightsQuestion": "Consentire a questa app di salvare le evidenziazioni con YouVersion?", + "dataExchangeHighlightsExplanation": "YouVersion ti chiederà di concedere l'accesso prima che le evidenziazioni possano essere salvate.", + "dataExchangeContinue": "Continua", + "genericCancel": "Annulla", + "signInIntroducing": "IN ARRIVO", + "signInParagraph": "{{appName}} vuole connettersi al tuo account YouVersion Bible App. Ciò consentirà loro di vedere e interagire con la tua attività su Bible App. Vuoi procedere?", + "signInYesButton": "Sì, grazie", + "signInNoButton": "No, grazie", + "signOutQuestion": "Sei sicuro di voler uscire da YouVersion?", + "signOutExplanation": "Dovrai accedere di nuovo per visualizzare le tue evidenziazioni.", + "signOutPendingHighlightsQuestion": "Salvare le evidenziazioni?", + "signOutPendingHighlightsExplanation": "Alcune delle tue evidenziazioni non sono ancora state salvate e andranno perse se ti disconnetti. Vuoi disconnetterti comunque?", + "signOutPendingHighlightsConfirm": "Disconnetti comunque", + "youVersionPlatformLogoAriaLabel": "YouVersion Platform", + "alphabetical": "Alfabetico", + "cancel": "Annulla", + "clearSearch": "Cancella ricerca", + "close": "Chiudi", + "done": "Fine", + "generic.requestErrorBody": "Non è possibile completare questa richiesta in questo momento.", + "error": "Errore", + "font": "Carattere", + "fontAndSettings": "Font e impostazioni", + "language": "Lingua", + "maybeLater": "Forse più tardi", + "moreMenuAriaLabel": "Altro", + "noChaptersAvailable": "Nessun capitolo disponibile", + "ok": "OK", + "offlineConnectionLostMessage": "Riscontriamo difficoltà con la tua connessione.", + "offlineDownloadAgreement": "Il nostro accordo con l'editore di questa versione della Bibbia ci richiede di condividere determinate informazioni con loro per offrire questa versione per l'uso offline. Procedendo, accetti di condividere le tue informazioni e di consentire all'editore di inviarti email.", + "offlineDownloadTagline": "Leggila in qualsiasi momento, ovunque—anche offline", + "passageUnavailable": "Questo brano non è disponibile nella versione della Bibbia selezionata.", + "regional": "Regionale", + "retry": "Riprova", + "search": "Cerca", + "searchLanguages": "Cerca lingue", + "searchVersions": "Cerca versioni", + "selectLanguage": "Seleziona una lingua", + "suggested": "Suggerito", + "traditional": "Tradizionale", + "versionUnavailableAutoSelectedMessage": "La versione della Bibbia precedentemente selezionata non è disponibile. Passa a un'altra versione.", + "agreeAndDownload": "Accetta e scarica", + "all": "Tutti", + "back": "Indietro", + "bibleApp": "App della Bibbia", + "bibleSearchBibleHeading": "Bibbia", + "bibleSearchClearAriaLabel": "Cancella ricerca", + "bibleSearchFilterBoth": "Entrambi", + "bibleSearchFilterNewTestament": "Nuovo Testamento", + "bibleSearchFilterOldTestament": "Antico Testamento", + "bibleSearchFiltersButton": "Filtri", + "bibleSearchRecentHeading": "Ricerche recenti", + "bibleSearchTrendingHeading": "Ricerche di tendenza", + "booksHeading": "Libri", + "bibleVersionsHeading": "Versioni della Bibbia", + "allLanguagesHeading": "Tutte le lingue", + "allLanguagesTab": "Tutte ({{count}})", + "allVersionsHeading": "Tutte le versioni", + "backToBibleVersionsAriaLabel": "Torna alle versioni della Bibbia", + "noLanguageSearchResults": "Siamo spiacenti, non ci sono risultati per questa ricerca.", + "noRegionalLanguagesAvailable": "Nessuna lingua regionale disponibile", + "recentlyUsedVersionsHeading": "Versioni recenti", + "changeLineSpacingAriaLabel": "Cambia interlinea", + "decreaseFontSizeAriaLabel": "Diminuisci dimensione carattere", + "footnoteAriaLabel": "Note a piè di pagina", + "increaseFontSizeAriaLabel": "Aumenta dimensione carattere", + "interFontName": "Inter", + "untitledSerifFontName": "Untitled Serif" +} diff --git a/packages/ui/src/i18n/locales/ko.json b/packages/ui/src/i18n/locales/ko.json index 63c5a4678..6df2ae497 100644 --- a/packages/ui/src/i18n/locales/ko.json +++ b/packages/ui/src/i18n/locales/ko.json @@ -33,7 +33,7 @@ "backToBibleVersionsAriaLabel": "성경 번역본으로 돌아가기", "selectLanguageHeading": "언어 선택", "selectLanguageAriaLabel": "언어 선택", - "recentlyUsedVersionsHeading": "최근 사용한 번역본", + "recentlyUsedVersionsHeading": "최근 번역본", "allVersionsHeading": "모든 번역본", "regionalHeading": "지역", "allLanguagesHeading": "모든 언어", @@ -82,5 +82,46 @@ "youVersionPlatformLogoAriaLabel": "YouVersion Platform", "booksHeading": "책", "bibleVersionsHeading": "성경 번역본", - "untitledSerifFontName": "Untitled Serif" + "untitledSerifFontName": "Untitled Serif", + "bibleLanguagesHeading": "성경 언어", + "languageVersionsHeading": "{{language}} 번역본", + "versionsStatistics": "{{versionsCount}}개 번역본, {{languagesCount}}개 언어", + "alphabetical": "가나다순", + "cancel": "취소", + "clearSearch": "검색 지우기", + "close": "닫기", + "done": "완료", + "generic.requestErrorBody": "현재 이 요청을 완료할 수 없습니다.", + "error": "오류", + "font": "글꼴", + "fontAndSettings": "글꼴 및 설정", + "language": "언어", + "maybeLater": "나중에", + "moreMenuAriaLabel": "더 보기", + "ok": "확인", + "offlineConnectionLostMessage": "인터넷 연결에 문제가 있습니다.", + "offlineDownloadAgreement": "오프라인 사용을 위해서는 성경 번역본 출판사와의 계약에 따라 특정 정보를 공유해야 합니다. 계속 진행하시면 귀하의 정보를 공유하고 출판사가 이메일을 보낼 수 있도록 동의하는 것으로 간주됩니다.", + "offlineDownloadTagline": "언제 어디서든 읽으세요. 오프라인에서도 읽을 수 있습니다.", + "passageUnavailable": "선택한 성경 번역본에서는 이 본문을 사용할 수 없습니다.", + "regional": "지역", + "retry": "재시도", + "search": "검색", + "searchLanguages": "언어 검색", + "searchVersions": "번역본 검색", + "selectLanguage": "언어 선택", + "suggested": "추천", + "traditional": "전통적 순서", + "versionUnavailableAutoSelectedMessage": "이전에 선택한 성경 번역본을 사용할 수 없습니다. 다른 번역본을 선택해 주세요.", + "agreeAndDownload": "동의 및 다운로드", + "all": "전체", + "back": "뒤로", + "bibleApp": "성경 앱", + "bibleSearchBibleHeading": "성경", + "bibleSearchClearAriaLabel": "검색 지우기", + "bibleSearchFilterBoth": "둘 다", + "bibleSearchFilterNewTestament": "신약", + "bibleSearchFilterOldTestament": "구약", + "bibleSearchFiltersButton": "필터", + "bibleSearchRecentHeading": "최근 검색", + "bibleSearchTrendingHeading": "인기 검색" } diff --git a/packages/ui/src/i18n/locales/nl.json b/packages/ui/src/i18n/locales/nl.json index 6fedfd072..5e0b39727 100644 --- a/packages/ui/src/i18n/locales/nl.json +++ b/packages/ui/src/i18n/locales/nl.json @@ -114,11 +114,14 @@ "backToBibleVersionsAriaLabel": "Terug naar Bijbelvertalingen", "noLanguageSearchResults": "Het spijt ons, er zijn geen resultaten voor deze zoekopdracht.", "noRegionalLanguagesAvailable": "Geen regionale talen beschikbaar", - "recentlyUsedVersionsHeading": "Onlangs gebruikte vertalingen", + "recentlyUsedVersionsHeading": "Recente vertalingen", "changeLineSpacingAriaLabel": "Regelafstand wijzigen", "decreaseFontSizeAriaLabel": "Lettergrootte verkleinen", "footnoteAriaLabel": "Voetnoot", "increaseFontSizeAriaLabel": "Lettergrootte vergroten", "interFontName": "Inter", - "untitledSerifFontName": "Untitled Serif" + "untitledSerifFontName": "Untitled Serif", + "bibleLanguagesHeading": "Bijbeltalen", + "languageVersionsHeading": "{{language}} vertalingen", + "versionsStatistics": "{{versionsCount}} vertalingen in {{languagesCount}} talen" } diff --git a/packages/ui/src/i18n/locales/ro.json b/packages/ui/src/i18n/locales/ro.json new file mode 100644 index 000000000..d3c873dd8 --- /dev/null +++ b/packages/ui/src/i18n/locales/ro.json @@ -0,0 +1,127 @@ +{ + "verseOfTheDay": "Versetul zilei", + "shareAriaLabel": "Distribuie", + "languageSearchAriaLabel": "Căutați limbi", + "loadingVerseAriaLabel": "Se încarcă versetul", + "loadingPassageAriaLabel": "Se încarcă pasajul", + "loadingBibleVersionAriaLabel": "Se încarcă versiunea Bibliei", + "loading": "Se încarcă", + "loadingEllipsis": "Se încarcă...", + "footnotesHeading": "Note de subsol", + "unableToShare": "Imposibil de distribuit. Vă rugăm să încercați din nou.", + "signIn": "Conectare", + "signOut": "Deconectare", + "signInWithYouVersion": "Conectează-te cu {{brandName}}", + "signOutOfYouVersion": "Deconectează-te din {{brandName}}", + "signInAppNameFallback": "Această aplicație", + "previousChapterAriaLabel": "Capitolul anterior", + "nextChapterAriaLabel": "Capitolul următor", + "changeBibleBookAndChapterAriaLabel": "Schimbați cartea și capitolul Bibliei", + "changeBibleVersionAriaLabel": "Schimbați versiunea Bibliei", + "settingsAriaLabel": "Setări", + "readerSettingsHeading": "Setări cititor", + "fontLabel": "Font", + "sourceSerifFontName": "Source Serif", + "closeAriaLabel": "Închide", + "searchPlaceholder": "Căutare", + "selectLanguageHeading": "Selectați o Limbă", + "bibleLanguagesHeading": "Limbi Biblie", + "languageVersionsHeading": "{{language}} Versiuni", + "versionsStatistics": "{{versionsCount}} versiuni în {{languagesCount}} limbi", + "selectLanguageAriaLabel": "Selectați o Limbă", + "regionalHeading": "Regional", + "selectVersion": "Selectați versiunea", + "select": "Selectați", + "selectChapter": "Selectați un capitol", + "learnMore": "Află mai multe", + "userAvatarAlt": "Avatar utilizator", + "chapterUnavailable": "Acest capitol nu este disponibil în această versiune. Vă rugăm să alegeți un alt capitol sau o altă versiune.", + "noBibleSearchResults": "Ne pare rău, nu există rezultate biblice pentru această căutare.", + "noVersionsFound": "Nu s-au găsit versiuni", + "suggestedTab": "Sugerate", + "errorHeading": "Eroare", + "verseLabel": "Versetul {{verseNum}}", + "bibleAppTitle": "Aplicația Biblia", + "sunIconTitle": "Soare", + "passageNotFoundError": "Acest pasaj nu este disponibil în versiunea Bibliei selectate.", + "invalidAppKeyError": "Conținutul acestei Biblii nu a putut fi încărcat deoarece cheia aplicației lipsește sau este invalidă.", + "forbiddenError": "Această aplicație nu are permisiunea de a accesa acest conținut biblic.", + "unreachableServerError": "Serverul Bibliei nu a putut fi accesat. Verificați conexiunea și încercați din nou.", + "rateLimitedError": "Serviciul biblic primește prea multe solicitări în acest moment. Vă rugăm să așteptați un moment și să încercați din nou.", + "serverError": "Serviciul biblic întâmpină ceva probleme momentan. Te rugăm să încerci din nou.", + "genericPassageError": "Nu am putut încărca acest pasaj biblic. Te rugăm să încerci din nou.", + "copy": "Copiați", + "share": "Distribuie", + "verseActionsAriaLabel": "Acțiuni verset", + "highlightColorsAriaLabel": "Culori de evidențiere", + "applyHighlightAriaLabel": "Aplică evidențierea", + "clearHighlightAriaLabel": "Șterge evidențierea", + "dataExchangeHighlightsQuestion": "Permiteți acestei aplicații să salveze evidențierile cu YouVersion?", + "dataExchangeHighlightsExplanation": "YouVersion vă va cere să acordați acces înainte ca evidențierile să poată fi salvate.", + "dataExchangeContinue": "Continuați", + "genericCancel": "Anulare", + "signInIntroducing": "PREZENTARE", + "signInParagraph": "{{appName}} dorește să se conecteze la contul dvs. YouVersion Bible App. Aceasta le va permite să vadă și să interacționeze cu activitatea dvs. din Bible App. Doriți să continuați?", + "signInYesButton": "Da, vă rog", + "signInNoButton": "Nu, mulțumesc", + "signOutQuestion": "Sigur dorești să te deconectezi de la YouVersion?", + "signOutExplanation": "Va trebui să te conectezi din nou pentru a accesa evidențierile tale.", + "signOutPendingHighlightsQuestion": "Salvați evidențierile?", + "signOutPendingHighlightsExplanation": "Unele dintre evidențierile tale nu au fost salvate încă și se vor pierde dacă te deconectezi. Vrei să te deconectezi oricum?", + "signOutPendingHighlightsConfirm": "Deconectați-vă oricum", + "youVersionPlatformLogoAriaLabel": "YouVersion Platform", + "alphabetical": "Alfabetic", + "cancel": "Anulare", + "clearSearch": "Șterge căutarea", + "close": "Închide", + "done": "Gata", + "generic.requestErrorBody": "Această solicitare nu poate fi finalizată în acest moment.", + "error": "Eroare", + "font": "Font", + "fontAndSettings": "Fonturi și setări", + "language": "Limbă", + "maybeLater": "Poate mai târziu", + "moreMenuAriaLabel": "Mai multe", + "noChaptersAvailable": "Nu există capitole disponibile", + "ok": "De acord", + "offlineConnectionLostMessage": "Avem dificultăți cu conexiunea ta.", + "offlineDownloadAgreement": "Acordul nostru cu editorul acestei versiuni a Bibliei ne obligă să împărtășim anumite informații cu aceștia pentru a oferi această versiune pentru utilizare în mod deconectat. Continuând, ești de acord să împărtășești aceste informații și să permiți editorului să îți trimită e-mailuri.", + "offlineDownloadTagline": "Citește oricând, oriunde, chiar și în mod deconectat", + "passageUnavailable": "Acest pasaj nu este disponibil în versiunea Bibliei selectate.", + "regional": "Regional", + "retry": "Reîncearcă", + "search": "Căutare", + "searchLanguages": "Caută limbi", + "searchVersions": "Caută versiuni", + "selectLanguage": "Selectați o Limbă", + "suggested": "Sugerate", + "traditional": "Tradițional", + "versionUnavailableAutoSelectedMessage": "Versiunea Bibliei selectată anterior nu este disponibilă. Te rugăm să alegi o altă versiune.", + "agreeAndDownload": "Acceptați și descărcați", + "all": "Toate", + "back": "Înapoi", + "bibleApp": "Aplicația Biblia", + "bibleSearchBibleHeading": "Biblie", + "bibleSearchClearAriaLabel": "Șterge căutarea", + "bibleSearchFilterBoth": "Ambele", + "bibleSearchFilterNewTestament": "Noul Testament", + "bibleSearchFilterOldTestament": "Vechiul Testament", + "bibleSearchFiltersButton": "Filtre", + "bibleSearchRecentHeading": "Căutări recente", + "bibleSearchTrendingHeading": "Căutări populare", + "booksHeading": "Cărți", + "bibleVersionsHeading": "Versiuni ale Bibliei", + "allLanguagesHeading": "Toate limbile", + "allLanguagesTab": "Toate ({{count}})", + "allVersionsHeading": "Toate versiunile", + "backToBibleVersionsAriaLabel": "Înapoi la versiunile Bibliei", + "noLanguageSearchResults": "Ne pare rău, nu există rezultate pentru această căutare.", + "noRegionalLanguagesAvailable": "Nu există limbi regionale disponibile", + "recentlyUsedVersionsHeading": "Versiuni recente", + "changeLineSpacingAriaLabel": "Schimbați spațierea dintre rânduri", + "decreaseFontSizeAriaLabel": "Micșorați dimensiunea fontului", + "footnoteAriaLabel": "Notă de subsol", + "increaseFontSizeAriaLabel": "Măriți dimensiunea fontului", + "interFontName": "Inter", + "untitledSerifFontName": "Untitled Serif" +} diff --git a/packages/ui/src/i18n/locales/ru.json b/packages/ui/src/i18n/locales/ru.json index 30cbb0805..70cc42b91 100644 --- a/packages/ui/src/i18n/locales/ru.json +++ b/packages/ui/src/i18n/locales/ru.json @@ -114,11 +114,14 @@ "backToBibleVersionsAriaLabel": "Вернуться к переводам Библии", "noLanguageSearchResults": "К сожалению, по этому запросу результатов не найдено.", "noRegionalLanguagesAvailable": "Региональные языки недоступны", - "recentlyUsedVersionsHeading": "Недавно использованные переводы", + "recentlyUsedVersionsHeading": "Недавние переводы", "changeLineSpacingAriaLabel": "Изменить межстрочный интервал", "decreaseFontSizeAriaLabel": "Уменьшить размер шрифта", "footnoteAriaLabel": "Сноска", "increaseFontSizeAriaLabel": "Увеличить размер шрифта", "interFontName": "Inter", - "untitledSerifFontName": "Untitled Serif" + "untitledSerifFontName": "Untitled Serif", + "bibleLanguagesHeading": "Языки Библии", + "languageVersionsHeading": "Переводы на: {{language}}", + "versionsStatistics": "Переводов: {{versionsCount}} на языках: {{languagesCount}}" } diff --git a/packages/ui/src/i18n/locales/sr.json b/packages/ui/src/i18n/locales/sr.json index e16a7d033..2a832e4f5 100644 --- a/packages/ui/src/i18n/locales/sr.json +++ b/packages/ui/src/i18n/locales/sr.json @@ -34,7 +34,7 @@ "backToBibleVersionsAriaLabel": "Nazad na prevode Biblije", "selectLanguageHeading": "Izaberite jezik", "selectLanguageAriaLabel": "Izaberite jezik", - "recentlyUsedVersionsHeading": "Nedavno korišćeni prevodi", + "recentlyUsedVersionsHeading": "Nedavni prevodi", "allVersionsHeading": "Svi prevodi", "regionalHeading": "Regionalno", "allLanguagesHeading": "Svi jezici", @@ -103,7 +103,7 @@ "regional": "Regionalno", "retry": "Pokušaj ponovo", "search": "Pretraži", - "searchLanguages": "Pretraži jezike", + "searchLanguages": "Pretražite jezike", "searchVersions": "Pretražite prevode", "selectLanguage": "Izaberite jezik", "suggested": "Predloženo", @@ -120,5 +120,8 @@ "bibleSearchFilterOldTestament": "Stari zavet", "bibleSearchFiltersButton": "Filteri", "bibleSearchRecentHeading": "Nedavne pretrage", - "bibleSearchTrendingHeading": "Popularne pretrage" + "bibleSearchTrendingHeading": "Popularne pretrage", + "bibleLanguagesHeading": "Jezici Biblije", + "languageVersionsHeading": "{{language}} prevodi", + "versionsStatistics": "{{versionsCount}} prevoda na {{languagesCount}} jezika" } diff --git a/packages/ui/src/i18n/locales/sv.json b/packages/ui/src/i18n/locales/sv.json new file mode 100644 index 000000000..234043495 --- /dev/null +++ b/packages/ui/src/i18n/locales/sv.json @@ -0,0 +1,127 @@ +{ + "verseOfTheDay": "Dagens vers", + "shareAriaLabel": "Dela", + "languageSearchAriaLabel": "Sök språk", + "loadingVerseAriaLabel": "Laddar bibelvers", + "loadingPassageAriaLabel": "Laddar avsnitt", + "loadingBibleVersionAriaLabel": "Laddar bibelöversättning", + "loading": "Laddar", + "loadingEllipsis": "Laddar...", + "footnotesHeading": "Fotnoter", + "unableToShare": "Det gick inte att dela. Försök igen.", + "signIn": "Logga in", + "signOut": "Logga ut", + "signInWithYouVersion": "Logga in med {{brandName}}", + "signOutOfYouVersion": "Logga ut från {{brandName}}", + "signInAppNameFallback": "Denna app", + "previousChapterAriaLabel": "Föregående kapitel", + "nextChapterAriaLabel": "Nästa kapitel", + "changeBibleBookAndChapterAriaLabel": "Ändra bibelbok och kapitel", + "changeBibleVersionAriaLabel": "Byt bibelöversättning", + "settingsAriaLabel": "Inställningar", + "readerSettingsHeading": "Läsarinställningar", + "fontLabel": "Teckensnitt", + "sourceSerifFontName": "Source Serif", + "closeAriaLabel": "Stäng", + "searchPlaceholder": "Sök", + "selectLanguageHeading": "Välj ett språk", + "bibleLanguagesHeading": "Bibelns språk", + "languageVersionsHeading": "{{language}} översättningar", + "versionsStatistics": "{{versionsCount}} översättningar på {{languagesCount}} språk", + "selectLanguageAriaLabel": "Välj ett språk", + "regionalHeading": "Regionalt", + "selectVersion": "Välj översättning", + "select": "Välj", + "selectChapter": "Välj ett kapitel", + "learnMore": "Läs mer", + "userAvatarAlt": "Användarens avatar", + "chapterUnavailable": "Det här kapitlet är inte tillgängligt i den här översättningen. Välj ett annat kapitel eller en annan översättning.", + "noBibleSearchResults": "Tyvärr finns det inga matchande resultat från Bibeln för denna sökning.", + "noVersionsFound": "Inga översättningar hittades", + "suggestedTab": "Förslag", + "errorHeading": "Fel", + "verseLabel": "Vers {{verseNum}}", + "bibleAppTitle": "Bibelappen", + "sunIconTitle": "Sol", + "passageNotFoundError": "Det här avsnittet finns inte i den valda bibelöversättningen.", + "invalidAppKeyError": "Det här bibelinnehållet kunde inte laddas eftersom appnyckeln saknas eller är ogiltig.", + "forbiddenError": "Den här appen har inte behörighet att komma åt detta bibelinnehåll.", + "unreachableServerError": "Bibelservern kunde inte nås. Kontrollera din anslutning och försök igen.", + "rateLimitedError": "Bibeltjänsten tar emot för många förfrågningar just nu. Vänta en stund och försök igen.", + "serverError": "Bibeltjänsten har problem just nu. Försök igen om en stund.", + "genericPassageError": "Vi kunde inte ladda det här bibelavsnittet. Försök igen.", + "copy": "Kopiera", + "share": "Dela", + "verseActionsAriaLabel": "Versåtgärder", + "highlightColorsAriaLabel": "Markeringsfärger", + "applyHighlightAriaLabel": "Applicera markering", + "clearHighlightAriaLabel": "Rensa markering", + "dataExchangeHighlightsQuestion": "Tillåt den här appen att spara markeringar med YouVersion?", + "dataExchangeHighlightsExplanation": "YouVersion kommer att be dig bevilja åtkomst innan markeringar kan sparas.", + "dataExchangeContinue": "Fortsätt", + "genericCancel": "Avbryt", + "signInIntroducing": "VI PRESENTERAR", + "signInParagraph": "{{appName}} vill ansluta till ditt YouVersion Bible App-konto. Detta gör att de kan se och interagera med din aktivitet i Bibelappen. Vill du fortsätta?", + "signInYesButton": "Ja tack", + "signInNoButton": "Nej tack", + "signOutQuestion": "Är du säker på att du vill logga ut från YouVersion?", + "signOutExplanation": "Du måste logga in igen för att komma åt dina markeringar.", + "signOutPendingHighlightsQuestion": "Spara dina markeringar?", + "signOutPendingHighlightsExplanation": "Några av dina markeringar har inte sparats än och de kommer att gå förlorade om du loggar ut. Vill du logga ut ändå?", + "signOutPendingHighlightsConfirm": "Logga ut ändå", + "youVersionPlatformLogoAriaLabel": "YouVersion Platform", + "alphabetical": "Alfabetisk", + "cancel": "Avbryt", + "clearSearch": "Rensa sökning", + "close": "Stäng", + "done": "Klar", + "generic.requestErrorBody": "Den här begäran kan inte slutföras just nu.", + "error": "Fel", + "font": "Teckensnitt", + "fontAndSettings": "Typsnitt & inställningar", + "language": "Språk", + "maybeLater": "Kanske senare", + "moreMenuAriaLabel": "Mer", + "noChaptersAvailable": "Inga kapitel tillgängliga", + "ok": "OK", + "offlineConnectionLostMessage": "Vi har problem med din anslutning.", + "offlineDownloadAgreement": "Enligt vårt avtal med utgivaren av denna bibelöversättning är vi skyldiga att dela viss information med dem för att kunna erbjuda denna översättning för användning offline. Genom att fortsätta samtycker du till att dela dina uppgifter och till att utgivaren får skicka e-post till dig.", + "offlineDownloadTagline": "Läs den när som helst, var som helst – även offline", + "passageUnavailable": "Det här avsnittet finns inte i den valda bibelöversättningen.", + "regional": "Regionalt", + "retry": "Försök igen", + "search": "Sök", + "searchLanguages": "Sök språk", + "searchVersions": "Sök efter översättningar", + "selectLanguage": "Välj ett språk", + "suggested": "Förslag", + "traditional": "Traditionell", + "versionUnavailableAutoSelectedMessage": "Den bibelöversättning du tidigare valt är inte tillgänglig. Byt till en annan.", + "agreeAndDownload": "Godkänn och ladda ner", + "all": "Alla", + "back": "Tillbaka", + "bibleApp": "Bibelappen", + "bibleSearchBibleHeading": "Bibeln", + "bibleSearchClearAriaLabel": "Rensa sökning", + "bibleSearchFilterBoth": "Båda", + "bibleSearchFilterNewTestament": "Nya testamentet", + "bibleSearchFilterOldTestament": "Gamla testamentet", + "bibleSearchFiltersButton": "Filter", + "bibleSearchRecentHeading": "Senaste sökningar", + "bibleSearchTrendingHeading": "Populära sökningar", + "booksHeading": "Böcker", + "bibleVersionsHeading": "Bibelöversättningar", + "allLanguagesHeading": "Alla språk", + "allLanguagesTab": "Alla ({{count}})", + "allVersionsHeading": "Alla översättningar", + "backToBibleVersionsAriaLabel": "Tillbaka till bibelöversättningar", + "noLanguageSearchResults": "Vi beklagar, det finns inga resultat för denna sökning.", + "noRegionalLanguagesAvailable": "Inga regionala språk tillgängliga", + "recentlyUsedVersionsHeading": "Nyligen använda översättningar", + "changeLineSpacingAriaLabel": "Ändra radavstånd", + "decreaseFontSizeAriaLabel": "Minska teckenstorlek", + "footnoteAriaLabel": "Fotnot", + "increaseFontSizeAriaLabel": "Öka teckenstorlek", + "interFontName": "Inter", + "untitledSerifFontName": "Untitled Serif" +} diff --git a/packages/ui/src/i18n/locales/tr.json b/packages/ui/src/i18n/locales/tr.json index 21fcb5139..a9b2f6dad 100644 --- a/packages/ui/src/i18n/locales/tr.json +++ b/packages/ui/src/i18n/locales/tr.json @@ -33,7 +33,7 @@ "backToBibleVersionsAriaLabel": "Kutsal Kitap çeviri versiyonlarına geri dön", "selectLanguageHeading": "Bir Dil Seçin", "selectLanguageAriaLabel": "Bir Dil Seçin", - "recentlyUsedVersionsHeading": "Son Kullanılan Sürümler", + "recentlyUsedVersionsHeading": "Son Versiyonlar", "allVersionsHeading": "Tüm Çeviri Versiyonları", "regionalHeading": "Bölgesel", "allLanguagesHeading": "Tüm Diller", @@ -103,8 +103,8 @@ "regional": "Bölgesel", "retry": "Yeniden Dene", "search": "Ara", - "searchLanguages": "Dilleri ara", - "searchVersions": "Çeviri versiyonu ara", + "searchLanguages": "Dilleri Ara", + "searchVersions": "Versiyonları Ara", "selectLanguage": "Bir Dil Seçin", "suggested": "Önerilen", "traditional": "Geleneksel", @@ -120,5 +120,8 @@ "bibleSearchFilterOldTestament": "Eski Antlaşma", "bibleSearchFiltersButton": "Filtreler", "bibleSearchRecentHeading": "Son Aramalar", - "bibleSearchTrendingHeading": "Popüler Aramalar" + "bibleSearchTrendingHeading": "Popüler Aramalar", + "bibleLanguagesHeading": "Kutsal Kitap Dilleri", + "languageVersionsHeading": "{{language}} Versiyonlar", + "versionsStatistics": "{{languagesCount}} Dilde {{versionsCount}} Versiyon" } diff --git a/packages/ui/src/i18n/locales/uk.json b/packages/ui/src/i18n/locales/uk.json index 3c4e46b0a..a7fbf2103 100644 --- a/packages/ui/src/i18n/locales/uk.json +++ b/packages/ui/src/i18n/locales/uk.json @@ -114,11 +114,14 @@ "backToBibleVersionsAriaLabel": "Назад до перекладів Біблії", "noLanguageSearchResults": "Вибачте, за цим запитом немає результатів.", "noRegionalLanguagesAvailable": "Регіональні мови недоступні", - "recentlyUsedVersionsHeading": "Нещодавно використані переклади", + "recentlyUsedVersionsHeading": "Нещодавні переклади", "changeLineSpacingAriaLabel": "Змінити міжрядковий інтервал", "decreaseFontSizeAriaLabel": "Зменшити розмір шрифту", "footnoteAriaLabel": "Виноска", "increaseFontSizeAriaLabel": "Збільшити розмір шрифту", "interFontName": "Inter", - "untitledSerifFontName": "Untitled Serif" + "untitledSerifFontName": "Untitled Serif", + "bibleLanguagesHeading": "Мови Біблії", + "languageVersionsHeading": "Перекладів: {{language}}", + "versionsStatistics": "{{versionsCount}} перекладів {{languagesCount}} мовами" } diff --git a/packages/ui/src/i18n/resources.generated.ts b/packages/ui/src/i18n/resources.generated.ts index 6d5de52f3..a40eb9670 100644 --- a/packages/ui/src/i18n/resources.generated.ts +++ b/packages/ui/src/i18n/resources.generated.ts @@ -9,16 +9,19 @@ import locale5 from './locales/de.json' with { type: 'json' }; import locale6 from './locales/es.json' with { type: 'json' }; import locale7 from './locales/fr.json' with { type: 'json' }; import locale8 from './locales/ig.json' with { type: 'json' }; -import locale9 from './locales/ko.json' with { type: 'json' }; -import locale10 from './locales/nl.json' with { type: 'json' }; -import locale11 from './locales/no.json' with { type: 'json' }; -import locale12 from './locales/pt.json' with { type: 'json' }; -import locale13 from './locales/ru.json' with { type: 'json' }; -import locale14 from './locales/sr.json' with { type: 'json' }; -import locale15 from './locales/tr.json' with { type: 'json' }; -import locale16 from './locales/uk.json' with { type: 'json' }; -import locale17 from './locales/vi.json' with { type: 'json' }; -import locale18 from './locales/zh.json' with { type: 'json' }; +import locale9 from './locales/it.json' with { type: 'json' }; +import locale10 from './locales/ko.json' with { type: 'json' }; +import locale11 from './locales/nl.json' with { type: 'json' }; +import locale12 from './locales/no.json' with { type: 'json' }; +import locale13 from './locales/pt.json' with { type: 'json' }; +import locale14 from './locales/ro.json' with { type: 'json' }; +import locale15 from './locales/ru.json' with { type: 'json' }; +import locale16 from './locales/sr.json' with { type: 'json' }; +import locale17 from './locales/sv.json' with { type: 'json' }; +import locale18 from './locales/tr.json' with { type: 'json' }; +import locale19 from './locales/uk.json' with { type: 'json' }; +import locale20 from './locales/vi.json' with { type: 'json' }; +import locale21 from './locales/zh.json' with { type: 'json' }; const defaultNS = 'translation'; @@ -32,16 +35,19 @@ export const resources = { es: { [defaultNS]: locale6 }, fr: { [defaultNS]: locale7 }, ig: { [defaultNS]: locale8 }, - ko: { [defaultNS]: locale9 }, - nl: { [defaultNS]: locale10 }, - no: { [defaultNS]: locale11 }, - pt: { [defaultNS]: locale12 }, - ru: { [defaultNS]: locale13 }, - sr: { [defaultNS]: locale14 }, - tr: { [defaultNS]: locale15 }, - uk: { [defaultNS]: locale16 }, - vi: { [defaultNS]: locale17 }, - zh: { [defaultNS]: locale18 }, + it: { [defaultNS]: locale9 }, + ko: { [defaultNS]: locale10 }, + nl: { [defaultNS]: locale11 }, + no: { [defaultNS]: locale12 }, + pt: { [defaultNS]: locale13 }, + ro: { [defaultNS]: locale14 }, + ru: { [defaultNS]: locale15 }, + sr: { [defaultNS]: locale16 }, + sv: { [defaultNS]: locale17 }, + tr: { [defaultNS]: locale18 }, + uk: { [defaultNS]: locale19 }, + vi: { [defaultNS]: locale20 }, + zh: { [defaultNS]: locale21 }, } as const; export const supportedLngs = Object.keys(resources); From c913c4e7de67efce8ad3a4684b0e49341cd44033 Mon Sep 17 00:00:00 2001 From: Cameron Pak Date: Tue, 24 Nov 2026 11:05:39 -0600 Subject: [PATCH 02/75] fix(core): sanitize planted footnote content in Bible HTML (#486) * fix(core): sanitize planted footnote content in Bible HTML Co-Authored-By: Cameron Pak * fix(core): address review on footnote sanitization Sanitize footnote content in an inert template, drop non-HTML-namespace elements, sanitize generated footnote content for idempotency, document the sanitization contract, and consolidate tests. Co-Authored-By: Cameron Pak --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .changeset/safe-footnote-content.md | 6 + .../core/src/bible-html-transformer.test.ts | 72 +++++++++ packages/core/src/bible-html-transformer.ts | 144 ++++++++++++------ packages/ui/src/components/verse.test.tsx | 18 ++- packages/ui/src/components/verse.tsx | 11 +- 5 files changed, 203 insertions(+), 48 deletions(-) create mode 100644 .changeset/safe-footnote-content.md diff --git a/.changeset/safe-footnote-content.md b/.changeset/safe-footnote-content.md new file mode 100644 index 000000000..da89897ca --- /dev/null +++ b/.changeset/safe-footnote-content.md @@ -0,0 +1,6 @@ +--- +"@youversion/platform-core": patch +"@youversion/platform-react-ui": patch +--- + +Sanitized `data-verse-footnote-content` found in Bible HTML input with the same allowlist as passage markup, so planted footnote markup can no longer run script in the Bible reader. `transformBibleHtml` now removes input `data-footnote-key` attributes and `data-yv-*` attributes other than `data-yv-transformed`, and drops all SVG and MathML content. `FootnoteContentProps` now documents that `notes` and `verseHtml` must be sanitized HTML. diff --git a/packages/core/src/bible-html-transformer.test.ts b/packages/core/src/bible-html-transformer.test.ts index 74e444312..e1797dbee 100644 --- a/packages/core/src/bible-html-transformer.test.ts +++ b/packages/core/src/bible-html-transformer.test.ts @@ -4,6 +4,20 @@ import { describe, it, expect } from 'vitest'; import { transformBibleHtml, transformBibleHtmlForBrowser } from './bible-html-transformer'; +function parse(html: string): Document { + return new DOMParser().parseFromString(html, 'text/html'); +} + +function toAttr(html: string): string { + return html.replace(/&/g, '&').replace(/"/g, '"').replace(/ new DOMParser().parseFromString(html, 'text/html'), @@ -445,6 +459,64 @@ describe('transformBibleHtml - sanitization', () => { expect(result.html).toContain('data-custom="value"'); }); + it('should sanitize planted footnote content and strip reserved attributes from raw and transformed input', () => { + const raw = `
Text
`; + const rawDoc = parse(transformBibleHtml(raw, createAdapters()).html); + const rawRoot = rawDoc.body.firstElementChild; + + expect(footnoteContent(rawDoc, '1')).toBe('Planted'); + expect(rawRoot?.hasAttribute('data-footnote-key')).toBe(false); + expect(rawRoot?.hasAttribute('data-yv-sdk')).toBe(false); + expect(rawRoot?.hasAttribute('data-yv-shadow-host')).toBe(false); + expect(rawRoot?.getAttribute('data-slot')).toBe('keep'); + expect(rawRoot?.hasAttribute('data-yv-transformed')).toBe(true); + + const plantedNote = + 'NoteNested'; + const transformed = `
Text
`; + const transformedDoc = parse(transformBibleHtml(transformed, createAdapters()).html); + + expect(footnoteContent(transformedDoc, '1')).toBe( + 'NoteNested', + ); + expect(transformedDoc.querySelectorAll('[data-verse-footnote]')).toHaveLength(1); + }); + + it('should block footnote content bypasses and stay stable when transformed again', () => { + const bypasses: Array<[payload: string, expected: string]> = [ + ['Safe', 'Safe'], + ['xSafe', 'Safe'], + ['Safe', 'Safe'], + ['Safe', 'Safe'], + ['<img src=x onerror=alert(1)>', '<img src=x onerror=alert(1)>'], + ['Safe', 'Safe'], + [ + 'Safe', + 'Safe', + ], + ['Safe', 'Safe'], + ]; + + for (const [payload, expected] of bypasses) { + const html = `
`; + const first = transformBibleHtml(html, createAdapters()); + const second = transformBibleHtml(first.html, createAdapters()); + + expect(footnoteContent(parse(first.html), '1'), payload).toBe(expected); + expect(second.html, payload).toBe(first.html); + } + + const genuine = + '
1Text1:1 A note n.
'; + const first = transformBibleHtml(genuine, createAdapters()); + const second = transformBibleHtml(first.html, createAdapters()); + + expect(footnoteContent(parse(first.html), '1')).toBe( + '1:1 A note n', + ); + expect(second.html).toBe(first.html); + }); + it('should preserve dir attribute for RTL support', () => { const html = '

Hebrew text

'; const result = transformBibleHtml(html, createAdapters()); diff --git a/packages/core/src/bible-html-transformer.ts b/packages/core/src/bible-html-transformer.ts index 97cb1b78e..a725cff75 100644 --- a/packages/core/src/bible-html-transformer.ts +++ b/packages/core/src/bible-html-transformer.ts @@ -6,49 +6,74 @@ const TRANSFORMED_ATTR = 'data-yv-transformed'; const NEEDS_SPACE_BEFORE = /^[^\s.,;:!?)}\]'"'»›]/; +const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; + const ALLOWED_TAGS = new Set([ - 'DIV', - 'P', - 'SPAN', - 'SUP', - 'SUB', - 'EM', - 'STRONG', - 'I', - 'B', - 'SMALL', - 'BR', - 'SECTION', - 'TABLE', - 'THEAD', - 'TBODY', - 'TR', - 'TD', - 'TH', + 'div', + 'p', + 'span', + 'sup', + 'sub', + 'em', + 'strong', + 'i', + 'b', + 'small', + 'br', + 'section', + 'table', + 'thead', + 'tbody', + 'tr', + 'td', + 'th', ]); const DROP_ENTIRELY_TAGS = new Set([ - 'SCRIPT', - 'STYLE', - 'IFRAME', - 'OBJECT', - 'EMBED', - 'SVG', - 'MATH', - 'FORM', - 'INPUT', - 'BUTTON', - 'TEXTAREA', - 'SELECT', - 'TEMPLATE', - 'LINK', - 'META', - 'BASE', - 'NOSCRIPT', + 'script', + 'style', + 'iframe', + 'object', + 'embed', + 'svg', + 'math', + 'form', + 'input', + 'button', + 'textarea', + 'select', + 'template', + 'link', + 'meta', + 'base', + 'noscript', ]); const ALLOWED_ATTRS = new Set(['class', 'v', 'colspan', 'rowspan', 'dir', 'usfm']); +const FOOTNOTE_ANCHOR_ATTR = 'data-verse-footnote'; + +const FOOTNOTE_CONTENT_ATTR = 'data-verse-footnote-content'; + +const FOOTNOTE_DATA_ATTRS = new Set([FOOTNOTE_ANCHOR_ATTR, FOOTNOTE_CONTENT_ATTR]); + +type SanitizeMode = 'passage' | 'footnote'; + +// Other data-* attributes stay because consumers style and query them (for +// example data-slot), and they carry no behavior. SDK-internal names are +// reserved so a passage cannot plant them. The transformed marker stays so +// re-transforming output is idempotent; footnote content is re-sanitized as +// HTML instead of trusted, and cannot nest further footnote anchors. +function isAllowedDataAttr(name: string, mode: SanitizeMode): boolean { + if (!name.startsWith('data-')) return false; + if (name === FOOTNOTE_KEY_ATTR) return false; + if (name.startsWith('data-yv-') && name !== TRANSFORMED_ATTR) return false; + if (mode === 'footnote' && (FOOTNOTE_DATA_ATTRS.has(name) || name === TRANSFORMED_ATTR)) { + return false; + } + return true; +} + export type TextDirection = 'ltr' | 'rtl'; function topLevelElements(doc: Document): Element[] { @@ -64,17 +89,16 @@ function resolveTextDirection(roots: Element[]): TextDirection | undefined { return undefined; } -function sanitizeBibleHtmlDocument(doc: Document): void { - const root = doc.body ?? doc.documentElement; +function sanitizeBibleHtmlTree(root: ParentNode, mode: SanitizeMode): void { for (const el of Array.from(root.querySelectorAll('*'))) { - const tag = el.tagName; - - if (DROP_ENTIRELY_TAGS.has(tag)) { + // SVG and MathML elements keep lowercase tag names and their own parsing + // rules, so anything outside the HTML namespace is dropped with its text. + if (el.namespaceURI !== HTML_NAMESPACE || DROP_ENTIRELY_TAGS.has(el.localName)) { el.remove(); continue; } - if (!ALLOWED_TAGS.has(tag)) { + if (!ALLOWED_TAGS.has(el.localName)) { el.replaceWith(...Array.from(el.childNodes)); continue; } @@ -86,13 +110,30 @@ function sanitizeBibleHtmlDocument(doc: Document): void { continue; } - if (!ALLOWED_ATTRS.has(name) && !name.startsWith('data-')) { + if (!ALLOWED_ATTRS.has(name) && !isAllowedDataAttr(name, mode)) { el.removeAttribute(attr.name); } } + + const footnoteContent = el.getAttribute(FOOTNOTE_CONTENT_ATTR); + if (footnoteContent !== null) { + el.setAttribute( + FOOTNOTE_CONTENT_ATTR, + sanitizeFootnoteHtml(footnoteContent, el.ownerDocument), + ); + } } } +// Footnote content is rendered as HTML by consumers, so it must pass the same +// allowlist as passage markup. An inert template avoids a full parse per note. +function sanitizeFootnoteHtml(html: string, doc: Document): string { + const template = doc.createElement('template'); + template.innerHTML = html; + sanitizeBibleHtmlTree(template.content, 'footnote'); + return template.innerHTML; +} + /** * Options for transforming Bible HTML. Requires DOM adapter functions * to parse and serialize HTML, making the transformer runtime-agnostic. @@ -113,6 +154,12 @@ export type TransformBibleHtmlOptions = { * * Consumers can access verse context by walking up from a footnote anchor * to `.closest('.yv-v[v]')`. + * + * Sanitization: `html` and every `data-verse-footnote-content` value pass the + * same tag and attribute allowlist, so both are safe to inject as HTML. Input + * `data-footnote-key` and `data-yv-*` attributes (except `data-yv-transformed`) + * are removed; footnote content also has no `data-verse-footnote`, + * `data-verse-footnote-content`, or `data-yv-transformed` attributes. */ export type TransformedBibleHtml = { /** The transformed HTML with footnotes replaced by marker elements */ @@ -290,8 +337,8 @@ function replaceFootnotesWithAnchors(doc: Document, footnotes: Element[]): void } const anchor = doc.createElement('span'); - anchor.setAttribute('data-verse-footnote', key); - anchor.setAttribute('data-verse-footnote-content', fn.innerHTML); + anchor.setAttribute(FOOTNOTE_ANCHOR_ATTR, key); + anchor.setAttribute(FOOTNOTE_CONTENT_ATTR, sanitizeFootnoteHtml(fn.innerHTML, doc)); fn.replaceWith(anchor); } } @@ -344,6 +391,13 @@ function fixIrregularTables(doc: Document): void { * Verse context is available by walking up from a footnote anchor: * `anchor.closest('.yv-v[v]')` returns the verse wrapper (null for intro footnotes). * + * Sanitization: input is treated as untrusted. Disallowed tags, SVG/MathML, + * `on*` handlers, and non-allowlisted attributes are removed. Footnote content + * already present in input (`data-verse-footnote-content`) is sanitized the same + * way, so the output and its footnote content are safe to inject as HTML. Input + * `data-footnote-key` and `data-yv-*` attributes (except `data-yv-transformed`) + * are removed. Other `data-*` attributes are kept. + * * @param html - The raw Bible HTML from the YouVersion API * @param options - DOM adapter options for parsing and serializing HTML * @returns The transformed HTML @@ -366,7 +420,7 @@ export function transformBibleHtml( ): TransformedBibleHtml { const doc = options.parseHtml(html); - sanitizeBibleHtmlDocument(doc); + sanitizeBibleHtmlTree(doc.body ?? doc.documentElement, 'passage'); // Only trust the marker when every top-level element carries it. A nested or // partially-marked fragment (transformed HTML concatenated with raw HTML, or diff --git a/packages/ui/src/components/verse.test.tsx b/packages/ui/src/components/verse.test.tsx index 0041dc395..20527d916 100644 --- a/packages/ui/src/components/verse.test.tsx +++ b/packages/ui/src/components/verse.test.tsx @@ -2,7 +2,7 @@ * @vitest-environment jsdom */ import { describe, it, expect, vi, afterEach } from 'vitest'; -import { act, render as rtlRender, waitFor } from '@testing-library/react'; +import { act, render as rtlRender, screen, waitFor, within } from '@testing-library/react'; import type { ReactElement } from 'react'; import { hydrateRoot } from 'react-dom/client'; import { renderToString } from 'react-dom/server'; @@ -367,6 +367,22 @@ describe('Verse.Html - Footnotes', () => { }); }); + it('should not render HTML planted in data-verse-footnote-content', async () => { + const plantedHtml = + '
1Text
'; + + render(); + + await userEvent.click(await screen.findByRole('button')); + + const dialog = await screen.findByRole('dialog'); + await waitFor(() => { + expect(within(dialog).getByText('Planted')).toBeInTheDocument(); + }); + expect(dialog.querySelector('img')).toBeNull(); + expect(dialog.innerHTML).not.toContain('onerror'); + }); + it('should use alphabetic markers beyond z in the popover list', async () => { const repeatedFootnotes = Array.from({ length: 27 }, () => { return '1:1 Footnote text'; diff --git a/packages/ui/src/components/verse.tsx b/packages/ui/src/components/verse.tsx index 427cc9392..cb6d630f4 100644 --- a/packages/ui/src/components/verse.tsx +++ b/packages/ui/src/components/verse.tsx @@ -60,6 +60,13 @@ export type FootnoteData = { reference?: string; }; +/** + * Props for {@link FootnoteContent}. + * + * Security: `notes` and `verseHtml` are injected as HTML without further + * sanitization. Pass only output from `transformBibleHtml` (or HTML that went + * through an equivalent allowlist sanitizer); never pass raw API or user HTML. + */ export type FootnoteContentProps = FootnoteData & { scriptureDirection?: TextDirection; fontSize?: number; @@ -95,7 +102,7 @@ function FootnoteContentImplementation({
@@ -109,7 +116,7 @@ function FootnoteContentImplementation({ className="yv:flex yv:gap-2 yv:text-xs yv:border-b yv:border-solid yv:border-border yv:py-2" > {marker}. - {/** biome-ignore lint/security/noDangerouslySetInnerHtml: Bible footnote HTML comes from our YouVersion APIs and is safe */} + {/* Caller must pass sanitized HTML; see FootnoteContentProps. */} ); From 1326e0a04618e9e7af024bb32cf2808b69392912 Mon Sep 17 00:00:00 2001 From: Austin Date: Tue, 24 Nov 2026 12:25:16 -0600 Subject: [PATCH 03/75] refactor(ui): organize Bible reader modules (#489) * refactor(ui): organize Bible reader modules (YPE-6808) * refactor(ui): extract reader settings lifecycle and toolbar (#495) * refactor(ui): extract reader settings lifecycle and toolbar (YPE-6815) * fix(ui): address reader settings review feedback --- .changeset/bible-reader-refactor.md | 2 + .../reader-settings-toolbar-refactor.md | 5 + .../ui/src/components/bible-reader-context.ts | 66 ++ .../ui/src/components/bible-reader-search.tsx | 2 +- .../src/components/bible-reader-settings.ts | 102 ++ .../ui/src/components/bible-reader-storage.ts | 5 + .../src/components/bible-reader-toolbar.tsx | 396 +++++++ .../ui/src/components/bible-reader.test.tsx | 208 +++- packages/ui/src/components/bible-reader.tsx | 991 ++---------------- .../ui/src/components/bible-reader.types.ts | 100 ++ .../src/components/bible-theme-settings.tsx | 161 +++ .../components/use-bible-reader-highlights.ts | 21 +- .../components/use-bible-reader-settings.ts | 151 +++ 13 files changed, 1284 insertions(+), 926 deletions(-) create mode 100644 .changeset/bible-reader-refactor.md create mode 100644 .changeset/reader-settings-toolbar-refactor.md create mode 100644 packages/ui/src/components/bible-reader-context.ts create mode 100644 packages/ui/src/components/bible-reader-settings.ts create mode 100644 packages/ui/src/components/bible-reader-storage.ts create mode 100644 packages/ui/src/components/bible-reader-toolbar.tsx create mode 100644 packages/ui/src/components/bible-reader.types.ts create mode 100644 packages/ui/src/components/bible-theme-settings.tsx create mode 100644 packages/ui/src/components/use-bible-reader-settings.ts diff --git a/.changeset/bible-reader-refactor.md b/.changeset/bible-reader-refactor.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/bible-reader-refactor.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/.changeset/reader-settings-toolbar-refactor.md b/.changeset/reader-settings-toolbar-refactor.md new file mode 100644 index 000000000..998efe0e2 --- /dev/null +++ b/.changeset/reader-settings-toolbar-refactor.md @@ -0,0 +1,5 @@ +--- +"@youversion/platform-react-ui": patch +--- + +Keep Bible reader toolbar settings synchronized with committed renders while host updates are suspended. diff --git a/packages/ui/src/components/bible-reader-context.ts b/packages/ui/src/components/bible-reader-context.ts new file mode 100644 index 000000000..08079d0fd --- /dev/null +++ b/packages/ui/src/components/bible-reader-context.ts @@ -0,0 +1,66 @@ +'use client'; + +import { createContext, useContext, type Dispatch, type SetStateAction } from 'react'; +import type { BibleBook, Highlight, TextDirection } from '@youversion/platform-core'; +import type { FontFamily } from '@/lib/verse-html-utils'; +import type { VerseFocusRequest } from '@/lib/use-transient-verse-focus'; +import type { BibleChapterPickerPressData } from './bible-chapter-picker'; +import type { BibleVersionPickerPressData } from './bible-version-picker'; +import type { BibleReaderSearchPressData } from './bible-reader-search'; +import type { FootnoteData } from './verse'; +import type { BibleReaderNavigation } from './bible-reader-navigation'; +import type { + BibleReaderHighlightIntent, + BibleReaderShareData, + BibleReaderVerseSelection, +} from './bible-reader.types'; + +export type BibleReaderContextType = { + book: string; + chapter: string; + versionId: number; + setBook: Dispatch>; + setChapter: Dispatch>; + setVersionId: Dispatch>; + booksData: BibleBook[]; + booksLoading: boolean; + currentFontFamily: FontFamily; + setCurrentFontFamily: Dispatch>; + currentFontSize: number; + setCurrentFontSize: Dispatch>; + currentLineSpacing: number; + setCurrentLineSpacing: Dispatch>; + showVerseNumbers: boolean; + background: 'light' | 'dark'; + onFootnotePress?: (data: FootnoteData) => void; + onChapterPickerPress?: (data: BibleChapterPickerPressData) => void; + onVersionPickerPress?: (data: BibleVersionPickerPressData) => void; + onSearchPress?: (data: BibleReaderSearchPressData) => void | Promise; + languageId?: string; + defaultLanguageId?: string; + onLanguageChange?: (languageId: string) => void; + onSignInPress?: () => void; + onSignOutPress?: () => void; + onCopy?: (data: BibleReaderShareData) => void | Promise; + onShare?: (data: BibleReaderShareData) => void | Promise; + highlights?: Highlight[]; + isHighlightsControlled: boolean; + onVerseSelect?: (selection: BibleReaderVerseSelection) => void; + onHighlightApply?: (intent: BibleReaderHighlightIntent) => void; + onHighlightRemove?: (intent: BibleReaderHighlightIntent) => void; + verseActions: 'popover' | 'none'; + clearSelectionSignal?: number; + navigation: BibleReaderNavigation; + verseFocus: VerseFocusRequest | null; + scriptureDirection?: TextDirection; +}; + +export const BibleReaderContext = createContext(null); + +export function useBibleReaderContext(): BibleReaderContextType { + const context = useContext(BibleReaderContext); + if (!context) { + throw new Error('BibleReader components must be used within BibleReader.Root'); + } + return context; +} diff --git a/packages/ui/src/components/bible-reader-search.tsx b/packages/ui/src/components/bible-reader-search.tsx index f29928459..b33a6d2d2 100644 --- a/packages/ui/src/components/bible-reader-search.tsx +++ b/packages/ui/src/components/bible-reader-search.tsx @@ -23,7 +23,7 @@ import { type RefObject, } from 'react'; import { useTranslation } from 'react-i18next'; -import { useBibleReaderContext } from './bible-reader'; +import { useBibleReaderContext } from './bible-reader-context'; import { SearchIcon } from './icons/search'; import { XIcon } from './icons/x'; import { LoaderIcon } from './icons/loader'; diff --git a/packages/ui/src/components/bible-reader-settings.ts b/packages/ui/src/components/bible-reader-settings.ts new file mode 100644 index 000000000..baba8e5ff --- /dev/null +++ b/packages/ui/src/components/bible-reader-settings.ts @@ -0,0 +1,102 @@ +import type { FontFamily } from '@/lib/verse-html-utils'; + +export const BIBLE_READER_FONT = { + MIN: 12, + MAX: 20, + DEFAULT: 16, + STEP: 2, +} as const; + +export const BIBLE_READER_SPACING = { + SM: 1.45, + DEFAULT: 1.7, + LG: 2.0, +} as const; + +const DEFAULT_FONT_SIZE = BIBLE_READER_FONT.DEFAULT; +const FONT_SIZE_STEP = BIBLE_READER_FONT.STEP; + +export type BibleThemeSettingsValues = { + fontSize: number; + fontFamily: FontFamily; + lineSpacing: number; +}; + +export type BibleThemeSettingsSnapshot = BibleThemeSettingsValues & { + minFontSize: number; + maxFontSize: number; +}; + +export type BibleThemeSettingsContentProps = { + theme: 'light' | 'dark'; + fontSize: number; + fontFamily: FontFamily; + lineSpacing: number; + onFontSelected: (fontFamily: FontFamily) => void; + onFontIncreased: () => void; + onFontDecreased: () => void; + onChangeLineSpacing: () => void; +}; + +export function clampBibleReaderFontSize(fontSize: number): number { + return Math.min(BIBLE_READER_FONT.MAX, Math.max(BIBLE_READER_FONT.MIN, fontSize)); +} + +export function normalizeReaderFontSizeForInitialization(size: number): number { + if (size > BIBLE_READER_FONT.MAX || size < BIBLE_READER_FONT.MIN) { + return DEFAULT_FONT_SIZE; + } + return size; +} + +export function nextBibleReaderFontSizeUp(current: number): number { + return clampBibleReaderFontSize(current + FONT_SIZE_STEP); +} + +export function nextBibleReaderFontSizeDown(current: number): number { + return clampBibleReaderFontSize(current - FONT_SIZE_STEP); +} + +export function changeBibleReaderLineSpacing(current: number): number { + switch (current) { + case BIBLE_READER_SPACING.DEFAULT: + return BIBLE_READER_SPACING.LG; + case BIBLE_READER_SPACING.LG: + return BIBLE_READER_SPACING.SM; + default: + return BIBLE_READER_SPACING.DEFAULT; + } +} + +/** + * Builds the handler props for `BibleThemeSettingsContent` from host-owned font state. + * Use this on the same side as `setFontSize` / `setFontFamily` (e.g. React Native before passing + * **top-level** props into a `BibleThemeSettingsContent` Expo DOM wrapper). Expo allows functions as + * top-level DOM props; do not nest these inside a {@link BibleThemeSettingsSnapshot}. + */ +export function createBibleThemeSettingsContentHandlers(options: { + getFontSize: () => number; + getFontFamily: () => FontFamily; + setFontSize: (size: number) => void; + setFontFamily: (fontFamily: FontFamily) => void; + getLineSpacing: () => number; + setLineSpacing: (size: number) => void; +}): Pick< + BibleThemeSettingsContentProps, + 'onFontIncreased' | 'onFontDecreased' | 'onFontSelected' | 'onChangeLineSpacing' +> { + return { + onFontIncreased: () => { + options.setFontSize(nextBibleReaderFontSizeUp(options.getFontSize())); + }, + onFontDecreased: () => { + options.setFontSize(nextBibleReaderFontSizeDown(options.getFontSize())); + }, + onFontSelected: (fontFamily) => { + options.setFontFamily(fontFamily); + }, + onChangeLineSpacing: () => { + options.setLineSpacing(changeBibleReaderLineSpacing(options.getLineSpacing())); + }, + }; +} diff --git a/packages/ui/src/components/bible-reader-storage.ts b/packages/ui/src/components/bible-reader-storage.ts new file mode 100644 index 000000000..113ea1683 --- /dev/null +++ b/packages/ui/src/components/bible-reader-storage.ts @@ -0,0 +1,5 @@ +export const READER_STORAGE_KEYS = { + fontSize: 'youversion-platform:reader:font-size', + fontFamily: 'youversion-platform:reader:font-family', + lineSpacing: 'youversion-platform:reader:line-spacing', +} as const; diff --git a/packages/ui/src/components/bible-reader-toolbar.tsx b/packages/ui/src/components/bible-reader-toolbar.tsx new file mode 100644 index 000000000..44e4265cc --- /dev/null +++ b/packages/ui/src/components/bible-reader-toolbar.tsx @@ -0,0 +1,396 @@ +'use client'; + +import { useContext, useLayoutEffect, useRef, type JSX } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useYVAuth, YouVersionContext } from '@youversion/platform-react-hooks'; +import { getAdjacentChapter } from '@youversion/platform-core'; +import i18n from '@/i18n'; +import { useInterfaceDirection } from '@/lib/direction'; +import { cn } from '@/lib/utils'; +import type { FontFamily } from '@/lib/verse-html-utils'; +import { ReuseShadowBoundary } from '@/lib/shadow-isolation'; +import { useBibleReaderContext } from './bible-reader-context'; +import { BibleChapterPicker } from './bible-chapter-picker'; +import { BibleVersionPicker } from './bible-version-picker'; +import { BibleReaderSearch } from './bible-reader-search'; +import { BibleThemeSettingsContent } from './bible-theme-settings'; +import { ChevronBackwardIcon } from './icons/chevron-backward'; +import { ChevronForwardIcon } from './icons/chevron-forward'; +import { GearIcon } from './icons/gear'; +import { LoaderIcon } from './icons/loader'; +import { PersonIcon } from './icons/person'; +import { ProfileAvatar } from './profile-avatar'; +import { Button } from './ui/button'; +import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from './ui/popover'; +import { + BIBLE_READER_FONT, + clampBibleReaderFontSize, + nextBibleReaderFontSizeUp, + nextBibleReaderFontSizeDown, + changeBibleReaderLineSpacing, + type BibleThemeSettingsValues, + type BibleThemeSettingsSnapshot, +} from './bible-reader-settings'; + +function UserMenu() { + const { t } = useTranslation(undefined, { i18n }); + const { auth, signIn, signOut, userInfo } = useYVAuth(); + const yvContext = useContext(YouVersionContext); + const { onSignInPress, onSignOutPress } = useBibleReaderContext(); + + // Prefer host-supplied native actions (e.g. the Expo DOM wrapper bridges these to + // native PKCE sign-in). Fall back to the Web SDK's own auth for pure-web usage. + const handleSignIn = () => { + if (onSignInPress) { + onSignInPress(); + } else { + void signIn({ scopes: ['profile'] }); + } + }; + const handleSignOut = () => { + if (onSignOutPress) { + onSignOutPress(); + } else { + signOut(); + } + }; + + return ( + + + {auth.isAuthenticated ? ( + + ) : ( + + )} + + + + + {auth.isAuthenticated ? ( + + ) : ( + + )} + + + + ); +} + +export type BibleReaderToolbarProps = { + border?: 'top' | 'bottom'; + onOpenBibleThemeSettings?: (snapshot: BibleThemeSettingsSnapshot) => void; + /** + * Whether the toolbar renders the built-in search control. + * `'control'` (default) | `'none'`. Mirrors `BibleReaderRootProps.verseActions`. + */ + search?: 'control' | 'none'; +}; + +export function Toolbar({ + border = 'top', + onOpenBibleThemeSettings, + search = 'control', +}: BibleReaderToolbarProps): JSX.Element { + const { t } = useTranslation(undefined, { i18n }); + const interfaceDirection = useInterfaceDirection(); + const { + book, + chapter, + versionId, + setBook, + setChapter, + setVersionId, + booksData, + booksLoading, + currentFontFamily, + setCurrentFontFamily, + currentFontSize, + setCurrentFontSize, + currentLineSpacing, + setCurrentLineSpacing, + background, + onChapterPickerPress, + onVersionPickerPress, + languageId, + defaultLanguageId, + onLanguageChange, + } = useBibleReaderContext(); + const yvContext = useContext(YouVersionContext); + const themesSettingsValuesRef = useRef({ + fontSize: currentFontSize, + fontFamily: currentFontFamily, + lineSpacing: currentLineSpacing, + }); + + useLayoutEffect(() => { + themesSettingsValuesRef.current = { + fontSize: currentFontSize, + fontFamily: currentFontFamily, + lineSpacing: currentLineSpacing, + }; + }); + + const applyThemeSettings = ( + themeSettings: BibleThemeSettingsValues, + ): BibleThemeSettingsValues => { + const nextThemeSettings = { + fontSize: clampBibleReaderFontSize(themeSettings.fontSize), + fontFamily: themeSettings.fontFamily, + lineSpacing: themeSettings.lineSpacing, + }; + + themesSettingsValuesRef.current = nextThemeSettings; + setCurrentFontSize(nextThemeSettings.fontSize); + setCurrentFontFamily(nextThemeSettings.fontFamily); + setCurrentLineSpacing(nextThemeSettings.lineSpacing); + + return nextThemeSettings; + }; + + const handleFontIncreased = (): BibleThemeSettingsValues => { + const settings = themesSettingsValuesRef.current; + return applyThemeSettings({ + ...settings, + fontSize: nextBibleReaderFontSizeUp(settings.fontSize), + }); + }; + + const handleFontDecreased = (): BibleThemeSettingsValues => { + const settings = themesSettingsValuesRef.current; + return applyThemeSettings({ + ...settings, + fontSize: nextBibleReaderFontSizeDown(settings.fontSize), + }); + }; + + const handleFontSelected = (fontFamily: FontFamily): BibleThemeSettingsValues => { + return applyThemeSettings({ + ...themesSettingsValuesRef.current, + fontFamily, + }); + }; + + const handleLineSpacingChange = (): BibleThemeSettingsValues => { + const settings = themesSettingsValuesRef.current; + return applyThemeSettings({ + ...settings, + lineSpacing: changeBibleReaderLineSpacing(settings.lineSpacing), + }); + }; + + const buildBibleThemeSettingsSnapshot = (): BibleThemeSettingsSnapshot => ({ + ...themesSettingsValuesRef.current, + minFontSize: BIBLE_READER_FONT.MIN, + maxFontSize: BIBLE_READER_FONT.MAX, + }); + + const prevResult = getAdjacentChapter(booksData, book, chapter, 'previous'); + const nextResult = getAdjacentChapter(booksData, book, chapter, 'next'); + const canNavigatePrevious = !booksLoading && prevResult !== null; + const canNavigateNext = !booksLoading && nextResult !== null; + const showSearch = search !== 'none'; + + return ( +
+
+ {yvContext?.authEnabled && } + + + + + {({ chapterLabel, currentBook, loading }) => ( +
+ + + + + +
+ )} +
+
+
+ + + + + {({ version, loading }) => ( + + )} + + + + + + {showSearch ? : null} + + {onOpenBibleThemeSettings ? ( + + ) : ( + + + + + + + + + + + + )} +
+
+ ); +} diff --git a/packages/ui/src/components/bible-reader.test.tsx b/packages/ui/src/components/bible-reader.test.tsx index 73d945ae8..a630a9a87 100644 --- a/packages/ui/src/components/bible-reader.test.tsx +++ b/packages/ui/src/components/bible-reader.test.tsx @@ -5,12 +5,16 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { act, render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { useState, type ReactElement } from 'react'; +import { startTransition, Suspense, useState, type ReactElement } from 'react'; import { hydrateRoot, type Root } from 'react-dom/client'; import { renderToString } from 'react-dom/server'; -import type { BibleBook, BibleVersion } from '@youversion/platform-core'; -import { YouVersionContext, type HookOverrides } from '@youversion/platform-react-hooks'; -import { HookOverrideProvider } from '@/test/hook-overrides'; +import { YouVersionAPIUsers, type BibleBook, type BibleVersion } from '@youversion/platform-core'; +import { + YouVersionAuthContext, + YouVersionContext, + type HookOverrides, +} from '@youversion/platform-react-hooks'; +import { HookOverrideProvider, TestQueryClientProvider } from '@/test/hook-overrides'; import { InterfaceDirectionProvider } from '@/lib/direction'; import { ReuseShadowBoundary } from '@/lib/shadow-isolation'; import { @@ -691,3 +695,199 @@ describe('BibleReader version picker language', () => { expect(requestedLanguages.includes('ko')).toBe(true); }); }); + +// Existing browser journeys exercise normal resizing and saved preferences. These +// cases cover initialization boundaries, host control, and batched events they miss. +it('normalizes an invalid default and rejects saved settings outside reader bounds', async () => { + localStorage.clear(); + const user = userEvent.setup(); + const onOpen = vi.fn<(snapshot: BibleThemeSettingsSnapshot) => void>(); + const first = renderWithOverrides( + + + , + ); + await user.click(screen.getByRole('button', { name: 'Settings' })); + expect(onOpen.mock.calls[0]?.[0].fontSize).toBe(16); + expect(localStorage.getItem('youversion-platform:reader:font-size')).toBe('16'); + first.unmount(); + + localStorage.setItem('youversion-platform:reader:font-size', '99'); + localStorage.setItem('youversion-platform:reader:line-spacing', '3'); + renderWithOverrides( + + + , + ); + await user.click(screen.getByRole('button', { name: 'Settings' })); + expect(onOpen.mock.lastCall?.[0]).toMatchObject({ fontSize: 18, lineSpacing: 1.45 }); + expect(localStorage.getItem('youversion-platform:reader:font-size')).toBe('18'); + expect(localStorage.getItem('youversion-platform:reader:line-spacing')).toBe('1.45'); +}); + +it('keeps controlled settings and saved preferences independent during initialization', async () => { + localStorage.clear(); + localStorage.setItem('youversion-platform:reader:font-size', '20'); + localStorage.setItem('youversion-platform:reader:font-family', INTER_FONT); + localStorage.setItem('youversion-platform:reader:line-spacing', '2'); + const user = userEvent.setup(); + const onOpen = vi.fn<(snapshot: BibleThemeSettingsSnapshot) => void>(); + const onFontSizeChange = vi.fn(); + const onFontFamilyChange = vi.fn(); + const onChangeLineSpacing = vi.fn(); + renderWithOverrides( + + + , + ); + await user.click(screen.getByRole('button', { name: 'Settings' })); + expect(onOpen.mock.lastCall?.[0]).toMatchObject({ + fontSize: 14, + fontFamily: UNTITLED_SERIF_FONT, + lineSpacing: 1.45, + }); + expect(onFontSizeChange).not.toHaveBeenCalled(); + expect(onFontFamilyChange).not.toHaveBeenCalled(); + expect(onChangeLineSpacing).not.toHaveBeenCalled(); + expect(localStorage.getItem('youversion-platform:reader:font-size')).toBe('20'); + expect(localStorage.getItem('youversion-platform:reader:font-family')).toBe(INTER_FONT); + expect(localStorage.getItem('youversion-platform:reader:line-spacing')).toBe('2'); +}); + +it('prefers defaultLineSpacing while retaining the deprecated lineHeight fallback', async () => { + localStorage.clear(); + const user = userEvent.setup(); + const onOpen = vi.fn<(snapshot: BibleThemeSettingsSnapshot) => void>(); + const first = renderWithOverrides( + + + , + ); + await user.click(screen.getByRole('button', { name: 'Settings' })); + expect(onOpen.mock.lastCall?.[0].lineSpacing).toBe(2); + first.unmount(); + localStorage.clear(); + renderWithOverrides( + + + , + ); + await user.click(screen.getByRole('button', { name: 'Settings' })); + expect(onOpen.mock.lastCall?.[0].lineSpacing).toBe(1.45); +}); + +it('accumulates rapid font changes and uses the latest host value after a rerender', async () => { + localStorage.clear(); + const user = userEvent.setup(); + const onFontSizeChange = vi.fn(); + const tree = (fontSize: number) => ( + + + + ); + const view = renderWithOverrides(tree(14)); + await user.click(screen.getByRole('button', { name: 'Settings' })); + const increase = screen.getByRole('button', { name: 'Increase font size' }); + act(() => { + increase.click(); + increase.click(); + }); + expect(onFontSizeChange.mock.calls).toEqual([[16], [18]]); + + // The host rejects both requests and commits another render at the same value. + view.rerender( + + {tree(14)} + , + ); + await user.click(screen.getByRole('button', { name: 'Increase font size' })); + expect(onFontSizeChange).toHaveBeenLastCalledWith(16); + + view.rerender( + + {tree(16)} + , + ); + await user.click(screen.getByRole('button', { name: 'Increase font size' })); + expect(onFontSizeChange).toHaveBeenLastCalledWith(18); +}); + +it('uses the host sign-in action instead of starting web authentication', async () => { + localStorage.clear(); + const user = userEvent.setup(); + const onSignInPress = vi.fn(); + const signIn = vi.spyOn(YouVersionAPIUsers, 'signIn').mockResolvedValue(undefined); + try { + render( + + + + + + + + + + + , + ); + await user.click(screen.getByTestId('user-menu-trigger')); + await user.click(await screen.findByRole('button', { name: 'Sign in' })); + expect(onSignInPress).toHaveBeenCalledTimes(1); + expect(signIn).not.toHaveBeenCalled(); + } finally { + signIn.mockRestore(); + } +}); + +it('keeps toolbar snapshots on committed settings while a host update is suspended', async () => { + localStorage.clear(); + const user = userEvent.setup(); + const onOpen = vi.fn<(snapshot: BibleThemeSettingsSnapshot) => void>(); + const pending = new Promise(() => undefined); + const requestedSettings: number[] = []; + function WaitForHostSettings({ fontSize }: { fontSize: number }) { + if (fontSize === 18) { + requestedSettings.push(fontSize); + throw pending; + } + return Host settings ready; + } + function Host() { + const [fontSize, setFontSize] = useState(16); + return ( + <> + + Loading host settings
}> + + + + + + + ); + } + renderWithOverrides(); + await user.click(screen.getByRole('button', { name: 'Load host settings' })); + expect(requestedSettings).toContain(18); + expect(screen.getByText('Host settings ready')).toBeVisible(); + await user.click(screen.getByRole('button', { name: 'Settings' })); + expect(onOpen.mock.lastCall?.[0].fontSize).toBe(16); +}); diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx index bea912f61..42e2146ed 100644 --- a/packages/ui/src/components/bible-reader.tsx +++ b/packages/ui/src/components/bible-reader.tsx @@ -6,53 +6,30 @@ import { useDelayedLoading } from '@/lib/use-delayed-loading'; import { useHighlightsControlledLatch } from '@/lib/use-highlights-controlled-latch'; import { useResolvedScriptureDirection } from '@/lib/scripture-direction'; import { cn } from '@/lib/utils'; -import { - INTER_FONT, - SOURCE_SERIF_FONT, - UNTITLED_SERIF_FONT, - type FontFamily, -} from '@/lib/verse-html-utils'; import { useControllableState } from '@radix-ui/react-use-controllable-state'; -import type { BibleBook, Highlight, TextDirection } from '@youversion/platform-core'; import { DEFAULT_LICENSE_FREE_BIBLE_VERSION, - getAdjacentChapter, - getLocalStorage, - setStorageItem, + YouVersionPlatformConfiguration, + getPassageAttribution, + type Highlight, + type TextDirection, } from '@youversion/platform-core'; +import { useBooks, usePassage, useTheme, useVersion } from '@youversion/platform-react-hooks'; import { - useBooks, - usePassage, - useTheme, - useVersion, - useYVAuth, - YouVersionContext, -} from '@youversion/platform-react-hooks'; -import React, { - createContext, useCallback, - useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, - type ReactElement, type ReactNode, } from 'react'; import { useTranslation } from 'react-i18next'; -import { BibleChapterPicker, type BibleChapterPickerPressData } from './bible-chapter-picker'; -import { BibleVersionPicker, type BibleVersionPickerPressData } from './bible-version-picker'; -import { ChevronBackwardIcon } from './icons/chevron-backward'; -import { ChevronForwardIcon } from './icons/chevron-forward'; -import { GearIcon } from './icons/gear'; +import type { BibleChapterPickerPressData } from './bible-chapter-picker'; +import type { BibleVersionPickerPressData } from './bible-version-picker'; import { InfoIcon } from './icons/info'; import { LoaderIcon } from './icons/loader'; -import { PersonIcon } from './icons/person'; -import { ProfileAvatar } from './profile-avatar'; import { ReuseShadowBoundary, ShadowIsolationBoundary } from '@/lib/shadow-isolation'; -import { Button } from './ui/button'; -import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from './ui/popover'; import { VerseActionPopover } from './verse-action-popover'; import { useBibleReaderHighlights } from './use-bible-reader-highlights'; import { HighlightPermissionDialog } from './highlight-permission-dialog'; @@ -61,144 +38,53 @@ import { BibleTextView, getCleanVerseText, type FootnoteData } from './verse'; import { buildVerseReference, buildVerseShareText, joinVerseTexts } from '@/lib/verse-share'; import { isHighlightsLive } from '@/lib/feature-flags'; import { YvComponentStyles } from '@/lib/yv-styles-components'; -import { YouVersionPlatformConfiguration, getPassageAttribution } from '@youversion/platform-core'; -import { BibleReaderSearch, type BibleReaderSearchPressData } from './bible-reader-search'; +import type { BibleReaderSearchPressData } from './bible-reader-search'; import { useTransientVerseFocus, type VerseFocusRequest } from '@/lib/use-transient-verse-focus'; -import { BibleReaderNavigation } from './bible-reader-navigation'; +import { + BibleReaderNavigation, + type BibleReaderNavigationRequest, +} from './bible-reader-navigation'; import { VerseActionPopoverFocusRestoreProvider } from '@/lib/verse-action-popover-focus'; import { isElementFromOwnerDocument } from '@/lib/shadow-root-host'; - -type BibleReaderContextType = { - book: string; - chapter: string; - versionId: number; - setBook: React.Dispatch>; - setChapter: React.Dispatch>; - setVersionId: React.Dispatch>; - booksData: BibleBook[]; - booksLoading: boolean; - currentFontFamily: FontFamily; - setCurrentFontFamily: React.Dispatch>; - currentFontSize: number; - setCurrentFontSize: React.Dispatch>; - currentLineSpacing: number; - setCurrentLineSpacing: React.Dispatch>; - showVerseNumbers: boolean; - background: 'light' | 'dark'; - onFootnotePress?: (data: FootnoteData) => void; - onChapterPickerPress?: (data: BibleChapterPickerPressData) => void; - onVersionPickerPress?: (data: BibleVersionPickerPressData) => void; - onSearchPress?: (data: BibleReaderSearchPressData) => void | Promise; - languageId?: string; - defaultLanguageId?: string; - onLanguageChange?: (languageId: string) => void; - onSignInPress?: () => void; - onSignOutPress?: () => void; - onCopy?: (data: BibleReaderShareData) => void | Promise; - onShare?: (data: BibleReaderShareData) => void | Promise; - highlights?: Highlight[]; - isHighlightsControlled: boolean; - onVerseSelect?: (selection: BibleReaderVerseSelection) => void; - onHighlightApply?: (intent: BibleReaderHighlightIntent) => void; - onHighlightRemove?: (intent: BibleReaderHighlightIntent) => void; - verseActions: 'popover' | 'none'; - clearSelectionSignal?: number; - navigation: BibleReaderNavigation; - verseFocus: VerseFocusRequest | null; - scriptureDirection?: TextDirection; -}; - -/** - * Serializable payload describing the reader's current verse selection. - * Bridge-safe primitives only, so React Native / Expo DOM hosts can forward it - * across the native bridge. `passageIds` is deliberately redundant with - * `book`/`chapter`/`verses` (always per-verse, never ranges): native hosts feed - * the API without USFM string-building; analytics reads `verses` without USFM - * parsing. - */ -export type BibleReaderVerseSelection = { - /** Matches `Highlight.version_id`. */ - versionId: number; - /** USFM book code, e.g. `'JHN'`. */ - book: string; - /** Chapter id, e.g. `'3'`. */ - chapter: string; - /** Selected verse numbers, ascending and de-duplicated. `[]` on clear. */ - verses: number[]; - /** Per-verse USFM ids, e.g. `['JHN.3.16', 'JHN.3.17']`. Never ranges. */ - passageIds: string[]; - /** - * Localized display reference **without** the version abbreviation, e.g. - * `Hebrews 11:4`. For a host that renders its own verse-action UI (see - * {@link RootProps.verseActions}) this is the label to show; the USFM `book` - * code above is not human-readable. - * - * Falls back to the USFM book code (`HEB 11:4`) until `useBooks` resolves the - * book title; when it resolves while the selection is still live, the reader - * re-emits that selection with the localized reference. `''` on clear. - * - * Deliberately different from `shareData.reference`, which keeps the version - * abbreviation (`Hebrews 11:4 BSB`) because copied text needs it. Do not - * "fix" one to match the other. - */ - reference: string; - /** - * The same payload the popover's Copy / Share buttons produce, so a host - * owning the verse-action UI can run copy/share without a popover press. - * `null` on clear (and if the reader's DOM is not mounted). - */ - shareData: BibleReaderShareData | null; -}; - -/** - * Serializable payload handed to `onHighlightApply` / `onHighlightRemove` in - * controlled mode. An intent is a request, not a fact: the reader paints - * nothing until the host round-trips an updated `highlights` prop. - * - * `reference` / `shareData` are deliberately omitted: an intent is addressed to - * the data layer, which needs identity and colour only. - */ -export type BibleReaderHighlightIntent = Omit< +import { + BibleReaderContext, + useBibleReaderContext, + type BibleReaderContextType, +} from './bible-reader-context'; + +import type { + BibleReaderHighlightIntent, + BibleReaderSettingsProps, + BibleReaderShareData, BibleReaderVerseSelection, - 'reference' | 'shareData' -> & { - /** - * 6-character lowercase hex, no `#`. For `onHighlightRemove`, the color - * being cleared. - */ - color: string; -}; - -/** - * Serializable payload handed to the `onCopy` / `onShare` overrides. Mirrors - * `VerseOfTheDayShareData` so React Native / Expo DOM hosts can forward verse - * selections across the native bridge. - */ -export type BibleReaderShareData = { - /** Full body: curly-quoted verse text, a blank line, then the reference. */ - text: string; - /** Reference line only, e.g. `John 1:1-3 NIV`. */ - reference: string; - /** Verse text only (no reference line), gaps joined with ` ... `. */ - verseText: string; - /** Selected verse numbers, ascending and de-duplicated. */ - verses: number[]; - book: string; - chapter: string; - versionId: number; -}; - -const BibleReaderContext = createContext(null); - -export function useBibleReaderContext(): BibleReaderContextType { - const context = useContext(BibleReaderContext); - if (!context) { - throw new Error('BibleReader components must be used within BibleReader.Root'); - } - return context; -} +} from './bible-reader.types'; + +import { Toolbar } from './bible-reader-toolbar'; +import { useBibleReaderSettings } from './use-bible-reader-settings'; + +export type { BibleReaderToolbarProps } from './bible-reader-toolbar'; +export { useBibleReaderContext } from './bible-reader-context'; +export { BibleThemeSettingsContent } from './bible-theme-settings'; +export { + BIBLE_READER_FONT, + BIBLE_READER_SPACING, + clampBibleReaderFontSize, + nextBibleReaderFontSizeUp, + nextBibleReaderFontSizeDown, + changeBibleReaderLineSpacing, + createBibleThemeSettingsContentHandlers, + type BibleThemeSettingsValues, + type BibleThemeSettingsSnapshot, + type BibleThemeSettingsContentProps, +} from './bible-reader-settings'; + +export type { + BibleReaderHighlightIntent, + BibleReaderShareData, + BibleReaderVerseSelection, +} from './bible-reader.types'; -export type RootProps = { +export type RootProps = BibleReaderSettingsProps & { /** Retain this connection outside the reader to request navigation before mount. */ navigation?: BibleReaderNavigation; book?: string; @@ -210,21 +96,6 @@ export type RootProps = { versionId?: number; defaultVersionId?: number; onVersionChange?: (versionId: number) => void; - fontSize?: number; - defaultFontSize?: number; - onFontSizeChange?: (fontSize: number) => void; - fontFamily?: FontFamily; - defaultFontFamily?: FontFamily; - onFontFamilyChange?: (fontFamily: FontFamily) => void; - lineSpacing?: number; - defaultLineSpacing?: number; - onChangeLineSpacing?: (size: number) => void; - /** - * @deprecated Use `defaultLineSpacing` (uncontrolled) or `lineSpacing` + - * `onChangeLineSpacing` (controlled) instead. When provided, this is used as - * the initial line spacing. Will be removed in the next major version. - */ - lineHeight?: number; showVerseNumbers?: boolean; background?: 'light' | 'dark'; onFootnotePress?: (data: FootnoteData) => void; @@ -350,118 +221,17 @@ export type RootProps = { children?: ReactNode; }; -export const BIBLE_READER_FONT = { - MIN: 12, - MAX: 20, - DEFAULT: 16, - STEP: 2, -} as const; - -export const BIBLE_READER_SPACING = { - SM: 1.45, - DEFAULT: 1.7, - LG: 2.0, -} as const; - -const MIN_FONT_SIZE = BIBLE_READER_FONT.MIN; -const MAX_FONT_SIZE = BIBLE_READER_FONT.MAX; -const DEFAULT_FONT_SIZE = BIBLE_READER_FONT.DEFAULT; -const FONT_SIZE_STEP = BIBLE_READER_FONT.STEP; - -export type BibleThemeSettingsValues = { - fontSize: number; - fontFamily: FontFamily; - lineSpacing: number; -}; - -export type BibleThemeSettingsSnapshot = BibleThemeSettingsValues & { - minFontSize: number; - maxFontSize: number; -}; - -export type BibleThemeSettingsContentProps = { - theme: 'light' | 'dark'; - fontSize: number; - fontFamily: FontFamily; - lineSpacing: number; - onFontSelected: (fontFamily: FontFamily) => void; - onFontIncreased: () => void; - onFontDecreased: () => void; - onChangeLineSpacing: () => void; -}; - -export function clampBibleReaderFontSize(fontSize: number): number { - return Math.min(MAX_FONT_SIZE, Math.max(MIN_FONT_SIZE, fontSize)); -} - -function normalizeReaderFontSizeForInitialization(size: number): number { - if (size > MAX_FONT_SIZE || size < MIN_FONT_SIZE) { - return DEFAULT_FONT_SIZE; - } - return size; -} - -export function nextBibleReaderFontSizeUp(current: number): number { - return clampBibleReaderFontSize(current + FONT_SIZE_STEP); -} - -export function nextBibleReaderFontSizeDown(current: number): number { - return clampBibleReaderFontSize(current - FONT_SIZE_STEP); -} - -export function changeBibleReaderLineSpacing(current: number): number { - switch (current) { - case BIBLE_READER_SPACING.DEFAULT: - return BIBLE_READER_SPACING.LG; - case BIBLE_READER_SPACING.LG: - return BIBLE_READER_SPACING.SM; - default: - return BIBLE_READER_SPACING.DEFAULT; - } -} - -function lineSpacingButtonGapClass(lineSpacing: number): string { - switch (lineSpacing) { - case BIBLE_READER_SPACING.SM: - return 'yv:gap-1'; - case BIBLE_READER_SPACING.LG: - return 'yv:gap-2'; - default: - return 'yv:gap-1.5'; - } -} - -/** - * Builds the three handler props for {@link BibleThemeSettingsContent} from host-owned font state. - * Use this on the same side as `setFontSize` / `setFontFamily` (e.g. React Native before passing - * **top-level** props into a `BibleThemeSettingsContent` Expo DOM wrapper). Expo allows functions as - * top-level DOM props; do not nest these inside a {@link BibleThemeSettingsSnapshot}. - */ -export function createBibleThemeSettingsContentHandlers(options: { - getFontSize: () => number; - getFontFamily: () => FontFamily; - setFontSize: (size: number) => void; - setFontFamily: (fontFamily: FontFamily) => void; - getLineSpacing: () => number; - setLineSpacing: (size: number) => void; -}): Pick< - BibleThemeSettingsContentProps, - 'onFontIncreased' | 'onFontDecreased' | 'onFontSelected' | 'onChangeLineSpacing' -> { - return { - onFontIncreased: () => { - options.setFontSize(nextBibleReaderFontSizeUp(options.getFontSize())); - }, - onFontDecreased: () => { - options.setFontSize(nextBibleReaderFontSizeDown(options.getFontSize())); - }, - onFontSelected: (fontFamily) => { - options.setFontFamily(fontFamily); - }, - onChangeLineSpacing: () => { - options.setLineSpacing(changeBibleReaderLineSpacing(options.getLineSpacing())); - }, - }; +// Non-scrolling focus requests apply only to the chapter/version already displayed. +function canApplyNavigationRequest( + target: BibleReaderNavigationRequest, + versionId: number, + book: string, + chapter: string, +): boolean { + return ( + target.scrollsToVerse || + (target.versionId === versionId && target.book === book && target.chapter === chapter) + ); } function Root({ @@ -476,10 +246,10 @@ function Root({ defaultVersionId = DEFAULT_LICENSE_FREE_BIBLE_VERSION, onVersionChange, fontSize: fontSizeProp, - defaultFontSize = DEFAULT_FONT_SIZE, + defaultFontSize, onFontSizeChange, fontFamily: fontFamilyProp, - defaultFontFamily = UNTITLED_SERIF_FONT, + defaultFontFamily, onFontFamilyChange, lineSpacing: lineSpacingProp, defaultLineSpacing, @@ -518,10 +288,12 @@ function Root({ const target = navigation.peek(); if ( target && - !target.scrollsToVerse && - (target.versionId !== (controlledVersionId ?? defaultVersionId) || - target.book !== (controlledBook ?? defaultBook) || - target.chapter !== (controlledChapter ?? defaultChapter)) + !canApplyNavigationRequest( + target, + controlledVersionId ?? defaultVersionId, + controlledBook ?? defaultBook, + controlledChapter ?? defaultChapter, + ) ) return null; return target; @@ -551,120 +323,25 @@ function Root({ const chapter = controlledChapter ?? initialNavigation?.chapter ?? currentChapter; const versionId = controlledVersionId ?? initialNavigation?.versionId ?? currentVersionId; - const validatedDefaultFontSize = - defaultFontSize > MAX_FONT_SIZE || defaultFontSize < MIN_FONT_SIZE - ? DEFAULT_FONT_SIZE - : defaultFontSize; - - const isFontSizeControlled = onFontSizeChange !== undefined; - const isFontFamilyControlled = onFontFamilyChange !== undefined; - const isLineSpacingControlled = onChangeLineSpacing !== undefined; - - const defaultPropFontSize = normalizeReaderFontSizeForInitialization( - fontSizeProp ?? validatedDefaultFontSize, - ); - - const [currentFontSize, setCurrentFontSize] = useControllableState({ - prop: isFontSizeControlled ? fontSizeProp : undefined, - defaultProp: defaultPropFontSize, - onChange: onFontSizeChange, - }); - - const defaultPropFontFamily = fontFamilyProp ?? defaultFontFamily; - - const [currentFontFamily, setCurrentFontFamily] = useControllableState({ - prop: isFontFamilyControlled ? fontFamilyProp : undefined, - defaultProp: defaultPropFontFamily, - onChange: onFontFamilyChange, - }); - - const resolvedDefaultLineSpacing = - defaultLineSpacing ?? lineHeight ?? BIBLE_READER_SPACING.DEFAULT; - - const [currentLineSpacing, setCurrentLineSpacing] = useControllableState({ - prop: isLineSpacingControlled ? lineSpacingProp : undefined, - defaultProp: resolvedDefaultLineSpacing, - onChange: onChangeLineSpacing, - }); - - const didHydrateThemeSettingsRef = useRef(false); - - useLayoutEffect(() => { - if (didHydrateThemeSettingsRef.current) return; - didHydrateThemeSettingsRef.current = true; - - if (!isFontSizeControlled) { - const savedFontSize = getLocalStorage()?.getItem('youversion-platform:reader:font-size'); - if (savedFontSize) { - const parsed = parseInt(savedFontSize); - if (parsed >= MIN_FONT_SIZE && parsed <= MAX_FONT_SIZE) { - setCurrentFontSize(parsed); - } - } - } - - if (!isFontFamilyControlled) { - const savedFontFamily = getLocalStorage()?.getItem('youversion-platform:reader:font-family'); - if (savedFontFamily) { - // Readers who picked serif before Untitled Serif shipped stored the old - // stack; map it forward so the picker still shows serif as active. - // Deliberately not full validation — `FontFamily` is open on purpose, so - // a host-supplied `defaultFontFamily="Georgia"` must still round-trip. - setCurrentFontFamily( - savedFontFamily === SOURCE_SERIF_FONT ? UNTITLED_SERIF_FONT : savedFontFamily, - ); - } - } - - if (!isLineSpacingControlled) { - const savedLineSpacing = getLocalStorage()?.getItem( - 'youversion-platform:reader:line-spacing', - ); - if (savedLineSpacing) { - const parsed = parseFloat(savedLineSpacing); - if (Object.values(BIBLE_READER_SPACING).some((spacing) => spacing === parsed)) { - setCurrentLineSpacing(parsed); - } - } - } - }, [ - isFontFamilyControlled, - isFontSizeControlled, - setCurrentFontFamily, + const { + currentFontSize, setCurrentFontSize, - isLineSpacingControlled, + currentFontFamily, + setCurrentFontFamily, + currentLineSpacing, setCurrentLineSpacing, - ]); - - useEffect(() => { - if (!isFontSizeControlled) { - setStorageItem( - getLocalStorage(), - 'youversion-platform:reader:font-size', - currentFontSize.toString(), - ); - } - }, [currentFontSize, isFontSizeControlled]); - - useEffect(() => { - if (!isFontFamilyControlled) { - setStorageItem( - getLocalStorage(), - 'youversion-platform:reader:font-family', - currentFontFamily, - ); - } - }, [currentFontFamily, isFontFamilyControlled]); - - useEffect(() => { - if (!isLineSpacingControlled) { - setStorageItem( - getLocalStorage(), - 'youversion-platform:reader:line-spacing', - currentLineSpacing.toString(), - ); - } - }, [currentLineSpacing, isLineSpacingControlled]); + } = useBibleReaderSettings({ + fontSize: fontSizeProp, + defaultFontSize, + onFontSizeChange, + fontFamily: fontFamilyProp, + defaultFontFamily, + onFontFamilyChange, + lineSpacing: lineSpacingProp, + defaultLineSpacing, + onChangeLineSpacing, + lineHeight, + }); const providerTheme = useTheme(); const theme = background || providerTheme; @@ -694,11 +371,7 @@ function Root({ const target = navigation.consume(); if (target === null) return; setInitialNavigation(null); - if ( - !target.scrollsToVerse && - (target.versionId !== versionId || target.book !== book || target.chapter !== chapter) - ) - return; + if (!canApplyNavigationRequest(target, versionId, book, chapter)) return; verseFocusSeqRef.current += 1; setVersionId(target.versionId); setBook(target.book); @@ -1397,497 +1070,5 @@ function Content() { ); } -function UserMenu() { - const { t } = useTranslation(undefined, { i18n }); - const { auth, signIn, signOut, userInfo } = useYVAuth(); - const yvContext = useContext(YouVersionContext); - const { onSignInPress, onSignOutPress } = useBibleReaderContext(); - - // Prefer host-supplied native actions (e.g. the Expo DOM wrapper bridges these to - // native PKCE sign-in). Fall back to the Web SDK's own auth for pure-web usage. - const handleSignIn = () => { - if (onSignInPress) { - onSignInPress(); - } else { - void signIn({ scopes: ['profile'] }); - } - }; - const handleSignOut = () => { - if (onSignOutPress) { - onSignOutPress(); - } else { - signOut(); - } - }; - - return ( - - - {auth.isAuthenticated ? ( - - ) : ( - - )} - - - - - {auth.isAuthenticated ? ( - - ) : ( - - )} - - - - ); -} - -const INTER_FONT_NAME = 'Inter'; -const UNTITLED_SERIF_FONT_NAME = 'Untitled Serif'; - -export function BibleThemeSettingsContent(props: BibleThemeSettingsContentProps): ReactElement { - return ( - - - - ); -} - -function BibleThemeSettingsBody({ - theme, - fontSize, - fontFamily, - lineSpacing, - onFontSelected, - onFontIncreased, - onFontDecreased, - onChangeLineSpacing, -}: BibleThemeSettingsContentProps): ReactElement { - const { t } = useTranslation(undefined, { i18n }); - const interfaceDirection = useInterfaceDirection(); - return ( - <> - -
-
-
- - -
- -
- -
- - -
-
- - ); -} - -export type BibleReaderToolbarProps = { - border?: 'top' | 'bottom'; - onOpenBibleThemeSettings?: (snapshot: BibleThemeSettingsSnapshot) => void; - /** - * Whether the toolbar renders the built-in search control. - * `'control'` (default) | `'none'`. Mirrors `RootProps.verseActions`. - */ - search?: 'control' | 'none'; -}; - -function Toolbar({ - border = 'top', - onOpenBibleThemeSettings, - search = 'control', -}: BibleReaderToolbarProps) { - const { t } = useTranslation(undefined, { i18n }); - const interfaceDirection = useInterfaceDirection(); - const { - book, - chapter, - versionId, - setBook, - setChapter, - setVersionId, - booksData, - booksLoading, - currentFontFamily, - setCurrentFontFamily, - currentFontSize, - setCurrentFontSize, - currentLineSpacing, - setCurrentLineSpacing, - background, - onChapterPickerPress, - onVersionPickerPress, - languageId, - defaultLanguageId, - onLanguageChange, - } = useBibleReaderContext(); - const yvContext = useContext(YouVersionContext); - const themesSettingsValuesRef = useRef({ - fontSize: currentFontSize, - fontFamily: currentFontFamily, - lineSpacing: currentLineSpacing, - }); - - themesSettingsValuesRef.current = { - fontSize: currentFontSize, - fontFamily: currentFontFamily, - lineSpacing: currentLineSpacing, - }; - - const applyThemeSettings = ( - themeSettings: BibleThemeSettingsValues, - ): BibleThemeSettingsValues => { - const nextThemeSettings = { - fontSize: clampBibleReaderFontSize(themeSettings.fontSize), - fontFamily: themeSettings.fontFamily, - lineSpacing: themeSettings.lineSpacing, - }; - - themesSettingsValuesRef.current = nextThemeSettings; - setCurrentFontSize(nextThemeSettings.fontSize); - setCurrentFontFamily(nextThemeSettings.fontFamily); - setCurrentLineSpacing(nextThemeSettings.lineSpacing); - - return nextThemeSettings; - }; - - const handleFontIncreased = (): BibleThemeSettingsValues => { - const settings = themesSettingsValuesRef.current; - return applyThemeSettings({ - ...settings, - fontSize: nextBibleReaderFontSizeUp(settings.fontSize), - }); - }; - - const handleFontDecreased = (): BibleThemeSettingsValues => { - const settings = themesSettingsValuesRef.current; - return applyThemeSettings({ - ...settings, - fontSize: nextBibleReaderFontSizeDown(settings.fontSize), - }); - }; - - const handleFontSelected = (fontFamily: FontFamily): BibleThemeSettingsValues => { - return applyThemeSettings({ - ...themesSettingsValuesRef.current, - fontFamily, - }); - }; - - const handleLineSpacingChange = (): BibleThemeSettingsValues => { - const settings = themesSettingsValuesRef.current; - return applyThemeSettings({ - ...settings, - lineSpacing: changeBibleReaderLineSpacing(settings.lineSpacing), - }); - }; - - const buildBibleThemeSettingsSnapshot = (): BibleThemeSettingsSnapshot => ({ - ...themesSettingsValuesRef.current, - minFontSize: MIN_FONT_SIZE, - maxFontSize: MAX_FONT_SIZE, - }); - - const prevResult = getAdjacentChapter(booksData, book, chapter, 'previous'); - const nextResult = getAdjacentChapter(booksData, book, chapter, 'next'); - const canNavigatePrevious = !booksLoading && prevResult !== null; - const canNavigateNext = !booksLoading && nextResult !== null; - const showSearch = search !== 'none'; - - return ( -
-
- {yvContext?.authEnabled && } - - - - - {({ chapterLabel, currentBook, loading }) => ( -
- - - - - -
- )} -
-
-
- - - - - {({ version, loading }) => ( - - )} - - - - - - {showSearch ? : null} - - {onOpenBibleThemeSettings ? ( - - ) : ( - - - - - - - - - - - - )} -
-
- ); -} - export const BibleReader = Object.assign({}, { Root, Content, Toolbar }); export type BibleReaderRootProps = RootProps; diff --git a/packages/ui/src/components/bible-reader.types.ts b/packages/ui/src/components/bible-reader.types.ts new file mode 100644 index 000000000..fc9f0a18a --- /dev/null +++ b/packages/ui/src/components/bible-reader.types.ts @@ -0,0 +1,100 @@ +import type { FontFamily } from '@/lib/verse-html-utils'; + +/** Reader typography props shared by the public root and its settings hook. */ +export type BibleReaderSettingsProps = { + fontSize?: number; + defaultFontSize?: number; + onFontSizeChange?: (fontSize: number) => void; + fontFamily?: FontFamily; + defaultFontFamily?: FontFamily; + onFontFamilyChange?: (fontFamily: FontFamily) => void; + lineSpacing?: number; + defaultLineSpacing?: number; + onChangeLineSpacing?: (size: number) => void; + /** + * @deprecated Use `defaultLineSpacing` (uncontrolled) or `lineSpacing` + + * `onChangeLineSpacing` (controlled) instead. When provided, this is used as + * the initial line spacing. Will be removed in the next major version. + */ + lineHeight?: number; +}; + +/** + * Serializable payload describing the reader's current verse selection. + * Bridge-safe primitives only, so React Native / Expo DOM hosts can forward it + * across the native bridge. `passageIds` is deliberately redundant with + * `book`/`chapter`/`verses` (always per-verse, never ranges): native hosts feed + * the API without USFM string-building; analytics reads `verses` without USFM + * parsing. + */ +export type BibleReaderVerseSelection = { + /** Matches `Highlight.version_id`. */ + versionId: number; + /** USFM book code, e.g. `'JHN'`. */ + book: string; + /** Chapter id, e.g. `'3'`. */ + chapter: string; + /** Selected verse numbers, ascending and de-duplicated. `[]` on clear. */ + verses: number[]; + /** Per-verse USFM ids, e.g. `['JHN.3.16', 'JHN.3.17']`. Never ranges. */ + passageIds: string[]; + /** + * Localized display reference **without** the version abbreviation, e.g. + * `Hebrews 11:4`. For a host that renders its own verse-action UI (see + * `BibleReaderRootProps.verseActions`) this is the label to show; the USFM `book` + * code above is not human-readable. + * + * Falls back to the USFM book code (`HEB 11:4`) until `useBooks` resolves the + * book title; when it resolves while the selection is still live, the reader + * re-emits that selection with the localized reference. `''` on clear. + * + * Deliberately different from `shareData.reference`, which keeps the version + * abbreviation (`Hebrews 11:4 BSB`) because copied text needs it. Do not + * "fix" one to match the other. + */ + reference: string; + /** + * The same payload the popover's Copy / Share buttons produce, so a host + * owning the verse-action UI can run copy/share without a popover press. + * `null` on clear (and if the reader's DOM is not mounted). + */ + shareData: BibleReaderShareData | null; +}; + +/** + * Serializable payload handed to `onHighlightApply` / `onHighlightRemove` in + * controlled mode. An intent is a request, not a fact: the reader paints + * nothing until the host round-trips an updated `highlights` prop. + * + * `reference` / `shareData` are deliberately omitted: an intent is addressed to + * the data layer, which needs identity and colour only. + */ +export type BibleReaderHighlightIntent = Omit< + BibleReaderVerseSelection, + 'reference' | 'shareData' +> & { + /** + * 6-character lowercase hex, no `#`. For `onHighlightRemove`, the color + * being cleared. + */ + color: string; +}; + +/** + * Serializable payload handed to the `onCopy` / `onShare` overrides. Mirrors + * `VerseOfTheDayShareData` so React Native / Expo DOM hosts can forward verse + * selections across the native bridge. + */ +export type BibleReaderShareData = { + /** Full body: curly-quoted verse text, a blank line, then the reference. */ + text: string; + /** Reference line only, e.g. `John 1:1-3 NIV`. */ + reference: string; + /** Verse text only (no reference line), gaps joined with ` ... `. */ + verseText: string; + /** Selected verse numbers, ascending and de-duplicated. */ + verses: number[]; + book: string; + chapter: string; + versionId: number; +}; diff --git a/packages/ui/src/components/bible-theme-settings.tsx b/packages/ui/src/components/bible-theme-settings.tsx new file mode 100644 index 000000000..eb7676b21 --- /dev/null +++ b/packages/ui/src/components/bible-theme-settings.tsx @@ -0,0 +1,161 @@ +'use client'; + +import type { ReactElement } from 'react'; +import { useTranslation } from 'react-i18next'; +import i18n from '@/i18n'; +import { useInterfaceDirection } from '@/lib/direction'; +import { ShadowIsolationBoundary } from '@/lib/shadow-isolation'; +import { cn } from '@/lib/utils'; +import { INTER_FONT, UNTITLED_SERIF_FONT } from '@/lib/verse-html-utils'; +import { YvComponentStyles } from '@/lib/yv-styles-components'; +import { Button } from './ui/button'; +import { + BIBLE_READER_FONT, + BIBLE_READER_SPACING, + type BibleThemeSettingsContentProps, +} from './bible-reader-settings'; + +const MIN_FONT_SIZE = BIBLE_READER_FONT.MIN; +const MAX_FONT_SIZE = BIBLE_READER_FONT.MAX; + +function lineSpacingButtonGapClass(lineSpacing: number): string { + switch (lineSpacing) { + case BIBLE_READER_SPACING.SM: + return 'yv:gap-1'; + case BIBLE_READER_SPACING.LG: + return 'yv:gap-2'; + default: + return 'yv:gap-1.5'; + } +} + +const INTER_FONT_NAME = 'Inter'; +const UNTITLED_SERIF_FONT_NAME = 'Untitled Serif'; + +export function BibleThemeSettingsContent(props: BibleThemeSettingsContentProps): ReactElement { + return ( + + + + ); +} + +function BibleThemeSettingsBody({ + theme, + fontSize, + fontFamily, + lineSpacing, + onFontSelected, + onFontIncreased, + onFontDecreased, + onChangeLineSpacing, +}: BibleThemeSettingsContentProps): ReactElement { + const { t } = useTranslation(undefined, { i18n }); + const interfaceDirection = useInterfaceDirection(); + return ( + <> + +
+
+
+ + +
+ +
+ +
+ + +
+
+ + ); +} diff --git a/packages/ui/src/components/use-bible-reader-highlights.ts b/packages/ui/src/components/use-bible-reader-highlights.ts index d0aabfb10..0c678287d 100644 --- a/packages/ui/src/components/use-bible-reader-highlights.ts +++ b/packages/ui/src/components/use-bible-reader-highlights.ts @@ -4,6 +4,7 @@ import { isHighlightsLive } from '@/lib/feature-flags'; import { deriveHighlightedVerses } from '@/lib/highlight-projection'; import { isPaletteHighlightColor, normalizeHighlightHex } from '@/lib/highlight-colors'; import type { Highlight } from '@youversion/platform-core'; +import type { BibleReaderHighlightIntent } from './bible-reader.types'; import { bibleReaderHighlightsMachine, scopesEqual, @@ -20,19 +21,7 @@ import { import { useActorRef, useSelector } from '@xstate/react'; import { useContext, useEffect, useMemo, useRef } from 'react'; -/** - * Bridge-safe highlight intent emitted in controlled mode. Structurally - * identical to `BibleReaderHighlightIntent` on `BibleReader` — kept local so - * this adapter does not import from the compound component. - */ -export type BibleReaderHighlightIntentPayload = { - versionId: number; - book: string; - chapter: string; - verses: number[]; - passageIds: string[]; - color: string; -}; +export type { BibleReaderHighlightIntent as BibleReaderHighlightIntentPayload } from './bible-reader.types'; /** * Host-owned highlight slice (YPE-3705). When present, the adapter is fully @@ -41,8 +30,8 @@ export type BibleReaderHighlightIntentPayload = { */ export type ControlledHighlightsInput = { highlights: readonly Highlight[]; - onApply?: (intent: BibleReaderHighlightIntentPayload) => void; - onRemove?: (intent: BibleReaderHighlightIntentPayload) => void; + onApply?: (intent: BibleReaderHighlightIntent) => void; + onRemove?: (intent: BibleReaderHighlightIntent) => void; }; export type UseBibleReaderHighlightsOptions = { @@ -140,7 +129,7 @@ function buildHighlightIntent( chapter: string, color: string, verses: number[], -): BibleReaderHighlightIntentPayload { +): BibleReaderHighlightIntent { const sorted = [...new Set(verses)].filter((verse) => verse > 0).sort((a, b) => a - b); return { versionId, diff --git a/packages/ui/src/components/use-bible-reader-settings.ts b/packages/ui/src/components/use-bible-reader-settings.ts new file mode 100644 index 000000000..7f229203c --- /dev/null +++ b/packages/ui/src/components/use-bible-reader-settings.ts @@ -0,0 +1,151 @@ +'use client'; + +import { useEffect, useLayoutEffect, useRef, type Dispatch, type SetStateAction } from 'react'; +import { useControllableState } from '@radix-ui/react-use-controllable-state'; +import { getLocalStorage, setStorageItem } from '@youversion/platform-core'; +import { SOURCE_SERIF_FONT, UNTITLED_SERIF_FONT, type FontFamily } from '@/lib/verse-html-utils'; +import { + BIBLE_READER_FONT, + BIBLE_READER_SPACING, + normalizeReaderFontSizeForInitialization, +} from './bible-reader-settings'; +import { READER_STORAGE_KEYS } from './bible-reader-storage'; +import type { BibleReaderSettingsProps } from './bible-reader.types'; + +type BibleReaderSettings = { + currentFontSize: number; + setCurrentFontSize: Dispatch>; + currentFontFamily: FontFamily; + setCurrentFontFamily: Dispatch>; + currentLineSpacing: number; + setCurrentLineSpacing: Dispatch>; +}; + +/** + * Initializes and persists reader typography. An on-change callback opts a setting + * into host control; pass its value prop to keep Radix state controlled. Saved + * values hydrate once in a layout effect before paint, and only uncontrolled + * settings are persisted. + * @internal + */ +export function useBibleReaderSettings({ + fontSize: fontSizeProp, + defaultFontSize = BIBLE_READER_FONT.DEFAULT, + onFontSizeChange, + fontFamily: fontFamilyProp, + defaultFontFamily = UNTITLED_SERIF_FONT, + onFontFamilyChange, + lineSpacing: lineSpacingProp, + defaultLineSpacing, + onChangeLineSpacing, + lineHeight, +}: BibleReaderSettingsProps): BibleReaderSettings { + const isFontSizeControlled = onFontSizeChange !== undefined; + const isFontFamilyControlled = onFontFamilyChange !== undefined; + const isLineSpacingControlled = onChangeLineSpacing !== undefined; + + const defaultPropFontSize = normalizeReaderFontSizeForInitialization( + fontSizeProp ?? defaultFontSize, + ); + + const [currentFontSize, setCurrentFontSize] = useControllableState({ + prop: isFontSizeControlled ? fontSizeProp : undefined, + defaultProp: defaultPropFontSize, + onChange: onFontSizeChange, + }); + + const defaultPropFontFamily = fontFamilyProp ?? defaultFontFamily; + + const [currentFontFamily, setCurrentFontFamily] = useControllableState({ + prop: isFontFamilyControlled ? fontFamilyProp : undefined, + defaultProp: defaultPropFontFamily, + onChange: onFontFamilyChange, + }); + + const resolvedDefaultLineSpacing = + defaultLineSpacing ?? lineHeight ?? BIBLE_READER_SPACING.DEFAULT; + + const [currentLineSpacing, setCurrentLineSpacing] = useControllableState({ + prop: isLineSpacingControlled ? lineSpacingProp : undefined, + defaultProp: resolvedDefaultLineSpacing, + onChange: onChangeLineSpacing, + }); + + const didHydrateThemeSettingsRef = useRef(false); + + useLayoutEffect(() => { + if (didHydrateThemeSettingsRef.current) return; + didHydrateThemeSettingsRef.current = true; + + if (!isFontSizeControlled) { + const savedFontSize = getLocalStorage()?.getItem(READER_STORAGE_KEYS.fontSize); + if (savedFontSize) { + const parsed = parseInt(savedFontSize); + if (parsed >= BIBLE_READER_FONT.MIN && parsed <= BIBLE_READER_FONT.MAX) { + setCurrentFontSize(parsed); + } + } + } + + if (!isFontFamilyControlled) { + const savedFontFamily = getLocalStorage()?.getItem(READER_STORAGE_KEYS.fontFamily); + if (savedFontFamily) { + // Readers who picked serif before Untitled Serif shipped stored the old + // stack; map it forward so the picker still shows serif as active. + // Deliberately not full validation — `FontFamily` is open on purpose, so + // a host-supplied `defaultFontFamily="Georgia"` must still round-trip. + setCurrentFontFamily( + savedFontFamily === SOURCE_SERIF_FONT ? UNTITLED_SERIF_FONT : savedFontFamily, + ); + } + } + + if (!isLineSpacingControlled) { + const savedLineSpacing = getLocalStorage()?.getItem(READER_STORAGE_KEYS.lineSpacing); + if (savedLineSpacing) { + const parsed = parseFloat(savedLineSpacing); + if (Object.values(BIBLE_READER_SPACING).some((spacing) => spacing === parsed)) { + setCurrentLineSpacing(parsed); + } + } + } + }, [ + isFontFamilyControlled, + isFontSizeControlled, + setCurrentFontFamily, + setCurrentFontSize, + isLineSpacingControlled, + setCurrentLineSpacing, + ]); + + useEffect(() => { + if (!isFontSizeControlled) { + setStorageItem(getLocalStorage(), READER_STORAGE_KEYS.fontSize, currentFontSize.toString()); + } + }, [currentFontSize, isFontSizeControlled]); + + useEffect(() => { + if (!isFontFamilyControlled) { + setStorageItem(getLocalStorage(), READER_STORAGE_KEYS.fontFamily, currentFontFamily); + } + }, [currentFontFamily, isFontFamilyControlled]); + + useEffect(() => { + if (!isLineSpacingControlled) { + setStorageItem( + getLocalStorage(), + READER_STORAGE_KEYS.lineSpacing, + currentLineSpacing.toString(), + ); + } + }, [currentLineSpacing, isLineSpacingControlled]); + + return { + currentFontSize, + setCurrentFontSize, + currentFontFamily, + setCurrentFontFamily, + currentLineSpacing, + setCurrentLineSpacing, + }; +} From ab1a56a69726621ac56afbbcccd3b7da588d0363 Mon Sep 17 00:00:00 2001 From: Cameron Pak Date: Tue, 24 Nov 2026 13:26:50 -0600 Subject: [PATCH 04/75] feat(ui): re-export passage and versions hooks (#500) * feat(ui): re-export passage and versions hooks Amp-Thread-ID: https://ampcode.com/threads/T-01a20e73-4446-71f0-950a-3054df5492c7 * chore(ci): remove packed UI consumer check * docs(ui): clarify shared provider import guidance Amp-Thread-ID: https://ampcode.com/threads/T-01a20e73-4446-71f0-950a-3054df5492c7 * docs: address hook re-export review nits Amp-Thread-ID: https://ampcode.com/threads/T-01a20e73-4446-71f0-950a-3054df5492c7 --------- Co-authored-by: Amp --- .changeset/ype-6769-ui-passage-versions.md | 5 +++++ .size-limit.js | 7 +++++++ CONTRIBUTING.md | 2 +- packages/hooks/src/usePassage.ts | 5 +++++ packages/hooks/src/useVersions.ts | 7 +++++++ packages/ui/README.md | 20 +++++++++++++++++++- packages/ui/src/index.ts | 6 ++++++ 7 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 .changeset/ype-6769-ui-passage-versions.md diff --git a/.changeset/ype-6769-ui-passage-versions.md b/.changeset/ype-6769-ui-passage-versions.md new file mode 100644 index 000000000..9ea2e3bc7 --- /dev/null +++ b/.changeset/ype-6769-ui-passage-versions.md @@ -0,0 +1,5 @@ +--- +'@youversion/platform-react-ui': minor +--- + +Re-exported `usePassage`, `useVersions`, and their public option and result types from `@youversion/platform-react-ui`. Apps can use these hooks and UI components under one `YouVersionProvider` without installing the hooks package directly. diff --git a/.size-limit.js b/.size-limit.js index 41e84e147..cfec72eeb 100644 --- a/.size-limit.js +++ b/.size-limit.js @@ -63,6 +63,13 @@ export default [ path: 'packages/ui/dist/index.js', ignore: ['react', 'react-dom', 'react/jsx-runtime', '@tanstack/react-query'], }, + { + name: 'ui / usePassage only', + path: 'packages/ui/dist/index.js', + import: '{ usePassage }', + limit: '13.8 KB', + ignore: ['react', 'react-dom', 'react/jsx-runtime', '@tanstack/react-query', 'jsdom'], + }, { name: 'ui / tailwind.css', path: 'packages/ui/dist/tailwind.css', diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3a2a4d851..96eba2847 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -138,7 +138,7 @@ Bundle size budgets and tree-shaking verification require a full build first — | `pnpm size:why` | Alias for `pnpm size:visualize` (size-limit `--why` is unavailable with `preset-small-lib`) | | `pnpm check:tree-shaking` | Verify single-symbol consumer bundles exclude unused-export sentinels; CI asserts package.json `sideEffects` | -**Export-size acceptance criteria:** `.size-limit.js` measures representative named imports (`ApiClient`, `useChapter`, `YouVersionProvider`). The Provider and full-barrel UI entries are measurement-only because they include all bundled translations; core, hooks, Separator, and CSS entries enforce size budgets. Per-export attribution is `pnpm size:visualize` plus [esbuild.github.io/analyze](https://esbuild.github.io/analyze/). +**Export-size acceptance criteria:** `.size-limit.js` measures representative named imports (`ApiClient`, `useChapter`, `YouVersionProvider`, `usePassage`). The Provider and full-barrel UI entries are measurement-only because they include all bundled translations; core, hooks, Separator, usePassage, and CSS entries enforce size budgets. The `ui / usePassage only` entry has a 13.8 KB limit. Per-export attribution is `pnpm size:visualize` plus [esbuild.github.io/analyze](https://esbuild.github.io/analyze/). **UI tree-shaking:** `check:tree-shaking` covers `@youversion/platform-react-ui`. A Provider-only import must drop `BibleReader` and both pickers, and must still contain SDK style markers. That win comes from listing every public component as a tsup entry, not from `splitting: true` alone. `pnpm --filter @youversion/platform-react-ui check:entries` fails if a new barrel export is missing from `tsup.config.ts`. Reader CSS is injected by `BibleTextView`, not `YouVersionProvider`. diff --git a/packages/hooks/src/usePassage.ts b/packages/hooks/src/usePassage.ts index 496e7ad36..11e265145 100644 --- a/packages/hooks/src/usePassage.ts +++ b/packages/hooks/src/usePassage.ts @@ -26,6 +26,11 @@ export type UsePassageProps = { export type UsePassageResult = UseNamedQueryResult<'passage', BiblePassage>; +/** + * Reads a Scripture passage by passage ID in the given Bible version, in HTML or plain text. + * @param props - Bible version, passage ID, content format, and query options. + * @returns The passage, loading state, error, and refetch function. + */ export function usePassage({ versionId, usfm, diff --git a/packages/hooks/src/useVersions.ts b/packages/hooks/src/useVersions.ts index f338d17f1..1996764db 100644 --- a/packages/hooks/src/useVersions.ts +++ b/packages/hooks/src/useVersions.ts @@ -22,6 +22,13 @@ export interface UseVersionsOptions extends UseApiDataOptions { export type UseVersionsResult = UseNamedQueryResult<'versions', Collection>; +/** + * Lists Bible versions by language range, with optional license, field, and paging filters. + * @param languageRanges - Language range or ranges to match; defaults to 'en'. + * @param licenseId - Optional license ID to filter by. + * @param options - Query options and optional field, paging, and availability filters. + * @returns The versions collection, loading state, error, and refetch function. + */ export function useVersions( languageRanges: string | string[] = 'en', licenseId?: string | number, diff --git a/packages/ui/README.md b/packages/ui/README.md index 453a85419..37194b746 100644 --- a/packages/ui/README.md +++ b/packages/ui/README.md @@ -15,7 +15,7 @@ Get your App Key at [platform.youversion.com](https://platform.youversion.com/) **Use other packages instead if you:** - ❌ Need low-level API access → Use [@youversion/platform-core](../core/README.md) -- ❌ Want custom UI → Use [@youversion/platform-react-hooks](../hooks/README.md) +- ❌ Need data hooks but no SDK components → Use [@youversion/platform-react-hooks](../hooks/README.md) ## Install @@ -66,6 +66,24 @@ By default the version picker offers Bible versions in every available language. Language tags are BCP 47 (`en`, `es`, `zh-Hans`). Version ids are YouVersion Bible version ids. An unusable id is refused everywhere — lists, picker, and `versionId` on reader/card/text/VOTD — and surfaces the existing forbidden error. Core-only hosts can set the same lists on `YouVersionPlatformConfiguration`. +### Data hooks + +Import `usePassage`, `useVersions`, and `YouVersionProvider` from this package using the same module format (ES modules or CommonJS). Call the hooks under the same provider as your UI components. You do not need to install the hooks package directly. + +If you also install `@youversion/platform-react-hooks` directly, pin it to the exact UI package version and avoid duplicate installations. Separate copies or module formats can create separate React contexts and cause a "context not found" error. + +```tsx +import { useVersions } from '@youversion/platform-react-ui'; + +function VersionList() { + const { versions, loading, error } = useVersions('en'); + if (loading) return

Loading Bible versions…

; + if (error) return

Bible versions are unavailable.

; + + return
    {versions?.data.map((version) =>
  • {version.title}
  • )}
; +} +``` + ## Styling All CSS is installed automatically when you wrap your app with diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index eae06e9bc..eeb1381a0 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -91,7 +91,13 @@ export { export { YouVersionProvider as BaseYouVersionProvider, + usePassage, + useVersions, useYVAuth, + type UsePassageProps, + type UsePassageResult, + type UseVersionsOptions, + type UseVersionsResult, type UseYVAuthReturn, } from '@youversion/platform-react-hooks'; From 38b654eaf70adc4cef812174721832c96b8e034e Mon Sep 17 00:00:00 2001 From: Austin Date: Tue, 24 Nov 2026 13:36:47 -0600 Subject: [PATCH 05/75] fix(ui): preserve focus at high zoom (#485) * fix(ui): preserve focus at high zoom * fix(ui): harden zoom focus coverage * refactor(ui): simplify zoom focus handling * test(ui): cover zoom focus behavior * test(ui): focus reader close before asserting * fix(ui): address zoom review findings * test(ui): compare pointer focus styles * test(ui): respect focus-visible heuristics * test(ui): use native focus traversal * fix(ui): scope focus preservation * fix(ui): preserve sign-in focus contrast * test(ui): await close focus transition * refactor(ui): centralize picker scroll geometry * fix(ui): keep picker focus visible in constrained panels * fix(ui): preserve the expanded book trigger in compact panels * test(ui): reach reader settings close with native keys * fix(ui): honor reduced motion in chapter reveal * fix(ui): address focus and scroll review feedback * fix(ui): reveal focused chapters in Firefox Keep focused book triggers fully visible within the built-in accordion on Linux Firefox. Wait for the settings dialog opening animation before asserting visibility in WebKit. * test(ui): query the current settings dialog while opening --- .changeset/calm-focus-at-zoom.md | 5 + ...hapter-picker.shadow-isolation.stories.tsx | 153 ++++++++++++++- .../components/bible-chapter-picker.test.tsx | 161 +++++++++++++++- .../src/components/bible-chapter-picker.tsx | 99 +++++++--- .../src/components/bible-reader-toolbar.tsx | 7 +- .../src/components/bible-reader.stories.tsx | 64 +++++++ .../bible-theme-settings.stories.tsx | 76 ++++++-- .../src/components/bible-theme-settings.tsx | 14 +- ...ersion-picker.shadow-isolation.stories.tsx | 179 +++++++++++++++++- .../bible-version-picker.stories.tsx | 4 + .../components/bible-version-picker/index.tsx | 2 +- .../bible-version-picker/version-list.tsx | 30 ++- ...ign-in-dialog.shadow-isolation.stories.tsx | 35 ++++ packages/ui/src/components/sign-in-dialog.tsx | 12 +- packages/ui/src/lib/reduced-motion.ts | 3 + packages/ui/src/lib/scroll-reveal.test.ts | 35 ++++ packages/ui/src/lib/scroll-reveal.ts | 24 +++ .../ui/src/lib/use-transient-verse-focus.ts | 5 +- 18 files changed, 839 insertions(+), 69 deletions(-) create mode 100644 .changeset/calm-focus-at-zoom.md create mode 100644 packages/ui/src/lib/reduced-motion.ts create mode 100644 packages/ui/src/lib/scroll-reveal.test.ts create mode 100644 packages/ui/src/lib/scroll-reveal.ts diff --git a/.changeset/calm-focus-at-zoom.md b/.changeset/calm-focus-at-zoom.md new file mode 100644 index 000000000..1db29af89 --- /dev/null +++ b/.changeset/calm-focus-at-zoom.md @@ -0,0 +1,5 @@ +--- +'@youversion/platform-react-ui': patch +--- + +Kept focused chapter and version rows visible and preserved control focus indicators at high browser zoom. Updated chapter expansion to honor reduced-motion preferences. diff --git a/packages/ui/src/components/bible-chapter-picker.shadow-isolation.stories.tsx b/packages/ui/src/components/bible-chapter-picker.shadow-isolation.stories.tsx index e6ac7afe9..0f45d912c 100644 --- a/packages/ui/src/components/bible-chapter-picker.shadow-isolation.stories.tsx +++ b/packages/ui/src/components/bible-chapter-picker.shadow-isolation.stories.tsx @@ -92,6 +92,18 @@ const FIXTURE_BOOKS: BibleBook[] = [ canon: 'old_testament', chapters: [{ id: '1', passage_id: '1KI.1', title: '1' }], }, + { + id: 'PSA', + title: 'Psalms', + full_title: 'Psalms', + abbreviation: 'Ps', + canon: 'old_testament', + chapters: Array.from({ length: 150 }, (_, index) => ({ + id: String(index + 1), + passage_id: `PSA.${index + 1}`, + title: String(index + 1), + })), + }, { id: 'MAT', title: 'Matthew', @@ -152,6 +164,27 @@ function AutomaticBibleChapterPicker(): React.ReactNode { ); } +function StandaloneBibleChapterPicker(): React.ReactNode { + return ( + undefined} + > +
+
+
+ +
+
+ + ); +} + const meta = { title: 'Components/BibleChapterPicker/Shadow isolation', component: AutomaticBibleChapterPicker, @@ -196,8 +229,13 @@ export const PublicRootJourney: Story = { }); const triggerStyle = getComputedStyle(trigger); const embeddedBorderRadius = triggerStyle.borderRadius; - await expect(triggerStyle.paddingBlockStart).toBe('8px'); - await expect(triggerStyle.paddingInlineStart).toBe('16px'); + const paddingUnit = trigger.ownerDocument.createElement('div'); + paddingUnit.style.blockSize = '1rem'; + root.append(paddingUnit); + const rem = Number.parseFloat(getComputedStyle(paddingUnit).blockSize); + paddingUnit.remove(); + await expect(Number.parseFloat(triggerStyle.paddingBlockStart)).toBeCloseTo(rem / 2); + await expect(Number.parseFloat(triggerStyle.paddingInlineStart)).toBeCloseTo(rem); await expect(embeddedBorderRadius).not.toBe('0px'); const hostileStyle = canvasElement.ownerDocument.createElement('style'); @@ -252,6 +290,9 @@ export const PublicRootJourney: Story = { const closeButton = panelQueries.getByRole('button', { name: 'Close' }); const genesisBook = panelQueries.getByRole('button', { name: /genesis/i }); const exodusBook = panelQueries.getByRole('button', { name: /exodus/i }); + const leviticusBook = panelQueries.getByRole('button', { name: /leviticus/i }); + const firstKingsBook = panelQueries.getByRole('button', { name: /1 kings/i }); + const psalmsBook = panelQueries.getByRole('button', { name: /psalms/i }); const bookList = await waitForElement( panel, '[data-slot="accordion"]', @@ -288,6 +329,13 @@ export const PublicRootJourney: Story = { await waitFor(async () => { await expect(root.activeElement).toBe(panel); }); + genesisBook.focus({ preventScroll: true }); + const focusedBookListScrollTop = bookList.scrollTop; + const focusedPanelScrollTop = panel.scrollTop; + await expect(root.activeElement).toBe(genesisBook); + await expect(bookList.scrollTop).toBe(focusedBookListScrollTop); + await expect(panel.scrollTop).toBe(focusedPanelScrollTop); + panel.focus({ preventScroll: true }); exitAnimationStyle.remove(); await userEvent.tab({ shift: true }); await expect(root.activeElement).toBe(initialSearch); @@ -295,9 +343,63 @@ export const PublicRootJourney: Story = { await expect(tabOrder.at(-2)).toBe(lastChapterButton); await expect(tabOrder.at(-1)).toBe(initialSearch); await expect(bookList.scrollHeight).toBeGreaterThan(bookList.clientHeight); + await expect(getComputedStyle(panel).overflowY).toBe('auto'); + panel.style.blockSize = '10rem'; + bookList.scrollTop = 0; + const clippedBookRect = firstKingsBook.getBoundingClientRect(); + const initialListRect = bookList.getBoundingClientRect(); + await expect(clippedBookRect.bottom).toBeGreaterThan(initialListRect.bottom); + const { userEvent: browserUserEvent } = await import('vitest/browser'); + const bookTriggers = Array.from( + panel.querySelectorAll('[data-slot="accordion-trigger"]'), + ); + genesisBook.focus(); + for (let index = 0; index < bookTriggers.indexOf(firstKingsBook); index += 1) { + await browserUserEvent.keyboard('{ArrowDown}'); + } + await waitFor(async () => { + await expect(root.activeElement).toBe(firstKingsBook); + const bookRect = firstKingsBook.getBoundingClientRect(); + const listRect = bookList.getBoundingClientRect(); + await expect(bookRect.top).toBeGreaterThanOrEqual(listRect.top - 1); + await expect(bookRect.bottom).toBeLessThanOrEqual(listRect.bottom + 1); + const style = getComputedStyle(firstKingsBook); + await expect(style.boxShadow).toContain('inset'); + await expect(style.boxShadow).toContain('0px 0px 0px 3px'); + await expect(style.getPropertyValue('--tw-ring-color').trim()).toBe( + style.getPropertyValue('--yv-ring').trim(), + ); + await expect(Number.parseFloat(style.paddingInlineStart)).toBeGreaterThanOrEqual(3); + await expect(Number.parseFloat(style.paddingInlineEnd)).toBeGreaterThanOrEqual(3); + }); + await browserUserEvent.keyboard('{ArrowDown}'); + await expect(root.activeElement).toBe(psalmsBook); + await browserUserEvent.keyboard('{Enter}'); + await waitFor(async () => await expect(psalmsBook).toHaveAttribute('aria-expanded', 'true')); + const expandedPsalms = psalmsBook.closest('[data-slot="accordion-item"]'); + if (!expandedPsalms) throw new Error('expanded Psalms item not rendered'); + const firstPsalmsChapter = within(expandedPsalms).getByRole('button', { name: '1' }); + await waitFor(async () => { + await expect(expandedPsalms.scrollHeight).toBeGreaterThan(bookList.clientHeight); + }); + await waitFor(async () => { + await expect(root.activeElement).toBe(psalmsBook); + if (!panel) throw new Error('chapter picker panel not rendered'); + const panelRect = panel.getBoundingClientRect(); + const listRect = bookList.getBoundingClientRect(); + await expect(psalmsBook.getBoundingClientRect().top).toBeGreaterThanOrEqual( + Math.max(panelRect.top, listRect.top) - 1, + ); + await expect(firstPsalmsChapter.getBoundingClientRect().bottom).toBeLessThanOrEqual( + Math.min(panelRect.bottom, listRect.bottom) + 1, + ); + }); + panel.style.blockSize = '24rem'; + await browserUserEvent.keyboard('{Enter}'); + await waitFor(async () => await expect(psalmsBook).toHaveAttribute('aria-expanded', 'false')); + panel.focus({ preventScroll: true }); await userEvent.tab(); await expect(root.activeElement).toBe(closeButton); - const { userEvent: browserUserEvent } = await import('vitest/browser'); const forwardTraversalKey = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) ? '{Alt>}{Tab}{/Alt}' : '{Tab}'; @@ -305,6 +407,8 @@ export const PublicRootJourney: Story = { await expect(root.activeElement).toBe(genesisBook); await browserUserEvent.keyboard(forwardTraversalKey); await expect(root.activeElement).toBe(exodusBook); + await browserUserEvent.keyboard(forwardTraversalKey); + await expect(root.activeElement).toBe(leviticusBook); await userEvent.click(closeButton); await waitFor(async () => { await expect(topLayer.querySelector('[data-slot="popover-content"]')).toBeNull(); @@ -343,6 +447,49 @@ export const PublicRootJourney: Story = { }, }; +export const StandaloneContentSupportsArrowNavigationInConsumerScroll: Story = { + render: () => ( + + + + ), + play: async ({ canvasElement }) => { + const root = await waitForShadowRoot(canvasElement); + const shell = await waitForElement( + root, + '[data-testid="standalone-chapter-panel"]', + 'standalone chapter panel not rendered', + ); + const host = shell.parentElement; + if (!host) throw new Error('standalone chapter host not rendered'); + const matthewBook = within(shell).getByRole('button', { name: /matthew/i }); + host.scrollTop = 0; + shell.scrollTop = 0; + const initialShellRect = shell.getBoundingClientRect(); + await expect(matthewBook.getBoundingClientRect().top).toBeGreaterThanOrEqual( + initialShellRect.bottom, + ); + + const { userEvent: browserUserEvent } = await import('vitest/browser'); + const bookTriggers = Array.from( + shell.querySelectorAll('[data-slot="accordion-trigger"]'), + ); + bookTriggers[0]!.focus(); + for (let index = 0; index < bookTriggers.indexOf(matthewBook); index += 1) { + await browserUserEvent.keyboard('{ArrowDown}'); + } + await waitFor(async () => { + await expect(root.activeElement).toBe(matthewBook); + await expect(shell.scrollTop).toBeGreaterThan(0); + const bookRect = matthewBook.getBoundingClientRect(); + const shellRect = shell.getBoundingClientRect(); + await expect(bookRect.top).toBeGreaterThanOrEqual(shellRect.top - 1); + await expect(bookRect.bottom).toBeLessThanOrEqual(shellRect.bottom + 1); + await expect(getComputedStyle(matthewBook).boxShadow).toContain('inset'); + }); + }, +}; + export const ExplicitLightThemeUnderDarkProvider: Story = { render: () => ( = {}) { ); } +function standaloneContent(onChapterPickerPress: () => void): ReactElement { + return ( + + + + + + + + + ); +} + +it('skips the scheduled reveal after focus moves to a host control', async () => { + vi.useFakeTimers(); + const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView'); + try { + render( + <> + + {standaloneContent(() => undefined)} + , + ); + findAccordionTrigger(/Exodus/i)?.focus(); + const hostControl = screen.getByRole('button', { name: 'Host control' }); + hostControl.focus(); + + await act(async () => { + await vi.runOnlyPendingTimersAsync(); + }); + + expect(hostControl).toHaveFocus(); + expect(scrollSpy).not.toHaveBeenCalled(); + } finally { + scrollSpy.mockRestore(); + vi.useRealTimers(); + } +}); + +it('keeps the focused chapter visible when a book reveal is pending', async () => { + vi.useFakeTimers(); + const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView'); + try { + render(standaloneContent(() => undefined)); + const chapter = screen.getByRole('button', { name: '2' }); + chapter.focus(); + + await act(async () => { + await vi.runOnlyPendingTimersAsync(); + }); + + expect(chapter).toHaveFocus(); + expect(scrollSpy).not.toHaveBeenCalled(); + } finally { + scrollSpy.mockRestore(); + vi.useRealTimers(); + } +}); + +it('does not scroll consumer ancestors again when only the callback identity changes', async () => { + vi.useFakeTimers(); + const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView'); + try { + const { rerender } = render(standaloneContent(() => undefined)); + await act(async () => { + await vi.runOnlyPendingTimersAsync(); + }); + expect(scrollSpy).toHaveBeenCalledTimes(1); + + rerender(standaloneContent(() => undefined)); + await act(async () => { + await vi.runOnlyPendingTimersAsync(); + }); + + expect(scrollSpy).toHaveBeenCalledTimes(1); + } finally { + scrollSpy.mockRestore(); + vi.useRealTimers(); + } +}); + +it('does not let focus in a sibling accordion suppress the current-book reveal', async () => { + const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView'); + try { + render( + <> +
+
+ +
+
+ {standaloneContent(() => undefined)} + , + ); + screen.getByRole('button', { name: 'Sibling accordion trigger' }).focus(); + + await waitFor(() => expect(scrollSpy).toHaveBeenCalledTimes(1)); + } finally { + scrollSpy.mockRestore(); + } +}); + +it.each([ + { prefersReduced: false, behavior: 'smooth' }, + { prefersReduced: true, behavior: 'auto' }, +])( + 'reveals the current book with $behavior scrolling based on motion preference', + async ({ prefersReduced, behavior }) => { + vi.useFakeTimers(); + const matchMedia = vi.fn(() => ({ matches: prefersReduced })); + vi.stubGlobal('matchMedia', matchMedia); + const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView'); + try { + render(standaloneContent(() => undefined)); + await act(async () => { + await vi.runOnlyPendingTimersAsync(); + }); + expect(matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)'); + expect(scrollSpy).toHaveBeenCalledExactlyOnceWith({ block: 'start', behavior }); + } finally { + scrollSpy.mockRestore(); + vi.unstubAllGlobals(); + vi.useRealTimers(); + } + }, +); + +it('cancels pending book reveals when the picker unmounts', async () => { + vi.useFakeTimers(); + const scheduleSpy = vi.spyOn(globalThis, 'setTimeout'); + const cancelSpy = vi.spyOn(globalThis, 'clearTimeout'); + const scrollSpy = vi.spyOn(Element.prototype, 'scrollIntoView'); + try { + const { unmount } = render(standaloneContent(() => undefined)); + scheduleSpy.mockClear(); + screen.getByRole('button', { name: 'Genesis 1' }).click(); + expect(scheduleSpy).toHaveBeenCalledTimes(1); + const revealTimer = scheduleSpy.mock.results[0]!.value; + unmount(); + expect(cancelSpy).toHaveBeenCalledWith(revealTimer); + await act(async () => { + await vi.runOnlyPendingTimersAsync(); + }); + expect(scrollSpy).not.toHaveBeenCalled(); + } finally { + scheduleSpy.mockRestore(); + cancelSpy.mockRestore(); + scrollSpy.mockRestore(); + vi.useRealTimers(); + } +}); + describe('BibleChapterPicker - onChapterPickerPress override', () => { beforeEach(() => { vi.clearAllMocks(); diff --git a/packages/ui/src/components/bible-chapter-picker.tsx b/packages/ui/src/components/bible-chapter-picker.tsx index b88a760c4..ae1339cfb 100644 --- a/packages/ui/src/components/bible-chapter-picker.tsx +++ b/packages/ui/src/components/bible-chapter-picker.tsx @@ -25,6 +25,9 @@ import { Popover, PopoverContent, PopoverTrigger } from './ui/popover'; import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from './ui/accordion'; import { InputGroup, InputGroupInput, InputGroupAddon } from './ui/input-group'; import { useInterfaceDirection } from '@/lib/direction'; +import { prefersReducedMotion } from '@/lib/reduced-motion'; +import { revealElementWithinScrollContainer } from '@/lib/scroll-reveal'; +import { cn } from '@/lib/utils'; import { ShadowIsolationBoundary } from '@/lib/shadow-isolation'; export interface BibleChapterPickerPressData { @@ -55,9 +58,17 @@ type BibleChapterPickerContextType = { setExpandedBook: (bookId: string) => void; filteredBooks: BibleBook[] | null; registerBookElement: (bookId: string, node: HTMLDivElement | null) => void; + markBookFocused: (button: HTMLButtonElement) => void; onChapterPickerPress?: (data: BibleChapterPickerPressData) => void; }; +function revealExpandedBook(element: HTMLElement): void { + element.scrollIntoView?.({ + block: 'start', + behavior: prefersReducedMotion(element.ownerDocument.defaultView) ? 'auto' : 'smooth', + }); +} + type TriggerElementProps = React.HTMLAttributes & { 'data-yv-sdk'?: boolean; 'data-yv-theme'?: string; @@ -141,6 +152,12 @@ function RootImplementation({ }, [books?.data, searchQuery]); const bookElementsRef = useRef>({}); + const bookFocusSequenceRef = useRef(0); + const usesConsumerScroll = Boolean(onChapterPickerPress); + const openRevealTimeout = useRef | undefined>(undefined); + + // Changing scroll ownership invalidates a reveal scheduled by the previous trigger. + useEffect(() => () => clearTimeout(openRevealTimeout.current), [usesConsumerScroll]); const registerBookElement = (bookId: string, node: HTMLDivElement | null) => { if (node) { @@ -150,39 +167,44 @@ function RootImplementation({ } }; - const scrollToCurrentBook = () => { - if (book) { - setExpandedBook(book); - setTimeout(() => { - const element = bookElementsRef.current[book]; - element?.scrollIntoView?.({ - behavior: 'smooth', - block: 'start', - }); + const shouldPreserveFocusedBook = useCallback((element: HTMLElement | undefined) => { + // SAFETY: A connected DOM element is rooted in either a Document or ShadowRoot. + const focusRoot = element?.getRootNode() as Document | ShadowRoot | undefined; + const activeElement = focusRoot?.activeElement; + const accordion = element?.closest('[data-slot="accordion"]'); + if (!accordion || !activeElement || !accordion.contains(activeElement)) return false; + const focusedBook = activeElement.closest('[data-slot="accordion-item"]'); + return Boolean( + focusedBook && + (focusedBook !== element || !activeElement.matches('[data-slot="accordion-trigger"]')), + ); + }, []); + + const scheduleBookReveal = useCallback( + (bookId: string) => { + const focusSequence = bookFocusSequenceRef.current; + return setTimeout(() => { + if (bookFocusSequenceRef.current !== focusSequence) return; + const element = bookElementsRef.current[bookId]; + if (!element || shouldPreserveFocusedBook(element)) return; + revealExpandedBook(element); }, 200); - } + }, + [shouldPreserveFocusedBook], + ); + + const scrollToCurrentBook = () => { + if (!book) return; + setExpandedBook(book); + clearTimeout(openRevealTimeout.current); + openRevealTimeout.current = scheduleBookReveal(book); }; - // When an accordion is expanded, scroll that book into view useEffect(() => { if (!expandedBook) return; - - const controller = new AbortController(); - const timeoutId = setTimeout(() => { - if (!controller.signal.aborted) { - const element = bookElementsRef.current[expandedBook]; - element?.scrollIntoView?.({ - behavior: 'smooth', - block: 'start', - }); - } - }, 200); - - return () => { - controller.abort(); - clearTimeout(timeoutId); - }; - }, [expandedBook]); + const timeout = scheduleBookReveal(expandedBook); + return () => clearTimeout(timeout); + }, [expandedBook, scheduleBookReveal]); const setIsPopoverOpen = (open: boolean) => { if (onChapterPickerPress) return; @@ -240,6 +262,13 @@ function RootImplementation({ setExpandedBook, filteredBooks, registerBookElement, + markBookFocused: (button) => { + bookFocusSequenceRef.current += 1; + if (usesConsumerScroll) return; + const list = button.closest('[data-slot="accordion"]'); + // Linux Firefox can focus a book while leaving part of its row clipped. + if (list) revealElementWithinScrollContainer(button, list); + }, onChapterPickerPress, }; @@ -257,6 +286,7 @@ function RootImplementation({ {/* data-yv-sdk for styles is needed because the popover gets rendered outside of the providers scope **/} { @@ -432,7 +464,11 @@ function Content({ onRequestClose, onSelect }: BibleChapterPickerContentProps) { data-yv-sdk data-yv-theme={background} dir={interfaceDirection} - className="yv:flex yv:h-full yv:min-h-0 yv:flex-col" + // Keep room for a book and the first chapter above search in the built-in picker. + className={cn( + 'yv:flex yv:h-full yv:flex-col', + onChapterPickerPress ? 'yv:min-h-0' : 'yv:[min-block-size:12.5rem]', + )} > registerBookElement(bookItem.id, node)} > - + markBookFocused(event.currentTarget)} + > {bookItem.title} diff --git a/packages/ui/src/components/bible-reader-toolbar.tsx b/packages/ui/src/components/bible-reader-toolbar.tsx index 44e4265cc..0d4825ac4 100644 --- a/packages/ui/src/components/bible-reader-toolbar.tsx +++ b/packages/ui/src/components/bible-reader-toolbar.tsx @@ -374,7 +374,12 @@ export function Toolbar({ - + ( + + + + ), + play: async ({ canvasElement }) => { + const { root, reader } = await getReaderStory(canvasElement); + const versionButton = await reader.findByRole('button', { + name: i18n.t('changeBibleVersionAriaLabel'), + }); + const settingsButton = reader.getByRole('button', { name: i18n.t('settingsAriaLabel') }); + versionButton.focus({ preventScroll: true }); + const forwardKey = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) + ? '{Alt>}{Tab}{/Alt}' + : '{Tab}'; + const nativeKeyAvailable = await verifyNativeBrowserKey(forwardKey, async () => { + await expect(root.activeElement).toBe(settingsButton); + await expect(settingsButton.matches(':focus-visible')).toBe(true); + }); + if (!nativeKeyAvailable) return; + await verifyNativeBrowserKey('{Enter}', async () => { + await waitFor(async () => { + const overlay = await getReaderOverlay(root); + await expect(overlay.getByRole('dialog')).toBeVisible(); + }); + }); + const settings = await getReaderOverlay(root); + const closeButton = await settings.findByRole('button', { name: i18n.t('close') }); + const dialog = closeButton.closest('[role="dialog"]'); + if (!dialog) throw new Error('reader settings dialog not rendered'); + dialog.focus({ preventScroll: true }); + await verifyNativeBrowserKey(forwardKey, async () => { + await expect(root.activeElement).toBe(closeButton); + }); + const focusedIndicator = await waitFor(async () => { + await expect(root.activeElement).toBe(closeButton); + await expect(closeButton.matches(':focus-visible')).toBe(true); + const style = getComputedStyle(closeButton); + await expect(style.boxShadow).toContain('inset'); + await expect(style.boxShadow).toContain('0px 0px 0px 3px'); + await expect(style.getPropertyValue('--tw-ring-color').trim()).toBe( + style.getPropertyValue('--yv-ring').trim(), + ); + return { boxShadow: style.boxShadow, outline: style.outline }; + }); + + await userEvent.click(settings.getByTestId('decrease-font-size')); + await waitFor(async () => { + const unfocusedStyle = getComputedStyle(closeButton); + await expect({ + boxShadow: unfocusedStyle.boxShadow, + outline: unfocusedStyle.outline, + }).not.toEqual(focusedIndicator); + }); + }, +}; + export const VerseSelectionReanchoringDismissalAndFocusRestoration: Story = { tags: ['integration', 'shadow-dom', 'cross-browser', 'shadow-fresh-process'], args: { diff --git a/packages/ui/src/components/bible-theme-settings.stories.tsx b/packages/ui/src/components/bible-theme-settings.stories.tsx index 85c64790d..04a1bc860 100644 --- a/packages/ui/src/components/bible-theme-settings.stories.tsx +++ b/packages/ui/src/components/bible-theme-settings.stories.tsx @@ -8,6 +8,7 @@ import { INTER_FONT, UNTITLED_SERIF_FONT, type FontFamily } from '../lib/verse-h import { BibleThemeSettingsContent } from './bible-reader'; import { Popover, PopoverContent, PopoverTrigger } from './ui/popover'; import { YvComponentStyles } from '../lib/yv-styles-components'; +import { verifyNativeBrowserKey } from '../test/storybook-dom'; function ConstrainedSettings(): React.ReactNode { const [boundary, setBoundary] = useState(null); @@ -101,6 +102,14 @@ const meta = { export default meta; type Story = StoryObj; +function focusStyle(element: HTMLElement) { + const style = getComputedStyle(element); + return { + boxShadow: style.boxShadow, + outline: style.outline, + }; +} + export const FontControlsRemainReachableInConstrainedSpace: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement); @@ -121,35 +130,78 @@ export const FontControlsRemainReachableInConstrainedSpace: Story = { void expect(controls).toHaveLength(5); const decreaseFontSizeButton = settings.getByTestId('decrease-font-size'); void expect(controls[0]).toBe(decreaseFontSizeButton); + const selectedFontButton = settings.getByRole('button', { name: `${i18n.t('font')} Inter` }); const serifButton = settings.getByRole('button', { name: `${i18n.t('font')} ${i18n.t('untitledSerifFontName')}`, }); void expect(controls[controls.length - 1]).toBe(serifButton); const closeButton = within(dialog).getByRole('button', { name: i18n.t('close') }); void expect(ownerDocument.activeElement).toBe(closeButton); - await userEvent.tab(); - void expect(settingsRoot.activeElement).toBe(decreaseFontSizeButton); + await userEvent.click(settingsScope); + const unfocusedStyles = new Map(controls.map((control) => [control, focusStyle(control)])); + await userEvent.click(decreaseFontSizeButton); + closeButton.focus(); + const forwardTraversalKey = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) + ? '{Alt>}{Tab}{/Alt}' + : '{Tab}'; + const nativeKeyAvailable = await verifyNativeBrowserKey(forwardTraversalKey, async () => { + void expect(settingsRoot.activeElement).toBe(decreaseFontSizeButton); + void expect(focusStyle(decreaseFontSizeButton)).not.toEqual( + unfocusedStyles.get(decreaseFontSizeButton), + ); + void expect(focusStyle(decreaseFontSizeButton).boxShadow).toContain('inset'); + }); + if (!nativeKeyAvailable) { + await userEvent.tab(); + void expect(settingsRoot.activeElement).toBe(decreaseFontSizeButton); + } await userEvent.keyboard('{Enter}'); - void expect(canvas.getByTestId('settings-boundary')).toHaveAttribute('data-font-size', '15'); + void expect(canvas.getByTestId('settings-boundary')).toHaveAttribute('data-font-size', '14'); let focusedControlReceivedTab = false; - decreaseFontSizeButton.addEventListener( - 'keydown', - (event) => { - if (event.key === 'Tab') focusedControlReceivedTab = true; - }, - { once: true }, - ); + const recordFocusedControlTab = (event: KeyboardEvent) => { + if (event.key === 'Tab') focusedControlReceivedTab = true; + }; + decreaseFontSizeButton.addEventListener('keydown', recordFocusedControlTab); for (const control of controls.slice(1)) { - await userEvent.tab(); - void expect(settingsRoot.activeElement).toBe(control); + if (nativeKeyAvailable) { + await verifyNativeBrowserKey(forwardTraversalKey, async () => { + void expect(settingsRoot.activeElement).toBe(control); + void expect(focusStyle(control)).not.toEqual(unfocusedStyles.get(control)); + await waitFor(async () => { + const style = getComputedStyle(control); + await expect(style.boxShadow).toContain('inset'); + await expect(style.boxShadow).toContain('0px 0px 0px 3px'); + if (control === selectedFontButton) { + await expect(style.getPropertyValue('--tw-ring-color').trim()).toBe( + style.getPropertyValue('--yv-primary-foreground').trim(), + ); + } + }); + }); + } else { + await userEvent.tab(); + void expect(settingsRoot.activeElement).toBe(control); + } } + decreaseFontSizeButton.removeEventListener('keydown', recordFocusedControlTab); void expect(focusedControlReceivedTab).toBe(true); await userEvent.keyboard('{Enter}'); void expect(canvas.getByTestId('settings-boundary')).toHaveAttribute( 'data-font-family', UNTITLED_SERIF_FONT, ); + if (nativeKeyAvailable) { + await waitFor(async () => { + await expect(settingsRoot.activeElement).toBe(serifButton); + const style = getComputedStyle(serifButton); + await expect(style.boxShadow).toContain('inset'); + await expect(style.boxShadow).toContain('0px 0px 0px 3px'); + await expect(style.getPropertyValue('--tw-ring-color').trim()).toBe( + style.getPropertyValue('--yv-primary-foreground').trim(), + ); + }); + } await userEvent.tab(); void expect(ownerDocument.activeElement).toBe(closeButton); for (const control of [...controls].reverse()) { diff --git a/packages/ui/src/components/bible-theme-settings.tsx b/packages/ui/src/components/bible-theme-settings.tsx index eb7676b21..4dc4456a7 100644 --- a/packages/ui/src/components/bible-theme-settings.tsx +++ b/packages/ui/src/components/bible-theme-settings.tsx @@ -64,7 +64,7 @@ function BibleThemeSettingsBody({
-
diff --git a/packages/ui/src/lib/reduced-motion.ts b/packages/ui/src/lib/reduced-motion.ts new file mode 100644 index 000000000..d2e95ac56 --- /dev/null +++ b/packages/ui/src/lib/reduced-motion.ts @@ -0,0 +1,3 @@ +export function prefersReducedMotion(view: Pick | null = globalThis): boolean { + return Boolean(view?.matchMedia?.('(prefers-reduced-motion: reduce)').matches); +} diff --git a/packages/ui/src/lib/scroll-reveal.test.ts b/packages/ui/src/lib/scroll-reveal.test.ts new file mode 100644 index 000000000..a5c6f3bd4 --- /dev/null +++ b/packages/ui/src/lib/scroll-reveal.test.ts @@ -0,0 +1,35 @@ +import { expect, it, vi } from 'vitest'; + +import { revealElementWithinScrollContainer } from './scroll-reveal'; + +it('reveals targets against the scrollport of a scaled, bordered container with a scrollbar', () => { + const container = document.createElement('div'); + Object.defineProperties(container, { + offsetHeight: { value: 100 }, + clientTop: { value: 4 }, + clientHeight: { value: 80 }, + }); + vi.spyOn(container, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 100, 300, 200)); + + const row = document.createElement('button'); + const rowRect = vi.spyOn(row, 'getBoundingClientRect'); + rowRect.mockReturnValue(new DOMRect(0, 250, 100, 40)); + revealElementWithinScrollContainer(row, container); + expect(container.scrollTop).toBe(11); + + rowRect.mockReturnValue(new DOMRect(0, 100, 100, 180)); + revealElementWithinScrollContainer(row, container); + expect(container.scrollTop).toBe(11); + + revealElementWithinScrollContainer(row, container, 'start'); + expect(container.scrollTop).toBe(7); + + // An oversized row wholly below the scrollport aligns its start; wholly above + // aligns its end. A row spanning both edges was already left in place above. + rowRect.mockReturnValue(new DOMRect(0, 300, 100, 180)); + revealElementWithinScrollContainer(row, container); + expect(container.scrollTop).toBe(103); + rowRect.mockReturnValue(new DOMRect(0, -100, 100, 180)); + revealElementWithinScrollContainer(row, container); + expect(container.scrollTop).toBe(9); +}); diff --git a/packages/ui/src/lib/scroll-reveal.ts b/packages/ui/src/lib/scroll-reveal.ts new file mode 100644 index 000000000..06729243b --- /dev/null +++ b/packages/ui/src/lib/scroll-reveal.ts @@ -0,0 +1,24 @@ +export function revealElementWithinScrollContainer( + element: Element, + container: HTMLElement, + align: 'nearest' | 'start' = 'nearest', +): void { + const elementRect = element.getBoundingClientRect(); + const containerRect = container.getBoundingClientRect(); + // offsetHeight includes the borders and scrollbar represented in the visual rect. + const scale = container.offsetHeight ? containerRect.height / container.offsetHeight : 1; + if (!scale || !container.clientHeight) return; + + const scrollportTop = containerRect.top + container.clientTop * scale; + const scrollportBottom = scrollportTop + container.clientHeight * scale; + const start = elementRect.top - scrollportTop; + const end = elementRect.bottom - scrollportBottom; + if (align === 'start') { + container.scrollTop += start / scale; + return; + } + if ((start < 0 && end > 0) || (start >= 0 && end <= 0)) return; + + const fits = elementRect.height <= container.clientHeight * scale; + container.scrollTop += (fits === (start < 0) ? start : end) / scale; +} diff --git a/packages/ui/src/lib/use-transient-verse-focus.ts b/packages/ui/src/lib/use-transient-verse-focus.ts index cf2eb1328..94d2568c3 100644 --- a/packages/ui/src/lib/use-transient-verse-focus.ts +++ b/packages/ui/src/lib/use-transient-verse-focus.ts @@ -1,5 +1,6 @@ import { useLayoutEffect, useRef, type RefObject } from 'react'; import type { BibleReaderNavigationRequest } from '@/components/bible-reader-navigation'; +import { prefersReducedMotion } from './reduced-motion'; export type VerseFocusRequest = BibleReaderNavigationRequest & Readonly<{ @@ -24,10 +25,6 @@ function clearFocusPaint(container: HTMLElement): void { }); } -function prefersReducedMotion(): boolean { - return Boolean(globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches); -} - function overflowAncestor(start: HTMLElement): HTMLElement { let node: HTMLElement | null = start; while (node !== null) { From e709a073b0298460edcf5283e1a76337e20f04bd Mon Sep 17 00:00:00 2001 From: Austin Date: Tue, 24 Nov 2026 13:40:13 -0600 Subject: [PATCH 06/75] feat(core): add Content Library video APIs (YPE-6573) (#488) * feat(core): add content library video APIs * refactor(core): simplify video schema ownership * fix(core): harden content library contracts * fix(core): validate video response boundaries * fix(core): distinguish no-content responses * fix(core): scope no-content status handling * fix(core): distinguish empty response bodies * test(core): isolate Content Library smoke coverage * feat(core): keep content library APIs compatible with v3 * fix(core): align content library rollout contracts (YPE-6573) * fix(core): accept empty video filters and trim search bundles (YPE-6573) * fix(core): address content library review feedback (YPE-6573) * docs(core): clarify video APIs and live validation (YPE-6573) * fix(core): use stable Content Library routes (YPE-6573) --- .changeset/brave-videos-play.md | 17 + .env.example | 3 + docs/cursor-cloud.md | 4 + docs/testing.md | 103 ++++ packages/core/README.md | 73 ++- packages/core/package.json | 4 + packages/core/src/__tests__/client.test.ts | 47 ++ .../core/src/__tests__/search-unified.test.ts | 64 ++- .../core/src/__tests__/search-videos.test.ts | 335 ++++++++++++++ .../src/__tests__/search.integration.test.ts | 13 +- .../src/__tests__/videos.integration.test.ts | 22 + packages/core/src/__tests__/videos.test.ts | 438 ++++++++++++++++++ packages/core/src/client.ts | 29 +- packages/core/src/index.ts | 8 + packages/core/src/schemas/index.ts | 1 + packages/core/src/schemas/search-videos.ts | 40 ++ packages/core/src/schemas/search.ts | 42 +- packages/core/src/schemas/video-id.ts | 17 + packages/core/src/schemas/video-resource.ts | 71 +++ packages/core/src/schemas/video.ts | 157 +++++-- packages/core/src/search-unified.ts | 12 +- packages/core/src/search-videos.ts | 58 +++ packages/core/src/search.ts | 23 +- packages/core/src/types/index.ts | 17 +- packages/core/src/video-thumbnail.ts | 49 ++ packages/core/src/videos.ts | 160 +++++++ packages/core/tsconfig.build.json | 3 +- packages/core/tsup.config.ts | 2 + packages/hooks/README.md | 8 + packages/ui/src/index.ts | 2 + scripts/check-tree-shaking.mjs | 16 + 31 files changed, 1753 insertions(+), 85 deletions(-) create mode 100644 .changeset/brave-videos-play.md create mode 100644 packages/core/src/__tests__/search-videos.test.ts create mode 100644 packages/core/src/__tests__/videos.integration.test.ts create mode 100644 packages/core/src/__tests__/videos.test.ts create mode 100644 packages/core/src/schemas/search-videos.ts create mode 100644 packages/core/src/schemas/video-id.ts create mode 100644 packages/core/src/schemas/video-resource.ts create mode 100644 packages/core/src/search-videos.ts create mode 100644 packages/core/src/video-thumbnail.ts create mode 100644 packages/core/src/videos.ts diff --git a/.changeset/brave-videos-play.md b/.changeset/brave-videos-play.md new file mode 100644 index 000000000..436207ae6 --- /dev/null +++ b/.changeset/brave-videos-play.md @@ -0,0 +1,17 @@ +--- +'@youversion/platform-core': minor +--- + +Add Content Library video detail, playlists, dedicated video search, and ID-only video hits in unified search. The new video APIs use `ContentLibraryVideo` with opaque string IDs and passage/publisher metadata. Existing `Video`, unified field selections, and hook overrides remain compatible with v3. + +Video details, playlists, dedicated video search, and unified search use `/v1` routes. Unified search uses `/v1/search-unified` for every field selection, including `videos`. + +Unified search results now include an enumerable `videos` array, including `[]` when no videos are returned. JSON output, exact snapshots, and `keyof SearchUnifiedResponse` gain this key; existing hook overrides may still omit it. Video field selection is available through core `SearchClient`; the existing React hook retains its verse/topic/image selections. Shared hook options should use `SearchUnifiedOptions` or `UseUnifiedSearchProps` rather than derive the wider selection from the core method signature. + +An empty `organizationIds` array now searches without publisher filters, matching an omitted option. Search-only bundles exclude playlist validation code. Dedicated video search can return empty pages with continuation tokens; continue until `nextPageToken` is null, rather than stopping on an empty video array. The response has no total result count. + +Preserve optional nullable `passage_ids`, `organization_id`, and `references` on video details and dedicated-search resources, alongside earlier `passage_id` responses. Thumbnail URL strings may be absolute, relative, or protocol-relative. + +Video queries use the shared 100-grapheme limit. Missing or null `user_intent` and `search_instead_for` fields are tolerated. Video search deliberately rejects HTTP 204 as an undocumented response, unlike Swift and Kotlin, which return an empty page. + +The new `VideosClient` consistently uses camelCase options: `acceptLanguage`, `pageSize`, `pageToken`, and `thumbnailSize`. Null video-search and playlist input cursors mean the first page, as when omitted; empty string cursors remain unchanged. Playlist requests default to English for YPE-6461 while honoring explicit language preferences. diff --git a/.env.example b/.env.example index cb2a2b6af..a1f0737cd 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,9 @@ YVP_APP_KEY="" YVP_API_HOST="api.youversion.com" +# Optional core video live smoke: an organization with populated video playlists. +# YVP_VIDEO_ORGANIZATION_ID="" + # Optional Vite demo overrides # Defaults to the demo's current origin. # VITE_YVP_AUTH_REDIRECT_URL="http://localhost:5173" diff --git a/docs/cursor-cloud.md b/docs/cursor-cloud.md index 3ebd8c241..3966d9b27 100644 --- a/docs/cursor-cloud.md +++ b/docs/cursor-cloud.md @@ -21,6 +21,10 @@ harness-specific app-key override, the demo renders the SDK missing-app-key pane shows its own Missing Environment Variables warning before mounting the SDK. Live core integration tests remain skipped. +The optional video live smoke also needs `YVP_VIDEO_ORGANIZATION_ID` in the root +`.env`, identifying an organization with populated video playlists. See +[the video test command](./testing.md#env). + ## Running the demo Start the demo and its workspace dependency watchers with: diff --git a/docs/testing.md b/docs/testing.md index 953540c88..7c848577a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -126,8 +126,111 @@ Bind on new/edited tests. When touching a file, bend the cases you edit toward t ## Env +To verify playlist-to-video lookup against a deployment, set `YVP_API_HOST` (a hostname such as `api.youversion.com`), an +`YVP_APP_KEY` with access to the video catalog, and `YVP_VIDEO_ORGANIZATION_ID` for an organization +with a populated video playlist. Run `pnpm --filter @youversion/platform-core test:integration src/__tests__/videos.integration.test.ts`. + Missing `YVP_API_HOST` or other env files: read `docs/cursor-cloud.md`. +## Content Library contract and routing + +YPE-6573 response validation follows the user-supplied Transformers `compiled.yaml` +snapshot (SHA-256 `e2458ce1008a5d5a1d6151e08b7769e6edf27f36abfdb40d06133b15c0a5475d`). +[Swift PR 302](https://github.com/youversion/platform-sdk-swift/pull/302) +(`bba84a3`) and [Kotlin PR 242](https://github.com/youversion/platform-sdk-kotlin/pull/242) +(`3e39b55`) are comparison references, +not substitutes for that contract. The mocked client tests cover video detail, +playlist-to-detail and unified-search-to-detail lookup, thumbnail renditions, +nullable and absent video metadata, required fields, pagination and HTTP errors. +Video search requires the `videos` and `did_you_mean` arrays. Absent or null +`user_intent` and `search_instead_for` normalize to absent intent and a null +correction, matching sibling SDK tolerance. Its undocumented 204 response still +rejects, while playlist 204 returns an empty page; this deliberate difference is +called out in the changeset. Malformed full video resources reject rather than +being silently dropped. + +Review follow-up adds optional nullable `passage_ids` (string array) and +`organization_id` (UUID), as specified in the review's newer `compiled-2.yaml`, +while retaining singular `passage_id` from the original supplied snapshot. That newer +attachment was not available locally; these are additive metadata-preservation +changes, not proof that the deployment serves the complete newer contract. +Optional `references` is also preserved for compatibility with sibling SDKs. +Thumbnail URLs remain strings, preserving absolute, relative and protocol-relative +forms without inventing a base URL. Video queries reuse the existing 100-grapheme +search validator, matching Swift, Kotlin and the other core search methods. + +Content Library requests use stable routes: + +- Video detail, playlist collection/detail and dedicated video search use `/v1`. +- Unified search always uses `/v1/search-unified`, including when `fields` includes + `videos` or is omitted. Routing does not depend on the selected fields. +- Playlist language defaults to English for YPE-6461; explicit preferences are + honored. Dedicated video search defaults to English per the search API. +- `VideosClient` options use camelCase (`acceptLanguage`, `pageSize`, `pageToken`, + `thumbnailSize`). Wire parameters and collection response cursors keep their + API names. Null input cursors are omitted; empty string cursors are preserved. + +The original supplied spec names stable routes for video details, playlists and +unified search. Its dedicated video-search route was `/v1-beta/search-videos`; +the current implementation uses `/v1/search-videos` per the updated routing direction. +The pinned Swift and Kotlin revisions used earlier rollout routes and do not define +the current React routing. +The live smoke remains optional deployment evidence, not a replacement for the +contract tests or a requirement for adding UI. No UI is added by YPE-6573. + +### Stable-route checks (2026-11-24) + +After switching all Content Library requests to `/v1`, the rebuilt SDK returned +populated dedicated and unified video searches for “Bible,” “Jesus,” and +“What Is The Bible?” The first video ID from each search resolved through +`getVideo`. English playlist pagination completed across nine pages of two +playlists, returning 18 unique playlists. Playlist detail and video detail passed +response validation. Spanish and Portuguese playlists and video details retained +the corresponding language tags. + +Media returned by stable video detail remained accessible without an App Key: +the thumbnail, both HLS sources (manifests and sampled media segments, including +initialization data where applicable), and the MP4 preview. Responses allowed +cross-origin access; full player playback was not tested. + +The accepted search pagination behavior also occurs on `/v1/search-videos`. +For “Jesus” with `page_size=5`, direct HTTP requests returned 4, 1, 0, and 3 +videos on the first four pages. The SDK followed 30 pages, returning 17 unique +videos without duplicates and 20 empty pages; a continuation token remained. +These bounded checks do not establish eventual termination. Consumers must use +the continuation token rather than the result count to decide whether to continue. + +### Earlier rollout checks (2026-11-24) + +Before the switch to `/v1`, manual requests and the built core SDK at `c748d1f` +verified populated `/v1-beta` +playlist collection/detail and video detail responses. The English BibleProject +catalog returned 18 playlists; pagination completed across nine pages of two +playlists, without duplicate playlist IDs. Spanish and Portuguese requests returned +localized playlists and video details with the corresponding language tags. + +Dedicated search and unified search selecting `videos` returned videos for +“Bible,” “Jesus,” and “What Is The Bible?” The first ID from each search resolved +through the video detail client. Detail validation preserved passage and publisher +metadata, and the card thumbnail rendition was applied. + +The thumbnail, both HLS playback sources (manifests and sampled media segments, +including initialization data where applicable), and the MP4 preview were accessible +without an App Key. Media responses allowed cross-origin access. Full player +playback was not tested. These manual checks are deployment evidence, not additional +automated test coverage or proof of the complete newer OpenAPI contract. + +Dedicated search returned empty pages with continuation tokens for all three +queries. For “Jesus” with `page_size=5`, the first four pages contained 4, 1, 0, +and 3 videos. A bounded SDK check followed 30 pages, returning 17 unique videos +without duplicates and 20 empty pages; another token remained. Direct HTTP requests +reproduced empty pages with tokens independently of SDK parsing. Eventual +termination was not verified, and the response provides no total result count. + +We accept this service behavior and retain the current implementation. Consumers +must follow non-null tokens even after empty pages. Any required behavior change +will be handled in a follow-up after clarification or a service contract change. + ## Before pushing Run the full test suite across all packages — a change in one package can break another. diff --git a/packages/core/README.md b/packages/core/README.md index 4e0e53fa4..26b2eaea7 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -137,15 +137,86 @@ A blank `passage_id` is rejected before the request. Pass a single verse or a verse range, such as `JHN.3.16` or `JHN.3.16-18`. Unified search returns one snapshot of top results, not the entire verse result -set. Omit `fields` for all available kinds, or pass a nonempty selection. +set. Omit `fields` for the stable endpoint's default selection, or pass a nonempty +selection. Explicitly include `videos` to request video hits. `userIntent` accepts `unknown`, `topical`, `text`, or `reference`; response intent strings remain open-ended. +Unified responses now always include a `videos` array, including stable-route +searches that return `videos: []`. This adds an enumerable property to returned +objects, so JSON output, exact snapshots, and `keyof SearchUnifiedResponse` include +it. The public type keeps the property optional for existing fixtures and hook +overrides. + +Explicit video selection is available through core `SearchClient.searchUnified` +with `ContentLibrarySearchOptions`. The existing React `useUnifiedSearch` hook +continues to accept only `verses`, `topics`, and `images`. For options shared with +the hook, use `SearchUnifiedOptions` or `UseUnifiedSearchProps` rather than deriving +the wider core selection from `Parameters`. + +`SearchClient.searchVideos` accepts `organizationIds` as UUID filters combined with +OR. Omit the option or pass `[]` to search all organizations accessible to the app. + The SDK also accepts `fields: ['images']` and maps image hits to `{ id, passageId }`, not image URLs. Image selection requires backend support. A production check on 2026-10-20 returned HTTP 400 for `fields: ['images']`; successful verse/topic responses omitted images, which the SDK returns as `images: []`. +### Video details, playlists, and search + +There are two ways to find videos: + +- Search by text. Unified search returns video IDs; pass each ID unchanged to + `VideosClient.getVideo`. Dedicated `SearchClient.searchVideos` returns full + video resources, including playback sources, so a second detail request is + usually unnecessary. +- Browse an organization's playlists. `VideosClient.getPlaylists` returns a + collection; `getPlaylist` returns one full playlist, including its ordered + video IDs. Pass those IDs unchanged to `getVideo` for metadata and playback URLs. + +These calls require an App Key with access to the video catalog. +Video details, playlist collection/detail, and dedicated video search use +`/v1`. Unified search always uses `/v1/search-unified`, including when `fields` +explicitly includes `videos`. +Unified search returns one unpaginated set of top results. + +Dedicated video search supports `pageSize` from 1 to 99. Repeat the query, +organization filters, and language when passing `nextPageToken` as `pageToken`; +`pageSize` may change. An empty video array can still include a continuation token, +and later pages can contain videos. Stop when `nextPageToken` is `null`, not when +`videos` is empty. Empty string tokens are preserved and must be passed unchanged. +No total result count is returned. Live checks reproduced empty pages with tokens +both through the SDK and with direct HTTP requests. We accept this service behavior; +eventual termination was not verified in the bounded live checks. + +Playlist collections use `data` and `next_page_token`. Follow that token until +it is `null`. `pageSize` accepts 1 to 99, or `'*'` when `fields` selects one to +three fields. Omitting `fields` requests full playlists; a selected field set can +omit IDs or video IDs, so include the fields needed for subsequent requests. +Playlist collection HTTP 204 or an empty response body returns an empty collection; +malformed nonempty responses and empty detail responses reject. + +`VideosClient` uses camelCase options: `acceptLanguage`, `thumbnailSize`, +`pageSize`, and `pageToken`. API query parameters and collection response keys +retain their wire names, such as `page_size` and `next_page_token`. A null input +cursor requests the first page; an empty string cursor is sent unchanged. + +Video detail and dedicated search preserve optional nullable `passage_ids`, +`organization_id`, and `references`, plus singular `passage_id` from earlier +responses. Thumbnail URL strings are preserved whether absolute, relative, or +protocol-relative. `getVideo` accepts `thumbnailSize: 'thumb'`, `'card'`, or +`'full'`. Omitting it removes any existing `size` parameter for the full-size +image; dedicated search also removes that parameter. Other query bytes and +fragments are preserved. Relative URLs remain relative; the SDK does not resolve +them against a base URL. +Queries use the same 100-grapheme validator as other search methods. Optional +query intent/correction fields may be absent or null. Unlike the sibling SDKs, +video search intentionally rejects undocumented HTTP 204 responses. + +Playlist requests default to English to avoid the missing-language catalog issue +tracked in YPE-6461, while explicit caller preferences are honored. Video details +keep the runtime language default; dedicated video search defaults to English. + ### Display Bible HTML Use `getPassageDisplay` when you need transformed HTML together with current diff --git a/packages/core/package.json b/packages/core/package.json index a79c340a3..5c43960a2 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -49,10 +49,14 @@ "!dist/search-topics.cjs", "!dist/search-unified.js", "!dist/search-unified.cjs", + "!dist/search-videos.js", + "!dist/search-videos.cjs", "!dist/highlights.js", "!dist/highlights.cjs", "!dist/images.js", "!dist/images.cjs", + "!dist/videos.js", + "!dist/videos.cjs", "!dist/organizations.js", "!dist/organizations.cjs", "!dist/data-exchange.js", diff --git a/packages/core/src/__tests__/client.test.ts b/packages/core/src/__tests__/client.test.ts index 5349fac65..0a8e82e7f 100644 --- a/packages/core/src/__tests__/client.test.ts +++ b/packages/core/src/__tests__/client.test.ts @@ -130,6 +130,53 @@ describe('ApiClient contracts', () => { } }); + it('exposes successful status without changing the legacy body-only result', async () => { + if (process.env.INTEGRATION_TESTS) server.listen(); + try { + server.use( + http.get( + 'https://test_placeholder.youversion.com/no-content', + () => new HttpResponse(null, { status: 204 }), + ), + http.get( + 'https://test_placeholder.youversion.com/empty-success', + () => new HttpResponse(null, { status: 200 }), + ), + http.get('https://test_placeholder.youversion.com/json-string', () => + HttpResponse.json(''), + ), + ); + const client = new ApiClient({ + apiHost: 'test_placeholder.youversion.com', + appKey: 'test-app', + }); + + await expect(client.get('/no-content')).resolves.toBe(''); + await expect(client.getWithStatus('/no-content')).resolves.toEqual({ + data: '', + emptyBody: true, + status: 204, + }); + await expect(client.get('/empty-success')).resolves.toBe(''); + await expect(client.getWithStatus('/empty-success')).resolves.toEqual({ + data: '', + emptyBody: true, + status: 200, + }); + await expect(client.get('/json-string')).resolves.toBe(''); + await expect(client.getWithStatus('/json-string')).resolves.toEqual({ + data: '', + emptyBody: false, + status: 200, + }); + } finally { + if (process.env.INTEGRATION_TESTS) { + server.resetHandlers(); + server.close(); + } + } + }); + it('only exposes numeric status values from unknown failures', () => { expect(getHttpStatus(Object.assign(new Error('forbidden'), { status: 403 }))).toBe(403); expect(getHttpStatus({ status: '403' })).toBeUndefined(); diff --git a/packages/core/src/__tests__/search-unified.test.ts b/packages/core/src/__tests__/search-unified.test.ts index 96371cf75..bfd59e6d6 100644 --- a/packages/core/src/__tests__/search-unified.test.ts +++ b/packages/core/src/__tests__/search-unified.test.ts @@ -2,20 +2,67 @@ import { describe, it, expect, vi } from 'vitest'; import { http, HttpResponse } from 'msw'; import { ApiClient } from '../client'; import { SearchClient } from '../search'; +import { VideosClient } from '../videos'; import { server } from './setup'; const apiHost = process.env.YVP_API_HOST; -function createSearchClient(): SearchClient { - const apiClient = new ApiClient({ +function createApiClient(): ApiClient { + return new ApiClient({ apiHost, appKey: 'test-app', installationId: 'test-installation', }); - return new SearchClient(apiClient); +} + +function createSearchClient(): SearchClient { + return new SearchClient(createApiClient()); } describe('SearchClient.searchUnified', () => { + it.skipIf(Boolean(process.env.INTEGRATION_TESTS))( + 'routes video-only and mixed searches to v1 and resolves the returned video id', + async () => { + const apiClient = createApiClient(); + const searchClient = new SearchClient(apiClient); + const videos = new VideosClient(apiClient); + let expectedFields: readonly string[]; + + server.use( + http.get(`https://${apiHost}/v1/search-unified`, ({ request }) => { + const url = new URL(request.url); + expect(url.searchParams.getAll('fields[]')).toEqual(expectedFields); + return HttpResponse.json({ + verses: [{ reference: 'JHN.3.16' }], + videos: [ + { id: 'search-issued-id', title: 'not part of a unified hit' }, + { id: '' }, + { nope: true }, + ], + did_you_mean: [], + search_instead_for: null, + }); + }), + http.get(`https://${apiHost}/v1/videos/search-issued-id`, () => + HttpResponse.json({ + id: 'detail-issued-id', + playback_sources: [], + playback_preview_sources: [], + }), + ), + ); + + for (const fields of [['videos'], ['verses', 'videos']] as const) { + expectedFields = fields; + const result = await searchClient.searchUnified('faith', 111, 'en', { fields }); + expect(result.verses).toEqual([{ id: 'JHN.3.16' }]); + expect(result.videos).toEqual([{ id: 'search-issued-id' }]); + const detail = await videos.getVideo(result.videos?.[0]?.id ?? ''); + expect(detail.id).toBe('detail-issued-id'); + } + }, + ); + it('requests images only, maps passage_id, and sends no paging params', async () => { const searchClient = createSearchClient(); @@ -47,6 +94,7 @@ describe('SearchClient.searchUnified', () => { verses: [], topics: [], images: [{ id: 'img-9', passageId: 'PSA.23.1' }], + videos: [], didYouMean: ['psalm'], searchInsteadFor: 'psalm 23', }); @@ -78,6 +126,7 @@ describe('SearchClient.searchUnified', () => { verses: [], topics: [{ id: null, text: 'hope', subtopics: [] }], images: [], + videos: [], didYouMean: [], searchInsteadFor: null, }); @@ -112,6 +161,7 @@ describe('SearchClient.searchUnified', () => { verses: [{ id: 'JHN.6.35' }], topics: [], images: [{ id: 'img-1', passageId: 'PSA.23.1' }], + videos: [], userIntent: 'topical', didYouMean: [], searchInsteadFor: null, @@ -148,6 +198,7 @@ describe('SearchClient.searchUnified', () => { verses: [], topics: [{ id: 42, text: 'hope', subtopics: ['trust'] }], images: [], + videos: [], didYouMean: [], searchInsteadFor: null, }); @@ -180,6 +231,7 @@ describe('SearchClient.searchUnified', () => { verses: [], topics: [], images: [], + videos: [], didYouMean: [], searchInsteadFor: null, }); @@ -217,7 +269,7 @@ describe('SearchClient.searchUnified', () => { // @ts-expect-error - verifies runtime validation for unsafe JavaScript callers fields: ['nope'], }), - ).rejects.toThrow('Search field must be verses, topics, or images'); + ).rejects.toThrow('Search field must be verses, topics, images, or videos'); await expect( searchClient.searchUnified('faith', 111, 'en', { // @ts-expect-error - verifies runtime validation for unsafe JavaScript callers @@ -275,6 +327,7 @@ describe('SearchClient.searchUnified', () => { { id: 'img-good', passageId: 'PSA.23.1' }, { id: 'img-good-last', passageId: 'JHN.6.35' }, ], + videos: [], didYouMean: [], searchInsteadFor: null, }); @@ -297,6 +350,7 @@ describe('SearchClient.searchUnified', () => { verses: [{ id: 'JHN.3.16' }], topics: [{ id: null, text: 'love', subtopics: [] }], images: [], + videos: [], userIntent: 'future-intent', didYouMean: [], searchInsteadFor: null, @@ -349,6 +403,7 @@ describe('SearchClient.searchUnified', () => { verses: [{ id: 'JHN.3.16' }], topics: [{ id: null, text: 'love', subtopics: [] }], images: [{ id: 'img-love', passageId: 'JHN.3.16' }], + videos: [], didYouMean: [], searchInsteadFor: null, }); @@ -370,6 +425,7 @@ describe('SearchClient.searchUnified', () => { verses: [], topics: [], images: [], + videos: [], didYouMean: [], searchInsteadFor: null, }); diff --git a/packages/core/src/__tests__/search-videos.test.ts b/packages/core/src/__tests__/search-videos.test.ts new file mode 100644 index 000000000..a9feaed1c --- /dev/null +++ b/packages/core/src/__tests__/search-videos.test.ts @@ -0,0 +1,335 @@ +import { describe, expect, it, vi } from 'vitest'; +import { http, HttpResponse } from 'msw'; +import { ApiClient, getHttpStatus, SearchClient, VideosClient } from '../index'; +import { server } from './setup'; + +const apiHost = process.env.YVP_API_HOST; +const organizationIds = [ + '550e8400-e29b-41d4-a716-446655440000', + '09d8dc67-6b79-4db8-95fb-b9055258b85b', +]; + +function createSearchClient(): SearchClient { + return new SearchClient( + new ApiClient({ + apiHost, + appKey: 'test-app', + installationId: 'test-installation', + }), + ); +} + +describe.skipIf(Boolean(process.env.INTEGRATION_TESTS))('SearchClient.searchVideos', () => { + it('searches full video records with stable paging parameters and full-size thumbnails', async () => { + const search = createSearchClient(); + + server.use( + http.get(`https://${apiHost}/v1/search-videos`, ({ request }) => { + const url = new URL(request.url); + expect(request.headers.get('Accept-Language')).toBe('en'); + expect(url.searchParams.get('query')).toBe('teaching clips'); + expect(url.searchParams.getAll('organization_ids[]')).toEqual(organizationIds); + expect(url.searchParams.get('page_size')).toBe('12'); + expect(url.searchParams.get('page_token')).toBe('a+/=&b'); + return HttpResponse.json({ + videos: [ + { + id: 'opaque-video-id', + passage_ids: ['JHN.3.16', 'ROM.8.28'], + organization_id: '550e8400-e29b-41d4-a716-446655440000', + references: ['JHN.3.16', 'ROM.8.28'], + title: 'Teaching clip', + thumbnail: { + url: 'https://cdn.example/video.jpg?size=card&token=x%2Fy#poster', + width: 640, + height: 360, + }, + playback_sources: [], + playback_preview_sources: [], + }, + ], + user_intent: 'topical', + did_you_mean: ['teaching clip'], + search_instead_for: null, + next_page_token: 'last-page', + }); + }), + ); + + const result = await search.searchVideos('teaching clips', { + organizationIds, + pageSize: 12, + pageToken: 'a+/=&b', + }); + + expect(result).toEqual({ + videos: [ + { + id: 'opaque-video-id', + passage_ids: ['JHN.3.16', 'ROM.8.28'], + organization_id: '550e8400-e29b-41d4-a716-446655440000', + references: ['JHN.3.16', 'ROM.8.28'], + title: 'Teaching clip', + thumbnail: { + url: 'https://cdn.example/video.jpg?token=x%2Fy#poster', + width: 640, + height: 360, + }, + playback_sources: [], + playback_preview_sources: [], + }, + ], + userIntent: 'topical', + didYouMean: ['teaching clip'], + searchInsteadFor: null, + nextPageToken: 'last-page', + }); + }); + + it('treats an empty organization filter like omitted filters', async () => { + const search = createSearchClient(); + const requests: string[] = []; + server.use( + http.get(`https://${apiHost}/v1/search-videos`, ({ request }) => { + const url = new URL(request.url); + requests.push(request.url); + expect(url.searchParams.get('query')).toBe('love'); + expect(url.searchParams.has('organization_ids[]')).toBe(false); + return HttpResponse.json({ + videos: [], + user_intent: null, + did_you_mean: [], + search_instead_for: null, + }); + }), + ); + const unfiltered = await search.searchVideos('love'); + await expect(search.searchVideos('love', { organizationIds: [] })).resolves.toEqual(unfiltered); + expect(requests).toHaveLength(2); + expect(requests[1]).toBe(requests[0]); + }); + + it('preserves an empty-page token and validates parameters before networking', async () => { + const search = createSearchClient(); + let requests = 0; + const fetchSpy = vi.spyOn(global, 'fetch'); + + try { + server.use( + http.get(`https://${apiHost}/v1/search-videos`, ({ request }) => { + requests += 1; + const url = new URL(request.url); + expect(request.headers.get('Accept-Language')).toBe('es-MX'); + expect(url.searchParams.get('query')).toBe('hope'); + expect(url.searchParams.getAll('organization_ids[]')).toEqual(organizationIds); + if (requests === 1) { + expect(url.searchParams.has('page_token')).toBe(false); + return HttpResponse.json({ + videos: [], + user_intent: null, + did_you_mean: [], + search_instead_for: null, + next_page_token: '', + }); + } + expect(url.searchParams.has('page_token')).toBe(true); + expect(url.searchParams.get('page_token')).toBe(''); + expect(url.searchParams.get('page_size')).toBe('99'); + return HttpResponse.json({ + videos: [], + user_intent: null, + did_you_mean: [], + search_instead_for: null, + next_page_token: null, + }); + }), + ); + + const emptyPage = await search.searchVideos('hope', { + acceptLanguage: 'es-MX', + organizationIds, + }); + expect(emptyPage).toEqual({ + videos: [], + didYouMean: [], + searchInsteadFor: null, + nextPageToken: '', + }); + await expect( + search.searchVideos('hope', { + acceptLanguage: 'es-MX', + pageSize: 99, + organizationIds, + pageToken: emptyPage.nextPageToken ?? undefined, + }), + ).resolves.toMatchObject({ nextPageToken: null }); + expect(fetchSpy).toHaveBeenCalledTimes(2); + + await expect(search.searchVideos('', {})).rejects.toThrow( + 'Query must be between 1 and 100 characters', + ); + await expect(search.searchVideos('é'.repeat(101))).rejects.toThrow( + 'Query must be between 1 and 100 characters', + ); + await expect(search.searchVideos('hope', { pageSize: 100 })).rejects.toThrow(); + await expect( + search.searchVideos('hope', { organizationIds: ['not-a-uuid'] }), + ).rejects.toThrow('Organization ID must be a valid UUID'); + expect(fetchSpy).toHaveBeenCalledTimes(2); + } finally { + fetchSpy.mockRestore(); + } + }); + + it('rejects malformed responses and preserves service failure status', async () => { + const search = createSearchClient(); + + server.use( + http.get(`https://${apiHost}/v1/search-videos`, ({ request }) => { + const query = new URL(request.url).searchParams.get('query'); + if (query === 'malformed') { + return HttpResponse.json({ + videos: [{ id: '', playback_sources: [], playback_preview_sources: [] }], + user_intent: null, + did_you_mean: [], + search_instead_for: null, + next_page_token: null, + }); + } + return query === 'empty-body' + ? new HttpResponse(null, { status: 204 }) + : HttpResponse.json({ message: 'catalog unavailable' }, { status: 424 }); + }), + ); + + await expect(search.searchVideos('malformed')).rejects.toThrow( + 'Unexpected search-videos API response', + ); + await expect(search.searchVideos('empty-body')).rejects.toThrow( + 'Unexpected search-videos API response', + ); + try { + await search.searchVideos('unavailable'); + throw new Error('expected searchVideos to reject'); + } catch (error) { + expect(getHttpStatus(error)).toBe(424); + } + }); + + it('requires result arrays while normalizing absent or null optional query metadata', async () => { + const search = createSearchClient(); + const valid = { + videos: [], + user_intent: null, + did_you_mean: [], + search_instead_for: null, + }; + server.use(http.get(`https://${apiHost}/v1/search-videos`, () => HttpResponse.json(valid))); + await expect(search.searchVideos('love')).resolves.toEqual({ + videos: [], + didYouMean: [], + searchInsteadFor: null, + nextPageToken: null, + }); + for (const field of ['user_intent', 'search_instead_for']) { + const missing = Object.fromEntries(Object.entries(valid).filter(([name]) => name !== field)); + server.use(http.get(`https://${apiHost}/v1/search-videos`, () => HttpResponse.json(missing))); + await expect(search.searchVideos('love')).resolves.toEqual({ + videos: [], + didYouMean: [], + searchInsteadFor: null, + nextPageToken: null, + }); + server.use( + http.get(`https://${apiHost}/v1/search-videos`, () => + HttpResponse.json({ ...valid, [field]: 42 }), + ), + ); + await expect(search.searchVideos('love')).rejects.toThrow( + 'Unexpected search-videos API response', + ); + } + for (const field of ['videos', 'did_you_mean']) { + const payload = Object.fromEntries(Object.entries(valid).filter(([name]) => name !== field)); + server.use(http.get(`https://${apiHost}/v1/search-videos`, () => HttpResponse.json(payload))); + await expect(search.searchVideos('love')).rejects.toThrow( + 'Unexpected search-videos API response', + ); + } + }); + + it('accepts multi-code-point queries and treats null search cursors as omitted', async () => { + const search = createSearchClient(); + const queries = ['👨‍👩‍👧‍👦'.repeat(15), 'é'.repeat(100)]; + server.use( + http.get(`https://${apiHost}/v1/search-videos`, ({ request }) => { + const url = new URL(request.url); + expect(queries).toContain(url.searchParams.get('query')); + expect(url.searchParams.has('page_token')).toBe(false); + return HttpResponse.json({ videos: [], did_you_mean: [] }); + }), + ); + for (const query of queries) { + await expect(search.searchVideos(query, { pageToken: null })).resolves.toEqual({ + videos: [], + didYouMean: [], + searchInsteadFor: null, + nextPageToken: null, + }); + } + }); + + it('preserves relative thumbnails without dropping sibling video search results', async () => { + const api = new ApiClient({ apiHost, appKey: 'test-app' }); + const search = new SearchClient(api); + const videos = new VideosClient(api); + const records = [ + { + id: 'relative', + thumbnail: { url: '/images/art.jpg?signature=a%2Fb&size=thumb' }, + playback_sources: [], + playback_preview_sources: [], + }, + { + id: 'protocol-relative', + thumbnail: { url: '//cdn.example/art.jpg?size=card' }, + playback_sources: [], + playback_preview_sources: [], + }, + ]; + server.use( + http.get(`https://${apiHost}/v1/search-videos`, () => + HttpResponse.json({ videos: records, did_you_mean: [] }), + ), + http.get(`https://${apiHost}/v1/videos/relative`, () => HttpResponse.json(records[0])), + ); + const page = await search.searchVideos('love'); + expect(page.videos.map((video) => video.thumbnail?.url)).toEqual([ + '/images/art.jpg?signature=a%2Fb', + '//cdn.example/art.jpg', + ]); + expect(page.videos.map((video) => video.id)).toEqual(['relative', 'protocol-relative']); + const detail = await videos.getVideo('relative', { thumbnailSize: 'card' }); + expect(detail.thumbnail?.url).toBe('/images/art.jpg?signature=a%2Fb&size=card'); + }); + + it('preserves a missing-app-key response as an HTTP status error', async () => { + const search = new SearchClient( + new ApiClient({ apiHost, appKey: '', installationId: 'test-installation' }), + ); + + server.use( + http.get(`https://${apiHost}/v1/search-videos`, ({ request }) => { + expect(request.headers.get('X-YVP-App-Key')).toBe(''); + return HttpResponse.json({ message: 'missing app key' }, { status: 401 }); + }), + ); + + try { + await search.searchVideos('faith'); + throw new Error('expected searchVideos to reject'); + } catch (error) { + expect(getHttpStatus(error)).toBe(401); + } + }); +}); diff --git a/packages/core/src/__tests__/search.integration.test.ts b/packages/core/src/__tests__/search.integration.test.ts index 0c2d1e698..98cb4689e 100644 --- a/packages/core/src/__tests__/search.integration.test.ts +++ b/packages/core/src/__tests__/search.integration.test.ts @@ -6,12 +6,13 @@ const shouldRunLiveSmoke = process.env.INTEGRATION_TESTS === 'true' && Boolean(process.env.YVP_APP_KEY); function createSearchClient(): SearchClient { - const apiClient = new ApiClient({ - apiHost: process.env.YVP_API_HOST, - appKey: process.env.YVP_APP_KEY || '', - installationId: 'integration-test', - }); - return new SearchClient(apiClient); + return new SearchClient( + new ApiClient({ + apiHost: process.env.YVP_API_HOST, + appKey: process.env.YVP_APP_KEY || '', + installationId: 'integration-test', + }), + ); } (shouldRunLiveSmoke ? describe : describe.skip)('SearchClient live smoke', () => { diff --git a/packages/core/src/__tests__/videos.integration.test.ts b/packages/core/src/__tests__/videos.integration.test.ts new file mode 100644 index 000000000..7ceeea0eb --- /dev/null +++ b/packages/core/src/__tests__/videos.integration.test.ts @@ -0,0 +1,22 @@ +import { expect, it } from 'vitest'; +import { ApiClient } from '../client'; +import { VideosClient } from '../videos'; + +const { INTEGRATION_TESTS, YVP_APP_KEY, YVP_API_HOST, YVP_VIDEO_ORGANIZATION_ID } = process.env; + +it.skipIf(INTEGRATION_TESTS !== 'true' || !YVP_APP_KEY || !YVP_VIDEO_ORGANIZATION_ID)( + 'resolves a video id returned by the organization playlists', + async () => { + if (!YVP_APP_KEY || !YVP_VIDEO_ORGANIZATION_ID) + throw new Error('Missing live video test configuration'); + const videos = new VideosClient(new ApiClient({ appKey: YVP_APP_KEY, apiHost: YVP_API_HOST })); + const page = await videos.getPlaylists(YVP_VIDEO_ORGANIZATION_ID, { + fields: ['id', 'videos'], + pageSize: '*', + }); + const id = page.data.flatMap((playlist) => playlist.videos ?? [])[0]; + if (!id) throw new Error('The test organization needs a playlist containing a video'); + const detail = await videos.getVideo(id); + expect(detail.id.length).toBeGreaterThan(0); + }, +); diff --git a/packages/core/src/__tests__/videos.test.ts b/packages/core/src/__tests__/videos.test.ts new file mode 100644 index 000000000..d8dfcfa0b --- /dev/null +++ b/packages/core/src/__tests__/videos.test.ts @@ -0,0 +1,438 @@ +import { describe, expect, expectTypeOf, it, vi } from 'vitest'; +import { http, HttpResponse } from 'msw'; +import { + ApiClient, + getHttpStatus, + VideosClient, + type Video, + type ContentLibraryVideo, +} from '../index'; +import { server } from './setup'; + +const apiHost = process.env.YVP_API_HOST; + +interface ThumbnailFixtures { + readonly [videoId: string]: string | null; +} + +function createVideosClient(): VideosClient { + return new VideosClient( + new ApiClient({ + apiHost, + appKey: 'test-app', + installationId: 'test-installation', + }), + ); +} + +describe.skipIf(Boolean(process.env.INTEGRATION_TESTS))('VideosClient', () => { + it('gets a video by opaque id and resolves its thumbnail without changing the playback contract', async () => { + const videos = createVideosClient(); + + server.use( + http.get(`https://${apiHost}/v1/videos/:videoId`, ({ params, request }) => { + expect(params.videoId).toBe('video/id'); + expect(request.headers.get('Accept-Language')).toBe('es'); + return HttpResponse.json({ + id: 'video/id', + title: 'La historia', + description: null, + passage_id: 'JHN.3.16', + passage_ids: ['JHN.3.16', 'ROM.8.28'], + organization_id: '550e8400-e29b-41d4-a716-446655440000', + references: ['JHN.3.16', 'ROM.8.28'], + language_tag: 'es', + runtime: 90, + orientation: 'landscape', + thumbnail: { + url: 'https://cdn.example/video.jpg?size=thumb&token=a%2Fb#frame', + width: 1280, + height: 720, + }, + playback_sources: [{ url: 'https://cdn.example/video.m3u8', format: 'hls' }], + playback_preview_sources: [{ url: 'https://cdn.example/preview.mp4', format: 'mp4' }], + share_url: 'https://www.bible.com/videos/video-id', + ignored: true, + }); + }), + ); + + const video = await videos.getVideo('video/id', { + acceptLanguage: 'es', + thumbnailSize: 'card', + }); + + expectTypeOf(video).toEqualTypeOf(); + expectTypeOf(video.id).toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expect(video).toEqual({ + id: 'video/id', + title: 'La historia', + description: null, + passage_id: 'JHN.3.16', + passage_ids: ['JHN.3.16', 'ROM.8.28'], + organization_id: '550e8400-e29b-41d4-a716-446655440000', + references: ['JHN.3.16', 'ROM.8.28'], + language_tag: 'es', + runtime: 90, + orientation: 'landscape', + thumbnail: { + url: 'https://cdn.example/video.jpg?token=a%2Fb&size=card#frame', + width: 1280, + height: 720, + }, + playback_sources: [{ url: 'https://cdn.example/video.m3u8', format: 'hls' }], + playback_preview_sources: [{ url: 'https://cdn.example/preview.mp4', format: 'mp4' }], + share_url: 'https://www.bible.com/videos/video-id', + }); + expect(video.thumbnail?.url).not.toContain('app_key'); + }); + + it('lists localized playlists and resolves a playlist video id unchanged', async () => { + const videos = createVideosClient(); + const organizationId = '550e8400-e29b-41d4-a716-446655440000'; + + server.use( + http.get( + `https://${apiHost}/v1/organizations/:organizationId/playlists`, + ({ params, request }) => { + expect(params.organizationId).toBe(organizationId); + const url = new URL(request.url); + expect(request.headers.get('Accept-Language')).toBe('en'); + expect(url.searchParams.getAll('fields[]')).toEqual(['id', 'videos', 'title']); + expect(url.searchParams.get('page_size')).toBe('*'); + expect(url.searchParams.get('page_token')).toBe('playlist-page'); + return HttpResponse.json({ + data: [{ id: 3669, title: 'Teaching Clips', videos: ['52186'] }], + next_page_token: null, + }); + }, + ), + http.get(`https://${apiHost}/v1/videos/52186`, ({ request }) => { + expect(request.headers.get('Accept-Language')).toBe('fr'); + return HttpResponse.json({ + id: '52186', + playback_sources: [], + playback_preview_sources: [], + }); + }), + ); + + const page = await videos.getPlaylists(organizationId, { + fields: ['id', 'videos', 'title'], + pageSize: '*', + pageToken: 'playlist-page', + }); + const videoId = page.data[0]?.videos?.[0] ?? ''; + const video = await videos.getVideo(videoId, { acceptLanguage: 'fr' }); + + expect(page).toEqual({ + data: [{ id: 3669, title: 'Teaching Clips', videos: ['52186'] }], + next_page_token: null, + }); + expect(video.id).toBe('52186'); + }); + + it('gets a full playlist and maps responses without a representation to an empty page', async () => { + const videos = createVideosClient(); + const organizationId = '550e8400-e29b-41d4-a716-446655440000'; + + server.use( + http.get( + `https://${apiHost}/v1/organizations/:organizationId/playlists/:playlistId`, + ({ params, request }) => { + expect(params.organizationId).toBe(organizationId); + expect(params.playlistId).toBe('3669'); + expect(request.headers.get('Accept-Language')).toBe('es'); + return HttpResponse.json({ + id: 3669, + title: 'Clips de enseñanza', + description: null, + type: 'TEACHING_CLIPS', + total: 1, + videos: ['52186'], + }); + }, + ), + http.get( + `https://${apiHost}/v1/organizations/:organizationId/playlists`, + ({ params, request }) => { + expect(params.organizationId).toBe(organizationId); + const language = request.headers.get('Accept-Language'); + if (language === 'en') { + const url = new URL(request.url); + expect(url.searchParams.has('fields[]')).toBe(false); + expect(url.searchParams.has('page_token')).toBe(true); + expect(url.searchParams.get('page_token')).toBe(''); + return HttpResponse.json({ + data: [ + { + id: 3669, + title: 'Teaching Clips', + description: null, + type: 'TEACHING_CLIPS', + total: 1, + videos: ['52186'], + }, + ], + next_page_token: '', + }); + } + if (language === 'it') return new HttpResponse(null, { status: 200 }); + expect(language).toBe('de'); + return new HttpResponse(null, { status: 204 }); + }, + ), + ); + + await expect( + videos.getPlaylist(organizationId, 3669, { acceptLanguage: 'es' }), + ).resolves.toEqual({ + id: 3669, + title: 'Clips de enseñanza', + description: null, + type: 'TEACHING_CLIPS', + total: 1, + videos: ['52186'], + }); + await expect(videos.getPlaylists(organizationId, { pageToken: '' })).resolves.toEqual({ + data: [ + { + id: 3669, + title: 'Teaching Clips', + description: null, + type: 'TEACHING_CLIPS', + total: 1, + videos: ['52186'], + }, + ], + next_page_token: '', + }); + await expect(videos.getPlaylists(organizationId, { acceptLanguage: 'de' })).resolves.toEqual({ + data: [], + next_page_token: null, + }); + await expect(videos.getPlaylists(organizationId, { acceptLanguage: 'it' })).resolves.toEqual({ + data: [], + next_page_token: null, + }); + }); + + it('preserves thumbnail query bytes while selecting every supported rendition', async () => { + const videos = createVideosClient(); + const thumbnailUrls: ThumbnailFixtures = { + untouched: 'https://cdn.example/video.jpg?signature=a%20b&flag#frame', + default: 'https://cdn.example/video.jpg?size=thumb&size=card&token=one#frame', + thumb: 'https://cdn.example/video.jpg?size=card&signature=a%20b&flag#frame', + full: 'https://cdn.example/video.jpg?size=thumb&token=one#frame', + null: null, + }; + + server.use( + http.get(`https://${apiHost}/v1/videos/:videoId`, ({ params, request }) => { + expect(request.headers.has('Accept-Language')).toBe(false); + const videoId = String(params.videoId); + return HttpResponse.json({ + id: `returned-${videoId}`, + thumbnail: { url: thumbnailUrls[videoId], width: null, height: null }, + playback_sources: [], + playback_preview_sources: [], + }); + }), + ); + + const untouched = await videos.getVideo('untouched'); + const defaultSize = await videos.getVideo('default'); + const thumbnail = await videos.getVideo('thumb', { thumbnailSize: 'thumb' }); + const full = await videos.getVideo('full', { thumbnailSize: 'full' }); + const noThumbnailUrl = await videos.getVideo('null'); + + expect(untouched.thumbnail?.url).toBe( + 'https://cdn.example/video.jpg?signature=a%20b&flag#frame', + ); + expect(defaultSize.thumbnail?.url).toBe('https://cdn.example/video.jpg?token=one#frame'); + expect(thumbnail.thumbnail?.url).toBe( + 'https://cdn.example/video.jpg?signature=a%20b&flag&size=thumb#frame', + ); + expect(full.thumbnail?.url).toBe('https://cdn.example/video.jpg?token=one&size=full#frame'); + expect(noThumbnailUrl.thumbnail).toEqual({ url: null, width: null, height: null }); + }); + + it('decodes absent and null metadata while rejecting missing required video fields', async () => { + const videos = createVideosClient(); + const required = { id: 'returned-id', playback_sources: [], playback_preview_sources: [] }; + const optional = { + title: null, + description: null, + passage_id: null, + passage_ids: null, + organization_id: null, + references: null, + language_tag: null, + runtime: null, + orientation: null, + thumbnail: null, + share_url: null, + }; + for (const payload of [required, { ...required, ...optional }]) { + server.use( + http.get(`https://${apiHost}/v1/videos/:videoId`, () => HttpResponse.json(payload)), + ); + await expect(videos.getVideo('requested-id')).resolves.toEqual(payload); + } + for (const field of ['id', 'playback_sources', 'playback_preview_sources']) { + for (const payload of [ + Object.fromEntries(Object.entries(required).filter(([name]) => name !== field)), + { ...required, [field]: null }, + ]) { + server.use( + http.get(`https://${apiHost}/v1/videos/:videoId`, () => HttpResponse.json(payload)), + ); + await expect(videos.getVideo('requested-id')).rejects.toThrow( + 'Unexpected videos API response', + ); + } + } + for (const payload of [ + { ...required, runtime: 1.5 }, + { ...required, playback_sources: [{ url: 'https://cdn.example/video.m3u8' }] }, + ]) { + server.use( + http.get(`https://${apiHost}/v1/videos/:videoId`, () => HttpResponse.json(payload)), + ); + await expect(videos.getVideo('requested-id')).rejects.toThrow( + 'Unexpected videos API response', + ); + } + }); + + it('treats null playlist cursors as omitted with camelCase options', async () => { + const videos = createVideosClient(); + const organizationId = '550e8400-e29b-41d4-a716-446655440000'; + const requests: string[] = []; + server.use( + http.get(`https://${apiHost}/v1/organizations/:organizationId/playlists`, ({ request }) => { + const url = new URL(request.url); + requests.push(request.url); + expect(url.searchParams.has('page_token')).toBe(false); + expect(url.searchParams.get('page_size')).toBe('1'); + expect(url.searchParams.getAll('fields[]')).toEqual(['id']); + expect(request.headers.get('Accept-Language')).toBe('fr'); + return HttpResponse.json({ data: [{ id: 7 }], next_page_token: null }); + }), + ); + const first = await videos.getPlaylists(organizationId, { + fields: ['id'], + pageSize: 1, + acceptLanguage: 'fr', + }); + await expect( + videos.getPlaylists(organizationId, { + fields: ['id'], + pageSize: 1, + pageToken: null, + acceptLanguage: 'fr', + }), + ).resolves.toEqual(first); + expect(requests).toHaveLength(2); + expect(requests[1]).toBe(requests[0]); + }); + + it('validates playlist inputs and full detail responses while preserving HTTP status errors', async () => { + const videos = createVideosClient(); + const organizationId = '550e8400-e29b-41d4-a716-446655440000'; + const fetchSpy = vi.spyOn(global, 'fetch'); + + try { + server.use( + http.get( + `https://${apiHost}/v1/organizations/:organizationId/playlists/:playlistId`, + ({ params }) => { + expect(params.organizationId).toBe(organizationId); + return HttpResponse.json({ id: 3669 }); + }, + ), + http.get(`https://${apiHost}/v1/organizations/:organizationId/playlists`, ({ request }) => { + const pageToken = new URL(request.url).searchParams.get('page_token'); + if (pageToken === 'null-body') return HttpResponse.json(null); + if (pageToken === 'forbidden') return new HttpResponse(null, { status: 403 }); + if (pageToken === 'json-string') return HttpResponse.json(''); + return HttpResponse.json({ + data: [ + { + id: 2_147_483_648, + title: 'Out of range', + description: null, + type: 'TEACHING_CLIPS', + total: 0, + videos: [], + }, + ], + next_page_token: null, + }); + }), + http.get(`https://${apiHost}/v1/videos/missing`, () => + HttpResponse.json({ message: 'not found' }, { status: 404 }), + ), + ); + + await expect(videos.getPlaylists('not-a-uuid')).rejects.toThrow( + 'Organization ID must be a valid UUID', + ); + await expect(videos.getPlaylists(organizationId, { pageSize: '*' })).rejects.toThrow( + 'pageSize="*" requires 1-3 fields to be specified', + ); + await expect( + videos.getPlaylists(organizationId, { + pageSize: '*', + fields: ['id', 'title', 'total', 'videos'], + }), + ).rejects.toThrow('requires 1-3 fields'); + await expect(videos.getPlaylists(organizationId, { pageSize: 0 })).rejects.toThrow( + 'Page size must be an integer from 1 to 99', + ); + await expect(videos.getPlaylists(organizationId, { pageSize: 100 })).rejects.toThrow( + 'Page size must be an integer from 1 to 99', + ); + await expect(videos.getPlaylist(organizationId, 2_147_483_648)).rejects.toThrow( + 'Playlist ID must be a 32-bit integer', + ); + // @ts-expect-error verifies runtime validation for unsafe JavaScript callers + await expect(videos.getPlaylists(organizationId, null)).rejects.toMatchObject({ + name: '$ZodError', + }); + await expect(videos.getVideo(' ')).rejects.toThrow('Video ID must be a non-empty string'); + await expect(videos.getVideo('..')).rejects.toThrow('Video ID must not be a URL dot segment'); + await expect(videos.getVideo('\ud800')).rejects.toThrow( + 'Video ID must contain valid Unicode', + ); + expect(fetchSpy).not.toHaveBeenCalled(); + + await expect( + videos.getPlaylists(organizationId, { pageToken: 'forbidden' }), + ).rejects.toMatchObject({ status: 403 }); + + await expect( + videos.getPlaylists(organizationId, { pageToken: 'out-of-range' }), + ).rejects.toThrow('Unexpected playlists API response'); + await expect(videos.getPlaylists(organizationId, { pageToken: 'null-body' })).rejects.toThrow( + 'Unexpected playlists API response', + ); + await expect( + videos.getPlaylists(organizationId, { pageToken: 'json-string' }), + ).rejects.toThrow('Unexpected playlists API response'); + await expect(videos.getPlaylist(organizationId, 3669)).rejects.toThrow( + 'Unexpected playlists API response', + ); + try { + await videos.getVideo('missing'); + throw new Error('expected getVideo to reject'); + } catch (error) { + expect(getHttpStatus(error)).toBe(404); + } + } finally { + fetchSpy.mockRestore(); + } + }); +}); diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index b7d7a69a9..f340f2f56 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -10,6 +10,7 @@ type JsonPrimitive = string | number | boolean; type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }; type RequestData = Record; type RequestHeaders = Record; +type ApiResponse = Readonly<{ data: T; emptyBody: boolean; status: number }>; const HttpStatusCarrierSchema = object({ status: z.number(), @@ -88,7 +89,7 @@ export class ApiClient { /** * Makes an HTTP request with timeout support */ - private async request(url: string, options: RequestInit = {}): Promise { + private async request(url: string, options: RequestInit = {}): Promise> { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), this.timeout); @@ -152,16 +153,16 @@ export class ApiClient { if (!text) { // SAFETY: empty 2xx JSON bodies (DELETE 200 with no payload) are // treated as undefined for the caller-owned generic T. - return undefined as T; + return { data: undefined as T, emptyBody: true, status: response.status }; } // SAFETY: this client only decodes JSON text. Callers own T and parse // untrusted payloads with Zod at their boundary. - return JSON.parse(text) as T; + return { data: JSON.parse(text) as T, emptyBody: false, status: response.status }; } else { const text = await response.text(); // SAFETY: non-JSON 2xx bodies are returned as raw text. Callers that // asked for T=string receive it; other T values are caller-owned. - return text as T; + return { data: text as T, emptyBody: text.length === 0, status: response.status }; } } catch (error) { clearTimeout(timeoutId); @@ -181,6 +182,20 @@ export class ApiClient { * @returns A promise resolving to the response data of type T. */ async get(path: string, params?: QueryParams, headers?: RequestHeaders): Promise { + const url = `${this.baseURL}${path}${this.buildQueryString(params)}`; + const response = await this.request(url, { + method: 'GET', + headers, + }); + return response.data; + } + + /** @internal GET variant for endpoint clients that must inspect a successful status. */ + async getWithStatus( + path: string, + params?: QueryParams, + headers?: RequestHeaders, + ): Promise> { const url = `${this.baseURL}${path}${this.buildQueryString(params)}`; return this.request(url, { method: 'GET', @@ -205,11 +220,12 @@ export class ApiClient { headers?: RequestHeaders, ): Promise { const url = `${this.baseURL}${path}${this.buildQueryString(params)}`; - return this.request(url, { + const response = await this.request(url, { method: 'POST', body: data ? JSON.stringify(data) : undefined, headers, }); + return response.data; } /** @@ -223,9 +239,10 @@ export class ApiClient { */ async delete(path: string, params?: QueryParams, headers?: RequestHeaders): Promise { const url = `${this.baseURL}${path}${this.buildQueryString(params)}`; - return this.request(url, { + const response = await this.request(url, { method: 'DELETE', headers, }); + return response.data; } } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a8193c941..4db1c5218 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -32,12 +32,14 @@ export { type SearchImagesOptions, type SearchUnifiedOptions, type SearchVersesOptions, + type SearchVideosOptions, } from './search'; export { getSuggestedQueries, getTrendingQueries } from './search-queries'; export { searchImages } from './search-images'; export { searchVerses } from './search-verses'; export { searchTopics } from './search-topics'; export { searchUnified } from './search-unified'; +export { searchVideos } from './search-videos'; export { MAX_SEARCH_QUERY_GRAPHEMES, clampSearchText, @@ -47,6 +49,12 @@ export { parseSearchLanguageRange } from './schemas/language-range'; export { parseUsfmReference, type UsfmReference } from './usfm-reference'; export { OrganizationsClient } from './organizations'; export { ImagesClient } from './images'; +export { + VideosClient, + type GetPlaylistOptions, + type GetPlaylistsOptions, + type GetVideoOptions, +} from './videos'; export { HighlightsClient, type GetHighlightsOptions, diff --git a/packages/core/src/schemas/index.ts b/packages/core/src/schemas/index.ts index 2cea84b5b..bda981381 100644 --- a/packages/core/src/schemas/index.ts +++ b/packages/core/src/schemas/index.ts @@ -14,6 +14,7 @@ export * from './organization'; export * from './passage'; export * from './passage-display'; export * from './search'; +export * from './search-videos'; export * from './version'; export * from './verse'; export * from './video'; diff --git a/packages/core/src/schemas/search-videos.ts b/packages/core/src/schemas/search-videos.ts new file mode 100644 index 000000000..9c911ea4d --- /dev/null +++ b/packages/core/src/schemas/search-videos.ts @@ -0,0 +1,40 @@ +import * as z from 'zod/mini'; +import { object } from './object'; +import { OrganizationIdSchema } from './organization'; +import { ContentLibraryVideoSchema } from './video-resource'; +import { SearchTextQuerySchema } from './search'; + +export const SearchVideosQuerySchema = SearchTextQuerySchema; + +export const SearchVideosOptionsSchema = object({ + /** Publisher filters combined with OR. Omit or pass an empty array for no filter. */ + organizationIds: z.optional(z.readonly(z.array(OrganizationIdSchema))), + /** Language preference. Defaults to English. */ + acceptLanguage: z.optional(z.string().check(z.minLength(1))), + /** Results per page, from 1 through 99. */ + pageSize: z.optional(z.int().check(z.gte(1), z.lte(99))), + /** Opaque cursor. Omit or pass null for the first page; empty strings are preserved. */ + pageToken: z.optional(z.nullable(z.string())), +}); + +export type SearchVideosOptions = z.infer; + +export const SearchVideosWireSchema = object({ + videos: z.array(ContentLibraryVideoSchema), + user_intent: z.optional(z.nullable(z.string())), + did_you_mean: z.array(z.string()), + search_instead_for: z.optional(z.nullable(z.string())), + next_page_token: z.optional(z.nullable(z.string())), +}); + +export type SearchVideosWire = z.infer; + +export const SearchVideosResponseSchema = object({ + videos: z.array(ContentLibraryVideoSchema), + userIntent: z.optional(z.string()), + didYouMean: z.array(z.string()), + searchInsteadFor: z.nullable(z.string()), + nextPageToken: z.nullable(z.string()), +}); + +export type SearchVideosResponse = Readonly>; diff --git a/packages/core/src/schemas/search.ts b/packages/core/src/schemas/search.ts index ea2029f6f..d4a8042ca 100644 --- a/packages/core/src/schemas/search.ts +++ b/packages/core/src/schemas/search.ts @@ -1,6 +1,7 @@ import * as z from 'zod/mini'; import { object } from './object'; import { parseUsfmReference } from '../usfm-reference'; +import { VideoIdSchema } from './video-id'; export const MAX_SEARCH_QUERY_GRAPHEMES = 100; @@ -228,12 +229,14 @@ export const SearchVersesOptionsSchema = object({ export type SearchVersesOptions = z.infer; -const SEARCH_UNIFIED_FIELDS = ['verses', 'topics', 'images'] as const; +const SEARCH_UNIFIED_FIELDS = ['verses', 'topics', 'images', 'videos'] as const; -export type SearchUnifiedField = (typeof SEARCH_UNIFIED_FIELDS)[number]; +export type ContentLibrarySearchField = (typeof SEARCH_UNIFIED_FIELDS)[number]; +/** Field selection supported by existing v3 search consumers. */ +export type SearchUnifiedField = Exclude; const SearchUnifiedFieldSchema = z.enum(SEARCH_UNIFIED_FIELDS, { - error: 'Search field must be verses, topics, or images', + error: 'Search field must be verses, topics, images, or videos', }); const SearchUnifiedFieldsSchema = z.pipe( @@ -254,6 +257,9 @@ export type SearchUnifiedOptions = Readonly<{ fields?: readonly SearchUnifiedField[]; }>; +export type ContentLibrarySearchOptions = Omit & + Readonly<{ fields?: readonly ContentLibrarySearchField[] }>; + const SearchUnifiedTopicHitWireSchema = object({ ...SearchTopicWireFields, id: z.nullable(z.int()), @@ -275,6 +281,13 @@ const SearchImageHitWireSchema = object({ type SearchImageHitWire = z.infer; +/** Lightweight video hit. Resolve the opaque id with `VideosClient.getVideo`. */ +export const SearchVideoHitSchema = object({ + id: VideoIdSchema, +}); + +export type SearchVideoHit = Readonly>; + export const SearchUnifiedWireSchema = object({ verses: z.optional(z.array(z.unknown())), topics: z.optional(z.array(z.unknown())), @@ -282,6 +295,7 @@ export const SearchUnifiedWireSchema = object({ did_you_mean: z.optional(z.array(z.string())), search_instead_for: z.optional(z.nullable(z.string())), images: z.optional(z.array(z.unknown())), + videos: z.optional(z.array(z.unknown())), }); export type SearchUnifiedWire = z.infer; @@ -292,18 +306,26 @@ export const SearchUnifiedResponseSchema = object({ topics: z.array(SearchTopicSchema), /** Image hits. Empty id or invalid `passageId` entries are removed. */ images: z.array(SearchImageHitSchema), + /** Video hits containing only opaque ids. */ + videos: z.array(SearchVideoHitSchema), /** Set only when the API returns a non-null user intent. */ userIntent: z.optional(z.string()), didYouMean: z.array(z.string()), searchInsteadFor: z.nullable(z.string()), }); -export type SearchUnifiedResponse = Readonly>; +type NormalizedSearchResponse = Readonly>; + +/** Core supplies video hits. Existing v3 hook overrides may omit them. */ +export type SearchUnifiedResponse = Omit & + Partial>; -type EnsureSearchUnifiedFieldArrays> = T; +type EnsureSearchUnifiedFieldArrays> = T; type _SearchUnifiedFieldCoverage = EnsureSearchUnifiedFieldArrays<{ - [K in SearchUnifiedField]: SearchUnifiedResponse[K] extends readonly unknown[] ? true : false; + [K in ContentLibrarySearchField]: NormalizedSearchResponse[K] extends readonly unknown[] + ? true + : false; }>; function toSearchImageHit(wire: SearchImageHitWire): SearchImageHit | null { @@ -355,8 +377,8 @@ export function toSearchImagesResponse(wire: SearchImagesWire): SearchImagesResp }; } -export function toSearchUnifiedResponse(wire: SearchUnifiedWire): SearchUnifiedResponse { - const response: SearchUnifiedResponse = { +export function toSearchUnifiedResponse(wire: SearchUnifiedWire): NormalizedSearchResponse { + const response: NormalizedSearchResponse = { verses: (wire.verses ?? []).flatMap((hit) => { const parsed = SearchVerseHitWireSchema.safeParse(hit); if (!parsed.success) { @@ -373,6 +395,10 @@ export function toSearchUnifiedResponse(wire: SearchUnifiedWire): SearchUnifiedR return [toSearchTopic(parsed.data)]; }), images: searchImageHits(wire.images ?? []), + videos: (wire.videos ?? []).flatMap((hit) => { + const parsed = SearchVideoHitSchema.safeParse(hit); + return parsed.success ? [parsed.data] : []; + }), didYouMean: wire.did_you_mean ?? [], searchInsteadFor: wire.search_instead_for ?? null, }; diff --git a/packages/core/src/schemas/video-id.ts b/packages/core/src/schemas/video-id.ts new file mode 100644 index 000000000..d4d8e2008 --- /dev/null +++ b/packages/core/src/schemas/video-id.ts @@ -0,0 +1,17 @@ +import * as z from 'zod/mini'; + +function isUriComponentEncodable(value: string): boolean { + try { + encodeURIComponent(value); + return true; + } catch { + return false; + } +} + +/** Opaque video id that can safely occupy one URL path segment. */ +export const VideoIdSchema = z.string().check( + z.refine((value) => value.trim().length > 0, 'Video ID must be a non-empty string'), + z.refine((value) => value !== '.' && value !== '..', 'Video ID must not be a URL dot segment'), + z.refine(isUriComponentEncodable, 'Video ID must contain valid Unicode'), +); diff --git a/packages/core/src/schemas/video-resource.ts b/packages/core/src/schemas/video-resource.ts new file mode 100644 index 000000000..9fd633a14 --- /dev/null +++ b/packages/core/src/schemas/video-resource.ts @@ -0,0 +1,71 @@ +import * as z from 'zod/mini'; +import { object } from './object'; +import { VideoIdSchema } from './video-id'; + +/** A playable video or audio source. */ +export const VideoPlaybackSourceSchema = object({ + /** + * URL for the playable video or audio source. + * + * Intentionally `z.string()`, not `z.url()`: the spec types video source URLs + * as plain strings (no `format: uri`, unlike `FontSource.url`), and playback + * URLs such as HLS manifests / CDN assets shouldn't be constrained by strict + * URL validation. + */ + url: z.string(), + /** Source format. */ + format: z.enum(['hls', 'webm', 'mp4', 'mp3']), +}); + +export type VideoPlaybackSource = Readonly>; + +/** A thumbnail image for a video. */ +export const VideoThumbnailSchema = object({ + /** URL for the thumbnail image. */ + url: z.optional(z.nullable(z.string())), + /** Thumbnail width in pixels. */ + width: z.optional(z.nullable(z.int())), + /** Thumbnail height in pixels. */ + height: z.optional(z.nullable(z.int())), +}); + +export type VideoThumbnail = Readonly>; + +/** Metadata shared by Content Library resources and the legacy v3 video model. */ +export const VideoFields = { + /** Bible references supplied by older video catalogs. */ + references: z.optional(z.nullable(z.array(z.string()))), + /** Video title. */ + title: z.optional(z.nullable(z.string())), + /** Video description. */ + description: z.optional(z.nullable(z.string())), + /** BCP 47 language tag for the video. */ + language_tag: z.optional(z.nullable(z.string())), + /** Runtime in seconds. */ + runtime: z.optional(z.nullable(z.int())), + /** Video orientation. */ + orientation: z.optional(z.nullable(z.enum(['landscape', 'portrait']))), + /** Thumbnail image. */ + thumbnail: z.optional(z.nullable(VideoThumbnailSchema)), + /** Playable video or audio sources. */ + playback_sources: z.array(VideoPlaybackSourceSchema), + /** Preview clip sources. */ + playback_preview_sources: z.array(VideoPlaybackSourceSchema), + /** Share URL for the video. */ + share_url: z.optional(z.nullable(z.string())), +}; + +/** Full Content Library video returned by video detail and dedicated search. */ +export const ContentLibraryVideoSchema = object({ + ...VideoFields, + /** Opaque video identifier. Pass it to `VideosClient.getVideo` unchanged. */ + id: VideoIdSchema, + /** Bible passage associated with the video (e.g., `1SA.17.45`). */ + passage_id: z.optional(z.nullable(z.string())), + /** Bible passages associated with the video in the newer resource contract. */ + passage_ids: z.optional(z.nullable(z.array(z.string()))), + /** Publisher organization identifier. */ + organization_id: z.optional(z.nullable(z.uuid())), +}); + +export type ContentLibraryVideo = Readonly>; diff --git a/packages/core/src/schemas/video.ts b/packages/core/src/schemas/video.ts index 4557d54ce..08e5c697d 100644 --- a/packages/core/src/schemas/video.ts +++ b/packages/core/src/schemas/video.ts @@ -1,59 +1,118 @@ import * as z from 'zod/mini'; import { object } from './object'; +import { VideoIdSchema } from './video-id'; +import { VideoFields } from './video-resource'; -/** A playable video or audio source. */ -export const VideoPlaybackSourceSchema = object({ - /** - * URL for the playable video or audio source. - * - * Intentionally `z.string()`, not `z.url()`: the spec types video source URLs - * as plain strings (no `format: uri`, unlike `FontSource.url`), and playback - * URLs such as HLS manifests / CDN assets shouldn't be constrained by strict - * URL validation. - */ - url: z.string(), - /** Source format. */ - format: z.enum(['hls', 'webm', 'mp4', 'mp3']), +export { VideoIdSchema }; +export { + ContentLibraryVideoSchema, + VideoPlaybackSourceSchema, + VideoThumbnailSchema, +} from './video-resource'; +export type { ContentLibraryVideo, VideoPlaybackSource, VideoThumbnail } from './video-resource'; + +const LegacyVideoSchema = object({ + ...VideoFields, + /** Legacy numeric video identifier. */ + id: z.number(), }); -export type VideoPlaybackSource = Readonly>; +/** Legacy v3 video model with numeric IDs and Bible references. */ +export type Video = Readonly>; + +/** Supported thumbnail renditions. Omit the option for the full-size image. */ +export const VideoThumbnailSizeSchema = z.enum(['thumb', 'card', 'full']); + +export type VideoThumbnailSize = z.infer; -/** A thumbnail image for a video. */ -export const VideoThumbnailSchema = object({ - /** URL for the thumbnail image. */ - url: z.optional(z.nullable(z.string())), - /** Thumbnail width in pixels. */ - width: z.optional(z.nullable(z.int())), - /** Thumbnail height in pixels. */ - height: z.optional(z.nullable(z.int())), +export const GetVideoOptionsSchema = object({ + /** Language preference sent as `Accept-Language`. Omit to use the runtime's default. */ + acceptLanguage: z.optional(z.string().check(z.minLength(1))), + /** Requested thumbnail rendition. Omit for the full-size image. */ + thumbnailSize: z.optional(VideoThumbnailSizeSchema), }); -export type VideoThumbnail = Readonly>; - -/** A dark-launched video resource approved for Platform consumers. */ -export const VideoSchema = object({ - /** Video identifier. */ - id: z.int(), - /** Video title. */ - title: z.optional(z.nullable(z.string())), - /** Video description. */ - description: z.optional(z.nullable(z.string())), - /** Bible references associated with the video (e.g., ["1SA.17.45"]). */ - references: z.optional(z.nullable(z.array(z.string()))), - /** BCP 47 language tag for the video. */ - language_tag: z.optional(z.nullable(z.string())), - /** Runtime in seconds. */ - runtime: z.optional(z.nullable(z.int())), - /** Video orientation. */ - orientation: z.optional(z.nullable(z.enum(['landscape', 'portrait']))), - /** Thumbnail image. */ - thumbnail: z.optional(z.nullable(VideoThumbnailSchema)), - /** Playable video or audio sources. */ - playback_sources: z.array(VideoPlaybackSourceSchema), - /** Preview clip sources. */ - playback_preview_sources: z.array(VideoPlaybackSourceSchema), - /** Share URL for the video. */ - share_url: z.optional(z.nullable(z.string())), +export type GetVideoOptions = z.infer; + +const PLAYLIST_ID_ERROR = 'Playlist ID must be a 32-bit integer'; + +export const VideoPlaylistIdSchema = z + .int({ error: PLAYLIST_ID_ERROR }) + .check(z.gte(-2_147_483_648, PLAYLIST_ID_ERROR), z.lte(2_147_483_647, PLAYLIST_ID_ERROR)); + +/** Full playlist wire shape used when field selection is not active. */ +const VideoPlaylistFields = { + id: VideoPlaylistIdSchema, + title: z.string(), + description: z.nullable(z.string()), + type: z.string(), + total: z.int(), + videos: z.array(VideoIdSchema), +}; + +export const VideoPlaylistFullSchema = object(VideoPlaylistFields); + +/** A video playlist. Fields are optional because collection field selection can omit any field. */ +export const VideoPlaylistSchema = object({ + /** Playlist identifier. */ + id: z.optional(VideoPlaylistFields.id), + /** Localized playlist title. */ + title: z.optional(VideoPlaylistFields.title), + /** Localized description, or null when the playlist has none. */ + description: z.optional(VideoPlaylistFields.description), + /** Upstream playlist type. */ + type: z.optional(VideoPlaylistFields.type), + /** Number of videos in the playlist. */ + total: z.optional(VideoPlaylistFields.total), + /** Ordered opaque video ids. */ + videos: z.optional(VideoPlaylistFields.videos), +}); + +export type VideoPlaylist = Readonly>; + +export const VideoPlaylistFieldSchema = z.keyof(VideoPlaylistSchema); +export type VideoPlaylistField = z.infer; + +const PlaylistNextPageTokenSchema = z.pipe( + z.optional(z.nullable(z.string())), + z.transform((token): string | null => token ?? null), +); + +export const VideoPlaylistCollectionSchema = object({ + data: z.array(VideoPlaylistSchema), + next_page_token: PlaylistNextPageTokenSchema, +}); + +export const VideoPlaylistFullCollectionSchema = object({ + data: z.array(VideoPlaylistFullSchema), + next_page_token: PlaylistNextPageTokenSchema, +}); + +const PLAYLIST_PAGE_SIZE_ERROR = 'Page size must be an integer from 1 to 99, or "*"'; + +export const GetPlaylistsOptionsSchema = object({ + /** Fields to include. Omit for full resources; wildcard page size requires 1–3 fields. */ + fields: z.optional(z.array(VideoPlaylistFieldSchema).check(z.minLength(1))), + /** Results per page (1–99), or "*" with 1–3 selected fields. */ + pageSize: z.optional( + z.union([ + z + .int({ error: PLAYLIST_PAGE_SIZE_ERROR }) + .check(z.gte(1, PLAYLIST_PAGE_SIZE_ERROR), z.lte(99, PLAYLIST_PAGE_SIZE_ERROR)), + z.literal('*'), + ]), + ), + /** Opaque cursor. Omit or pass null for the first page; empty strings are preserved. */ + pageToken: z.optional(z.nullable(z.string())), + /** Accept-Language preference. Defaults to English. */ + acceptLanguage: z.optional(z.string().check(z.minLength(1))), +}); + +export type GetPlaylistsOptions = z.infer; + +export const GetPlaylistOptionsSchema = object({ + /** Accept-Language preference. Defaults to English. */ + acceptLanguage: z.optional(z.string().check(z.minLength(1))), }); -export type Video = Readonly>; +export type GetPlaylistOptions = z.infer; diff --git a/packages/core/src/search-unified.ts b/packages/core/src/search-unified.ts index 593681479..7cd93ce74 100644 --- a/packages/core/src/search-unified.ts +++ b/packages/core/src/search-unified.ts @@ -6,7 +6,8 @@ import { SearchUnifiedOptionsSchema, SearchUnifiedWireSchema, toSearchUnifiedResponse, - type SearchUnifiedField, + type ContentLibrarySearchField, + type ContentLibrarySearchOptions, type SearchUnifiedOptions, type SearchUnifiedResponse, } from './schemas/search'; @@ -18,22 +19,23 @@ type SearchUnifiedQuery = { bible_id: number; 'language_ranges[]': string[]; user_intent?: string; - 'fields[]'?: SearchUnifiedField[]; + 'fields[]'?: ContentLibrarySearchField[]; }; /** - * Searches verses and topics in one unpaginated request. + * Searches verses, topics, images, and lightweight video ids in one unpaginated request. + * Video search requires an app key with access to the video catalog. * @param query Search text (1 to 100 graphemes). * @param versionId Bible version identifier (sent to the API as `bible_id`). * @param languageRanges Ordered language ranges (`en_US` is normalized to `en-us` on the wire). - * @param options Optional `userIntent` and nonempty `fields` selection (`verses` or `topics`). + * @param options Optional `userIntent` and nonempty `fields` selection. */ export async function searchUnified( client: ApiClient, query: string, versionId: number, languageRanges: string | readonly string[], - options: SearchUnifiedOptions = {}, + options: ContentLibrarySearchOptions = {}, ): Promise { const parsedQuery = SearchTextQuerySchema.parse(query); BibleVersionIdSchema.parse(versionId); diff --git a/packages/core/src/search-videos.ts b/packages/core/src/search-videos.ts new file mode 100644 index 000000000..5041d5c93 --- /dev/null +++ b/packages/core/src/search-videos.ts @@ -0,0 +1,58 @@ +import type { ApiClient } from './client'; +import { + SearchVideosOptionsSchema, + SearchVideosQuerySchema, + SearchVideosWireSchema, + type SearchVideosOptions, + type SearchVideosResponse, +} from './schemas/search-videos'; +import { resolveVideoThumbnail } from './video-thumbnail'; + +export type { SearchVideosOptions }; + +type SearchVideosQuery = { + query: string; + 'organization_ids[]'?: string[]; + page_size?: number; + page_token?: string; +}; + +/** + * Searches the video catalog and returns full video resource records. + * When continuing with a page token, repeat the query, organization filters, and + * language from the previous request. The page size may change. A null input + * cursor requests the first page. Language defaults to English, as in the search API. + * Empty pages can have continuation tokens. Continue until `nextPageToken` is + * null. Empty string tokens are preserved unchanged. No total count is returned. + */ +export async function searchVideos( + client: ApiClient, + query: string, + options: SearchVideosOptions = {}, +): Promise { + const parsedQuery = SearchVideosQuerySchema.parse(query); + const parsedOptions = SearchVideosOptionsSchema.parse(options); + const params: SearchVideosQuery = { query: parsedQuery }; + if (parsedOptions.organizationIds !== undefined) { + params['organization_ids[]'] = [...parsedOptions.organizationIds]; + } + if (parsedOptions.pageSize !== undefined) params.page_size = parsedOptions.pageSize; + if (parsedOptions.pageToken != null) params.page_token = parsedOptions.pageToken; + + const body = await client.get('/v1/search-videos', params, { + 'Accept-Language': parsedOptions.acceptLanguage ?? 'en', + }); + const parsed = SearchVideosWireSchema.safeParse(body); + if (!parsed.success) { + throw new Error(`Unexpected search-videos API response: ${parsed.error.message}`); + } + const response: SearchVideosResponse = { + videos: parsed.data.videos.map((video) => resolveVideoThumbnail(video)), + didYouMean: parsed.data.did_you_mean, + searchInsteadFor: parsed.data.search_instead_for ?? null, + nextPageToken: parsed.data.next_page_token ?? null, + }; + return parsed.data.user_intent == null + ? response + : { ...response, userIntent: parsed.data.user_intent }; +} diff --git a/packages/core/src/search.ts b/packages/core/src/search.ts index 4db0c3f1d..74cd25cd8 100644 --- a/packages/core/src/search.ts +++ b/packages/core/src/search.ts @@ -3,16 +3,19 @@ import { getSuggestedQueries, getTrendingQueries } from './search-queries'; import { searchTopics } from './search-topics'; import { searchUnified, type SearchUnifiedOptions } from './search-unified'; import { searchImages, type SearchImagesOptions } from './search-images'; +import { searchVideos, type SearchVideosOptions } from './search-videos'; import { searchVerses, type SearchVersesOptions } from './search-verses'; import type { + ContentLibrarySearchOptions, SearchImagesResponse, SearchQueries, SearchTopicsResponse, SearchUnifiedResponse, SearchVersesResponse, } from './schemas/search'; +import type { SearchVideosResponse } from './schemas/search-videos'; -export type { SearchImagesOptions, SearchUnifiedOptions, SearchVersesOptions }; +export type { SearchImagesOptions, SearchUnifiedOptions, SearchVersesOptions, SearchVideosOptions }; /** * Client for YouVersion Platform Search API endpoints (`/v1/*`). @@ -79,6 +82,17 @@ export class SearchClient { return searchImages(this.client, query, versionId, options); } + /** + * Searches video metadata through `/v1/search-videos`. + * Send the same query, organization filters, and language with a continuation + * token; `pageSize` may change. Language defaults to English. + * Empty pages can have continuation tokens. Continue until `nextPageToken` is + * null. Empty string tokens are preserved unchanged. No total count is returned. + */ + async searchVideos(query: string, options?: SearchVideosOptions): Promise { + return searchVideos(this.client, query, options); + } + /** * Returns topics related to a query. This endpoint is unpaginated. * @param query Search text (1–100 characters). @@ -92,18 +106,19 @@ export class SearchClient { } /** - * Searches verses, topics, and images in one unpaginated request. + * Searches verses, topics, images, and lightweight video ids in one unpaginated request. * Image hits are `id` and `passageId` only. + * Video search requires an app key with access to the video catalog. * @param query Search text (1 to 100 graphemes). * @param versionId Bible version identifier (sent to the API as `bible_id`). * @param languageRanges Ordered language ranges (`en_US` is normalized to `en-us` on the wire). - * @param options Optional `userIntent` and `fields` (`verses`, `topics`, or `images`). + * @param options Optional `userIntent` and `fields` (`verses`, `topics`, `images`, or `videos`). */ async searchUnified( query: string, versionId: number, languageRanges: string | readonly string[], - options?: SearchUnifiedOptions, + options?: ContentLibrarySearchOptions, ): Promise { return searchUnified(this.client, query, versionId, languageRanges, options); } diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 3c014041d..efd8ce8ef 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -27,6 +27,8 @@ export type { Language } from '../schemas/language'; export type { User } from '../schemas/user'; export type { Highlight, CreateHighlight } from '../schemas/highlight'; export type { + ContentLibrarySearchField, + ContentLibrarySearchOptions, KnownSearchUserIntent, SearchImagesOptions, SearchImagesResponse, @@ -41,11 +43,24 @@ export type { SearchVerseHit, SearchVersesOptions, SearchVersesResponse, + SearchVideoHit, } from '../schemas/search'; +export type { SearchVideosOptions, SearchVideosResponse } from '../schemas/search-videos'; export type { Collection } from '../schemas/collection'; export type { Organization, OrganizationAddress } from '../schemas/organization'; export type { VerseImage, GetImagesOptions } from '../schemas/image'; -export type { Video, VideoPlaybackSource, VideoThumbnail } from '../schemas/video'; +export type { + GetVideoOptions, + GetPlaylistOptions, + GetPlaylistsOptions, + ContentLibraryVideo, + Video, + VideoPlaylist, + VideoPlaylistField, + VideoPlaybackSource, + VideoThumbnail, + VideoThumbnailSize, +} from '../schemas/video'; export type { Font, FontVariant, FontSource } from '../schemas/font'; export type { License } from '../schemas/license'; export type { AppSummary } from '../schemas/app'; diff --git a/packages/core/src/video-thumbnail.ts b/packages/core/src/video-thumbnail.ts new file mode 100644 index 000000000..55423ec14 --- /dev/null +++ b/packages/core/src/video-thumbnail.ts @@ -0,0 +1,49 @@ +import type { ContentLibraryVideo } from './schemas/video-resource'; +import type { VideoThumbnailSize } from './schemas/video'; + +/** @internal Response normalization shared by video detail and video search. */ +export function resolveVideoThumbnail( + video: ContentLibraryVideo, + size?: VideoThumbnailSize, +): ContentLibraryVideo { + if (video.thumbnail?.url == null) { + return video; + } + const resolvedUrl = withThumbnailSize(video.thumbnail.url, size); + if (resolvedUrl === video.thumbnail.url) { + return video; + } + return { ...video, thumbnail: { ...video.thumbnail, url: resolvedUrl } }; +} + +function withThumbnailSize(url: string, size?: VideoThumbnailSize): string { + const fragmentIndex = url.indexOf('#'); + const fragment = fragmentIndex === -1 ? '' : url.slice(fragmentIndex); + const beforeFragment = fragmentIndex === -1 ? url : url.slice(0, fragmentIndex); + const queryIndex = beforeFragment.indexOf('?'); + const resource = queryIndex === -1 ? beforeFragment : beforeFragment.slice(0, queryIndex); + const rawQuery = queryIndex === -1 ? '' : beforeFragment.slice(queryIndex + 1); + const parameters = rawQuery === '' ? [] : rawQuery.split('&'); + if (size === undefined && !parameters.some(isSizeParameter)) { + return url; + } + const keptParameters = parameters.filter((parameter) => !isSizeParameter(parameter)); + + if (size !== undefined) { + keptParameters.push(`size=${size}`); + } + if (keptParameters.length === 0) { + return `${resource}${fragment}`; + } + return `${resource}?${keptParameters.join('&')}${fragment}`; +} + +function isSizeParameter(parameter: string): boolean { + const equalsIndex = parameter.indexOf('='); + const encodedName = equalsIndex === -1 ? parameter : parameter.slice(0, equalsIndex); + try { + return decodeURIComponent(encodedName.replaceAll('+', ' ')) === 'size'; + } catch { + return false; + } +} diff --git a/packages/core/src/videos.ts b/packages/core/src/videos.ts new file mode 100644 index 000000000..fbeb22935 --- /dev/null +++ b/packages/core/src/videos.ts @@ -0,0 +1,160 @@ +import type { ApiClient } from './client'; +import { + GetPlaylistOptionsSchema, + GetPlaylistsOptionsSchema, + GetVideoOptionsSchema, + VideoIdSchema, + VideoPlaylistCollectionSchema, + VideoPlaylistFullCollectionSchema, + VideoPlaylistFullSchema, + VideoPlaylistIdSchema, + ContentLibraryVideoSchema, + type GetPlaylistOptions, + type GetPlaylistsOptions, + type GetVideoOptions, + type ContentLibraryVideo, + type VideoPlaylist, + type VideoPlaylistField, +} from './schemas/video'; +import { OrganizationIdSchema } from './schemas/organization'; +import type { Collection } from './types'; +import { resolveVideoThumbnail } from './video-thumbnail'; + +export type { GetPlaylistOptions, GetPlaylistsOptions, GetVideoOptions }; + +const VIDEOS_PATH = '/v1/videos'; + +type PlaylistsQuery = { + 'fields[]'?: VideoPlaylistField[]; + page_size?: number | '*'; + page_token?: string; +}; + +/** + * Client for video detail and playlist resources. Requires an app key with catalog access. + * + * Playlist requests explicitly default to English for YPE-6461, which can return + * a cached empty catalog when the language header is absent. Explicit caller + * preferences are honored. Video details preserve the runtime's language default. + * + * Failures: + * - Invalid options or IDs throw schema errors before a request. + * - Playlist collection 204 or empty wire bodies return an empty collection. + * - Nonempty malformed payloads, including JSON null, throw contract errors. + * - Detail calls require a resource body; a 204 or empty body rejects. + * - Non-2xx responses throw; read their status with `getHttpStatus`. + */ +export class VideosClient { + private client: ApiClient; + + /** @param client The API client to use for requests. */ + constructor(client: ApiClient) { + this.client = client; + } + + /** + * Fetches one video by its opaque id. + * + * If `acceptLanguage` is omitted, browsers may send the user's locale while + * non-browser runtimes may send no language preference. + * + * @param videoId A video id returned by search or a playlist. Pass it unchanged. + * @param options Language and thumbnail rendition preferences. + * @returns The validated video with a ready-to-use thumbnail URL. + * @throws An error with status 404 for an unknown or expired opaque id. A 404 + * can also mean the app has not accepted the Extra-Biblical Content agreement. + * Read the status with `getHttpStatus`. + */ + async getVideo(videoId: string, options: GetVideoOptions = {}): Promise { + const id = VideoIdSchema.parse(videoId); + const parsedOptions = GetVideoOptionsSchema.parse(options); + const headers = parsedOptions.acceptLanguage + ? { 'Accept-Language': parsedOptions.acceptLanguage } + : undefined; + const body = await this.client.get( + `${VIDEOS_PATH}/${encodeURIComponent(id)}`, + undefined, + headers, + ); + const parsed = ContentLibraryVideoSchema.safeParse(body); + if (!parsed.success) { + throw new Error(`Unexpected videos API response: ${parsed.error.message}`); + } + return resolveVideoThumbnail(parsed.data, parsedOptions.thumbnailSize); + } + + /** + * Lists an organization's localized video playlists. + * @param organizationId Organization UUID. + * @param options Field selection, pagination, and language. Language defaults to English. + * `pageSize: '*'` requires one to three selected fields. + * @returns One page, or an empty page when no language catalog matches. + * @throws Invalid input, malformed nonempty payloads (including JSON null), or + * HTTP errors. Read HTTP status with `getHttpStatus`. + */ + async getPlaylists( + organizationId: string, + options: GetPlaylistsOptions = {}, + ): Promise> { + const id = OrganizationIdSchema.parse(organizationId); + const parsedOptions = GetPlaylistsOptionsSchema.parse(options); + if ( + parsedOptions.pageSize === '*' && + (parsedOptions.fields === undefined || parsedOptions.fields.length > 3) + ) { + throw new Error('pageSize="*" requires 1-3 fields to be specified'); + } + const query: PlaylistsQuery = {}; + if (parsedOptions.fields !== undefined) query['fields[]'] = parsedOptions.fields; + if (parsedOptions.pageSize !== undefined) query.page_size = parsedOptions.pageSize; + if (parsedOptions.pageToken != null) query.page_token = parsedOptions.pageToken; + + const response = await this.client.getWithStatus( + `/v1/organizations/${encodeURIComponent(id)}/playlists`, + query, + { 'Accept-Language': parsedOptions.acceptLanguage ?? 'en' }, + ); + if (response.status === 204 || response.emptyBody) { + return { data: [], next_page_token: null }; + } + const body = response.data; + const parsed = ( + parsedOptions.fields === undefined + ? VideoPlaylistFullCollectionSchema + : VideoPlaylistCollectionSchema + ).safeParse(body); + if (!parsed.success) { + throw new Error(`Unexpected playlists API response: ${parsed.error.message}`); + } + return parsed.data; + } + + /** + * Fetches one full localized playlist. Language defaults to English. + * @param organizationId Publisher organization UUID. + * @param playlistId Numeric playlist identifier. + * @param options Accept-Language preference. + * @returns The validated full playlist, with every resource field present. + * @throws Invalid input, malformed/empty responses, or HTTP errors. Read HTTP + * status with `getHttpStatus`. + */ + async getPlaylist( + organizationId: string, + playlistId: number, + options: GetPlaylistOptions = {}, + ): Promise>> { + const organization = OrganizationIdSchema.parse(organizationId); + const playlist = VideoPlaylistIdSchema.parse(playlistId); + const parsedOptions = GetPlaylistOptionsSchema.parse(options); + const body = await this.client.get( + `/v1/organizations/${encodeURIComponent(organization)}/playlists/${playlist}`, + undefined, + { 'Accept-Language': parsedOptions.acceptLanguage ?? 'en' }, + ); + const parsed = VideoPlaylistFullSchema.safeParse(body); + if (!parsed.success) { + throw new Error(`Unexpected playlists API response: ${parsed.error.message}`); + } + return parsed.data; + } +} diff --git a/packages/core/tsconfig.build.json b/packages/core/tsconfig.build.json index 469441048..5f7156a64 100644 --- a/packages/core/tsconfig.build.json +++ b/packages/core/tsconfig.build.json @@ -6,7 +6,8 @@ "outDir": "dist", "rootDir": "src", "declaration": true, - "declarationMap": true + "declarationMap": true, + "stripInternal": true }, "include": ["src", "global.d.ts"] } diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.ts index 5f67795d5..7953951be 100644 --- a/packages/core/tsup.config.ts +++ b/packages/core/tsup.config.ts @@ -41,8 +41,10 @@ export default defineConfig({ 'src/search-images.ts', 'src/search-topics.ts', 'src/search-unified.ts', + 'src/search-videos.ts', 'src/highlights.ts', 'src/images.ts', + 'src/videos.ts', 'src/organizations.ts', 'src/data-exchange.ts', 'src/Users.ts', diff --git a/packages/hooks/README.md b/packages/hooks/README.md index b013311f7..fc632a4ac 100644 --- a/packages/hooks/README.md +++ b/packages/hooks/README.md @@ -78,6 +78,14 @@ The props also accept `userIntent` and `fields` (`verses`, `topics`, and/or `fields: ['images']`. An empty array is invalid. Image hits contain `id` and `passageId`, not image URLs. Verse hits contain passage IDs, not passage text. +Video field selection is currently available through core `SearchClient`, not +this hook. Core's `ContentLibrarySearchOptions` accepts `videos`, while +`UseUnifiedSearchProps` and the legacy `SearchUnifiedOptions` keep the hook's +selection types. Use those narrower types when sharing options with this hook. +Unified responses now include a `videos` array (empty when no videos are returned), +which adds an enumerable property to serialized results and exact snapshots. +Existing hook overrides may continue to omit it. + Image selection requires backend support. A production check on 2026-10-20 returned HTTP 400 for `fields: ['images']`; the SDK supports mapping image hits, but this does not make image selection available on that deployment. diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index eeb1381a0..4f2e88c9b 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -30,6 +30,7 @@ export { SignInWithYouVersionPermission, SignInWithYouVersionResult, UNTITLED_SERIF_FONT_ID, + VideosClient, YouVersionAPI, YouVersionAPIUsers, YouVersionPlatformConfiguration, @@ -81,6 +82,7 @@ export { searchTopics, searchUnified, searchVerses, + searchVideos, setStorageItem, throwUnusableBibleVersion, transformBibleHtml, diff --git a/scripts/check-tree-shaking.mjs b/scripts/check-tree-shaking.mjs index bb325f4cd..bd401819d 100644 --- a/scripts/check-tree-shaking.mjs +++ b/scripts/check-tree-shaking.mjs @@ -152,6 +152,22 @@ const CHECKS = [ }, ], focused: [ + { + label: 'SearchClient without playlist validation', + source: `import { SearchClient } from '@youversion/platform-core'; +export { SearchClient }; +`, + absent: [ + 'Playlist ID must be a 32-bit integer', + 'Page size must be an integer from 1 to 99, or "*"', + ], + control: { + label: 'VideosClient', + source: `import { VideosClient } from '@youversion/platform-core'; +export { VideosClient }; +`, + }, + }, { label: 'Bible reads only', source: `import { BibleClient, getBooks } from '@youversion/platform-core'; From d582d73846af6fb29e06599d76a71b9c4e5ed4e8 Mon Sep 17 00:00:00 2001 From: Cameron Pak Date: Tue, 24 Nov 2026 13:56:20 -0600 Subject: [PATCH 07/75] feat(core): add Notes API client (#497) * feat(core): add Notes API client Amp-Thread-ID: https://ampcode.com/threads/T-01a2095d-25a9-72c5-a0fb-baa79c35e05a * fix(core): address Notes API review feedback Amp-Thread-ID: https://ampcode.com/threads/T-01a2095d-25a9-72c5-a0fb-baa79c35e05a * fix(core): normalize Notes write colors * fix(core): address Notes API contract review * fix(core): enforce Notes version filters and tolerate malformed passages * fix(core): isolate malformed Notes list records Amp-Thread-ID: https://ampcode.com/threads/T-01a2095d-25a9-72c5-a0fb-baa79c35e05a * chore: refresh combined core bundle budget Amp-Thread-ID: https://ampcode.com/threads/T-01a2095d-25a9-72c5-a0fb-baa79c35e05a --------- Co-authored-by: Amp --- .changeset/quiet-notes-client.md | 10 + .size-limit.js | 4 +- CONTEXT.md | 5 + packages/core/README.md | 39 ++ packages/core/package.json | 2 + packages/core/src/Users.ts | 19 +- .../SignInWithYouVersionPKCE.test.ts | 3 +- packages/core/src/__tests__/Users.test.ts | 4 +- packages/core/src/__tests__/client.test.ts | 45 +- packages/core/src/__tests__/notes.test.ts | 396 ++++++++++++++++++ packages/core/src/client.ts | 53 ++- packages/core/src/index.ts | 3 +- packages/core/src/notes.ts | 167 ++++++++ packages/core/src/schemas/note.ts | 112 +++++ packages/core/src/schemas/object.ts | 9 + packages/core/src/types/index.ts | 3 +- packages/core/tsup.config.ts | 1 + packages/hooks/src/useYVAuth.ts | 8 +- .../src/components/YouVersionAuthButton.tsx | 3 +- packages/ui/src/index.ts | 1 + scripts/check-tree-shaking.mjs | 6 + 21 files changed, 864 insertions(+), 29 deletions(-) create mode 100644 .changeset/quiet-notes-client.md create mode 100644 packages/core/src/__tests__/notes.test.ts create mode 100644 packages/core/src/notes.ts create mode 100644 packages/core/src/schemas/note.ts diff --git a/.changeset/quiet-notes-client.md b/.changeset/quiet-notes-client.md new file mode 100644 index 000000000..ee7477607 --- /dev/null +++ b/.changeset/quiet-notes-client.md @@ -0,0 +1,10 @@ +--- +'@youversion/platform-core': minor +--- + +Add `NotesClient` to list, get, create, update, and delete a user's notes through the regular `/v1/notes` API. + +- Notes checks app version filters for supplied list version IDs and write passage references. Malformed response passages are omitted while preserving the note. Lists skip other malformed notes without losing valid notes or pagination. +- `AuthenticationScopes` supports `read_notes` and `write_notes`, including in `useYVAuth` and `YouVersionAuthButton`. +- `ApiClient` adds `patch` for JSON updates and `getWithStatus` for reading the HTTP status and decoded body as an `ApiResponse`. +- The React UI package re-exports `NotesClient`. diff --git a/.size-limit.js b/.size-limit.js index cfec72eeb..11c74cef6 100644 --- a/.size-limit.js +++ b/.size-limit.js @@ -3,8 +3,8 @@ export default [ { name: 'core / full barrel (esm)', path: 'packages/core/dist/index.js', - // Measured brotlied size 24687 B; set to measured + ~10% per CONTRIBUTING. - limit: '27.2 KB', + // Measured brotlied size 27410 B; set to measured + ~10% per CONTRIBUTING. + limit: '30.2 KB', ignore: ['jsdom'], }, { diff --git a/CONTEXT.md b/CONTEXT.md index b46c7d0c0..df1b20567 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -107,6 +107,11 @@ content."). Hooks surface that `error`. UI does not throw, does not render an empty tree, does not swap in another version. Dev: one `console.warn` for a host-passed unusable `versionId`. +`NotesClient` applies the same version filter to a supplied list `version_id` +or a passage supplied to create or update a note. An excluded version is +refused before the Notes request; language restrictions may require a +version metadata request first. Notes without a passage remain account data. + Language-only allowlists need `language_tag`. Content methods may fetch version metadata once; if metadata is missing, refuse (fail closed). `getVersion` itself is refused when the id is already unusable without diff --git a/packages/core/README.md b/packages/core/README.md index 26b2eaea7..f6fd91dbe 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -64,6 +64,45 @@ const unified = await searchClient.searchUnified('psalm 23', versions.data[0].id console.log(trending.queries[0]?.text, verses.verses[0]?.id, unified.topics[0]?.text); ``` +### Notes + +`NotesClient` lists, fetches, creates, updates, and deletes the signed-in user's +notes through `/v1/notes`. Reads require `read_notes` and writes require +`write_notes`. With `YouVersionAPIUsers.signIn`, pass these as OAuth scopes in the +second argument, not as data-exchange permissions. Pass a long access token +explicitly outside a signed-in browser session. + +```ts +import { ApiClient, NotesClient } from '@youversion/platform-core'; + +const notes = new NotesClient(new ApiClient({ appKey: 'YOUR_APP_KEY' })); +const filters = { version_id: 3034, passage_id: 'JHN.3' }; +const page = await notes.getNotes(filters, accessToken); +if (page.next_page_token !== null) { + await notes.getNotes({ ...filters, page_token: page.next_page_token }, accessToken); +} + +const note = await notes.createNote( + { request_id: crypto.randomUUID(), content: 'Trust in God.', status: 'private' }, + accessToken, +); +await notes.updateNote(note.id, { title: 'Morning reflection' }, accessToken); +``` + +Keep the filters unchanged when paging. A page can be empty and still have a +next token. Generate a UUID for each new note and reuse it if you retry that +create. For updates, omit fields to keep their values or pass `null` to clear +`title`, `color`, `passage`, `language_tag`, or `tags`. + +`NotesClient` checks the app's Bible version filter when you supply `version_id` +to a list query or a passage to create or update. A malformed passage in an API +response is omitted without losing the note's text or the rest of the page. +List responses skip notes with other malformed fields while preserving valid notes +and the continuation token, even if no notes remain on that page. Invalid list +envelopes and invalid single-note responses still reject. +If your app caches highlights, refetch the affected chapter's highlights after +creating, updating, or deleting a colored note attached to a passage. + ### Verse-art images `ImagesClient` reads image metadata from `GET /v1/images`. Image bytes stay on diff --git a/packages/core/package.json b/packages/core/package.json index 5c43960a2..2011797a2 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -53,6 +53,8 @@ "!dist/search-videos.cjs", "!dist/highlights.js", "!dist/highlights.cjs", + "!dist/notes.js", + "!dist/notes.cjs", "!dist/images.js", "!dist/images.cjs", "!dist/videos.js", diff --git a/packages/core/src/Users.ts b/packages/core/src/Users.ts index acef7758d..f003cc02c 100644 --- a/packages/core/src/Users.ts +++ b/packages/core/src/Users.ts @@ -61,8 +61,15 @@ const PENDING_GRANTED_PERMISSIONS_KEY = 'youversion-auth-pending-granted-permiss */ const REQUESTED_PERMISSIONS_KEY = 'youversion-auth-requested-permissions'; -/** OIDC scopes that must not be stored in the data-exchange permission cache. */ -const OIDC_SCOPES = new Set(['openid', 'profile', 'email', 'offline_access']); +/** OAuth scopes that must not be stored in the data-exchange permission cache. */ +const NON_PERMISSION_SCOPES = { + openid: true, + profile: true, + email: true, + offline_access: true, + read_notes: true, + write_notes: true, +} satisfies Record; type PendingGrantedPermissionsStash = StatePermissionsStash; @@ -213,9 +220,9 @@ export class YouVersionAPIUsers { * The function redirects to the YouVersion authorization URL and expects the callback to be handled separately. * * @param redirectURL - The URL to redirect back to after authentication. - * @param scopes - The OIDC scopes given to the authentication call (e.g. `profile`, `email`). + * @param scopes - OAuth scopes to request, such as `profile`, `email`, or `read_notes`. * @param permissions - YouVersion data-exchange permissions to request (e.g. `highlights`). - * These are sent as a comma-joined `requested_permissions` param, separate from OIDC scopes. + * These are sent as a comma-joined `requested_permissions` param, separate from OAuth scopes. * @throws An error if authentication fails or configuration is invalid. */ static async signIn( @@ -391,7 +398,7 @@ export class YouVersionAPIUsers { const tokens = parsed.data; // Match Swift: union grants from (1) this URL, (2) stashed pre-code hop, - // (3) token scope — then drop OIDC scopes before seeding the data-exchange + // (3) token scope — then drop scopes that aren't data-exchange permissions before seeding the // permission cache. Stash is state-bound so a leftover from another flow // cannot seed this user's optimistic permission cache. // @@ -414,7 +421,7 @@ export class YouVersionAPIUsers { ...parsePermissionList(tokens.scope), ...requestedGrants, ]), - ].filter((permission) => !OIDC_SCOPES.has(permission)); + ].filter((permission) => !Object.hasOwn(NON_PERMISSION_SCOPES, permission)); // Extract user info from ID token const result = this.extractSignInResult(tokens); diff --git a/packages/core/src/__tests__/SignInWithYouVersionPKCE.test.ts b/packages/core/src/__tests__/SignInWithYouVersionPKCE.test.ts index 2c25c2515..f0232db82 100644 --- a/packages/core/src/__tests__/SignInWithYouVersionPKCE.test.ts +++ b/packages/core/src/__tests__/SignInWithYouVersionPKCE.test.ts @@ -72,8 +72,9 @@ describe('SignInWithYouVersionPKCEAuthorizationRequestBuilder', () => { const none = await SignInWithYouVersionPKCEAuthorizationRequestBuilder.make( 'test-app-key', new URL('https://example.com/callback'), - ['profile'], + ['read_notes', 'write_notes'], ); + expect(none.url.searchParams.get('scope')).toBe('read_notes write_notes openid'); expect(none.url.searchParams.has('requested_permissions')).toBe(false); cleanupBrowserMocks(); }); diff --git a/packages/core/src/__tests__/Users.test.ts b/packages/core/src/__tests__/Users.test.ts index 1666329ef..1004b75f7 100644 --- a/packages/core/src/__tests__/Users.test.ts +++ b/packages/core/src/__tests__/Users.test.ts @@ -515,9 +515,9 @@ describe('YouVersionAPIUsers', () => { clearAuthTokensSpy.mockRestore(); }); - it('unions stashed early grants with token scope when final URL omits them', async () => { + it('keeps stashed grants without treating authentication scopes as data-exchange permissions', async () => { setupCallbackFlow({ - scope: 'openid profile email', + scope: 'openid profile email offline_access read_notes write_notes', pendingGrant: JSON.stringify({ state: 'test-state', permissions: ['highlights'] }), }); diff --git a/packages/core/src/__tests__/client.test.ts b/packages/core/src/__tests__/client.test.ts index 0a8e82e7f..96e0b4c7e 100644 --- a/packages/core/src/__tests__/client.test.ts +++ b/packages/core/src/__tests__/client.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; import { http, HttpResponse } from 'msw'; -import { ApiClient, getHttpStatus } from '../client'; +import { ApiClient, getHttpStatus, type ApiResponse } from '../index'; import { server } from './setup'; describe('ApiClient contracts', () => { @@ -182,4 +182,47 @@ describe('ApiClient contracts', () => { expect(getHttpStatus({ status: '403' })).toBeUndefined(); expect(getHttpStatus(null)).toBeUndefined(); }); + + it('returns GET status and decoded body, and PATCH sends partial JSON with explicit nulls', async () => { + if (process.env.INTEGRATION_TESTS) server.listen(); + const apiHost = 'transport.example.test'; + const url = `https://${apiHost}/resource`; + const client = new ApiClient({ apiHost, appKey: 'test-app' }); + try { + server.use( + http.get(url, ({ request }) => { + expect(new URL(request.url).search).toBe('?fields=title'); + expect(request.headers.get('x-request-test')).toBe('get'); + return HttpResponse.json({ title: 'Original' }, { status: 202 }); + }), + http.patch(url, async ({ request }) => { + expect(new URL(request.url).search).toBe('?fields=title'); + expect(request.headers.get('x-request-test')).toBe('patch'); + expect(request.headers.get('content-type')).toContain('application/json'); + expect(await request.json()).toEqual({ title: null }); + return HttpResponse.json({ title: null }); + }), + ); + + const read: ApiResponse<{ title: string }> = await client.getWithStatus( + '/resource', + { fields: 'title' }, + { 'X-Request-Test': 'get' }, + ); + expect(read).toEqual({ status: 202, data: { title: 'Original' }, emptyBody: false }); + await expect( + client.patch( + '/resource', + { title: null }, + { fields: 'title' }, + { 'X-Request-Test': 'patch' }, + ), + ).resolves.toEqual({ title: null }); + } finally { + if (process.env.INTEGRATION_TESTS) { + server.resetHandlers(); + server.close(); + } + } + }); }); diff --git a/packages/core/src/__tests__/notes.test.ts b/packages/core/src/__tests__/notes.test.ts new file mode 100644 index 000000000..de3f41d36 --- /dev/null +++ b/packages/core/src/__tests__/notes.test.ts @@ -0,0 +1,396 @@ +import { http, HttpResponse } from 'msw'; +import { expect, it } from 'vitest'; +import { ApiClient, getHttpStatus, NotesClient, type Note, type UpdateNote } from '../index'; +import { server } from './setup'; +import { YouVersionPlatformConfiguration as config } from '../YouVersionPlatformConfiguration'; + +const apiHost = 'notes.example.test'; +const collectionUrl = `https://${apiHost}/v1/notes`; +const noteId = 'note/1%'; +const resourceUrl = `${collectionUrl}/note%2F1%25`; +const requestId = '2f8c5d2e-6f6c-4b4f-9b36-8c1b5a17d3f9'; +const passageId = 'JHN.3.16+JHN.3.18'; +const note = { + id: noteId, + title: 'Morning reflection', + content: 'Trust in God.', + color: '44aa44', + passage: { version_id: 3034, passage_id: passageId }, + language_tag: 'en-US', + tags: ['faith', 'hope'], + status: 'private', + created_dt: '2026-10-23T17:00:00Z', + updated_dt: null, +} satisfies Note; +const wireNote = { ...note, passage: { bible_id: 3034, passage_id: passageId } }; + +function createClient(): NotesClient { + return new NotesClient(new ApiClient({ apiHost, appKey: 'test-key' })); +} + +it('omits a null cursor, follows an empty filtered page, and handles terminal pages', async () => { + const client = createClient(); + const cursor = 'next+/='; + const filters = { version_id: 3034, passage_id: passageId, page_size: 2 }; + const color = '44AA44'; + server.use( + http.get(collectionUrl, ({ request }) => { + expect(request.headers.get('authorization')).toBe('Bearer reader'); + expect(request.headers.get('x-yvp-app-key')).toBe('test-key'); + const query = Object.fromEntries(new URL(request.url).searchParams); + if (Object.keys(query).length === 0) { + return new HttpResponse(null, { + status: 204, + headers: { 'Content-Type': 'application/json' }, + }); + } + const expectedFilters = { bible_id: '3034', passage_id: passageId, page_size: '2' }; + if (!('page_token' in query)) { + expect(query).toEqual(expectedFilters); + return HttpResponse.json({ data: [], next_page_token: cursor }); + } + expect(query).toEqual({ ...expectedFilters, page_token: cursor }); + return HttpResponse.json({ data: [{ ...wireNote, color }] }); + }), + ); + + const first = await client.getNotes({ ...filters, page_token: null }, 'reader'); + expect(first).toEqual({ data: [], next_page_token: cursor }); + const last = await client.getNotes({ ...filters, page_token: first.next_page_token }, 'reader'); + expect(last).toEqual({ data: [{ ...note, color }], next_page_token: null }); + expect(await client.getNotes(undefined, 'reader')).toEqual({ data: [], next_page_token: null }); +}); + +it.each([ + ['no body', () => new HttpResponse(null)], + [ + 'no JSON body', + () => new HttpResponse(null, { headers: { 'Content-Type': 'application/json' } }), + ], + ['a JSON empty string', () => HttpResponse.json('')], +] as const)('rejects a 200 Notes page with %s instead of ending pagination', async (_, respond) => { + server.use(http.get(collectionUrl, respond)); + await expect(createClient().getNotes({ page_token: 'next' }, 'reader')).rejects.toThrow( + 'invalid_type', + ); +}); + +it('creates, gets, partially updates, and deletes a note on the regular Notes routes', async () => { + const client = createClient(); + const create = { + request_id: requestId, + title: note.title, + content: note.content, + color: '44AA44', + passage: note.passage, + language_tag: note.language_tag, + tags: note.tags, + status: note.status, + }; + const update = { title: null, color: null, passage: null, language_tag: null, tags: null }; + let stored: + | (Omit & { + [K in keyof typeof update]: (typeof wireNote)[K] | null; + }) + | undefined; + server.use( + http.post(collectionUrl, async ({ request }) => { + expect(request.headers.get('authorization')).toBe('Bearer writer'); + expect(await request.json()).toEqual({ + ...create, + color: note.color, + passage: wireNote.passage, + }); + stored = { ...wireNote, color: create.color }; + return HttpResponse.json(stored, { status: 201 }); + }), + http.get(resourceUrl, ({ request }) => { + expect(request.headers.get('authorization')).toBe('Bearer reader'); + return stored ? HttpResponse.json(stored) : new HttpResponse(null, { status: 404 }); + }), + http.patch(resourceUrl, async ({ request }) => { + expect(request.headers.get('authorization')).toBe('Bearer writer'); + expect(await request.json()).toEqual({ color: note.color, passage: wireNote.passage }); + stored = wireNote; + return HttpResponse.json(stored); + }), + http.delete(resourceUrl, ({ request }) => { + expect(request.headers.get('authorization')).toBe('Bearer writer'); + stored = undefined; + return new HttpResponse(null, { status: 204 }); + }), + ); + + const created = await client.createNote(create, 'writer'); + expect(created).toEqual({ ...note, color: create.color }); + const read = await client.getNote(created.id, 'reader'); + expect(read).toEqual(created); + expect( + await client.updateNote(read.id, { color: read.color, passage: read.passage }, 'writer'), + ).toEqual(note); + server.use( + http.patch(resourceUrl, async ({ request }) => { + expect(request.headers.get('authorization')).toBe('Bearer writer'); + expect(await request.json()).toEqual(update); + stored = { ...wireNote, ...update }; + return HttpResponse.json(stored); + }), + ); + const updated = await client.updateNote(created.id, update, 'writer'); + expect(updated).toEqual({ ...note, ...update }); + expect(await client.getNote(updated.id, 'reader')).toEqual(updated); + expect(await client.deleteNote(updated.id, 'writer')).toBeUndefined(); + await expect(client.getNote(updated.id, 'reader').catch(getHttpStatus)).resolves.toBe(404); +}); + +it('propagates API authentication and permission failures for every Notes operation', async () => { + const client = createClient(); + const create = { request_id: requestId, content: note.content, status: note.status }; + for (const status of [401, 403]) { + server.use( + http.all(`${collectionUrl}*`, () => HttpResponse.json({ message: 'Denied' }, { status })), + ); + for (const operation of [ + () => client.getNotes({}, 'token'), + () => client.getNote(noteId, 'token'), + () => client.createNote(create, 'token'), + () => client.updateNote(noteId, { title: null }, 'token'), + () => client.deleteNote(noteId, 'token'), + ]) { + await expect(operation().catch(getHttpStatus)).resolves.toBe(status); + } + } +}); + +it('rejects invalid writes, pagination, and missing auth before sending a request', async () => { + const client = createClient(); + let requests = 0; + server.use( + http.all(`${collectionUrl}*`, () => { + requests += 1; + return new HttpResponse(null, { status: 500 }); + }), + ); + + await expect(client.getNotes()).rejects.toThrow('Authentication required'); + for (const page_size of [0, 1.5, 100]) { + await expect(client.getNotes({ page_size }, 'reader')).rejects.toThrow('page_size'); + } + for (const version_id of [-1, 2 ** 31]) { + await expect(client.getNotes({ version_id }, 'reader')).rejects.toThrow('version_id'); + } + await expect( + client.updateNote(noteId, { passage: { version_id: 0, passage_id: passageId } }, 'writer'), + ).rejects.toThrow('version_id'); + await expect(client.updateNote(noteId, { color: '#44AA44' }, 'writer')).rejects.toThrow('color'); + await expect( + client.createNote({ request_id: 'not-a-uuid', content: 'Note', status: 'private' }, 'writer'), + ).rejects.toThrow('request_id'); + await expect(client.updateNote(noteId, { title: undefined }, 'writer')).rejects.toThrow( + 'At least one note field is required', + ); + const passage = { ...note.passage, unexpected: 'field' }; + await expect(client.updateNote(noteId, { passage }, 'writer')).rejects.toThrow('unexpected'); + const unexpected = { title: 'Title', unexpected: 'field' }; + await expect(client.updateNote(noteId, unexpected, 'writer')).rejects.toThrow('unexpected'); + await expect( + client.createNote( + { ...unexpected, request_id: requestId, content: 'Note', status: 'private' }, + 'writer', + ), + ).rejects.toThrow('unexpected'); + for (const [fields, field] of [ + [{ language_tag: 'fil' }, 'language_tag'], + [{ language_tag: 'en-us' }, 'language_tag'], + [{ tags: ['a,b'] }, 'tags'], + [{ tags: [''] }, 'tags'], + [{ content: '' }, 'content'], + [{ passage: { ...note.passage, passage_id: ' ' } }, 'passage_id'], + ] as const satisfies ReadonlyArray) { + await expect(client.updateNote(noteId, fields, 'writer')).rejects.toThrow(field); + } + expect(requests).toBe(0); +}); + +it('rejects blank and dot-segment note IDs before making a request', async () => { + const client = createClient(); + let requests = 0; + server.use( + http.all(`https://${apiHost}/*`, () => { + requests += 1; + return new HttpResponse(null, { status: 500 }); + }), + ); + + await Promise.all([ + expect(client.getNote('', 'reader')).rejects.toThrow('Note ID'), + expect(client.getNote(' ', 'reader')).rejects.toThrow('Note ID'), + expect(client.getNote('.', 'reader')).rejects.toThrow('Note ID'), + expect(client.deleteNote('..', 'writer')).rejects.toThrow('Note ID'), + ]); + expect(requests).toBe(0); +}); + +it.each([ + ['status', 'draft'], + ['color', '#44AA44'], + ['id', 123], +])('rejects an invalid %s in a note response', async (field, value) => { + server.use(http.get(resourceUrl, () => HttpResponse.json({ ...wireNote, [field]: value }))); + await expect(createClient().getNote(noteId, 'reader')).rejects.toThrow(field); +}); + +it('preserves lowercase RFC 3339 timestamps but still rejects invalid dates', async () => { + const client = createClient(); + const timestamps = { + created_dt: '2026-10-23t17:00:00z', + updated_dt: '2026-10-24t19:30:00+02:00', + }; + server.use(http.get(resourceUrl, () => HttpResponse.json({ ...wireNote, ...timestamps }))); + expect(await client.getNote(noteId, 'reader')).toEqual({ ...note, ...timestamps }); + + server.use( + http.get(resourceUrl, () => + HttpResponse.json({ ...wireNote, updated_dt: '2026-02-30t17:00:00z' }), + ), + ); + await expect(client.getNote(noteId, 'reader')).rejects.toThrow('updated_dt'); +}); + +it('refuses blocked list and write versions before Notes requests, including language filters', async () => { + const client = createClient(); + const previous = { + excludedVersionIds: config.excludedVersionIds, + permittedVersionIds: config.permittedVersionIds, + permittedLanguageTags: config.permittedLanguageTags, + }; + let noteRequests = 0; + let metadataRequests = 0; + let language: string | undefined = 'es'; + const create = { + request_id: requestId, + content: note.content, + status: note.status, + passage: note.passage, + }; + server.use( + http.get(`https://${apiHost}/v1/bibles/3034`, () => { + metadataRequests += 1; + return HttpResponse.json({ id: 3034, language_tag: language }); + }), + http.all(`${collectionUrl}*`, ({ request }) => { + noteRequests += 1; + return request.method === 'GET' + ? HttpResponse.json({ data: [wireNote] }) + : HttpResponse.json(wireNote); + }), + ); + try { + for (const filters of [ + { excludedVersionIds: [3034], permittedVersionIds: [3034], permittedLanguageTags: undefined }, + { excludedVersionIds: undefined, permittedVersionIds: [], permittedLanguageTags: undefined }, + { excludedVersionIds: undefined, permittedVersionIds: [3034], permittedLanguageTags: ['en'] }, + ]) { + Object.assign(config, filters); + await expect( + client.getNotes({ version_id: 3034 }, 'reader').catch(getHttpStatus), + ).resolves.toBe(403); + await expect(client.createNote(create, 'writer').catch(getHttpStatus)).resolves.toBe(403); + await expect( + client.updateNote(noteId, { passage: note.passage }, 'writer').catch(getHttpStatus), + ).resolves.toBe(403); + expect(noteRequests).toBe(0); + if (filters.permittedLanguageTags === undefined) expect(metadataRequests).toBe(0); + } + language = undefined; + await expect(client.createNote(create, 'writer').catch(getHttpStatus)).resolves.toBe(403); + expect(noteRequests).toBe(0); + + language = 'en'; + expect(await client.getNotes({ version_id: 3034 }, 'reader')).toEqual({ + data: [note], + next_page_token: null, + }); + expect(await client.createNote(create, 'writer')).toEqual(note); + expect(await client.updateNote(noteId, { passage: note.passage }, 'writer')).toEqual(note); + expect(noteRequests).toBe(3); + } finally { + Object.assign(config, previous); + } +}); + +it('preserves notes and pagination when a returned passage is malformed', async () => { + const client = createClient(); + const malformed = [ + { passage_id: passageId }, + { bible_id: 3034, passage_id: 123 }, + { bible_id: -1, passage_id: passageId }, + { bible_id: 3034, passage_id: ' ' }, + ]; + const data = malformed.map((passage, index) => ({ ...wireNote, id: `note-${index}`, passage })); + server.use( + http.get(collectionUrl, () => + HttpResponse.json({ data: [...data, wireNote], next_page_token: 'continue' }), + ), + http.get(resourceUrl, () => HttpResponse.json(data[0])), + ); + const page = await client.getNotes({}, 'reader'); + expect(page.next_page_token).toBe('continue'); + expect(page.data).toEqual([ + ...malformed.map((_, index) => ({ ...note, id: `note-${index}`, passage: undefined })), + note, + ]); + expect(await client.getNote(noteId, 'reader')).toEqual({ + ...note, + id: 'note-0', + passage: undefined, + }); +}); + +it('skips malformed notes without losing valid neighbors or continuation pages', async () => { + const client = createClient(); + const invalid = [ + null, + { ...wireNote, id: 123 }, + { ...wireNote, content: undefined }, + { ...wireNote, status: 'draft' }, + { ...wireNote, created_dt: 'not-a-date' }, + ]; + const filters = { passage_id: passageId, page_size: 10 }; + server.use( + http.get(collectionUrl, ({ request }) => { + const query = new URL(request.url).searchParams; + expect(query.get('passage_id')).toBe(passageId); + expect(query.get('page_size')).toBe('10'); + switch (query.get('page_token')) { + case null: + return HttpResponse.json({ + data: [wireNote, ...invalid, { ...wireNote, id: 'second' }], + next_page_token: 'all-invalid', + }); + case 'all-invalid': + return HttpResponse.json({ data: invalid, next_page_token: 'last' }); + case 'last': + return HttpResponse.json({ data: [{ ...wireNote, id: 'last' }] }); + default: + return new HttpResponse(null, { status: 400 }); + } + }), + ); + + const first = await client.getNotes(filters, 'reader'); + expect(first).toEqual({ + data: [note, { ...note, id: 'second' }], + next_page_token: 'all-invalid', + }); + const empty = await client.getNotes({ ...filters, page_token: first.next_page_token }, 'reader'); + expect(empty).toEqual({ data: [], next_page_token: 'last' }); + expect( + await client.getNotes({ ...filters, page_token: empty.next_page_token }, 'reader'), + ).toEqual({ data: [{ ...note, id: 'last' }], next_page_token: null }); + + for (const envelope of [{}, { data: null }, { data: {} }, { data: [], next_page_token: 123 }]) { + server.use(http.get(collectionUrl, () => HttpResponse.json(envelope))); + await expect(client.getNotes({}, 'reader')).rejects.toThrow(); + } +}); diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index f340f2f56..b7f8be8f0 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -6,11 +6,19 @@ import { SDK_VERSION_HEADER_NAME, buildSdkVersionHeaderValue } from './version'; type PrimitiveQueryParam = string | number | boolean; type QueryParamValue = PrimitiveQueryParam | PrimitiveQueryParam[]; type QueryParams = Record; -type JsonPrimitive = string | number | boolean; +type JsonPrimitive = string | number | boolean | null; type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }; type RequestData = Record; type RequestHeaders = Record; -type ApiResponse = Readonly<{ data: T; emptyBody: boolean; status: number }>; +/** The HTTP status and decoded body of a successful API request. */ +export type ApiResponse = Readonly<{ + /** Successful HTTP response status. */ + status: number; + /** Decoded response body. Choose `T` to match the endpoint's body, including empty responses. */ + data: T; + /** Whether the HTTP body is empty, distinct from a JSON empty string or null. */ + emptyBody: boolean; +}>; const HttpStatusCarrierSchema = object({ status: z.number(), @@ -182,15 +190,18 @@ export class ApiClient { * @returns A promise resolving to the response data of type T. */ async get(path: string, params?: QueryParams, headers?: RequestHeaders): Promise { - const url = `${this.baseURL}${path}${this.buildQueryString(params)}`; - const response = await this.request(url, { - method: 'GET', - headers, - }); - return response.data; + const { data } = await this.getWithStatus(path, params, headers); + return data; } - /** @internal GET variant for endpoint clients that must inspect a successful status. */ + /** + * Sends a GET request and returns its status alongside the decoded body. + * @typeParam T - The expected response body type. + * @param path - The API endpoint path (relative to baseURL). + * @param params - Optional query parameters to include in the request. + * @param headers - Optional headers merged over the default headers. + * @returns The HTTP status and decoded response body. + */ async getWithStatus( path: string, params?: QueryParams, @@ -228,6 +239,30 @@ export class ApiClient { return response.data; } + /** + * Sends a JSON PATCH request and returns the decoded response. + * @typeParam T - The expected response body type. + * @param path - The API endpoint path (relative to baseURL). + * @param data - JSON request body. Explicit `null` values are preserved. + * @param params - Optional query parameters to include in the request. + * @param headers - Optional headers merged over the default headers. + * @returns The decoded response body. + */ + async patch( + path: string, + data: RequestData, + params?: QueryParams, + headers?: RequestHeaders, + ): Promise { + const url = `${this.baseURL}${path}${this.buildQueryString(params)}`; + const response = await this.request(url, { + method: 'PATCH', + body: JSON.stringify(data), + headers, + }); + return response.data; + } + /** * Sends a DELETE request to the specified API path with optional query parameters. * diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4db1c5218..2e3fbf54f 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,4 +1,4 @@ -export { ApiClient, getHttpStatus } from './client'; +export { ApiClient, getHttpStatus, type ApiResponse } from './client'; export { BibleClient } from './bible'; export { getChapter, getVersion } from './bible-chapter'; export { @@ -60,6 +60,7 @@ export { type GetHighlightsOptions, type DeleteHighlightOptions, } from './highlights'; +export { NotesClient, type GetNotesOptions } from './notes'; export { DataExchangeClient, buildDataExchangeUrl, diff --git a/packages/core/src/notes.ts b/packages/core/src/notes.ts new file mode 100644 index 000000000..571609aa9 --- /dev/null +++ b/packages/core/src/notes.ts @@ -0,0 +1,167 @@ +import * as z from 'zod/mini'; +import { resolveAuthToken } from './auth-token'; +import { assertUsableVersion } from './bible-chapter'; +import type { ApiClient } from './client'; +import { + CreateNoteSchema, + NotePassageIdSchema, + NoteSchema, + NotesPageSchema, + NoteVersionIdSchema, + UpdateNoteSchema, +} from './schemas/note'; +import { object } from './schemas/object'; +import type { Collection, CreateNote, Note, NotePassage, UpdateNote } from './types'; + +const NOTES_PATH = '/v1/notes'; + +const GetNotesOptionsSchema = object({ + /** Filter by Bible version. Sent on the wire as `bible_id`. */ + version_id: z.optional(NoteVersionIdSchema), + /** Filter by overlapping verses, range, or chapter. */ + passage_id: z.optional(NotePassageIdSchema), + /** Results per page, from 1 to 99. The API default is 25. */ + page_size: z.optional(z.int().check(z.gte(1), z.lte(99))), + /** Cursor from the previous response. Keep both filters unchanged when paging. */ + page_token: z.optional(z.nullable(z.string())), +}); + +/** Optional filters and pagination for listing a user's notes. */ +export type GetNotesOptions = z.infer; + +type NotesQuery = { + bible_id?: number; + passage_id?: string; + page_size?: number; + page_token?: string; +}; + +type BearerAuthHeaders = { Authorization: string }; + +const NoteIdSchema = z + .string() + .check( + z.refine( + (id) => id.trim().length > 0 && id !== '.' && id !== '..', + 'Note ID must be a non-empty resource identifier', + ), + ); + +function notePath(noteId: string): string { + return `${NOTES_PATH}/${encodeURIComponent(NoteIdSchema.parse(noteId))}`; +} + +function authHeaders(lat?: string): BearerAuthHeaders { + return { Authorization: `Bearer ${resolveAuthToken(lat, 'accessing notes')}` }; +} + +function toNoteBody(data: T) { + const { passage, ...fields } = data; + return passage === undefined + ? fields + : { + ...fields, + passage: passage && { bible_id: passage.version_id, passage_id: passage.passage_id }, + }; +} + +/** + * Client for the authenticated user's notes (`/v1/notes`). + * Reads require `read_notes`; writes require `write_notes`. + * Pass a long access token per call, or use the signed-in platform session. + */ +export class NotesClient { + private client: ApiClient; + + /** @param client - HTTP client configured for the YouVersion Platform API. */ + constructor(client: ApiClient) { + this.client = client; + } + + /** + * Lists one page of notes with `read_notes` access. An empty page can still have a continuation token. + * Malformed notes are skipped without discarding the page's continuation token. + * @param options - Passage and version filters, page size, and optional cursor. + * @param lat - Long access token. Defaults to the signed-in session. + * @returns The notes and the next page token, or `null` when the list ends. + * @throws If input, authentication, the request, or the response is invalid. + */ + async getNotes(options: GetNotesOptions = {}, lat?: string): Promise> { + const { version_id, passage_id, page_size, page_token } = GetNotesOptionsSchema.parse(options); + if (version_id !== undefined) await assertUsableVersion(this.client, version_id); + const query: NotesQuery = {}; + if (version_id !== undefined) query.bible_id = version_id; + if (passage_id !== undefined) query.passage_id = passage_id; + if (page_size !== undefined) query.page_size = page_size; + if (page_token != null) query.page_token = page_token; + const { status, data } = await this.client.getWithStatus( + NOTES_PATH, + query, + authHeaders(lat), + ); + if (status === 204) { + return { data: [], next_page_token: null }; + } + const page = NotesPageSchema.parse(data); + return { data: page.data, next_page_token: page.next_page_token ?? null }; + } + + /** + * Gets one note with `read_notes` access. + * @param noteId - Opaque ID returned by the Notes API. + * @param lat - Long access token. Defaults to the signed-in session. + * @returns The requested note. + * @throws If input, authentication, the request, or the response is invalid. + */ + async getNote(noteId: string, lat?: string): Promise { + const response = await this.client.get(notePath(noteId), undefined, authHeaders(lat)); + return NoteSchema.parse(response); + } + + /** + * Creates a note with `write_notes` access. + * @param data - Note fields. Reuse `request_id` to retry the same create. + * @param lat - Long access token. Defaults to the signed-in session. + * @returns The saved note, including its ID. + * @throws If input, authentication, the request, or the response is invalid. + */ + async createNote(data: CreateNote, lat?: string): Promise { + const parsed = CreateNoteSchema.parse(data); + if (parsed.passage) await assertUsableVersion(this.client, parsed.passage.version_id); + const body = toNoteBody(parsed); + const response = await this.client.post(NOTES_PATH, body, undefined, authHeaders(lat)); + return NoteSchema.parse(response); + } + + /** + * Updates a note with `write_notes` access. + * @param noteId - Opaque ID returned by the Notes API. + * @param data - Fields to change. Omit a field to keep it; use `null` to clear a nullable field. + * @param lat - Long access token. Defaults to the signed-in session. + * @returns The updated note. + * @throws If input, authentication, the request, or the response is invalid. + */ + async updateNote(noteId: string, data: UpdateNote, lat?: string): Promise { + const parsed = UpdateNoteSchema.parse(data); + if (parsed.passage) await assertUsableVersion(this.client, parsed.passage.version_id); + const body = toNoteBody(parsed); + const response = await this.client.patch( + notePath(noteId), + body, + undefined, + authHeaders(lat), + ); + return NoteSchema.parse(response); + } + + /** + * Deletes a note with `write_notes` access. + * @param noteId - Opaque ID returned by the Notes API. + * @param lat - Long access token. Defaults to the signed-in session. + * @returns A promise that resolves when the note is deleted. + * @throws If the ID is invalid, authentication is missing, or the request fails. + */ + async deleteNote(noteId: string, lat?: string): Promise { + await this.client.delete(notePath(noteId), undefined, authHeaders(lat)); + } +} diff --git a/packages/core/src/schemas/note.ts b/packages/core/src/schemas/note.ts new file mode 100644 index 000000000..4ba4cfac9 --- /dev/null +++ b/packages/core/src/schemas/note.ts @@ -0,0 +1,112 @@ +import * as z from 'zod/mini'; +import { object, strictObject } from './object'; + +export const NotePassageIdSchema = z.string().check(z.refine((value) => value.trim().length > 0)); +export const NoteVersionIdSchema = z + .int32() + .check(z.positive('Version ID must be a positive integer')); +const title = z.optional(z.nullable(z.string())); +const status = z.enum(['private', 'public']); +const isoTimestamp = z.iso.datetime({ offset: true }); +// RFC 3339 allows lowercase t and z. Validate without rewriting the API value. +const timestamp = z + .string() + .check( + z.refine((value) => isoTimestamp.safeParse(value.toUpperCase()).success, 'Invalid timestamp'), + ); + +const NotePassageInputSchema = strictObject({ + /** Bible version identifier, sent on the wire as `bible_id`. */ + version_id: NoteVersionIdSchema, + /** Single verse, same-chapter range, or same-chapter verses joined by `+`. */ + passage_id: NotePassageIdSchema, +}); + +const NotePassageSchema = z.pipe( + object({ bible_id: NoteVersionIdSchema, passage_id: NotePassageIdSchema }), + z.transform(({ bible_id, passage_id }): NotePassage => ({ version_id: bible_id, passage_id })), +); + +const optionalWriteFields = { + /** An optional short title. */ + title, + /** Six hex digits without `#`, sent lowercase. */ + color: z.optional(z.nullable(z.string().check(z.toLowerCase(), z.regex(/^[0-9a-f]{6}$/)))), + /** A note can attach to at most one passage. */ + passage: z.optional(z.nullable(NotePassageInputSchema)), + /** Two-letter language code, optionally with an uppercase region (e.g. `en-US`). */ + language_tag: z.optional(z.nullable(z.string().check(z.regex(/^[a-z]{2}(-[A-Z]{2})?$/)))), + /** Labels that are non-empty and contain no commas. */ + tags: z.optional(z.nullable(z.array(z.string().check(z.regex(/^[^,]+$/))))), +}; + +const nonEmptyContent = z.string().check(z.minLength(1)); + +export const CreateNoteSchema = strictObject({ + ...optionalWriteFields, + /** Reuse this UUID to retry the same logical create without duplicating the note. */ + request_id: z.uuid(), + /** Non-empty note text. */ + content: nonEmptyContent, + /** `private` is visible only to the author; `public` is visible to others. */ + status, +}); + +export const UpdateNoteSchema = strictObject({ + ...optionalWriteFields, + /** Replacement note text. Must not be empty. */ + content: z.optional(nonEmptyContent), + /** `private` is visible only to the author; `public` is visible to others. */ + status: z.optional(status), +}).check( + z.refine( + (value) => Object.values(value).some((field) => field !== undefined), + 'At least one note field is required', + ), +); + +export const NoteSchema = object({ + /** Opaque identifier. Pass it unchanged to get, update, or delete this note. */ + id: z.string(), + /** Optional short title. */ + title, + /** Text written by the note's author. */ + content: z.string(), + /** Six hex digits without `#`, preserving the case returned by the API. */ + color: z.optional(z.nullable(z.string().check(z.regex(/^[0-9a-f]{6}$/i)))), + /** The attached Scripture passage, if any. Malformed API passage data is omitted. */ + passage: z.catch(z.optional(z.nullable(NotePassageSchema)), undefined), + /** Language tag for the note, if set. */ + language_tag: z.optional(z.nullable(z.string())), + /** Labels applied to the note, if set. */ + tags: z.optional(z.nullable(z.array(z.string()))), + /** `private` is visible only to the author; `public` is visible to others. */ + status, + /** Creation timestamp in RFC 3339 format, when supplied by the API. */ + created_dt: z.optional(timestamp), + /** Last update timestamp in RFC 3339 format, if supplied and non-null. */ + updated_dt: z.optional(z.nullable(timestamp)), +}); + +export const NotesPageSchema = z.pipe( + object({ + data: z.array(z.unknown()), + next_page_token: z.optional(z.nullable(z.string())), + }), + z.transform((page) => ({ + ...page, + data: page.data.flatMap((item) => { + const parsed = NoteSchema.safeParse(item); + return parsed.success ? [parsed.data] : []; + }), + })), +); + +/** Scripture passage attached to a note, using SDK version IDs. */ +export type NotePassage = z.infer; +/** A note returned by the regular Notes API. */ +export type Note = z.infer; +/** Fields for creating a note, including an idempotency UUID. */ +export type CreateNote = z.infer; +/** Omit fields to leave them unchanged; pass `null` to clear nullable fields. */ +export type UpdateNote = z.infer; diff --git a/packages/core/src/schemas/object.ts b/packages/core/src/schemas/object.ts index 4c91dd02c..39c2ebf91 100644 --- a/packages/core/src/schemas/object.ts +++ b/packages/core/src/schemas/object.ts @@ -16,3 +16,12 @@ export const object = fields: T, params?: string | z.core.$ZodObjectParams, ) => z.ZodMiniObject; + +/** Like {@link object}, but rejects fields outside the schema. */ +export const strictObject = + // SAFETY: as with `object`, this preserves the supplied shape instead of applying + // `Writeable`. The runtime parser and strict config are unchanged. + z.strictObject as >( + fields: T, + params?: string | z.core.$ZodObjectParams, + ) => z.ZodMiniObject; diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index efd8ce8ef..acbd50741 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -26,6 +26,7 @@ export type { export type { Language } from '../schemas/language'; export type { User } from '../schemas/user'; export type { Highlight, CreateHighlight } from '../schemas/highlight'; +export type { CreateNote, Note, NotePassage, UpdateNote } from '../schemas/note'; export type { ContentLibrarySearchField, ContentLibrarySearchOptions, @@ -91,7 +92,7 @@ export interface AuthenticationState { readonly error: Error | null; } -export type AuthenticationScopes = 'profile' | 'email'; +export type AuthenticationScopes = 'profile' | 'email' | 'read_notes' | 'write_notes'; export interface HighlightColor { id: number; diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.ts index 7953951be..977625cae 100644 --- a/packages/core/tsup.config.ts +++ b/packages/core/tsup.config.ts @@ -43,6 +43,7 @@ export default defineConfig({ 'src/search-unified.ts', 'src/search-videos.ts', 'src/highlights.ts', + 'src/notes.ts', 'src/images.ts', 'src/videos.ts', 'src/organizations.ts', diff --git a/packages/hooks/src/useYVAuth.ts b/packages/hooks/src/useYVAuth.ts index 26eaa0fa7..5c7f409da 100644 --- a/packages/hooks/src/useYVAuth.ts +++ b/packages/hooks/src/useYVAuth.ts @@ -17,7 +17,9 @@ export interface UseYVAuthReturn { // Actions signIn: (params?: { redirectUrl?: string; + /** OAuth scopes to request, including `read_notes` and `write_notes` for Notes access. */ scopes?: AuthenticationScopes[]; + /** YouVersion data-exchange permissions (e.g. `highlights`), separate from OAuth scopes. */ permissions?: SignInWithYouVersionPermissionValues[]; }) => Promise; signOut: () => void; @@ -132,11 +134,7 @@ export function useYVAuth(): UseYVAuthReturn { // Sign in function const signIn = useCallback( - async (params?: { - redirectUrl?: string; - scopes?: AuthenticationScopes[]; - permissions?: SignInWithYouVersionPermissionValues[]; - }) => { + async (params?: Parameters[0]) => { const url = params?.redirectUrl ?? redirectUri; if (!url) { throw new Error( diff --git a/packages/ui/src/components/YouVersionAuthButton.tsx b/packages/ui/src/components/YouVersionAuthButton.tsx index 22d274496..32e425e46 100644 --- a/packages/ui/src/components/YouVersionAuthButton.tsx +++ b/packages/ui/src/components/YouVersionAuthButton.tsx @@ -21,10 +21,11 @@ interface SignInAuthProps { * @param error - The error thrown by the sign-in flow. */ onAuthError?: (error: Error) => void; + /** OAuth scopes to request, including `read_notes` and `write_notes` for Notes access. */ scopes?: AuthenticationScopes[]; /** * YouVersion data-exchange permissions to request at sign-in (e.g. `highlights`). - * These are distinct from OIDC `scopes` and are sent as `requested_permissions`. + * These are distinct from OAuth `scopes` and are sent as `requested_permissions`. */ permissions?: SignInWithYouVersionPermissionValues[]; } diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index 4f2e88c9b..cb1faca89 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -21,6 +21,7 @@ export { MAX_SEARCH_QUERY_GRAPHEMES, MemoryStorageStrategy, MissingPassageAttributionError, + NotesClient, OrganizationsClient, SDK_NAME, SDK_VERSION, diff --git a/scripts/check-tree-shaking.mjs b/scripts/check-tree-shaking.mjs index bd401819d..f0c99263a 100644 --- a/scripts/check-tree-shaking.mjs +++ b/scripts/check-tree-shaking.mjs @@ -130,6 +130,7 @@ const CHECKS = [ source: `import { ApiClient } from '@youversion/platform-core';\nnew ApiClient({ apiHost: 'https://api.youversion.com' });\n`, absent: [ 'Color must be a 6-character hex string without #', + 'At least one note field is required', 'App key is required to request a data exchange token.', 'Invalid state parameter - possible CSRF attack', ], @@ -140,6 +141,11 @@ const CHECKS = [ source: `import { HighlightsClient } from '@youversion/platform-core';\nexport { HighlightsClient };\n`, present: ['Color must be a 6-character hex string without #'], }, + { + label: 'NotesClient', + source: `import { NotesClient } from '@youversion/platform-core';\nexport { NotesClient };\n`, + present: ['At least one note field is required'], + }, { label: 'DataExchangeClient', source: `import { DataExchangeClient } from '@youversion/platform-core';\nexport { DataExchangeClient };\n`, From 7ce0341163396c8d145d264ce12c8052fd4f3ff1 Mon Sep 17 00:00:00 2001 From: Austin Date: Tue, 24 Nov 2026 14:02:23 -0600 Subject: [PATCH 08/75] fix(ui): preserve newer selection after native Share (YPE-6812) (#494) --- .changeset/reader-native-share-selection.md | 5 + .../bible-reader-controlled.test.tsx | 92 ++++++++++++++++++- packages/ui/src/components/bible-reader.tsx | 7 +- 3 files changed, 102 insertions(+), 2 deletions(-) create mode 100644 .changeset/reader-native-share-selection.md diff --git a/.changeset/reader-native-share-selection.md b/.changeset/reader-native-share-selection.md new file mode 100644 index 000000000..6a8261103 --- /dev/null +++ b/.changeset/reader-native-share-selection.md @@ -0,0 +1,5 @@ +--- +'@youversion/platform-react-ui': patch +--- + +Preserve newer verse selections when an earlier native Share request completes, avoiding stale selection-cleared events after navigation. diff --git a/packages/ui/src/components/bible-reader-controlled.test.tsx b/packages/ui/src/components/bible-reader-controlled.test.tsx index 9b25e793e..9e3251e9c 100644 --- a/packages/ui/src/components/bible-reader-controlled.test.tsx +++ b/packages/ui/src/components/bible-reader-controlled.test.tsx @@ -13,10 +13,11 @@ import { vi, beforeEach, afterEach, + onTestFinished, type Mock, type MockInstance, } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { act, render, screen, fireEvent, waitFor } from '@testing-library/react'; import { DataExchangeClient, YouVersionAPIUsers, @@ -1271,3 +1272,92 @@ it('does not restore the verse menu after an outside click if the permission gra localStorage.clear(); } }); + +it.each([ + 'original selection', + 'new selection', + 'reselected same verse', + 'new passage', + 'new passage without selection', +])('native Share completion only clears its original selection: %s', async (scenario) => { + onTestFinished(() => { + vi.unstubAllGlobals(); + }); + let finishShare: () => void = () => { + throw new Error('Share promise not initialized'); + }; + const pendingShare = new Promise((resolve) => { + finishShare = resolve; + }); + const share = vi.fn(() => pendingShare); + vi.stubGlobal('navigator', { + userAgent: navigator.userAgent, + platform: navigator.platform, + share, + }); + const onVerseSelect = verseSelectSpy(); + const overrides: HookOverrides = { + ...defaultOverrides(), + usePassage: ({ usfm }) => ({ + passage: { + ...mockPassage, + id: usfm, + reference: usfm, + content: + usfm === 'JHN.2' + ? mockPassage.content.replace('In the beginning was the Word.', 'The second chapter.') + : mockPassage.content, + }, + loading: false, + error: null, + refetch: () => undefined, + }), + }; + const reader = (chapter: string) => + wrapReader({ highlights: [], chapter, onVerseSelect }, overrides); + const view = render(reader('1')); + selectVerse(view.container, 1); + fireEvent.click(await screen.findByRole('button', { name: /^share$/i })); + expect(share).toHaveBeenCalledExactlyOnceWith({ + text: '“In the beginning was the Word.”\n\nJohn 1:1 NIV', + }); + expect(getVerseEl(view.container, 1)).toHaveClass('yv-v-selected'); + + if (scenario === 'new passage' || scenario === 'new passage without selection') { + view.rerender(reader('2')); + expect(getVerseEl(view.container, 1)).not.toHaveClass('yv-v-selected'); + if (scenario === 'new passage') { + selectVerse(view.container, 2); + expect(lastSelection(onVerseSelect)).toMatchObject({ chapter: '2', verses: [2] }); + } + } else if (scenario === 'new selection') { + selectVerse(view.container, 1); + selectVerse(view.container, 2); + expect(lastSelection(onVerseSelect)).toMatchObject({ chapter: '1', verses: [2] }); + } else if (scenario === 'reselected same verse') { + selectVerse(view.container, 1); + selectVerse(view.container, 1); + expect(lastSelection(onVerseSelect)).toMatchObject({ chapter: '1', verses: [1] }); + } + onVerseSelect.mockClear(); + + await act(async () => { + finishShare(); + await pendingShare; + }); + + if (scenario === 'original selection') { + expect(lastSelection(onVerseSelect)).toEqual(selection([])); + expect(getVerseEl(view.container, 1)).not.toHaveClass('yv-v-selected'); + expect(screen.queryByRole('button', { name: /^share$/i })).toBeNull(); + } else if (scenario === 'new passage without selection') { + expect(onVerseSelect).not.toHaveBeenCalled(); + expect(getVerseEl(view.container, 1)).not.toHaveClass('yv-v-selected'); + expect(screen.queryByRole('button', { name: /^share$/i })).toBeNull(); + } else { + expect.soft(onVerseSelect).not.toHaveBeenCalled(); + const selectedVerse = scenario === 'reselected same verse' ? 1 : 2; + expect.soft(getVerseEl(view.container, selectedVerse)).toHaveClass('yv-v-selected'); + expect.soft(screen.queryByRole('button', { name: /^share$/i })).not.toBeNull(); + } +}); diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx index 42e2146ed..4ebf0dbbf 100644 --- a/packages/ui/src/components/bible-reader.tsx +++ b/packages/ui/src/components/bible-reader.tsx @@ -857,9 +857,14 @@ function Content() { } const text = data?.text ?? ''; if (text && globalThis.navigator?.share instanceof Function) { + // Each selection update replaces this array, even when the same verses are reselected. + const sharedSelection = lastSelectionRef.current; globalThis.navigator .share({ text }) - .then(() => closeAndClearSelection()) + .then(() => { + if (lastSelectionRef.current !== sharedSelection) return; + closeAndClearSelectionRef.current(); + }) .catch(() => { // Cancelled or failed — keep the popover open (AC 4). }); From f9bd01422072c26821f6acf5e9967e379188e6ea Mon Sep 17 00:00:00 2001 From: Austin Date: Tue, 24 Nov 2026 14:33:48 -0600 Subject: [PATCH 09/75] fix(ui): label reader sign-in menu trigger (YPE-6810) (#492) * fix(ui): label reader sign-in menu trigger (YPE-6810) * test(ui): capture Linux WebKit dialog visibility failures * test(ui): stress WebKit visibility diagnostics * test(ui): check settings visibility after keyboard focus Assert dialog opening state after Enter and visibility on the Close button after native Tab, alongside the focus-ring checks. Remove temporary WebKit diagnostics and repeated CI groups. --- .changeset/reader-signin-accessible-name.md | 5 +++ .../src/components/bible-reader-toolbar.tsx | 2 +- .../src/components/bible-reader.stories.tsx | 7 ++-- .../ui/src/components/bible-reader.test.tsx | 40 ++++++++++++++++++- 4 files changed, 48 insertions(+), 6 deletions(-) create mode 100644 .changeset/reader-signin-accessible-name.md diff --git a/.changeset/reader-signin-accessible-name.md b/.changeset/reader-signin-accessible-name.md new file mode 100644 index 000000000..a550bef45 --- /dev/null +++ b/.changeset/reader-signin-accessible-name.md @@ -0,0 +1,5 @@ +--- +"@youversion/platform-react-ui": patch +--- + +Give the signed-out Bible reader user-menu trigger an accessible name using the existing translated sign-in label. diff --git a/packages/ui/src/components/bible-reader-toolbar.tsx b/packages/ui/src/components/bible-reader-toolbar.tsx index 0d4825ac4..0242d1620 100644 --- a/packages/ui/src/components/bible-reader-toolbar.tsx +++ b/packages/ui/src/components/bible-reader-toolbar.tsx @@ -70,7 +70,7 @@ function UserMenu() {
) : ( - )} diff --git a/packages/ui/src/components/bible-reader.stories.tsx b/packages/ui/src/components/bible-reader.stories.tsx index 155e624f9..7610b26db 100644 --- a/packages/ui/src/components/bible-reader.stories.tsx +++ b/packages/ui/src/components/bible-reader.stories.tsx @@ -256,10 +256,8 @@ export const SettingsCloseShowsFocusThroughToolbar: Story = { }); if (!nativeKeyAvailable) return; await verifyNativeBrowserKey('{Enter}', async () => { - await waitFor(async () => { - const overlay = await getReaderOverlay(root); - await expect(overlay.getByRole('dialog')).toBeVisible(); - }); + const overlay = await getReaderOverlay(root); + await expect(overlay.getByRole('dialog')).toHaveAttribute('data-state', 'open'); }); const settings = await getReaderOverlay(root); const closeButton = await settings.findByRole('button', { name: i18n.t('close') }); @@ -271,6 +269,7 @@ export const SettingsCloseShowsFocusThroughToolbar: Story = { }); const focusedIndicator = await waitFor(async () => { await expect(root.activeElement).toBe(closeButton); + await expect(closeButton).toBeVisible(); await expect(closeButton.matches(':focus-visible')).toBe(true); const style = getComputedStyle(closeButton); await expect(style.boxShadow).toContain('inset'); diff --git a/packages/ui/src/components/bible-reader.test.tsx b/packages/ui/src/components/bible-reader.test.tsx index a630a9a87..6271e7a70 100644 --- a/packages/ui/src/components/bible-reader.test.tsx +++ b/packages/ui/src/components/bible-reader.test.tsx @@ -849,7 +849,8 @@ it('uses the host sign-in action instead of starting web authentication', async
, ); await user.click(screen.getByTestId('user-menu-trigger')); - await user.click(await screen.findByRole('button', { name: 'Sign in' })); + const menu = await screen.findByRole('dialog', { name: i18n.t('signIn') }); + await user.click(within(menu).getByRole('button', { name: i18n.t('signIn') })); expect(onSignInPress).toHaveBeenCalledTimes(1); expect(signIn).not.toHaveBeenCalled(); } finally { @@ -891,3 +892,40 @@ it('keeps toolbar snapshots on committed settings while a host update is suspend await user.click(screen.getByRole('button', { name: 'Settings' })); expect(onOpen.mock.lastCall?.[0].fontSize).toBe(16); }); + +it('names the signed-out user menu trigger and supports keyboard sign-in through the host callback', async () => { + const user = userEvent.setup(); + const onSignInPress = vi.fn(); + render( + + + + + + + + + + + , + ); + + const trigger = screen.getByRole('button', { name: i18n.t('signIn') }); + trigger.focus(); + await user.keyboard('{Enter}'); + + const menu = await screen.findByRole('dialog', { name: i18n.t('signIn') }); + const signIn = within(menu).getByRole('button', { name: i18n.t('signIn') }); + signIn.focus(); + await user.keyboard('{Enter}'); + expect(onSignInPress).toHaveBeenCalledTimes(1); +}); From 6994c73216db2451dabdb87d8fff1a4ee491e3d0 Mon Sep 17 00:00:00 2001 From: Austin Date: Tue, 24 Nov 2026 15:03:12 -0600 Subject: [PATCH 10/75] fix(ui): handle reader clipboard failures (#490) * fix(ui): handle reader clipboard failures (YPE-6809) * fix(ui): report clipboard failures and retry failed shares * fix(ui): keep clipboard warnings visible while scrolling * fix(ui): ignore stale clipboard action results --- .changeset/reader-clipboard-failures.md | 5 + .../bible-reader-controlled.test.tsx | 156 ++++++++++++++++++ .../src/components/bible-reader.stories.tsx | 73 ++++++++ packages/ui/src/components/bible-reader.tsx | 64 +++++-- .../src/components/verse-of-the-day.test.tsx | 29 +++- .../ui/src/components/verse-of-the-day.tsx | 7 +- packages/ui/src/lib/clipboard.test.ts | 23 +++ packages/ui/src/lib/clipboard.ts | 11 ++ 8 files changed, 346 insertions(+), 22 deletions(-) create mode 100644 .changeset/reader-clipboard-failures.md create mode 100644 packages/ui/src/lib/clipboard.test.ts create mode 100644 packages/ui/src/lib/clipboard.ts diff --git a/.changeset/reader-clipboard-failures.md b/.changeset/reader-clipboard-failures.md new file mode 100644 index 000000000..fff5802dd --- /dev/null +++ b/.changeset/reader-clipboard-failures.md @@ -0,0 +1,5 @@ +--- +"@youversion/platform-react-ui": patch +--- + +Report rejected or unavailable clipboard writes in Bible reader Copy and Share fallback actions while preserving verse-selection clearing and popover dismissal. Keep the failure message visible within the reader when scrolling long chapters. Fall back to copying when native Share fails for reasons other than cancellation, and share clipboard handling with Verse of the Day. Clear clipboard failure feedback when navigating to another passage. Ignore pending clipboard results after navigation or a newer Copy or Share attempt. diff --git a/packages/ui/src/components/bible-reader-controlled.test.tsx b/packages/ui/src/components/bible-reader-controlled.test.tsx index 9e3251e9c..18cf8f516 100644 --- a/packages/ui/src/components/bible-reader-controlled.test.tsx +++ b/packages/ui/src/components/bible-reader-controlled.test.tsx @@ -39,6 +39,7 @@ import type { HighlightedVerses } from '@/lib/highlight-colors'; import { HIGHLIGHT_COLORS } from './verse-action-popover'; import { buildVerseReference, buildVerseShareText, joinVerseTexts } from '@/lib/verse-share'; import { ReuseShadowBoundary } from '@/lib/shadow-isolation'; +import en from '@/i18n/locales/en.json'; import { HIGHLIGHTS_LIVE, setHighlightsLive } from '@/lib/feature-flags'; import { peekPendingHighlights } from '@/lib/pending-highlight'; @@ -1273,6 +1274,161 @@ it('does not restore the verse menu after an outside click if the permission gra } }); +it('clears failed clipboard feedback on navigation after closing the verse menu', async ({ + onTestFinished, +}) => { + onTestFinished(() => { + vi.unstubAllGlobals(); + }); + const writes: string[] = []; + const writeText = (text: string): Promise => { + writes.push(text); + return Promise.reject(new DOMException('Clipboard permission denied', 'NotAllowedError')); + }; + vi.stubGlobal('navigator', { + userAgent: navigator.userAgent, + platform: navigator.platform, + clipboard: { writeText }, + share: undefined, + }); + const onVerseSelect = verseSelectSpy(); + const { container, rerender } = renderReader({ highlights: [], onVerseSelect, chapter: '1' }); + + for (const action of ['Copy', 'Share']) { + selectVerse(container, 1); + expect(getVerseEl(container, 1)).toHaveClass('yv-v-selected'); + const actionButton = await screen.findByRole('button', { + name: new RegExp(`^${action}$`, 'i'), + }); + const previousWrites = writes.length; + onVerseSelect.mockClear(); + + fireEvent.click(actionButton); + + expect(writes).toHaveLength(previousWrites + 1); + expect(writes.at(-1)).toBe('“In the beginning was the Word.”\n\nJohn 1:1 NIV'); + expect(lastSelection(onVerseSelect)).toEqual(selection([])); + expect(getVerseEl(container, 1)).not.toHaveClass('yv-v-selected'); + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent(en.unableToShare)); + expect(screen.getByRole('status')).toHaveAttribute('aria-live', 'polite'); + expect(screen.getByRole('status')).toBeVisible(); + await waitFor(() => { + expect(screen.queryByRole('button', { name: /^copy$/i })).toBeNull(); + expect(screen.queryByRole('button', { name: /^share$/i })).toBeNull(); + }); + + rerender(wrapReader({ highlights: [], onVerseSelect, chapter: '2' })); + await waitFor(() => expect(screen.getByRole('status')).toBeEmptyDOMElement()); + rerender(wrapReader({ highlights: [], onVerseSelect, chapter: '1' })); + } +}); + +it.each(['navigation', 'newer success', 'newer failure'])( + 'ignores an old clipboard result after %s', + async (scenario) => { + onTestFinished(() => { + vi.unstubAllGlobals(); + }); + const writes: { resolve: () => void; reject: (error: Error) => void }[] = []; + const writeText = () => + new Promise((resolve, reject) => { + writes.push({ resolve, reject }); + }); + vi.stubGlobal('navigator', { + userAgent: navigator.userAgent, + platform: navigator.platform, + clipboard: { writeText }, + share: undefined, + }); + const { container, rerender } = renderReader({ highlights: [], chapter: '1' }); + selectVerse(container, 1); + fireEvent.click(await screen.findByRole('button', { name: /^copy$/i })); + expect(writes).toHaveLength(1); + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + + if (scenario === 'navigation') { + rerender(wrapReader({ highlights: [], chapter: '2' })); + } else { + selectVerse(container, 1); + fireEvent.click(await screen.findByRole('button', { name: /^share$/i })); + expect(writes).toHaveLength(2); + await act(async () => { + if (scenario === 'newer failure') writes[1]!.reject(new Error('Permission denied')); + else writes[1]!.resolve(); + }); + } + if (scenario === 'newer failure') { + expect(screen.getByRole('status')).toHaveTextContent(en.unableToShare); + } else { + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + } + + await act(async () => { + if (scenario === 'newer failure') writes[0]!.resolve(); + else writes[0]!.reject(new Error('Permission denied')); + }); + if (scenario === 'newer failure') { + expect(screen.getByRole('status')).toHaveTextContent(en.unableToShare); + } else { + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + } + }, +); + +it('keeps native Share cancellation retryable and falls back to copying other failures', async ({ + onTestFinished, +}) => { + onTestFinished(() => { + vi.unstubAllGlobals(); + }); + let shareError: DOMException | null = new DOMException('Cancelled', 'AbortError'); + const share = vi.fn(async () => { + if (shareError) throw shareError; + }); + const writes: string[] = []; + const writeText = (text: string): Promise => { + writes.push(text); + return Promise.resolve(); + }; + const browser = { + userAgent: navigator.userAgent, + platform: navigator.platform, + clipboard: { writeText }, + share, + }; + vi.stubGlobal('navigator', browser); + const { container } = renderReader({ highlights: [] }); + selectVerse(container, 1); + fireEvent.click(await screen.findByRole('button', { name: /^share$/i })); + await waitFor(() => expect(share).toHaveBeenCalledTimes(1)); + expect(writes).toHaveLength(0); + expect(getVerseEl(container, 1)).toHaveClass('yv-v-selected'); + expect(screen.getByRole('button', { name: /^share$/i })).toBeVisible(); + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + + shareError = new DOMException('Not permitted', 'NotAllowedError'); + fireEvent.click(screen.getByRole('button', { name: /^share$/i })); + await waitFor(() => expect(writes).toHaveLength(1)); + expect(writes[0]).toBe('“In the beginning was the Word.”\n\nJohn 1:1 NIV'); + await waitFor(() => expectVerseMenuAbsent()); + expect(getVerseEl(container, 1)).not.toHaveClass('yv-v-selected'); + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + + vi.stubGlobal('navigator', { ...browser, clipboard: undefined }); + selectVerse(container, 1); + fireEvent.click(await screen.findByRole('button', { name: /^share$/i })); + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent(en.unableToShare)); + expectVerseMenuAbsent(); + expect(getVerseEl(container, 1)).not.toHaveClass('yv-v-selected'); + + shareError = null; + selectVerse(container, 1); + fireEvent.click(await screen.findByRole('button', { name: /^share$/i })); + await waitFor(() => expectVerseMenuAbsent()); + expect(getVerseEl(container, 1)).not.toHaveClass('yv-v-selected'); + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + expect(writes).toHaveLength(1); +}); it.each([ 'original selection', 'new selection', diff --git a/packages/ui/src/components/bible-reader.stories.tsx b/packages/ui/src/components/bible-reader.stories.tsx index 7610b26db..e258153ff 100644 --- a/packages/ui/src/components/bible-reader.stories.tsx +++ b/packages/ui/src/components/bible-reader.stories.tsx @@ -1926,3 +1926,76 @@ export const ChapterChangeLoadingOverlay: Story = { await expect(scroller?.scrollTop).toBe(0); }, }; + +export const ClipboardFailureAfterScrolling: Story = { + tags: ['integration', 'shadow-dom', 'cross-browser'], + args: { + defaultVersionId: 111, + defaultBook: 'JHN', + defaultChapter: '1', + }, + render: (args) => ( +
+ + + + +
+ ), + play: async ({ canvasElement }) => { + const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard'); + const shareDescriptor = Object.getOwnPropertyDescriptor(navigator, 'share'); + const writes: string[] = []; + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { + writeText: (text: string): Promise => { + writes.push(text); + return Promise.reject(new DOMException('Clipboard permission denied', 'NotAllowedError')); + }, + }, + }); + Object.defineProperty(navigator, 'share', { configurable: true, value: undefined }); + try { + const { root, reader } = await getReaderStory(canvasElement); + const { scroller, verse } = await waitFor(() => { + const scroller = root.querySelector('main'); + const verse = root.querySelector('.yv-v[v="40"]'); + if (!scroller || !verse) throw new Error('long chapter not rendered'); + return { scroller, verse }; + }); + await reader.findByRole('heading', { name: /John/i }); + const status = reader.getByRole('status', { name: '' }); + for (const action of ['Copy', 'Share']) { + verse.scrollIntoView({ block: 'center' }); + await waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(scroller.clientHeight)); + await userEvent.click(verse); + const overlay = await getReaderOverlay(root); + await userEvent.click(await overlay.findByRole('button', { name: action })); + await waitFor(() => expect(status).not.toBeEmptyDOMElement()); + await expect(status).toHaveAttribute('aria-live', 'polite'); + await expect(verse).not.toHaveClass('yv-v-selected'); + await waitFor(() => expect(overlay.queryByRole('dialog')).toBeNull()); + + const expectWarningInView = () => { + const warningBounds = status.getBoundingClientRect(); + const readerBounds = scroller.getBoundingClientRect(); + void expect(warningBounds.height).toBeGreaterThan(0); + void expect(warningBounds.top).toBeGreaterThanOrEqual(Math.max(readerBounds.top, 0)); + void expect(warningBounds.bottom).toBeLessThanOrEqual( + Math.min(readerBounds.bottom, window.innerHeight), + ); + }; + await waitFor(expectWarningInView); + scroller.scrollTop += 80; + await waitFor(expectWarningInView); + } + await expect(writes).toHaveLength(2); + } finally { + if (clipboardDescriptor) Object.defineProperty(navigator, 'clipboard', clipboardDescriptor); + else Reflect.deleteProperty(navigator, 'clipboard'); + if (shareDescriptor) Object.defineProperty(navigator, 'share', shareDescriptor); + else Reflect.deleteProperty(navigator, 'share'); + } + }, +}; diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx index 4ebf0dbbf..7d7a52074 100644 --- a/packages/ui/src/components/bible-reader.tsx +++ b/packages/ui/src/components/bible-reader.tsx @@ -1,6 +1,7 @@ 'use client'; import i18n from '@/i18n'; +import { copyTextToClipboard } from '@/lib/clipboard'; import { useInterfaceDirection } from '@/lib/direction'; import { useDelayedLoading } from '@/lib/use-delayed-loading'; import { useHighlightsControlledLatch } from '@/lib/use-highlights-controlled-latch'; @@ -553,6 +554,8 @@ function Content() { }); const [selectedVerses, setSelectedVerses] = useState([]); const [popoverOpen, setPopoverOpen] = useState(false); + const [clipboardFailed, setClipboardFailed] = useState(false); + const actionAttemptRef = useRef(0); const [anchorElement, setAnchorElement] = useState(null); const verseFocusRestoreTargetRef = useRef(null); const takeVerseFocusRestoreTarget = useCallback(() => { @@ -612,6 +615,8 @@ function Content() { // Navigating away (book/chapter/version) drops the selection — those verses // no longer exist on screen (ADR-007). useEffect(() => { + actionAttemptRef.current += 1; + setClipboardFailed(false); setSelectedVerses([]); setPopoverOpen(false); setAnchorElement(null); @@ -829,22 +834,32 @@ function Content() { }; } + async function copySelectionText(text: string, attempt: number) { + const copied = await copyTextToClipboard(text); + if (actionAttemptRef.current !== attempt) return; + setClipboardFailed(!copied); + } + function handleCopy() { + const attempt = ++actionAttemptRef.current; + setClipboardFailed(false); const data = buildSelectionShareData(selectedVerses); if (onCopy) { if (data) { void Promise.resolve(onCopy(data)).catch(() => { - // Host rejected — mirror the silent failure of navigator.clipboard. + // Host overrides own their error feedback. }); } closeAndClearSelection(); return; } - if (data?.text) void navigator.clipboard?.writeText(data.text); + if (data?.text) void copySelectionText(data.text, attempt); closeAndClearSelection(); } function handleShare() { + const attempt = ++actionAttemptRef.current; + setClipboardFailed(false); const data = buildSelectionShareData(selectedVerses); if (onShare) { if (data) { @@ -855,25 +870,32 @@ function Content() { closeAndClearSelection(); return; } - const text = data?.text ?? ''; + void shareSelectionText(data?.text ?? '', attempt); + } + + async function shareSelectionText(text: string, attempt: number) { if (text && globalThis.navigator?.share instanceof Function) { // Each selection update replaces this array, even when the same verses are reselected. const sharedSelection = lastSelectionRef.current; - globalThis.navigator - .share({ text }) - .then(() => { - if (lastSelectionRef.current !== sharedSelection) return; - closeAndClearSelectionRef.current(); - }) - .catch(() => { - // Cancelled or failed — keep the popover open (AC 4). - }); - return; - } - // No Web Share support (e.g. most desktop browsers) — fall back to clipboard. - if (text && globalThis.navigator) { - void globalThis.navigator.clipboard?.writeText(text); + try { + await globalThis.navigator.share({ text }); + if (actionAttemptRef.current !== attempt || lastSelectionRef.current !== sharedSelection) + return; + closeAndClearSelectionRef.current(); + return; + } catch (error) { + // A cancelled share keeps the selection and popover available for retry. + if ( + (error instanceof DOMException || error instanceof Error) && + error.name === 'AbortError' + ) + return; + if (actionAttemptRef.current !== attempt || lastSelectionRef.current !== sharedSelection) + return; + } } + // Unsupported or failed Web Share falls back to clipboard. + if (text) void copySelectionText(text, attempt); closeAndClearSelection(); } @@ -952,6 +974,14 @@ function Content() { +
+ {clipboardFailed ? t('unableToShare') : null} +
+ {chapterUnavailable ? (

{t('chapterUnavailable')} diff --git a/packages/ui/src/components/verse-of-the-day.test.tsx b/packages/ui/src/components/verse-of-the-day.test.tsx index 3654e1cb3..d93537ff6 100644 --- a/packages/ui/src/components/verse-of-the-day.test.tsx +++ b/packages/ui/src/components/verse-of-the-day.test.tsx @@ -2,7 +2,7 @@ * @vitest-environment jsdom */ import { describe, expect, it, vi } from 'vitest'; -import { render as rtlRender, screen } from '@testing-library/react'; +import { render as rtlRender, screen, waitFor } from '@testing-library/react'; import type { ReactElement } from 'react'; import userEvent from '@testing-library/user-event'; import type { HookOverrides } from '@youversion/platform-react-hooks'; @@ -349,3 +349,30 @@ describe('VerseOfTheDay - host highlights (controlled mode)', () => { } }); }); + +it('reports denied and unavailable Verse of the Day clipboard access', async ({ + onTestFinished, +}) => { + onTestFinished(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + const user = userEvent.setup(); + const writes: string[] = []; + const writeText = (text: string): Promise => { + writes.push(text); + return Promise.reject(new DOMException('Clipboard permission denied', 'NotAllowedError')); + }; + const alert = vi.spyOn(window, 'alert').mockImplementation(() => undefined); + vi.stubGlobal('navigator', { clipboard: { writeText }, share: undefined }); + renderVotd(); + await user.click(screen.getByRole('button', { name: en.share })); + await waitFor(() => expect(alert).toHaveBeenCalledWith(en.unableToShare)); + expect(writes).toHaveLength(1); + alert.mockClear(); + + vi.stubGlobal('navigator', { share: undefined }); + await user.click(screen.getByRole('button', { name: en.share })); + await waitFor(() => expect(alert).toHaveBeenCalledWith(en.unableToShare)); + expect(writes).toHaveLength(1); +}); diff --git a/packages/ui/src/components/verse-of-the-day.tsx b/packages/ui/src/components/verse-of-the-day.tsx index b12d2c8b0..5ff559da8 100644 --- a/packages/ui/src/components/verse-of-the-day.tsx +++ b/packages/ui/src/components/verse-of-the-day.tsx @@ -10,6 +10,7 @@ import { import React from 'react'; import { useTranslation } from 'react-i18next'; import i18n from '@/i18n'; +import { copyTextToClipboard } from '@/lib/clipboard'; import { YvComponentStyles } from '@/lib/yv-styles-components'; import { AnimatedHeight } from '@/components/animated-height'; import { BibleAppLogoLockup } from '@/components/bible-app-logo-lockup'; @@ -141,10 +142,8 @@ async function share({ } catch { // Silently fail } - } else if (navigator.clipboard) { - navigator.clipboard.writeText(text).catch(() => { - alert(errorMessage); - }); + } else if (!(await copyTextToClipboard(text))) { + alert(errorMessage); } } diff --git a/packages/ui/src/lib/clipboard.test.ts b/packages/ui/src/lib/clipboard.test.ts new file mode 100644 index 000000000..b79b1656c --- /dev/null +++ b/packages/ui/src/lib/clipboard.test.ts @@ -0,0 +1,23 @@ +import { expect, it, vi } from 'vitest'; +import { copyTextToClipboard } from './clipboard'; + +it('copies text and tolerates denied or unavailable clipboard access', async ({ onTestFinished }) => { + onTestFinished(() => { + vi.unstubAllGlobals(); + }); + const writeText = vi.fn().mockResolvedValue(undefined); + vi.stubGlobal('navigator', { clipboard: { writeText } }); + + await expect(copyTextToClipboard('John 3:16')).resolves.toBe(true); + expect(writeText).toHaveBeenCalledWith('John 3:16'); + + writeText.mockRejectedValue(new Error('Clipboard permission denied')); + await expect(copyTextToClipboard('John 3:17')).resolves.toBe(false); + expect(writeText).toHaveBeenLastCalledWith('John 3:17'); + + vi.stubGlobal('navigator', {}); + await expect(copyTextToClipboard('John 3:18')).resolves.toBe(false); + + vi.stubGlobal('navigator', undefined); + await expect(copyTextToClipboard('John 3:19')).resolves.toBe(false); +}); diff --git a/packages/ui/src/lib/clipboard.ts b/packages/ui/src/lib/clipboard.ts new file mode 100644 index 000000000..a2e9b855d --- /dev/null +++ b/packages/ui/src/lib/clipboard.ts @@ -0,0 +1,11 @@ +/** Resolves with whether the text was copied, including when clipboard access is denied or unavailable. */ +export async function copyTextToClipboard(text: string): Promise { + try { + const clipboard = globalThis.navigator?.clipboard; + if (!clipboard) return false; + await clipboard.writeText(text); + return true; + } catch { + return false; + } +} From 51024a3afdd931f26f7fa1eb0ce3939c0cfaf40c Mon Sep 17 00:00:00 2001 From: Austin Date: Tue, 24 Nov 2026 15:11:08 -0600 Subject: [PATCH 11/75] fix(ui): support Bible reader interactions in iframes (YPE-6410) (#491) * fix(ui): retain iframe verse selection and anchors (YPE-6410) * test(ui): cover iframe highlight painting and reset * fix(ui): complete iframe reader text and focus handling --- .changeset/reader-iframe-selection.md | 5 + .../bible-reader-controlled.test.tsx | 196 ++++++++++++++++++ packages/ui/src/components/bible-reader.tsx | 5 +- packages/ui/src/components/verse.tsx | 11 +- .../ui/src/lib/use-transient-verse-focus.ts | 52 +++-- 5 files changed, 241 insertions(+), 28 deletions(-) create mode 100644 .changeset/reader-iframe-selection.md diff --git a/.changeset/reader-iframe-selection.md b/.changeset/reader-iframe-selection.md new file mode 100644 index 000000000..62b4cf8f5 --- /dev/null +++ b/.changeset/reader-iframe-selection.md @@ -0,0 +1,5 @@ +--- +"@youversion/platform-react-ui": patch +--- + +Use the owning document for iframe verse selection, highlight painting, popover anchoring, clean Copy and Share text, footnote verse HTML, and transient verse focus with its scroll and reduced-motion settings. diff --git a/packages/ui/src/components/bible-reader-controlled.test.tsx b/packages/ui/src/components/bible-reader-controlled.test.tsx index 18cf8f516..66b557664 100644 --- a/packages/ui/src/components/bible-reader-controlled.test.tsx +++ b/packages/ui/src/components/bible-reader-controlled.test.tsx @@ -45,6 +45,7 @@ import { HIGHLIGHTS_LIVE, setHighlightsLive } from '@/lib/feature-flags'; import { peekPendingHighlights } from '@/lib/pending-highlight'; import { fillFor, mockUserInfo } from '@/test/highlights-test-utils'; import { installResizeObserverStub } from '@/test/dom-stubs'; +import { BibleReaderNavigation } from './bible-reader-navigation'; installResizeObserverStub(); @@ -1274,6 +1275,201 @@ it('does not restore the verse menu after an outside click if the permission gra } }); +it('selects and anchors iframe verses and resets highlight fills and label colors', async ({ + onTestFinished, +}) => { + const iframe = document.createElement('iframe'); + document.body.append(iframe); + onTestFinished(() => iframe.remove()); + const iframeDocument = iframe.contentDocument; + if (!iframeDocument) throw new Error('same-origin iframe document not available'); + Object.defineProperty(Object.getPrototypeOf(iframeDocument.createElement('main')), 'scrollTo', { + value: vi.fn(), + configurable: true, + }); + const mount = iframeDocument.createElement('div'); + iframeDocument.body.append(mount); + const onVerseSelect = verseSelectSpy(); + const view = render( + wrapReader({ + highlights: [{ version_id: 111, passage_id: 'JHN.1.1', color: YELLOW }], + onVerseSelect, + }), + { container: mount, baseElement: iframeDocument.body }, + ); + onTestFinished(() => view.unmount()); + const verse = getVerseEl(mount, 1); + const label = verse.querySelector('.yv-vlbl'); + if (!label) throw new Error('verse number label not rendered'); + expect(verse.ownerDocument).toBe(iframeDocument); + expect(verse).not.toBeInstanceOf(HTMLElement); + expect(label.ownerDocument).toBe(iframeDocument); + expect(label).not.toBeInstanceOf(HTMLElement); + expect(verse.style.backgroundColor).toBe(fillFor(YELLOW)); + expect(label.style.color).toBe('inherit'); + vi.spyOn(verse, 'getBoundingClientRect').mockReturnValue(new DOMRect(100, 100, 240, 24)); + + fireEvent.click(verse); + + expect(lastSelection(onVerseSelect).verses).toEqual([1]); + expect(verse).toHaveClass('yv-v-selected'); + await waitFor(() => { + const popover = document.querySelector('[data-radix-popper-content-wrapper]'); + expect(popover?.style.getPropertyValue('--radix-popper-anchor-width')).toBe('240px'); + }); + + view.rerender(wrapReader({ highlights: [], onVerseSelect })); + + const unhighlightedVerse = getVerseEl(mount, 1); + const unhighlightedLabel = unhighlightedVerse.querySelector('.yv-vlbl'); + if (!unhighlightedLabel) + throw new Error('verse number label not rendered after highlight removal'); + expect(unhighlightedVerse.style.backgroundColor).toBe(''); + expect(unhighlightedLabel.style.color).toBe(''); +}); + +function renderIframeReader( + props: Partial = {}, + overrides = defaultOverrides(), +) { + const iframe = document.createElement('iframe'); + document.body.append(iframe); + const iframeDocument = iframe.contentDocument; + if (!iframeDocument) throw new Error('same-origin iframe document unavailable'); + Object.defineProperty(Object.getPrototypeOf(iframeDocument.createElement('main')), 'scrollTo', { + value: vi.fn(), + configurable: true, + }); + const mount = iframeDocument.createElement('div'); + iframeDocument.body.append(mount); + const view = render(wrapReader({ highlights: [], ...props }, overrides), { + container: mount, + baseElement: iframeDocument.body, + }); + onTestFinished(() => { + view.unmount(); + iframe.remove(); + }); + expect(getVerseEl(mount, 1).ownerDocument).toBe(iframeDocument); + expect(getVerseEl(mount, 1)).not.toBeInstanceOf(HTMLElement); + return { ...view, mount, iframeDocument }; +} + +it('matches top-document selection and Copy payloads in an iframe and clears on a second verse tap', async () => { + const topSelections = verseSelectSpy(); + const topView = renderReader({ highlights: [], onVerseSelect: topSelections }); + selectVerse(topView.container, 1); + selectVerse(topView.container, 3); + const expected = lastSelection(topSelections); + expect(expected).toEqual(selection([1, 3])); + expect(expected.shareData?.verseText).toBe( + 'In the beginning was the Word. ... Through him all things were made.', + ); + topView.unmount(); + + const iframeSelections = verseSelectSpy(); + const onCopy = vi.fn<(data: BibleReaderShareData) => void>(); + const view = renderIframeReader({ onVerseSelect: iframeSelections, onCopy }); + selectVerse(view.mount, 1); + selectVerse(view.mount, 3); + expect.soft(lastSelection(iframeSelections)).toEqual(expected); + + fireEvent.click(await screen.findByRole('button', { name: /^copy$/i })); + expect.soft(onCopy).toHaveBeenCalledExactlyOnceWith(expected.shareData); + + const verse = getVerseEl(view.mount, 1); + fireEvent.click(verse); + expect(verse).toHaveClass('yv-v-selected'); + fireEvent.click(verse); + expect(lastSelection(iframeSelections)).toEqual(selection([])); + expect(verse).not.toHaveClass('yv-v-selected'); + expect(screen.queryByRole('button', { name: /^copy$/i })).toBeNull(); +}); + +it('paints and focuses the requested iframe verse until user input', async () => { + const navigation = new BibleReaderNavigation(); + const onVerseSelect = verseSelectSpy(); + const view = renderIframeReader({ navigation, onVerseSelect }); + const verse = getVerseEl(view.mount, 1); + const renderer = view.mount.querySelector('[data-slot="yv-bible-renderer"]'); + if (!renderer) throw new Error('reader renderer unavailable'); + + act(() => navigation.focusReference({ versionId: 111, passageId: 'JHN.1.1' }, false)); + + await waitFor(() => expect(renderer).toHaveAttribute('data-yv-verse-focus')); + expect.soft(verse).toHaveClass('yv-v-focused'); + expect.soft(view.iframeDocument.activeElement === verse).toBe(true); + expect(onVerseSelect).not.toHaveBeenCalled(); + + fireEvent.pointerDown(verse); + expect(renderer).not.toHaveAttribute('data-yv-verse-focus'); + expect(verse).not.toHaveClass('yv-v-focused'); +}); + +it('extracts iframe footnote verse HTML without verse labels or note text', async () => { + const onFootnotePress = vi.fn>(); + const overrides: HookOverrides = { + ...defaultOverrides(), + usePassage: () => ({ + passage: { + ...mockPassage, + content: mockPassage.content.replace( + 'In the beginning was the Word.', + 'In the beginning was the Word.1:1 A note.', + ), + }, + loading: false, + error: null, + refetch: () => undefined, + }), + }; + const view = renderIframeReader({ onFootnotePress }, overrides); + const footnote = await waitFor(() => { + const button = view.mount.querySelector('[data-verse-footnote="1"] button'); + if (!button) throw new Error('iframe footnote button unavailable'); + return button; + }); + + fireEvent.click(footnote); + + expect(onFootnotePress).toHaveBeenCalledTimes(1); + const payload = onFootnotePress.mock.lastCall?.[0]; + expect(payload?.verseHtml).toContain('In the beginning was the Word.'); + expect(payload?.verseHtml).toContain(' { + const navigation = new BibleReaderNavigation(); + const view = renderIframeReader({ navigation }); + const ownerWindow = view.iframeDocument.defaultView; + if (!ownerWindow) throw new Error('iframe window unavailable'); + const matchMedia = vi.fn(() => ({ matches: true })); + Object.defineProperty(ownerWindow, 'matchMedia', { value: matchMedia, configurable: true }); + const verse = getVerseEl(view.mount, 1); + const scrollVerse = vi.fn(); + verse.scrollIntoView = scrollVerse; + const renderer = view.mount.querySelector('[data-slot="yv-bible-renderer"]'); + if (!renderer) throw new Error('reader renderer unavailable'); + const scrollContainer = vi.fn(); + renderer.scrollIntoView = scrollContainer; + + act(() => navigation.focusReference({ versionId: 111, passageId: 'JHN.1.1' })); + + await waitFor(() => expect(renderer).toHaveAttribute('data-yv-verse-focus')); + expect.soft(matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)'); + expect.soft(scrollVerse).toHaveBeenCalledWith({ block: 'center', behavior: 'auto' }); + expect.soft(scrollContainer).not.toHaveBeenCalled(); + expect.soft(verse).toHaveClass('yv-v-focused'); + expect.soft(view.iframeDocument.activeElement === verse).toBe(true); + + fireEvent.wheel(view.iframeDocument.documentElement); + + expect(renderer).not.toHaveAttribute('data-yv-verse-focus'); + expect(verse).not.toHaveClass('yv-v-focused'); +}); + it('clears failed clipboard feedback on navigation after closing the verse menu', async ({ onTestFinished, }) => { diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx index 7d7a52074..1bd7b7a40 100644 --- a/packages/ui/src/components/bible-reader.tsx +++ b/packages/ui/src/components/bible-reader.tsx @@ -766,7 +766,10 @@ function Content() { const anchorVerse = added ?? Math.max(...verses); const wrappers = readerRef.current?.querySelectorAll(`.yv-v[v="${anchorVerse}"]`); const anchor = wrappers?.[wrappers.length - 1]; - setAnchorElement(anchor instanceof HTMLElement ? anchor : null); + const container = readerRef.current; + setAnchorElement( + container && isElementFromOwnerDocument(anchor, container, 'HTMLElement') ? anchor : null, + ); setPopoverOpen(true); } diff --git a/packages/ui/src/components/verse.tsx b/packages/ui/src/components/verse.tsx index cb6d630f4..c640c5980 100644 --- a/packages/ui/src/components/verse.tsx +++ b/packages/ui/src/components/verse.tsx @@ -37,6 +37,7 @@ import { useScriptureHighlightPaint } from '@/lib/use-scripture-highlight-paint' import { useInterfaceDirection } from '@/lib/direction'; import { useHydrationSafeScriptureDirection } from '@/lib/scripture-direction'; import { ReuseShadowBoundary, ShadowIsolationBoundary } from '@/lib/shadow-isolation'; +import { isElementFromOwnerDocument } from '@/lib/shadow-root-host'; const LETTERS = 'abcdefghijklmnopqrstuvwxyz'; type ResolvedScriptureDirection = TextDirection | 'auto'; @@ -170,7 +171,7 @@ function getVerseHtmlFromDom(container: HTMLElement, verseNum: string): string { wrappers.forEach((wrapper, i) => { if (i > 0) parts.push(' '); const clone = wrapper.cloneNode(true); - if (!(clone instanceof Element)) return; + if (!isElementFromOwnerDocument(clone, wrapper, 'Element')) return; clone.querySelectorAll('.yv-h, .yv-vlbl, .va').forEach((el) => el.remove()); clone.querySelectorAll('[data-verse-footnote]').forEach((anchor) => { const sup = wrapper.ownerDocument.createElement('sup'); @@ -208,7 +209,7 @@ export function getCleanVerseText(container: HTMLElement, verseNum: number): str const parts: string[] = []; wrappers.forEach((wrapper) => { const clone = wrapper.cloneNode(true); - if (!(clone instanceof Element)) return; + if (!isElementFromOwnerDocument(clone, wrapper, 'Element')) return; clone .querySelectorAll('.yv-h, .yv-vlbl, .va, [data-verse-footnote]') .forEach((el) => el.remove()); @@ -424,7 +425,7 @@ function BibleTextHtml({ if (!contentRef.current) return; const isDark = currentTheme === 'dark'; contentRef.current.querySelectorAll('.yv-v[v]').forEach((el) => { - if (!(el instanceof HTMLElement)) return; + if (!isElementFromOwnerDocument(el, el, 'HTMLElement')) return; const verseNum = parseInt(el.getAttribute('v') || '0', 10); el.classList.toggle('yv-v-selected', selectedVerses.includes(verseNum)); const color = highlightedVerses[verseNum]; @@ -446,7 +447,7 @@ function BibleTextHtml({ // so they keep their CSS muted color. Deliberate divergence from the Swift // SDK, which only recolors the label in dark mode. el.querySelectorAll('.yv-vlbl, .va').forEach((label) => { - if (!(label instanceof HTMLElement)) return; + if (!isElementFromOwnerDocument(label, el, 'HTMLElement')) return; label.style.color = isHighlighted ? 'inherit' : ''; }); }); @@ -457,7 +458,7 @@ function BibleTextHtml({ const handleClick = onVerseSelect ? (e: React.MouseEvent) => { const target = e.target; - if (!(target instanceof Element)) return; + if (!isElementFromOwnerDocument(target, e.currentTarget, 'Element')) return; const verseEl = target.closest('.yv-v[v]'); if (!verseEl) return; const verseNum = parseInt(verseEl.getAttribute('v') || '0', 10); diff --git a/packages/ui/src/lib/use-transient-verse-focus.ts b/packages/ui/src/lib/use-transient-verse-focus.ts index 94d2568c3..c8fbbbf63 100644 --- a/packages/ui/src/lib/use-transient-verse-focus.ts +++ b/packages/ui/src/lib/use-transient-verse-focus.ts @@ -1,5 +1,6 @@ import { useLayoutEffect, useRef, type RefObject } from 'react'; import type { BibleReaderNavigationRequest } from '@/components/bible-reader-navigation'; +import { isElementFromOwnerDocument } from './shadow-root-host'; import { prefersReducedMotion } from './reduced-motion'; export type VerseFocusRequest = BibleReaderNavigationRequest & @@ -12,7 +13,7 @@ function paintFocus(container: HTMLElement, verses: readonly number[]): void { container.setAttribute('data-yv-verse-focus', ''); const wanted = new Set(verses); container.querySelectorAll('.yv-v[v]').forEach((node) => { - if (!(node instanceof HTMLElement)) return; + if (!isElementFromOwnerDocument(node, container, 'HTMLElement')) return; const verseNum = Number.parseInt(node.getAttribute('v') ?? '', 10); node.classList.toggle('yv-v-focused', wanted.has(verseNum)); }); @@ -26,15 +27,16 @@ function clearFocusPaint(container: HTMLElement): void { } function overflowAncestor(start: HTMLElement): HTMLElement { + const ownerDocument = start.ownerDocument; let node: HTMLElement | null = start; while (node !== null) { - const overflowY = globalThis.getComputedStyle(node).overflowY; + const overflowY = ownerDocument.defaultView?.getComputedStyle(node).overflowY; if (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') { return node; } node = node.parentElement; } - return document.documentElement; + return ownerDocument.documentElement; } /** @@ -56,6 +58,9 @@ export function useTransientVerseFocus(args: { if (request === null || container === null || handledSeq.current === request.seq) { return; } + const ownerDocument = container.ownerDocument; + const ownerWindow = ownerDocument.defaultView; + if (ownerWindow === null) return; const reference = request.showsFullChapter ? `${request.book}.${request.chapter}` : request.passageId; @@ -65,36 +70,39 @@ export function useTransientVerseFocus(args: { const verses = request.verses; const first = verses[0]; - const target = container.querySelector(`.yv-v[v="${String(first)}"]`); + const candidate = container.querySelector(`.yv-v[v="${String(first)}"]`); + const target = isElementFromOwnerDocument(candidate, container, 'HTMLElement') + ? candidate + : null; const scroller = overflowAncestor(container); - const scrollEvents = scroller === document.documentElement ? document : scroller; + const scrollEvents = scroller === ownerDocument.documentElement ? ownerDocument : scroller; let waiting = false; let cleared = false; - let settle: ReturnType | undefined; - let fallback: ReturnType | undefined; + let settle: number | undefined; + let fallback: number | undefined; const clear = (): void => { cleared = true; waiting = false; - globalThis.clearTimeout(settle); - globalThis.clearTimeout(fallback); + ownerWindow.clearTimeout(settle); + ownerWindow.clearTimeout(fallback); clearFocusPaint(container); }; const landed = (): void => { handledSeq.current = request.seq; waiting = false; - globalThis.clearTimeout(settle); - globalThis.clearTimeout(fallback); + ownerWindow.clearTimeout(settle); + ownerWindow.clearTimeout(fallback); if (cleared || !request.shouldFocus || verses.length === 0) return; paintFocus(container, verses); - if (target instanceof HTMLElement) { + if (target !== null) { target.tabIndex = -1; target.focus({ preventScroll: true }); } }; const onScroll = (): void => { if (!waiting) return; - globalThis.clearTimeout(settle); - settle = globalThis.setTimeout(landed, 100); + ownerWindow.clearTimeout(settle); + settle = ownerWindow.setTimeout(landed, 100); }; const onScrollEnd = (): void => { if (waiting) landed(); @@ -110,18 +118,18 @@ export function useTransientVerseFocus(args: { for (const event of ['pointerdown', 'keydown', 'wheel', 'touchstart']) { scroller.addEventListener(event, onInteract, { passive: true }); } - const frame = globalThis.requestAnimationFrame(() => { + const frame = ownerWindow.requestAnimationFrame(() => { if (cleared) return; if (!request.scrollsToVerse) { landed(); return; } - const reducedMotion = prefersReducedMotion(); + const reducedMotion = prefersReducedMotion(ownerWindow); waiting = true; - const destination = - request.showsFullChapter && target instanceof HTMLElement ? target : container; + const scrollToVerse = request.showsFullChapter && target !== null; + const destination = scrollToVerse ? target : container; destination.scrollIntoView({ - block: request.showsFullChapter && target instanceof HTMLElement ? 'center' : 'start', + block: scrollToVerse ? 'center' : 'start', behavior: reducedMotion ? 'auto' : 'smooth', }); if (reducedMotion) { @@ -129,12 +137,12 @@ export function useTransientVerseFocus(args: { return; } // scrollend is not universal, and a no-op scroll emits no events. - settle = globalThis.setTimeout(landed, 100); - fallback = globalThis.setTimeout(landed, 2000); + settle = ownerWindow.setTimeout(landed, 100); + fallback = ownerWindow.setTimeout(landed, 2000); }); return () => { - globalThis.cancelAnimationFrame(frame); + ownerWindow.cancelAnimationFrame(frame); scrollEvents.removeEventListener('scroll', onScroll); scrollEvents.removeEventListener('scrollend', onScrollEnd); for (const event of ['pointerdown', 'keydown', 'wheel', 'touchstart']) { From 7398f57e5c910ed5afb1dcf7326ecb09a46e506b Mon Sep 17 00:00:00 2001 From: Austin Date: Tue, 24 Nov 2026 15:27:55 -0600 Subject: [PATCH 12/75] fix(ui): handle reader host callback exceptions (YPE-6811) (#493) --- .changeset/reader-host-callback-errors.md | 5 +++ .../bible-reader-controlled.test.tsx | 45 +++++++++++++++++++ packages/ui/src/components/bible-reader.tsx | 23 +++++----- 3 files changed, 63 insertions(+), 10 deletions(-) create mode 100644 .changeset/reader-host-callback-errors.md diff --git a/.changeset/reader-host-callback-errors.md b/.changeset/reader-host-callback-errors.md new file mode 100644 index 000000000..244273426 --- /dev/null +++ b/.changeset/reader-host-callback-errors.md @@ -0,0 +1,5 @@ +--- +'@youversion/platform-react-ui': patch +--- + +Handle immediate exceptions from Bible reader host Copy and Share callbacks consistently with rejected promises, preserving verse-selection clearing and popover dismissal. diff --git a/packages/ui/src/components/bible-reader-controlled.test.tsx b/packages/ui/src/components/bible-reader-controlled.test.tsx index 66b557664..c32a37d01 100644 --- a/packages/ui/src/components/bible-reader-controlled.test.tsx +++ b/packages/ui/src/components/bible-reader-controlled.test.tsx @@ -1275,6 +1275,51 @@ it('does not restore the verse menu after an outside click if the permission gra } }); +it.each([ + { action: 'Copy', failure: 'synchronous throw' }, + { action: 'Share', failure: 'synchronous throw' }, + { action: 'Copy', failure: 'rejected promise' }, + { action: 'Share', failure: 'rejected promise' }, +])( + 'clears selection and dismisses $action after a host callback $failure', + async ({ action, failure }) => { + const callbackError = new Error('Host callback failed'); + const reportedErrors: unknown[] = []; + const onError = (event: ErrorEvent) => { + if (event.error !== callbackError) return; + reportedErrors.push(event.error); + // Observe the deliberate error without letting it abort the state assertions. + event.preventDefault(); + }; + window.addEventListener('error', onError); + onTestFinished(() => window.removeEventListener('error', onError)); + const callback = vi.fn<(data: BibleReaderShareData) => void | Promise>(() => { + if (failure === 'synchronous throw') throw callbackError; + return Promise.reject(callbackError); + }); + const onVerseSelect = verseSelectSpy(); + const { container } = renderReader({ + highlights: [], + onVerseSelect, + onCopy: action === 'Copy' ? callback : undefined, + onShare: action === 'Share' ? callback : undefined, + }); + selectVerse(container, 1); + expect(getVerseEl(container, 1)).toHaveClass('yv-v-selected'); + const button = await screen.findByRole('button', { name: new RegExp(`^${action}$`, 'i') }); + onVerseSelect.mockClear(); + + fireEvent.click(button); + expect(callback).toHaveBeenCalledTimes(1); + await Promise.resolve(); + + expect.soft(reportedErrors).toEqual([]); + expect.soft(onVerseSelect).toHaveBeenLastCalledWith(selection([])); + expect.soft(getVerseEl(container, 1)).not.toHaveClass('yv-v-selected'); + expect.soft(screen.queryByRole('button', { name: new RegExp(`^${action}$`, 'i') })).toBeNull(); + }, +); + it('selects and anchors iframe verses and resets highlight fills and label colors', async ({ onTestFinished, }) => { diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx index 1bd7b7a40..80e90c66d 100644 --- a/packages/ui/src/components/bible-reader.tsx +++ b/packages/ui/src/components/bible-reader.tsx @@ -837,6 +837,17 @@ function Content() { }; } + async function runHostVerseAction( + action: (data: BibleReaderShareData) => void | Promise, + data: BibleReaderShareData, + ): Promise { + try { + await action(data); + } catch { + // Host failure must not interrupt verse-selection and popover cleanup. + } + } + async function copySelectionText(text: string, attempt: number) { const copied = await copyTextToClipboard(text); if (actionAttemptRef.current !== attempt) return; @@ -848,11 +859,7 @@ function Content() { setClipboardFailed(false); const data = buildSelectionShareData(selectedVerses); if (onCopy) { - if (data) { - void Promise.resolve(onCopy(data)).catch(() => { - // Host overrides own their error feedback. - }); - } + if (data) void runHostVerseAction(onCopy, data); closeAndClearSelection(); return; } @@ -865,11 +872,7 @@ function Content() { setClipboardFailed(false); const data = buildSelectionShareData(selectedVerses); if (onShare) { - if (data) { - void Promise.resolve(onShare(data)).catch(() => { - // Host rejected or cancelled — mirror the silent navigator.share dismiss. - }); - } + if (data) void runHostVerseAction(onShare, data); closeAndClearSelection(); return; } From 1ddd22d949a2585ceb07808db864983cdbd6ceb3 Mon Sep 17 00:00:00 2001 From: Austin Date: Wed, 25 Nov 2026 10:52:46 -0600 Subject: [PATCH 13/75] chore(ui): align declaration build with strict checks (YPE-6464) (#503) chore(ui): align declaration build with strict checks Refs: YPE-6464 --- .changeset/salty-bugs-pick.md | 2 ++ packages/ui/tsconfig.build.json | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 .changeset/salty-bugs-pick.md diff --git a/.changeset/salty-bugs-pick.md b/.changeset/salty-bugs-pick.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/salty-bugs-pick.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/packages/ui/tsconfig.build.json b/packages/ui/tsconfig.build.json index 7abb664c2..be922e14e 100644 --- a/packages/ui/tsconfig.build.json +++ b/packages/ui/tsconfig.build.json @@ -1,6 +1,7 @@ { - "extends": "../../tsconfig.json", + "extends": "./tsconfig.json", "compilerOptions": { + "noEmit": false, "declaration": true, "declarationMap": true, "emitDeclarationOnly": true, From d5f52792f62e162ed2932643f1ae3bc9d7e08ef1 Mon Sep 17 00:00:00 2001 From: Austin Date: Wed, 25 Nov 2026 10:54:08 -0600 Subject: [PATCH 14/75] chore: enable additional TypeScript safety checks (#505) * chore(ui): align declaration build with strict checks Refs: YPE-6464 * chore: enable additional TypeScript safety checks Refs: YPE-6832 --- .changeset/plenty-showers-push.md | 2 ++ packages/core/src/__tests__/handlers.ts | 1 + packages/core/src/version-filters.test.ts | 11 ++++------- .../src/components/bible-reader-highlights-machine.ts | 2 +- packages/ui/tsconfig.build.json | 2 +- tools/tsconfig/base.json | 6 ++++++ 6 files changed, 15 insertions(+), 9 deletions(-) create mode 100644 .changeset/plenty-showers-push.md diff --git a/.changeset/plenty-showers-push.md b/.changeset/plenty-showers-push.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/plenty-showers-push.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/packages/core/src/__tests__/handlers.ts b/packages/core/src/__tests__/handlers.ts index 2b05f5a68..33f5486fb 100644 --- a/packages/core/src/__tests__/handlers.ts +++ b/packages/core/src/__tests__/handlers.ts @@ -256,6 +256,7 @@ export const handlers = [ } else if (includeNotes && includeHeadings) { return HttpResponse.json(mockNIVRom1PassageHTMLHeadingsNotes); } + return undefined; }), // Verse Of The Day endpoints diff --git a/packages/core/src/version-filters.test.ts b/packages/core/src/version-filters.test.ts index a8034874b..1e6879289 100644 --- a/packages/core/src/version-filters.test.ts +++ b/packages/core/src/version-filters.test.ts @@ -84,15 +84,12 @@ describe('version filters', () => { }); it('throws a 403-shaped refuse and adds filter fields to projections', () => { - try { - throwUnusableBibleVersion(); - expect.unreachable(); - } catch (error) { - expect(error).toMatchObject({ + expect(throwUnusableBibleVersion).toThrow( + expect.objectContaining({ status: 403, message: 'This app is not allowed to access this Bible version.', - }); - } + }), + ); clearFilters(); expect(fieldsNeededForVersionFilter(['title'])).toEqual(['title']); diff --git a/packages/ui/src/components/bible-reader-highlights-machine.ts b/packages/ui/src/components/bible-reader-highlights-machine.ts index b23b70797..18ede76d8 100644 --- a/packages/ui/src/components/bible-reader-highlights-machine.ts +++ b/packages/ui/src/components/bible-reader-highlights-machine.ts @@ -193,7 +193,7 @@ function writeResultFromActionEvent(event: MachineActionEvent): WriteResult | un export class BibleReaderHighlightError extends Error { readonly operation: 'apply' | 'remove'; readonly passageId: string; - readonly cause: unknown; + override readonly cause: unknown; constructor(operation: 'apply' | 'remove', passageId: string, cause: unknown) { super(`Highlight ${operation} failed for ${passageId}`); diff --git a/packages/ui/tsconfig.build.json b/packages/ui/tsconfig.build.json index be922e14e..8d3a79e45 100644 --- a/packages/ui/tsconfig.build.json +++ b/packages/ui/tsconfig.build.json @@ -8,7 +8,7 @@ "module": "ESNext", "moduleResolution": "Bundler", "target": "ES2020", - "lib": ["ES2020", "DOM"], + "lib": ["ES2020", "ES2022.Error", "DOM"], "types": ["react", "vite/client"], "jsx": "react-jsx", "jsxImportSource": "react", diff --git a/tools/tsconfig/base.json b/tools/tsconfig/base.json index 27e5db88f..e5bab135a 100644 --- a/tools/tsconfig/base.json +++ b/tools/tsconfig/base.json @@ -7,6 +7,12 @@ "lib": ["ES2022", "DOM", "DOM.Iterable"], "jsx": "react-jsx", "strict": true, + "noUncheckedSideEffectImports": true, + "noImplicitOverride": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "allowUnreachableCode": false, + "allowUnusedLabels": false, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, From 594e005c47f51151d7ea1b0689dc6ba98442244a Mon Sep 17 00:00:00 2001 From: Austin Date: Fri, 27 Nov 2026 09:33:18 -0600 Subject: [PATCH 15/75] feat(ui): customize verse actions and indicators (#506) * feat(ui): customize verse actions and indicators Refs: YPE-6782 Signed-off-by: Austin * test(ui): wait for verse layout in browser journeys Refs: YPE-6782 Signed-off-by: Austin * fix(ui): keep configured verse actions reachable Make exiting actions inert and keep the visible verse indicator inside its pointer target. Refs: YPE-6782 Signed-off-by: Austin * fix(ui): keep verse callbacks scoped to the displayed passage Refs: YPE-6782 Signed-off-by: Austin * fix(ui): preserve verse action focus and warning visibility Signed-off-by: Austin * fix(ui): restore focus after rejected verse action dismissal Refs: YPE-6782 Signed-off-by: Austin --------- Signed-off-by: Austin --- .changeset/reader-verse-actions.md | 5 + CONTEXT.md | 5 +- examples/vite-react/README.md | 16 + .../vite-react/src/pages/BibleReaderPage.tsx | 64 +++- packages/ui/README.md | 17 ++ .../ui/src/components/bible-reader-context.ts | 6 +- .../src/components/bible-reader.stories.tsx | 277 +++++++++++++++++- packages/ui/src/components/bible-reader.tsx | 84 +++++- .../ui/src/components/bible-reader.types.ts | 16 + packages/ui/src/components/index.ts | 10 +- ...ction-popover.shadow-isolation.stories.tsx | 14 + .../src/components/verse-action-popover.tsx | 215 ++++++++++---- packages/ui/src/components/verse.stories.tsx | 143 ++++++++- packages/ui/src/components/verse.tsx | 126 +++++++- packages/ui/src/test/shadow-recovery-mocks.ts | 2 +- packages/ui/src/test/storybook-dom.ts | 20 +- 16 files changed, 923 insertions(+), 97 deletions(-) create mode 100644 .changeset/reader-verse-actions.md diff --git a/.changeset/reader-verse-actions.md b/.changeset/reader-verse-actions.md new file mode 100644 index 000000000..770c24a5c --- /dev/null +++ b/.changeset/reader-verse-actions.md @@ -0,0 +1,5 @@ +--- +'@youversion/platform-react-ui': minor +--- + +Customize the Bible reader's verse action popover with ordered built-in and host actions that receive the verse selection. Mark verse numbers in BibleReader and BibleTextView with host-styled indicators and separate pointer and keyboard activation. diff --git a/CONTEXT.md b/CONTEXT.md index df1b20567..69bb0e494 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -178,8 +178,9 @@ round-trips an updated `highlights` prop. ## Verse action popover -The floating action bar (YPE-642) that appears over a verse selection, -offering highlight colors, copy, and share. +The floating action bar for a verse selection, with highlight colors, copy, and +share as the default actions. The host can reorder or omit these actions and add +its own. ## Highlights permission diff --git a/examples/vite-react/README.md b/examples/vite-react/README.md index 5a9e8d476..ac47bccc2 100644 --- a/examples/vite-react/README.md +++ b/examples/vite-react/README.md @@ -23,3 +23,19 @@ pnpm dev:web - **Bible Card** — Embeddable Bible passage card - **Images** — Smoke page for `ImagesClient` list and detail (metadata only) - **Sign in with YouVersion Button** - Authentication with YouVersion + +## Verse marker smoke test + +1. Open the browser developer tools' **Network** panel, enable **Preserve log**, + clear the log, and filter for `/notes`. +2. Reload the demo with Network recording enabled and open **Bible Reader** at + John 1. Click the purple marker beside verse 3 and check that the status reads + “Opened marker for JHN.1.3.” +3. Tap the text of verses 1 and 4, then choose **Mark verses** in the verse + action popover. Check that the popover closes and markers appear on verses + 1 and 4 while verse 2 stays unmarked. +4. Tab to a marker and press Enter. Check that the status shows its passage ID + and the verse action popover stays closed. +5. Verify that the Network panel recorded zero requests to Notes API routes. + +The demo keeps markers in memory for the current page session. diff --git a/examples/vite-react/src/pages/BibleReaderPage.tsx b/examples/vite-react/src/pages/BibleReaderPage.tsx index 5cdf7aa1d..cb04de04c 100644 --- a/examples/vite-react/src/pages/BibleReaderPage.tsx +++ b/examples/vite-react/src/pages/BibleReaderPage.tsx @@ -1,19 +1,61 @@ -import { BibleReader } from '@youversion/platform-react-ui'; +import { BibleReader, type BibleReaderReference } from '@youversion/platform-react-ui'; +import { BookmarkPlus } from 'lucide-react'; +import { useState } from 'react'; + +function markerKey({ versionId, passageId }: BibleReaderReference): string { + return `${versionId}:${passageId}`; +} export function BibleReaderPage() { const defaultLanguageId = import.meta.env.VITE_YVP_DEFAULT_LANGUAGE_ID?.trim() || undefined; + const [markers, setMarkers] = useState(() => new Set(['3034:JHN.1.3'])); + const [openedMarker, setOpenedMarker] = useState(); return ( -

- - - - +
+

+ {openedMarker + ? `Opened marker for ${openedMarker}.` + : 'Select verses and choose Mark verses to add a marker.'} +

+
+ , + onSelect: ({ versionId, passageIds }) => + setMarkers( + (existing) => + new Set([ + ...existing, + ...passageIds.map((passageId) => markerKey({ versionId, passageId })), + ]), + ), + }, + 'copy', + 'share', + ]} + getVerseIndicator={(reference) => + markers.has(markerKey(reference)) + ? { + label: `Open marker for ${reference.passageId}`, + style: { backgroundColor: '#a855f7' }, + } + : undefined + } + onVerseIndicatorPress={({ passageId }) => setOpenedMarker(passageId)} + > + + + +
); } diff --git a/packages/ui/README.md b/packages/ui/README.md index 37194b746..9cf87a198 100644 --- a/packages/ui/README.md +++ b/packages/ui/README.md @@ -49,6 +49,23 @@ Optional `locale` sets bundled UI copy (Verse of the Day heading, buttons, etc.) ``` +### Customize verse actions and indicators + +Pass `verseActionItems` to `BibleReader.Root` to choose the order of +`'highlights'`, `'copy'`, `'share'`, and custom actions. The default order is +highlights, copy, then share. Each custom item supplies an `id`, a localized +`label`, a decorative `icon`, and an `onSelect` callback. Its callback receives +the current `BibleReaderVerseSelection` before the reader clears the selection. +`passageIds` lists each selected verse separately, including when the selection +has gaps. + +Both `BibleReader.Root` and `BibleTextView` accept `getVerseIndicator`. Return a +`VerseIndicator` with a localized `label` and optional `style` to mark a verse +number, or return `undefined` to leave it unchanged. Use +`onVerseIndicatorPress` to handle activation by pointer or keyboard. Both hooks +receive a `BibleReaderReference` with the Bible version ID and verse passage ID. +Without the press callback, the indicator is decorative. + ### Limit which Bible versions the SDK uses By default the version picker offers Bible versions in every available language. Limit that with `permittedLanguageTags`, `permittedVersionIds`, and `excludedVersionIds` on `YouVersionProvider`. A version must satisfy every list that is set. Exclusion wins if an id is in both permit and exclude lists. Unset means no restriction; an empty permit list permits nothing. diff --git a/packages/ui/src/components/bible-reader-context.ts b/packages/ui/src/components/bible-reader-context.ts index 08079d0fd..c93810d9b 100644 --- a/packages/ui/src/components/bible-reader-context.ts +++ b/packages/ui/src/components/bible-reader-context.ts @@ -7,15 +7,16 @@ import type { VerseFocusRequest } from '@/lib/use-transient-verse-focus'; import type { BibleChapterPickerPressData } from './bible-chapter-picker'; import type { BibleVersionPickerPressData } from './bible-version-picker'; import type { BibleReaderSearchPressData } from './bible-reader-search'; -import type { FootnoteData } from './verse'; +import type { FootnoteData, VerseIndicatorProps } from './verse'; import type { BibleReaderNavigation } from './bible-reader-navigation'; import type { BibleReaderHighlightIntent, BibleReaderShareData, + BibleReaderVerseActionItem, BibleReaderVerseSelection, } from './bible-reader.types'; -export type BibleReaderContextType = { +export type BibleReaderContextType = VerseIndicatorProps & { book: string; chapter: string; versionId: number; @@ -49,6 +50,7 @@ export type BibleReaderContextType = { onHighlightApply?: (intent: BibleReaderHighlightIntent) => void; onHighlightRemove?: (intent: BibleReaderHighlightIntent) => void; verseActions: 'popover' | 'none'; + verseActionItems?: readonly BibleReaderVerseActionItem[]; clearSelectionSignal?: number; navigation: BibleReaderNavigation; verseFocus: VerseFocusRequest | null; diff --git a/packages/ui/src/components/bible-reader.stories.tsx b/packages/ui/src/components/bible-reader.stories.tsx index e258153ff..dc3c25de2 100644 --- a/packages/ui/src/components/bible-reader.stories.tsx +++ b/packages/ui/src/components/bible-reader.stories.tsx @@ -21,7 +21,9 @@ import { } from './bible-reader'; import { VerseActionPopover } from './verse-action-popover'; import { + clickStoryElement, verifyNativeBrowserKey, + getBackgroundColorChannels, waitForShadowContent, waitForShadowRoot, } from '@/test/storybook-dom'; @@ -384,7 +386,9 @@ export const VerseSelectionReanchoringDismissalAndFocusRestoration: Story = { await Promise.all(dialog.getAnimations().map((animation) => animation.finished)); const firstDialogRect = dialog.getBoundingClientRect(); - await userEvent.click(secondSelectedVerseLabel); + await expect(secondSelectedVerseLabel).toBeVisible(); + await expect(secondSelectedVerseLabel).toHaveTextContent('10'); + await clickStoryElement(secondSelectedVerseLabel); await expect(firstVerse).toHaveClass('yv-v-selected'); await expect(secondSelectedVerse).toHaveClass('yv-v-selected'); await expect(dialog).toBeInTheDocument(); @@ -394,6 +398,10 @@ export const VerseSelectionReanchoringDismissalAndFocusRestoration: Story = { const movedBlock = Math.abs(reanchoredRect.top - firstDialogRect.top) > 8; void expect(movedInline || movedBlock).toBe(true); }); + await userEvent.click(secondSelectedVerseLabel); + await expect(firstVerse).toHaveClass('yv-v-selected'); + await expect(secondSelectedVerse).not.toHaveClass('yv-v-selected'); + await userEvent.click(secondSelectedVerseLabel); await userEvent.pointer({ keys: '[MouseLeft>]', target: outsideControl }); await waitFor(() => expect(dialog).not.toBeInTheDocument(), { timeout: 10000 }); @@ -430,6 +438,209 @@ export const VerseSelectionReanchoringDismissalAndFocusRestoration: Story = { }, }; +const LONG_VERSE_ACTION_LABEL = + 'Add these selected verses to the collection of passages for tomorrow’s reading discussion'; + +export const CustomVerseActions: Story = { + tags: ['integration', 'shadow-dom', 'cross-browser'], + args: { + defaultVersionId: 111, + defaultBook: 'JHN', + defaultChapter: '1', + background: 'dark', + highlights: [{ version_id: 111, passage_id: 'JHN.1.1', color: 'ffec5b' }], + getVerseIndicator: ({ passageId }) => + passageId === 'JHN.1.1' + ? { label: 'Open marker for John 1:1', style: { backgroundColor: 'rgb(222, 172, 255)' } } + : undefined, + onVerseIndicatorPress: fn(), + verseActionItems: [ + 'share', + { + id: 'mark', + label: 'Mark verses', + icon: ( + + ), + onSelect: fn(), + }, + 'copy', + ], + }, + render: function ConfigurableActions(args) { + const [omittedAction, setOmittedAction] = useState<'copy' | 'share'>(); + const [editingNote, setEditingNote] = useState(false); + const configuredItems: BibleReaderRootProps['verseActionItems'] = omittedAction + ? [ + omittedAction === 'copy' ? 'share' : 'copy', + 'highlights', + ...(args.verseActionItems?.slice(1, 2) ?? []), + { id: 'compare', label: 'Compare selected translations', icon: '⇄', onSelect: fn() }, + { id: 'collect', label: LONG_VERSE_ACTION_LABEL, icon: '+', onSelect: fn() }, + ] + : [ + ...(args.verseActionItems ?? []), + { id: 'edit-note', label: 'Edit note', icon: '+', onSelect: () => setEditingNote(true) }, + ]; + return ( +
+
+ + + {editingNote && ( + + )} +
+
+ + + +
+
+ ); + }, + play: async ({ args, canvasElement }) => { + const root = await waitForShadowRoot(canvasElement); + const [first, third] = await waitFor( + () => { + const first = root.querySelector('.yv-v[v="1"]'); + const third = root.querySelector('.yv-v[v="3"]'); + if (!first || !third) throw new Error('Reader verses not rendered'); + return [first, third]; + }, + { timeout: 10000 }, + ); + const thirdLabel = third.querySelector('.yv-vlbl'); + if (!thirdLabel) throw new Error('Unmarked verse number not rendered'); + await expect(thirdLabel).toBeVisible(); + await expect(thirdLabel).toHaveTextContent('3'); + await expect(within(thirdLabel).queryByRole('button')).toBeNull(); + await clickStoryElement(thirdLabel); + await userEvent.click(first); + const overlay = await getReaderOverlay(root); + const dialog = await overlay.findByRole('dialog', { name: 'Verse actions' }); + const indicator = within(first).getByRole('button', { name: 'Open marker for John 1:1' }); + const visibleMark = indicator.querySelector('[data-slot="verse-indicator-mark"]'); + if (!visibleMark) throw new Error('Verse number marker not rendered'); + await expect(indicator.closest('[data-yv-theme="dark"]')).toBeInTheDocument(); + await waitFor(() => expect(getBackgroundColorChannels(first)).toEqual([65, 62, 33, 255])); + await expect(visibleMark).toBeVisible(); + await expect(getComputedStyle(visibleMark).backgroundColor).toBe('rgb(222, 172, 255)'); + await userEvent.click(indicator); + await expect(args.onVerseIndicatorPress).toHaveBeenCalledTimes(1); + await expect(args.onVerseIndicatorPress).toHaveBeenCalledWith({ + versionId: 111, + passageId: 'JHN.1.1', + }); + await expect(first).toHaveClass('yv-v-selected'); + await expect(third).toHaveClass('yv-v-selected'); + await expect(dialog).toHaveAttribute('data-state', 'open'); + const actions = within(dialog); + const mark = actions.getByRole('button', { name: 'Mark verses' }); + await expect(actions.getAllByRole('button')).toEqual([ + actions.getByRole('button', { name: 'Share' }), + mark, + actions.getByRole('button', { name: 'Copy' }), + actions.getByRole('button', { name: 'Edit note' }), + ]); + await expect(within(mark).getByTestId('mark-icon')).toBeVisible(); + await Promise.all(dialog.getAnimations().map((animation) => animation.finished)); + dialog.style.animationDuration = '1s'; + if (__YV_STORYBOOK_VITEST__) { + const { userEvent: browserUserEvent } = await import('vitest/browser'); + await browserUserEvent.dblClick(mark); + } else { + await userEvent.dblClick(mark); + } + await expect(dialog).toHaveAttribute('data-state', 'closed'); + await expect(mark).toBeInTheDocument(); + const item = args.verseActionItems?.[1]; + if (!item || item === 'highlights' || item === 'copy' || item === 'share') { + throw new Error('Custom action fixture missing'); + } + await expect(item.onSelect).toHaveBeenCalledTimes(1); + await expect(item.onSelect).toHaveBeenCalledWith( + expect.objectContaining({ + versionId: 111, + verses: [1, 3], + passageIds: ['JHN.1.1', 'JHN.1.3'], + }), + ); + await expect(first).not.toHaveClass('yv-v-selected'); + await expect(third).not.toHaveClass('yv-v-selected'); + await waitFor(() => expect(dialog).not.toBeInTheDocument(), { timeout: 5000 }); + + const browser = __YV_STORYBOOK_VITEST__ ? await import('vitest/browser') : undefined; + const host = within(canvasElement); + const prior = host.getByRole('button', { name: 'Omit Copy' }); + prior.focus(); + await userEvent.click(third); + const noteActions = await overlay.findByRole('dialog', { name: 'Verse actions' }); + const editNote = within(noteActions).getByRole('button', { name: 'Edit note' }); + editNote.focus(); + await (browser?.userEvent ?? userEvent).keyboard('{Enter}'); + const note = await host.findByRole('textbox', { name: 'Note' }); + await waitFor(() => expect(noteActions).not.toBeInTheDocument()); + await expect(third).not.toHaveClass('yv-v-selected'); + await verifyNativeBrowserKey('Remember this', async () => { + await expect(note).toHaveFocus(); + await expect(note).toHaveValue('Remember this'); + }); + + const page = browser?.server.provider === 'playwright' ? browser.page : undefined; + const { innerWidth, innerHeight } = window; + await page?.viewport(320, 640); + try { + for (const [omitted, retained] of [ + ['Copy', 'Share'], + ['Share', 'Copy'], + ] as const) { + await userEvent.click( + within(canvasElement).getByRole('button', { name: `Omit ${omitted}` }), + ); + await userEvent.click(first); + const configured = await overlay.findByRole('dialog', { name: 'Verse actions' }); + const queries = within(configured); + const firstAction = queries.getByRole('button', { name: retained }); + const swatches = queries.getByRole('group', { name: 'Highlight colors' }); + const lastAction = queries.getByRole('button', { name: LONG_VERSE_ACTION_LABEL }); + await expect(queries.queryByRole('button', { name: omitted })).toBeNull(); + await expect(queries.getAllByRole('button')).toEqual([ + firstAction, + ...within(swatches).getAllByRole('button'), + queries.getByRole('button', { name: 'Mark verses' }), + queries.getByRole('button', { name: 'Compare selected translations' }), + lastAction, + ]); + if (page) { + await Promise.all(configured.getAnimations().map((animation) => animation.finished)); + firstAction.focus(); + await expect(lastAction.getBoundingClientRect().right).toBeGreaterThan(320); + await verifyNativeBrowserKey('{Shift>}{Tab}{/Shift}', async () => { + await waitFor(() => expect(root.activeElement).toBe(lastAction)); + const bounds = lastAction.getBoundingClientRect(); + await expect(bounds.left).toBeGreaterThanOrEqual(0); + await expect(bounds.right).toBeLessThanOrEqual(320); + }); + } + await userEvent.keyboard('{Escape}'); + await waitFor(() => expect(configured).not.toBeInTheDocument(), { timeout: 5000 }); + } + } finally { + await page?.viewport(innerWidth, innerHeight); + } + }, +}; + export const HostileCssConstrainedLayout: Story = { tags: ['integration', 'shadow-dom', 'cross-browser', 'shadow-fresh-process'], args: { @@ -999,6 +1210,7 @@ function EnterExitProbe() { activeHighlights={new Set()} selectedVerses={[]} highlightedVerses={{}} + highlightsEnabled={open} onHighlight={fn()} onClearHighlight={fn()} onCopy={fn()} @@ -1013,6 +1225,7 @@ export const EnterAndExitMotion: Story = { render: () => , play: async () => { const dialog = await screen.findByRole('dialog'); + await expect(within(dialog).getByRole('group')).toBeInTheDocument(); const openStyle = getComputedStyle(dialog); await expect(openStyle.animationDuration).toBe('0.18s'); await expect(openStyle.animationTimingFunction).toBe('cubic-bezier(0.16, 1, 0.3, 1)'); @@ -1022,6 +1235,7 @@ export const EnterAndExitMotion: Story = { const closed = screen.getByRole('dialog'); const closedStyle = getComputedStyle(closed); await expect(closed).toHaveAttribute('data-state', 'closed'); + await expect(closed.querySelector('[role="group"]')).toBeNull(); await expect(closedStyle.animationDuration).toBe('0.15s'); await expect(closedStyle.animationTimingFunction).toBe('ease'); }); @@ -1846,6 +2060,7 @@ export const ChapterChangeLoadingOverlay: Story = { defaultVersionId: 111, defaultBook: 'JHN', defaultChapter: '1', + verseActionItems: [{ id: 'mark', label: 'Mark verse', icon: '★', onSelect: fn() }], }, render: (args) => ( <> @@ -1858,8 +2073,12 @@ export const ChapterChangeLoadingOverlay: Story = { ), - play: async ({ canvasElement }) => { + play: async ({ args, canvasElement }) => { const { root, reader } = await getReaderStory(canvasElement); + const [mark] = args.verseActionItems ?? []; + if (!mark || mark === 'highlights' || mark === 'copy' || mark === 'share') { + throw new Error('Custom action fixture missing'); + } await waitFor( async () => { const renderer = root.querySelector('[data-slot="yv-bible-renderer"]'); @@ -1899,6 +2118,13 @@ export const ChapterChangeLoadingOverlay: Story = { await expect(nextButton).toBeVisible(); }); + const retainedVerse = root.querySelector('.yv-v[v="1"]'); + if (!retainedVerse) throw new Error('Retained verse not rendered'); + await clickStoryElement(retainedVerse); + await expect(retainedVerse).not.toHaveClass('yv-v-selected'); + await expect(root.querySelector('[data-slot="verse-action-popover"]')).toBeNull(); + await expect(mark.onSelect).not.toHaveBeenCalled(); + const lastReaderControl = reader.getAllByRole('button').at(-1); if (!lastReaderControl) throw new Error('reader control not rendered'); lastReaderControl.focus(); @@ -1924,6 +2150,21 @@ export const ChapterChangeLoadingOverlay: Story = { const scroller = root.querySelector('main'); await expect(scroller?.scrollTop).toBe(0); + const nextVerse = root.querySelector('.yv-v[v="1"]'); + if (!nextVerse) throw new Error('Destination verse not rendered'); + await expect(nextVerse).not.toHaveClass('yv-v-selected'); + await expect(root.querySelector('[data-slot="verse-action-popover"]')).toBeNull(); + await userEvent.click(nextVerse); + const overlay = await getReaderOverlay(root); + await userEvent.click(await overlay.findByRole('button', { name: 'Mark verse' })); + await expect(mark.onSelect).toHaveBeenCalledTimes(1); + await expect(mark.onSelect).toHaveBeenCalledWith( + expect.objectContaining({ + versionId: 111, + passageIds: ['JHN.2.1'], + shareData: expect.objectContaining({ verseText: 'Passage text for JHN.2.' }), + }), + ); }, }; @@ -1933,6 +2174,9 @@ export const ClipboardFailureAfterScrolling: Story = { defaultVersionId: 111, defaultBook: 'JHN', defaultChapter: '1', + getVerseIndicator: ({ passageId }) => + passageId === 'JHN.1.3' ? { label: 'Open marker for John 1:3' } : undefined, + onVerseIndicatorPress: fn(), }, render: (args) => (
@@ -1942,7 +2186,7 @@ export const ClipboardFailureAfterScrolling: Story = {
), - play: async ({ canvasElement }) => { + play: async ({ args, canvasElement }) => { const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard'); const shareDescriptor = Object.getOwnPropertyDescriptor(navigator, 'share'); const writes: string[] = []; @@ -1991,6 +2235,33 @@ export const ClipboardFailureAfterScrolling: Story = { await waitFor(expectWarningInView); } await expect(writes).toHaveLength(2); + + const indicator = reader.getByRole('button', { name: 'Open marker for John 1:3' }); + const mark = indicator.querySelector('[data-slot="verse-indicator-mark"]'); + if (!mark) throw new Error('Verse number marker not rendered'); + const warning = status.getBoundingClientRect(); + const marker = mark.getBoundingClientRect(); + scroller.scrollTop += marker.top + marker.height / 2 - (warning.top + warning.height / 2); + + const bounds = status.getBoundingClientRect(); + const overlap = mark.getBoundingClientRect(); + const x = overlap.left + overlap.width / 2; + const y = overlap.top + overlap.height / 2; + await expect(x).toBeGreaterThan(bounds.left); + await expect(x).toBeLessThan(bounds.right); + await expect(y).toBeGreaterThan(bounds.top); + await expect(y).toBeLessThan(bounds.bottom); + await expect(root.elementFromPoint(x, y)).toBe(status); + + if (__YV_STORYBOOK_VITEST__) { + const { server, userEvent: browserUserEvent } = await import('vitest/browser'); + if (server.provider === 'playwright') { + await browserUserEvent.click(status, { + position: { x: x - bounds.left, y: y - bounds.top }, + }); + await expect(args.onVerseIndicatorPress).not.toHaveBeenCalled(); + } + } } finally { if (clipboardDescriptor) Object.defineProperty(navigator, 'clipboard', clipboardDescriptor); else Reflect.deleteProperty(navigator, 'clipboard'); diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx index 80e90c66d..fc6bb6506 100644 --- a/packages/ui/src/components/bible-reader.tsx +++ b/packages/ui/src/components/bible-reader.tsx @@ -35,7 +35,12 @@ import { VerseActionPopover } from './verse-action-popover'; import { useBibleReaderHighlights } from './use-bible-reader-highlights'; import { HighlightPermissionDialog } from './highlight-permission-dialog'; import { SignInDialog } from './sign-in-dialog'; -import { BibleTextView, getCleanVerseText, type FootnoteData } from './verse'; +import { + BibleTextView, + getCleanVerseText, + type FootnoteData, + type VerseIndicatorProps, +} from './verse'; import { buildVerseReference, buildVerseShareText, joinVerseTexts } from '@/lib/verse-share'; import { isHighlightsLive } from '@/lib/feature-flags'; import { YvComponentStyles } from '@/lib/yv-styles-components'; @@ -57,6 +62,7 @@ import type { BibleReaderHighlightIntent, BibleReaderSettingsProps, BibleReaderShareData, + BibleReaderVerseActionItem, BibleReaderVerseSelection, } from './bible-reader.types'; @@ -82,6 +88,7 @@ export { export type { BibleReaderHighlightIntent, BibleReaderShareData, + BibleReaderVerseActionItem, BibleReaderVerseSelection, } from './bible-reader.types'; @@ -206,6 +213,15 @@ export type RootProps = BibleReaderSettingsProps & { * {@link clearSelectionSignal}. */ verseActions?: 'popover' | 'none'; + /** + * Items in the existing popover, in display order. Defaults to highlights, + * copy and share. Omit an item to hide it. Each built-in may appear once. + * Respects highlight availability and is ignored when `verseActions="none"`. + * + * An empty list hides the popover while keeping verse selection enabled. + * The host can clear the selection through {@link clearSelectionSignal}. + */ + verseActionItems?: readonly BibleReaderVerseActionItem[]; /** * Clears the current verse selection from outside the reader. Any change to * this value runs the reader's own "close and clear" path, emitting @@ -220,7 +236,7 @@ export type RootProps = BibleReaderSettingsProps & { clearSelectionSignal?: number; scriptureDirection?: TextDirection; children?: ReactNode; -}; +} & VerseIndicatorProps; // Non-scrolling focus requests apply only to the chapter/version already displayed. function canApplyNavigationRequest( @@ -274,6 +290,9 @@ function Root({ onHighlightApply, onHighlightRemove, verseActions = 'popover', + verseActionItems, + getVerseIndicator, + onVerseIndicatorPress, clearSelectionSignal, scriptureDirection, children, @@ -432,6 +451,9 @@ function Root({ onHighlightApply, onHighlightRemove, verseActions, + verseActionItems, + getVerseIndicator, + onVerseIndicatorPress, clearSelectionSignal, navigation, verseFocus, @@ -476,6 +498,9 @@ function Content() { onHighlightApply, onHighlightRemove, verseActions, + verseActionItems, + getVerseIndicator, + onVerseIndicatorPress, clearSelectionSignal, verseFocus, scriptureDirection, @@ -547,6 +572,16 @@ function Content() { // popover and supplies clean verse text for Copy / Share. const readerRef = useRef(null); const renderedReference = !passageLoading && !passageError && passage ? usfmReference : ''; + const renderedVerseScope = renderedReference ? `${versionId}:${renderedReference}` : null; + const selectionScopeRef = useRef(null); + const hasCustomVerseActions = + verseActions === 'popover' && + verseActionItems?.some((item) => item !== 'highlights' && item !== 'copy' && item !== 'share'); + // Retained HTML can still be tapped by callers using the built-in actions. + // Its selection cannot become the input to a custom action for the next passage. + const selectionMatchesScope = + renderedVerseScope !== null && selectionScopeRef.current === renderedVerseScope; + const canShowSelection = !hasCustomVerseActions || selectionMatchesScope; useTransientVerseFocus({ request: activeNavigation, renderedReference, @@ -620,6 +655,7 @@ function Content() { setSelectedVerses([]); setPopoverOpen(false); setAnchorElement(null); + selectionScopeRef.current = null; if (lastSelectionRef.current.length > 0) { lastSelectionRef.current = []; onVerseSelectRef.current?.({ @@ -649,6 +685,7 @@ function Content() { setPopoverOpen(false); setSelectedVerses([]); setAnchorElement(null); + selectionScopeRef.current = null; // The deselect-tap path emits its own `[]` via handleVerseSelect. Read via // ref: async callers (navigator.share().then) capture this closure, and a // host-swapped callback must not go stale on that path. @@ -749,7 +786,10 @@ function Content() { }, [bookTitle, versionAbbreviation]); function handleVerseSelect(verses: number[]) { - const added = verses.find((verse) => !lastSelectionRef.current.includes(verse)); + if (hasCustomVerseActions && renderedVerseScope === null) return; + const previous = canShowSelection ? lastSelectionRef.current : []; + const added = verses.find((verse) => !previous.includes(verse)); + selectionScopeRef.current = verses.length > 0 ? renderedVerseScope : null; lastSelectionRef.current = verses; setSelectedVerses(verses); onVerseSelect?.(buildVerseSelection(verses)); @@ -837,9 +877,9 @@ function Content() { }; } - async function runHostVerseAction( - action: (data: BibleReaderShareData) => void | Promise, - data: BibleReaderShareData, + async function runHostVerseAction( + action: (data: Data) => void | Promise, + data: Data, ): Promise { try { await action(data); @@ -983,7 +1023,7 @@ function Content() {
{clipboardFailed ? t('unableToShare') : null}
@@ -1013,8 +1053,10 @@ function Content() { theme={background} onFootnotePress={onFootnotePress} scriptureDirection={scriptureDirection} - selectedVerses={selectedVerses} + selectedVerses={canShowSelection ? selectedVerses : undefined} onVerseSelect={handleVerseSelect} + getVerseIndicator={isRefetching ? undefined : getVerseIndicator} + onVerseIndicatorPress={onVerseIndicatorPress} highlightedVerses={highlightedVerses} passageState={{ passage, @@ -1032,7 +1074,12 @@ function Content() { {verseActions !== 'none' && ( 0 && !highlightPromptOpen} + open={ + popoverOpen && + canShowSelection && + selectedVerses.length > 0 && + !highlightPromptOpen + } onOpenChange={handlePopoverOpenChange} activeHighlights={activeHighlights} selectedVerses={selectedVerses} @@ -1044,6 +1091,25 @@ function Content() { onClearHighlight={handleClearHighlight} onCopy={handleCopy} onShare={handleShare} + actionItems={verseActionItems?.map((item) => + item === 'highlights' || item === 'copy' || item === 'share' + ? item + : { + ...item, + onSelect: () => { + if ( + renderedVerseScope === null || + selectionScopeRef.current !== renderedVerseScope || + lastSelectionRef.current !== selectedVerses + ) { + return; + } + const selection = buildVerseSelection(selectedVerses); + void runHostVerseAction(item.onSelect, selection); + closeAndClearSelection(); + }, + }, + )} theme={background} /> diff --git a/packages/ui/src/components/bible-reader.types.ts b/packages/ui/src/components/bible-reader.types.ts index fc9f0a18a..aee3abfda 100644 --- a/packages/ui/src/components/bible-reader.types.ts +++ b/packages/ui/src/components/bible-reader.types.ts @@ -1,4 +1,20 @@ import type { FontFamily } from '@/lib/verse-html-utils'; +import type { ReactNode } from 'react'; +import type { BuiltInVerseAction } from './verse-action-popover'; + +/** A built-in action or a host action in the verse action popover. */ +export type BibleReaderVerseActionItem = + | BuiltInVerseAction + | { + /** Stable ID unique among the custom actions. */ + id: string; + /** Visible and accessible label, localized by the host. */ + label: string; + /** Decorative icon for the action button. */ + icon: ReactNode; + /** Receives a snapshot before the reader clears the selection. */ + onSelect: (selection: BibleReaderVerseSelection) => void | Promise; + }; /** Reader typography props shared by the public root and its settings hook. */ export type BibleReaderSettingsProps = { diff --git a/packages/ui/src/components/index.ts b/packages/ui/src/components/index.ts index f893548d3..aebc38159 100644 --- a/packages/ui/src/components/index.ts +++ b/packages/ui/src/components/index.ts @@ -19,6 +19,7 @@ export { type BibleReaderRootProps, type BibleReaderShareData, type BibleReaderToolbarProps, + type BibleReaderVerseActionItem, type BibleReaderVerseSelection, type BibleThemeSettingsContentProps, type BibleThemeSettingsSnapshot, @@ -45,6 +46,8 @@ export { export { BibleTextView, type BibleTextViewProps, + type VerseIndicator, + type VerseIndicatorProps, type FootnoteData, FootnoteContent, type FootnoteContentProps, @@ -52,7 +55,12 @@ export { // NOTE: the popover's `HighlightColor` (a hex-string union) is intentionally not // re-exported here — core already exports a different `HighlightColor` (the API's // { id, color, label } shape). Import it from './verse-action-popover' if needed. -export { VerseActionPopover, HIGHLIGHT_COLORS } from './verse-action-popover'; +export { + VerseActionPopover, + HIGHLIGHT_COLORS, + type BuiltInVerseAction, + type VerseActionPopoverItem, +} from './verse-action-popover'; export { BibleCard, type BibleCardProps } from './bible-card'; export { BibleReaderSearch, diff --git a/packages/ui/src/components/verse-action-popover.shadow-isolation.stories.tsx b/packages/ui/src/components/verse-action-popover.shadow-isolation.stories.tsx index 430a72705..8debea21c 100644 --- a/packages/ui/src/components/verse-action-popover.shadow-isolation.stories.tsx +++ b/packages/ui/src/components/verse-action-popover.shadow-isolation.stories.tsx @@ -310,6 +310,20 @@ export const PortalPlacementDockingReanchoringAndFocusRestoration: Story = { await waitForClosed(topLayer); await waitForFocus(shadowRoot, priorControl); + await userEvent.click(firstVerse); + dialog = await waitForElement( + topLayer, + '[role="dialog"]', + 'popover did not reopen for Escape after rejected outside close', + ); + await userEvent.click(rejectedOutsideControl); + await expect(dialog).toHaveAttribute('data-state', 'open'); + await expect(canvasElement.ownerDocument.activeElement).toBe(rejectedOutsideControl); + const browser = __YV_STORYBOOK_VITEST__ ? await import('vitest/browser') : undefined; + await (browser?.userEvent ?? userEvent).keyboard('{Escape}'); + await waitForClosed(topLayer); + await waitForFocus(shadowRoot, priorControl); + priorControl.focus(); await userEvent.click(firstVerse); await waitForElement(topLayer, '[role="dialog"]', 'popover did not reopen for delayed close'); diff --git a/packages/ui/src/components/verse-action-popover.tsx b/packages/ui/src/components/verse-action-popover.tsx index d1c26e019..e3fc1473c 100644 --- a/packages/ui/src/components/verse-action-popover.tsx +++ b/packages/ui/src/components/verse-action-popover.tsx @@ -1,6 +1,7 @@ 'use client'; import { + Fragment, useEffect, useLayoutEffect, useMemo, @@ -8,6 +9,7 @@ import { useState, type CSSProperties, type FC, + type ReactNode, } from 'react'; import * as PopoverPrimitive from '@radix-ui/react-popover'; import { useTranslation } from 'react-i18next'; @@ -118,6 +120,25 @@ function isDurableFocusRestoreTarget( ); } +/** The SDK-provided actions for highlighting, copying, and sharing a verse selection. */ +export type BuiltInVerseAction = 'highlights' | 'copy' | 'share'; + +/** A built-in or host-provided action for a standalone {@link VerseActionPopover}. */ +export type VerseActionPopoverItem = + | BuiltInVerseAction + | { + /** Stable ID unique among the custom actions. */ + id: string; + /** Visible and accessible label, localized by the host. */ + label: string; + /** Decorative icon for the action button. */ + icon: ReactNode; + /** Zero-argument activation callback. The caller owns selection and dismissal. */ + onSelect: () => void; + }; + +const DEFAULT_ACTION_ITEMS: readonly BuiltInVerseAction[] = ['highlights', 'copy', 'share']; + type VerseActionPopoverProps = { open: boolean; onOpenChange: (open: boolean) => void; @@ -132,11 +153,12 @@ type VerseActionPopoverProps = { */ scrollRoot?: HTMLElement | null; /** - * Whether the highlights UI is available. When `false` (the `HIGHLIGHTS_LIVE` - * dark-launch flag is off) the color row and the remove (checkmark) circles are - * hidden entirely — only Copy / Share remain. Defaults to `true`. + * Whether the Highlights action is available. When `false`, the swatches are + * omitted and the other configured actions remain. Defaults to `true`. */ highlightsEnabled?: boolean; + /** Actions in display order. Each built-in and each custom ID should appear once. */ + actionItems?: readonly VerseActionPopoverItem[]; onHighlight: (color: string) => void; onClearHighlight: (color: string) => void; onCopy: () => void; @@ -190,31 +212,35 @@ function ColorCircle({ color, showRemove, label, onClick, theme }: ColorCirclePr } type ActionButtonProps = { - icon: React.ReactNode; + icon: ReactNode; label: string; onClick: () => void; + onClickCapture?: () => void; }; -function ActionButton({ icon, label, onClick }: ActionButtonProps) { +function ActionButton({ icon, label, onClick, onClickCapture }: ActionButtonProps) { return ( ); } export const VerseActionPopover: FC = ({ - open, + open: requestedOpen, onOpenChange, activeHighlights, selectedVerses, @@ -222,6 +248,7 @@ export const VerseActionPopover: FC = ({ anchorElement, scrollRoot, highlightsEnabled = true, + actionItems = DEFAULT_ACTION_ITEMS, onHighlight, onClearHighlight, onCopy, @@ -230,6 +257,10 @@ export const VerseActionPopover: FC = ({ }) => { const { t } = useTranslation(undefined, { i18n }); const direction = useInterfaceDirection(); + const visibleActionItems = highlightsEnabled + ? actionItems + : actionItems.filter((item) => item !== 'highlights'); + const open = requestedOpen && visibleActionItems.length > 0; const portal = useShadowPortalState({ open, onOpenChange }); const getShadowFocusRestoreTarget = useShadowFocusRestoreTarget(); const takeReaderFocusRestoreTarget = useTakeVerseActionPopoverFocusRestoreTarget(); @@ -247,8 +278,10 @@ export const VerseActionPopover: FC = ({ const documentFocusRestoreTargetRef = useRef(null); const versePointerEventsRef = useRef(new WeakSet()); const retainOutsideFocusRef = useRef(false); + const customActionActivatedRef = useRef(false); const allowPriorFocusRestoration = (): void => { retainOutsideFocusRef.current = false; + customActionActivatedRef.current = false; }; // The swatch row is capped to the viewport width (see the Content max-width @@ -346,6 +379,8 @@ export const VerseActionPopover: FC = ({ sideOffset: docked ? 24 : 20, showCaret: !docked, colorCircles, + actionItems: visibleActionItems, + scrollAllActions: actionItems !== DEFAULT_ACTION_ITEMS, }; const frozenView = useRef(live); if (open) frozenView.current = live; @@ -462,7 +497,7 @@ export const VerseActionPopover: FC = ({ if (!content) return; const root = getOwnShadowRoot(content); - retainOutsideFocusRef.current = false; + allowPriorFocusRestoration(); const readerFocusRestoreTarget = takeReaderFocusRestoreTarget?.() ?? null; const readerTarget = isElementFromOwnerDocument(readerFocusRestoreTarget, content, 'HTMLElement') && @@ -483,6 +518,19 @@ export const VerseActionPopover: FC = ({ }} onCloseAutoFocus={(event) => { const root = portal.container ? getOwnShadowRoot(portal.container) : null; + const focusDocument = portal.container?.ownerDocument ?? anchor?.ownerDocument; + const activeElement = root?.activeElement ?? focusDocument?.activeElement; + const closingContent = event.currentTarget; + // A custom action can mount and focus host UI before Radix finishes closing. + const focusMovedOutside = + customActionActivatedRef.current && + activeElement?.isConnected && + activeElement !== focusDocument?.body && + activeElement !== focusDocument?.documentElement && + activeElement !== root?.host && + !activeElement.hasAttribute('data-radix-focus-guard') && + isElementFromOwnerDocument(closingContent, activeElement, 'Element') && + !closingContent.contains(activeElement); const target = focusRestoreTargetRef.current; const fallbackTarget = getShadowFocusRestoreTarget?.(); const restoreTarget = isDurableFocusRestoreTarget(target, root?.ownerDocument) @@ -490,9 +538,11 @@ export const VerseActionPopover: FC = ({ : isDurableFocusRestoreTarget(fallbackTarget, root?.ownerDocument) ? fallbackTarget : null; - if (root || restoreTarget) event.preventDefault(); - if (!retainOutsideFocusRef.current) restoreTarget?.focus({ preventScroll: true }); - retainOutsideFocusRef.current = false; + if (focusMovedOutside || root || restoreTarget) event.preventDefault(); + if (!focusMovedOutside && !retainOutsideFocusRef.current) { + restoreTarget?.focus({ preventScroll: true }); + } + allowPriorFocusRestoration(); focusRestoreTargetRef.current = null; }} onPointerDownCapture={allowPriorFocusRestoration} @@ -524,7 +574,7 @@ export const VerseActionPopover: FC = ({ 'yv:bg-card yv:text-popover-foreground', 'yv:rounded-full yv:drop-shadow-[0px_4.8432px_20px_rgba(0,0,0,0.19)]', 'yv:px-4 yv:py-2', - 'yv:flex yv:items-center yv:gap-3', + 'yv:flex yv:items-center yv:gap-1', // Never wider than the viewport (minus collision padding). When the // swatch row can't fit, it scrolls inside instead of overflowing the // screen. Radix sets `--radix-popover-content-available-width`, but @@ -532,6 +582,7 @@ export const VerseActionPopover: FC = ({ // resize. `min()` with a live `100vw` term keeps the cap honest when // the viewport shrinks under an open popover (24px = 2×collisionPadding). 'yv:max-w-[min(var(--radix-popover-content-available-width),calc(100vw-24px))]', + view.scrollAllActions && 'yv:box-border', 'yv:z-50 yv:outline-hidden', 'yv:overflow-visible yv:relative', 'yv:origin-(--radix-popover-content-transform-origin)', @@ -559,55 +610,97 @@ export const VerseActionPopover: FC = ({ )} - {/* Highlights UI is hidden entirely when the feature is off (flag off): - only Copy / Share remain. */} - {highlightsEnabled && ( - <> -
- {view.colorCircles.map(({ color, showRemove, key }) => ( - + {view.actionItems.map((item, index) => { + if (item === 'copy' || item === 'share') { + return ( + + ) : ( + + ) } - onClick={() => (showRemove ? onClearHighlight(color) : onHighlight(color))} + label={item === 'copy' ? t('copy') : t('share')} + onClick={item === 'copy' ? onCopy : onShare} /> - ))} -
- - {/* Separator — never shrinks, so only the swatch row scrolls. */} -