(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 (
+
+
+ setOmittedAction('copy')}>
+ Omit Copy
+
+ setOmittedAction('share')}>
+ Omit Share
+
+ {editingNote && (
+
+ Note
+
+
+ )}
+
+
+
+
+
+
+
+ );
+ },
+ 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 = {
After reader
>
),
- 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 (
- {icon}
- {label}
+
+ {icon}
+
+ {label}
);
}
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. */}
-
- >
- )}
-
- {/* Copy / Share stay pinned and fully visible; only the swatch row
- scrolls when space is tight. */}
-
-
}
- label={t('copy')}
- onClick={onCopy}
- />
-
}
- label={t('share')}
- onClick={onShare}
- />
+ );
+ }
+ if (item !== 'highlights') {
+ return (
+
{
+ customActionActivatedRef.current = true;
+ }}
+ />
+ );
+ }
+ if (!highlightsEnabled) return null;
+
+ const divider = (
+
+ );
+ const isLast = index === view.actionItems.length - 1;
+ return (
+
+ {isLast && index > 0 && divider}
+
+ {view.colorCircles.map(({ color, showRemove, key }) => (
+
+ showRemove ? onClearHighlight(color) : onHighlight(color)
+ }
+ />
+ ))}
+
+ {!isLast && divider}
+
+ );
+ })}
diff --git a/packages/ui/src/components/verse.stories.tsx b/packages/ui/src/components/verse.stories.tsx
index a49435a08..d251cfc3f 100644
--- a/packages/ui/src/components/verse.stories.tsx
+++ b/packages/ui/src/components/verse.stories.tsx
@@ -13,10 +13,18 @@ import {
getCleanVerseText,
} from './verse';
import { VerseActionPopover } from './verse-action-popover';
+import type { BibleReaderReference } from './bible-reader-navigation';
import { buildVerseShareText } from '@/lib/verse-share';
import { Button } from './ui/button';
import { XIcon } from '@/components/icons/x';
-import { waitForElement, waitForShadowContent, waitForShadowRoot } from '@/test/storybook-dom';
+import {
+ clickStoryElement,
+ getBackgroundColorChannels,
+ verifyNativeBrowserKey,
+ waitForElement,
+ waitForShadowContent,
+ waitForShadowRoot,
+} from '@/test/storybook-dom';
import { YvComponentStyles } from '@/lib/yv-styles-components';
import { YvReaderStyles } from '@/lib/yv-styles-reader';
import { ShadowRootHost } from '@/lib/shadow-root-host';
@@ -291,12 +299,33 @@ export const RealAPI: Story = {
},
};
+const NEXT_INDICATOR_PASSAGE = {
+ id: 'JHN.2.1',
+ reference: 'John 2:1',
+ content:
+ '1 On the third day a wedding took place at Cana in Galilee.
',
+};
+
export const FootnoteInteraction: Story = {
args: {
reference: 'JHN.1.51',
versionId: 111,
renderNotes: true,
showVerseNumbers: true,
+ highlightedVerses: { 51: 'ffec5b' },
+ getVerseIndicator: fn(({ passageId, versionId }: BibleReaderReference) => {
+ if (versionId !== 111) return undefined;
+ if (passageId === 'JHN.1.51') {
+ return {
+ label: 'Open marker for John 1:51',
+ style: { backgroundColor: 'rgb(118, 45, 175)' },
+ };
+ }
+ if (passageId === 'JHN.2.1') return { label: 'Open marker for John 2:1' };
+ return undefined;
+ }),
+ onVerseIndicatorPress: fn(),
+ onVerseSelect: fn(),
passageState: {
passage: mockPassages['JHN.1.51'],
loading: false,
@@ -304,15 +333,102 @@ export const FootnoteInteraction: Story = {
},
},
tags: ['integration', 'shadow-dom', 'cross-browser'],
- play: async ({ canvasElement }) => {
+ render: function IndicatorPassage(args) {
+ const [showNext, setShowNext] = React.useState(false);
+ return (
+
+ setShowNext(true)}>
+ Show John 2:1
+
+
+
+ );
+ },
+ play: async ({ args, canvasElement }) => {
const root = await waitForShadowRoot(canvasElement);
+ const content = await waitForShadowContent(root);
+ const indicator = await within(content).findByRole('button', {
+ name: 'Open marker for John 1:51',
+ });
+ const mark = indicator.querySelector('[data-slot="verse-indicator-mark"]');
+ const verse = indicator.closest('.yv-v[v="51"]');
+ if (!mark || !verse) throw new Error('Verse number marker not rendered');
+ await document.fonts.ready;
+ await expect(verse.getClientRects().length).toBeGreaterThan(1);
+ await expect(indicator.closest('[data-yv-theme="light"]')).toBeInTheDocument();
+ await waitFor(() => expect(getBackgroundColorChannels(verse)).toEqual([255, 236, 91, 255]));
+ await expect(mark).toBeVisible();
+ await expect(getComputedStyle(mark).backgroundColor).toBe('rgb(118, 45, 175)');
+ const visible = await waitFor(async () => {
+ const bounds = mark.getBoundingClientRect();
+ const x = bounds.left + bounds.width / 2;
+ const y = bounds.top + bounds.height / 2;
+ await expect(
+ Array.from(verse.getClientRects()).some(
+ (line) => x > line.left && x < line.right && y > line.top && y < line.bottom,
+ ),
+ ).toBe(true);
+ return bounds;
+ });
+ const hit = indicator.getBoundingClientRect();
+ await expect(hit.width).toBeGreaterThan(visible.width);
+ await expect(hit.height).toBeGreaterThan(visible.height);
+ let indicatorPresses = 0;
+ if (__YV_STORYBOOK_VITEST__) {
+ const { server, userEvent: browserUserEvent } = await import('vitest/browser');
+ if (server.provider === 'playwright') {
+ const centerX = visible.left + visible.width / 2;
+ const centerY = visible.top + visible.height / 2;
+ await browserUserEvent.click(indicator, {
+ timeout: 5000,
+ position: {
+ x: centerX - hit.left,
+ y: centerY - hit.top,
+ },
+ });
+ await expect(args.onVerseIndicatorPress).toHaveBeenCalledTimes(1);
+ const position = { x: hit.width - 2, y: hit.height / 2 };
+ const x = hit.left + position.x;
+ const y = hit.top + position.y;
+ await expect(x).toBeGreaterThan(visible.right);
+ await expect(
+ Array.from(verse.getClientRects()).some(
+ (line) => x > line.left && x < line.right && y > line.top && y < line.bottom,
+ ),
+ ).toBe(true);
+ await browserUserEvent.click(indicator, { position });
+ indicatorPresses = 2;
+ await expect(args.onVerseIndicatorPress).toHaveBeenCalledTimes(indicatorPresses);
+ await expect(args.onVerseIndicatorPress).toHaveBeenCalledWith({
+ versionId: 111,
+ passageId: 'JHN.1.51',
+ });
+ await expect(args.onVerseSelect).not.toHaveBeenCalled();
+ }
+ }
+ indicator.focus();
+ await expect(root.activeElement).toBe(indicator);
+ await verifyNativeBrowserKey('{Enter}', async () => {
+ indicatorPresses += 1;
+ await expect(args.onVerseIndicatorPress).toHaveBeenCalledTimes(indicatorPresses);
+ await expect(args.onVerseIndicatorPress).toHaveBeenLastCalledWith({
+ versionId: 111,
+ passageId: 'JHN.1.51',
+ });
+ await expect(args.onVerseSelect).not.toHaveBeenCalled();
+ });
+
const footnoteButton = await waitForElement(
root,
'[data-verse-footnote] button',
'footnote button not rendered',
);
- await userEvent.click(footnoteButton);
+ await clickStoryElement(footnoteButton);
const overlay = await waitForElement(
root,
'[data-yv-shadow-local-overlay]',
@@ -329,6 +445,27 @@ export const FootnoteInteraction: Story = {
);
await expect(overlay).toContainElement(noteItem);
await expect(root.querySelector('[data-yv-shadow-host]')).toBeNull();
+ await expect(args.onVerseIndicatorPress).toHaveBeenCalledTimes(indicatorPresses);
+ await expect(args.onVerseSelect).not.toHaveBeenCalled();
+
+ await clickStoryElement(within(canvasElement).getByRole('button', { name: 'Show John 2:1' }));
+ const nextIndicator = await within(content).findByRole('button', {
+ name: 'Open marker for John 2:1',
+ });
+ await expect(args.getVerseIndicator).not.toHaveBeenCalledWith({
+ versionId: 111,
+ passageId: 'JHN.2.51',
+ });
+ await expect(args.getVerseIndicator).toHaveBeenCalledWith({
+ versionId: 111,
+ passageId: 'JHN.2.1',
+ });
+ await clickStoryElement(nextIndicator);
+ await expect(args.onVerseIndicatorPress).toHaveBeenCalledTimes(indicatorPresses + 1);
+ await expect(args.onVerseIndicatorPress).toHaveBeenLastCalledWith({
+ versionId: 111,
+ passageId: 'JHN.2.1',
+ });
},
};
diff --git a/packages/ui/src/components/verse.tsx b/packages/ui/src/components/verse.tsx
index c640c5980..5090e65be 100644
--- a/packages/ui/src/components/verse.tsx
+++ b/packages/ui/src/components/verse.tsx
@@ -31,6 +31,7 @@ import {
chapterScopeForHighlightPaint,
clipUsfmForHighlightPaint,
} from '@/lib/highlight-projection';
+import type { BibleReaderReference } from './bible-reader-navigation';
import { useHighlightsControlledLatch, warnOnce } from '@/lib/use-highlights-controlled-latch';
import { highlightFillColorMix, highlightMixP } from '@/lib/highlight-colors';
import { useScriptureHighlightPaint } from '@/lib/use-scripture-highlight-paint';
@@ -61,6 +62,28 @@ export type FootnoteData = {
reference?: string;
};
+/** A visual mark displayed with a verse number. */
+export type VerseIndicator = {
+ /** Accessible name of the indicator button, localized by the host. */
+ label: string;
+ /** Inline styles for the visible mark, inside the indicator's hit target. */
+ style?: CSSProperties;
+};
+
+export type VerseIndicatorProps = {
+ /**
+ * Return a mark for a displayed verse, or undefined to leave its number
+ * unchanged. The reader shows the mark when verse numbers are visible.
+ */
+ getVerseIndicator?: (reference: BibleReaderReference) => VerseIndicator | undefined;
+ /** Handle indicator activation. When omitted, marks are decorative. */
+ onVerseIndicatorPress?: (reference: BibleReaderReference) => void;
+};
+
+type VerseHtmlIndicatorProps = VerseIndicatorProps & {
+ indicatorChapter?: BibleReaderReference;
+};
+
/**
* Props for {@link FootnoteContent}.
*
@@ -323,6 +346,41 @@ function VerseUnavailableMessage({ message }: { message: string }): React.ReactE
);
}
+function VerseNumberIndicator({
+ indicator,
+ onPress,
+}: {
+ indicator: VerseIndicator;
+ onPress?: () => void;
+}) {
+ const targetClassName =
+ 'yv:absolute yv:z-10 yv:start-[calc(50%-12px)] yv:[inset-block-start:50%] yv:-translate-y-1/2 yv:size-[24px] yv:rounded-full';
+ const mark = (
+
+ );
+ if (!onPress) {
+ return {mark} ;
+ }
+ return (
+
+ {mark}
+
+ );
+}
+
function BibleTextHtml({
html,
reference,
@@ -332,9 +390,12 @@ function BibleTextHtml({
onVerseSelect,
highlightedVerses = {},
onFootnotePress,
+ indicatorChapter,
+ getVerseIndicator,
+ onVerseIndicatorPress,
direction,
directionOverride,
-}: {
+}: VerseHtmlIndicatorProps & {
html: string;
reference?: string;
fontSize?: number;
@@ -349,8 +410,17 @@ function BibleTextHtml({
const contentRef = useRef(null);
const passageRootDirectionsRef = useRef(new Map());
const [footnoteData, setFootnoteData] = useState([]);
+ const [indicatorTargets, setIndicatorTargets] = useState<{
+ html: string;
+ scope: string;
+ labels: Map;
+ } | null>(null);
const providerTheme = useTheme();
const currentTheme = theme || providerTheme;
+ const indicatorScope =
+ indicatorChapter && getVerseIndicator
+ ? `${indicatorChapter.versionId}:${indicatorChapter.passageId}`
+ : null;
// Set innerHTML and extract footnote data from the DOM.
// Portals need stable element references, so we set innerHTML manually.
@@ -363,6 +433,21 @@ function BibleTextHtml({
);
}, [html]);
+ useLayoutEffect(() => {
+ if (indicatorScope === null || !contentRef.current) {
+ setIndicatorTargets(null);
+ return;
+ }
+ const labels = new Map();
+ for (const verse of contentRef.current.querySelectorAll('.yv-v[v]')) {
+ const verseNum = parseInt(verse.getAttribute('v') ?? '', 10);
+ if (!verseNum || labels.has(verseNum)) continue;
+ const label = verse.querySelector('.yv-vlbl') ?? verse.querySelector('.va');
+ if (label) labels.set(verseNum, label);
+ }
+ setIndicatorTargets({ html, scope: indicatorScope, labels });
+ }, [html, indicatorScope]);
+
// An explicit consumer override owns each passage root while preserving
// intentional nested bidi islands. Restore API-provided root directions when
// the override is removed without replacing the passage DOM.
@@ -491,6 +576,26 @@ function BibleTextHtml({
`${verseNum}-${index}`,
),
)}
+ {indicatorChapter &&
+ getVerseIndicator &&
+ indicatorTargets?.html === html &&
+ indicatorTargets.scope === indicatorScope &&
+ Array.from(indicatorTargets.labels, ([verse, label]) => {
+ const reference = {
+ versionId: indicatorChapter.versionId,
+ passageId: `${indicatorChapter.passageId}.${verse}`,
+ };
+ const indicator = getVerseIndicator(reference);
+ if (!indicator) return null;
+ return createPortal(
+ onVerseIndicatorPress(reference))}
+ />,
+ label,
+ verse,
+ );
+ })}
>
);
}
@@ -513,7 +618,7 @@ type VerseProps = {
size?: 'default' | 'lg';
};
-type VerseHtmlProps = {
+type VerseHtmlProps = VerseHtmlIndicatorProps & {
html: string;
fontFamily?: FontFamily;
fontSize?: number;
@@ -583,6 +688,9 @@ export const Verse = {
onVerseSelect,
highlightedVerses,
onFootnotePress,
+ indicatorChapter,
+ getVerseIndicator,
+ onVerseIndicatorPress,
scriptureDirection,
}: VerseHtmlProps,
ref,
@@ -631,6 +739,9 @@ export const Verse = {
onVerseSelect={onVerseSelect}
highlightedVerses={highlightedVerses}
onFootnotePress={onFootnotePress}
+ indicatorChapter={showVerseNumbers ? indicatorChapter : undefined}
+ getVerseIndicator={getVerseIndicator}
+ onVerseIndicatorPress={onVerseIndicatorPress}
direction={direction}
directionOverride={scriptureDirection}
/>
@@ -640,7 +751,7 @@ export const Verse = {
),
};
-export type BibleTextViewProps = {
+export type BibleTextViewProps = VerseIndicatorProps & {
reference: string;
fontFamily?: FontFamily;
fontSize?: number;
@@ -696,6 +807,8 @@ const BibleTextViewImplementation = forwardRef
diff --git a/packages/ui/src/test/shadow-recovery-mocks.ts b/packages/ui/src/test/shadow-recovery-mocks.ts
index c930cf7a4..39b1a24dc 100644
--- a/packages/ui/src/test/shadow-recovery-mocks.ts
+++ b/packages/ui/src/test/shadow-recovery-mocks.ts
@@ -70,7 +70,7 @@ export function createBibleReaderRecovery(): BibleReaderRecovery {
}
return HttpResponse.json({
id: usfm,
- content: `Passage text for ${usfm}.
`,
+ content: `1 Passage text for ${usfm}.
`,
reference: usfm,
});
}),
diff --git a/packages/ui/src/test/storybook-dom.ts b/packages/ui/src/test/storybook-dom.ts
index b02e1a24a..2c81bc0f5 100644
--- a/packages/ui/src/test/storybook-dom.ts
+++ b/packages/ui/src/test/storybook-dom.ts
@@ -1,4 +1,4 @@
-import { waitFor as storybookWaitFor } from 'storybook/test';
+import { userEvent as storybookUserEvent, waitFor as storybookWaitFor } from 'storybook/test';
import { requireShadowRoot } from './dom-stubs';
interface StorybookWaitOptions {
@@ -39,6 +39,24 @@ export function waitForShadowContent(root: ShadowRoot): Promise {
return waitFor(() => requireShadowContent(root));
}
+/** Resolve computed CSS colors to sRGB bytes across browser serialization formats. */
+export function getBackgroundColorChannels(element: Element): number[] {
+ const context = element.ownerDocument.createElement('canvas').getContext('2d');
+ if (!context) throw new Error('2D canvas is unavailable');
+ context.fillStyle = getComputedStyle(element).backgroundColor;
+ context.fillRect(0, 0, 1, 1);
+ return Array.from(context.getImageData(0, 0, 1, 1).data);
+}
+
+export async function clickStoryElement(element: Element): Promise {
+ if (__YV_STORYBOOK_VITEST__) {
+ const { userEvent } = await import('vitest/browser');
+ await userEvent.click(element);
+ return;
+ }
+ await storybookUserEvent.click(element);
+}
+
async function pressNativeBrowserKey(keys: string): Promise {
if (!__YV_STORYBOOK_VITEST__) return false;
const { userEvent } = await import('vitest/browser');
From 6c375cbf6d68025bb4954b1739f00a8758d16b5c Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 08:31:29 -0600
Subject: [PATCH 16/75] feat(ui): add Reader note saving
Ref: YPE-6783
---
.changeset/reader-saves-notes.md | 12 +
CONTEXT.md | 6 +-
examples/vite-react/README.md | 20 +
examples/vite-react/src/ThemedApp.tsx | 1 +
.../vite-react/src/pages/BibleReaderPage.tsx | 3 +-
packages/core/src/Users.ts | 49 +-
.../src/YouVersionPlatformConfiguration.ts | 43 +-
packages/core/src/__tests__/Users.test.ts | 307 +++++++++++--
.../YouVersionPlatformConfiguration.test.ts | 44 +-
packages/core/src/__tests__/notes.test.ts | 20 +
packages/core/src/schemas/auth.ts | 11 +-
packages/core/src/schemas/note.ts | 11 +-
.../context/YouVersionAuthProvider.test.tsx | 161 +++++--
.../src/context/YouVersionAuthProvider.tsx | 37 +-
packages/hooks/src/index.ts | 1 +
packages/hooks/src/types/auth.ts | 4 +
packages/hooks/src/useCreateNote.ts | 12 +
packages/hooks/src/useHighlightAuthActions.ts | 10 +-
packages/ui/README.md | 13 +-
.../ui/scripts/smoke-vite-reader-notes.mjs | 221 +++++++++
.../ui/src/components/bible-reader-auth.ts | 7 +
.../bible-reader-notes-composer.tsx | 150 +++++++
.../components/bible-reader-notes.stories.tsx | 419 ++++++++++++++++++
.../src/components/bible-reader-toolbar.tsx | 3 +-
.../src/components/bible-reader.stories.tsx | 4 +-
packages/ui/src/components/bible-reader.tsx | 87 +++-
.../src/components/highlight-color-circle.tsx | 51 +++
...-highlights.auth-flow.integration.test.tsx | 2 +-
.../components/use-bible-reader-highlights.ts | 15 +-
.../src/components/use-bible-reader-note.ts | 303 +++++++++++++
.../src/components/verse-action-popover.tsx | 83 ++--
31 files changed, 1963 insertions(+), 147 deletions(-)
create mode 100644 .changeset/reader-saves-notes.md
create mode 100644 packages/hooks/src/useCreateNote.ts
create mode 100644 packages/ui/scripts/smoke-vite-reader-notes.mjs
create mode 100644 packages/ui/src/components/bible-reader-auth.ts
create mode 100644 packages/ui/src/components/bible-reader-notes-composer.tsx
create mode 100644 packages/ui/src/components/bible-reader-notes.stories.tsx
create mode 100644 packages/ui/src/components/highlight-color-circle.tsx
create mode 100644 packages/ui/src/components/use-bible-reader-note.ts
diff --git a/.changeset/reader-saves-notes.md b/.changeset/reader-saves-notes.md
new file mode 100644
index 000000000..4907707bb
--- /dev/null
+++ b/.changeset/reader-saves-notes.md
@@ -0,0 +1,12 @@
+---
+'@youversion/platform-core': patch
+'@youversion/platform-react-hooks': minor
+'@youversion/platform-react-ui': minor
+---
+
+Add Save to the Bible Reader's verse actions. The Notes composer keeps the exact
+selection, including gaps, and saves a passage with optional text, privacy, and
+highlight color. Reader sign-in requests Notes scopes. The reader refreshes
+chapter highlights after a successful save.
+
+`NotesClient` supports creating a passage-only note with empty `content`.
diff --git a/CONTEXT.md b/CONTEXT.md
index 69bb0e494..be222648d 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -178,9 +178,9 @@ round-trips an updated `highlights` prop.
## Verse action popover
-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.
+The floating action bar for a verse selection, with highlight colors, Save,
+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 ac47bccc2..4942ddb3b 100644
--- a/examples/vite-react/README.md
+++ b/examples/vite-react/README.md
@@ -24,6 +24,26 @@ pnpm dev:web
- **Images** — Smoke page for `ImagesClient` list and detail (metadata only)
- **Sign in with YouVersion Button** - Authentication with YouVersion
+## Reader Notes smoke test
+
+Select verses and choose **Save** to open the Notes composer. Sign in from the
+Reader when prompted, then save the passage with optional note text, visibility,
+and color. The demo also exposes **Mark verses** for its local verse markers.
+
+Run the repeatable browser smoke with a mocked YouVersion API. The script
+checks the Navbar and Reader OAuth scopes, declined authorization, exact
+selection resumption, cross-account invalidation, and the Notes create payload.
+Run these commands from the repository root after installing Playwright Chromium.
+
+```bash
+pnpm build
+VITE_YVP_APP_KEY=notes-smoke VITE_YVP_API_HOST=notes-smoke.example.test \
+ VITE_YVP_AUTH_REDIRECT_URL=http://127.0.0.1:5176 VITE_YVP_LOCALE=en \
+ pnpm --filter vite-react dev --port 5176 --strictPort
+```
+
+With the server running, execute `node packages/ui/scripts/smoke-vite-reader-notes.mjs`.
+
## Verse marker smoke test
1. Open the browser developer tools' **Network** panel, enable **Preserve log**,
diff --git a/examples/vite-react/src/ThemedApp.tsx b/examples/vite-react/src/ThemedApp.tsx
index 71c55a486..483f0c9b2 100644
--- a/examples/vite-react/src/ThemedApp.tsx
+++ b/examples/vite-react/src/ThemedApp.tsx
@@ -21,6 +21,7 @@ export default function ThemedApp() {
includeAuth
authRedirectUrl={authRedirectUrl}
appName="SDK Demo"
+ signInPromptMessage="Save Notes and highlights to your YouVersion account."
locale={locale}
>
diff --git a/examples/vite-react/src/pages/BibleReaderPage.tsx b/examples/vite-react/src/pages/BibleReaderPage.tsx
index cb04de04c..057a8369c 100644
--- a/examples/vite-react/src/pages/BibleReaderPage.tsx
+++ b/examples/vite-react/src/pages/BibleReaderPage.tsx
@@ -16,7 +16,7 @@ export function BibleReaderPage() {
{openedMarker
? `Opened marker for ${openedMarker}.`
- : 'Select verses and choose Mark verses to add a marker.'}
+ : 'Select verses and choose Save to add a note or Mark verses to add a marker.'}
void,
): Promise {
const appKey = YouVersionPlatformConfiguration.appKey;
if (!appKey) {
@@ -244,6 +246,8 @@ export class YouVersionAPIUsers {
permissions,
);
+ beforeRedirect?.(authorizationRequest.parameters.state);
+
// Store auth data for callback handler
persistOrThrow(
storage,
@@ -272,7 +276,6 @@ export class YouVersionAPIUsers {
stashRequestedPermissions(storage, authorizationRequest.parameters.state, permissions);
}
- // Simple redirect to authorization URL
window.location.href = authorizationRequest.url.toString();
}
@@ -375,6 +378,11 @@ export class YouVersionAPIUsers {
urlParams: URLSearchParams,
storage: Storage,
): Promise {
+ const initiatingUserId = YouVersionPlatformConfiguration.storedUserInfo?.id;
+ const isCurrentSignIn = () =>
+ storage.getItem('youversion-auth-state') === state &&
+ YouVersionPlatformConfiguration.storedUserInfo?.id === initiatingUserId;
+ let savingSession = false;
try {
// Exchange authorization code for tokens
const tokenRequest = SignInWithYouVersionPKCEAuthorizationRequestBuilder.tokenURLRequest(
@@ -396,6 +404,7 @@ export class YouVersionAPIUsers {
throw new Error(`Token exchange response was invalid: ${parsed.error.message}`);
}
const tokens = parsed.data;
+ if (!isCurrentSignIn()) throw new Error('The authentication session changed during sign-in');
// Match Swift: union grants from (1) this URL, (2) stashed pre-code hop,
// (3) token scope — then drop scopes that aren't data-exchange permissions before seeding the
@@ -428,10 +437,12 @@ export class YouVersionAPIUsers {
// Store tokens in configuration. The ID token is intentionally not
// persisted — it is only used here to derive the user profile below.
+ savingSession = true;
const tokensPersisted = YouVersionPlatformConfiguration.saveAuthData(
result.accessToken || null,
result.refreshToken || null,
result.expiryDate || null,
+ result.yvpUserId ? { scope: tokens.scope, userId: result.yvpUserId } : undefined,
);
// Persist the decoded user profile so it survives reloads without
@@ -470,8 +481,10 @@ export class YouVersionAPIUsers {
return result;
} catch (error) {
- YouVersionPlatformConfiguration.clearAuthTokens();
- clearOAuthHandoff(storage);
+ if (savingSession || isCurrentSignIn()) {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ clearOAuthHandoff(storage);
+ }
throw error;
}
}
@@ -627,7 +640,10 @@ export class YouVersionAPIUsers {
* @throws An error if refresh fails or no refresh token is available
*/
static async refreshTokens(): Promise {
+ const accessToken = YouVersionPlatformConfiguration.accessToken;
const refreshToken = YouVersionPlatformConfiguration.refreshToken;
+ const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
+ const oauthSession = YouVersionPlatformConfiguration.readOAuthSession();
const appKey = YouVersionPlatformConfiguration.appKey;
if (!refreshToken) {
@@ -639,6 +655,9 @@ export class YouVersionAPIUsers {
'YouVersionPlatformConfiguration.appKey must be set before refreshing tokens',
);
}
+ if (oauthSession === null || (oauthSession && oauthSession.refreshToken !== refreshToken)) {
+ throw new Error('The authentication session changed before token refresh');
+ }
try {
const url = new URL(`https://${YouVersionPlatformConfiguration.apiHost}/auth/token`);
@@ -664,6 +683,14 @@ export class YouVersionAPIUsers {
}
const tokens = TokenRefreshResponseSchema.parse(await response.json());
+ if (
+ YouVersionPlatformConfiguration.accessToken !== accessToken ||
+ YouVersionPlatformConfiguration.refreshToken !== refreshToken ||
+ YouVersionPlatformConfiguration.storedUserInfo?.id !== userId ||
+ YouVersionPlatformConfiguration.readOAuthSession() === null
+ ) {
+ throw new Error('The authentication session changed during token refresh');
+ }
// Create result with new tokens. The persisted user profile is left
// untouched — refreshing only rotates the access/refresh tokens.
@@ -679,6 +706,9 @@ export class YouVersionAPIUsers {
result.accessToken || null,
result.refreshToken || null,
result.expiryDate || null,
+ oauthSession
+ ? { scope: tokens.scope ?? oauthSession.scope, userId: oauthSession.userId }
+ : undefined,
);
if (!persisted) {
throw new Error('the rotated tokens could not be saved to browser storage');
@@ -748,12 +778,23 @@ export class YouVersionAPIUsers {
* resolves false for every caller awaiting it.
*/
private static async performTokenRefresh(): Promise {
+ const accessToken = YouVersionPlatformConfiguration.accessToken;
+ const refreshToken = YouVersionPlatformConfiguration.refreshToken;
+ const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
+ if (YouVersionPlatformConfiguration.readOAuthSession() === null) return false;
try {
const result = await this.refreshTokens();
return !!result;
} catch {
// Refresh failed, clear tokens
- YouVersionPlatformConfiguration.clearAuthTokens();
+ if (
+ YouVersionPlatformConfiguration.accessToken === accessToken &&
+ YouVersionPlatformConfiguration.refreshToken === refreshToken &&
+ YouVersionPlatformConfiguration.storedUserInfo?.id === userId &&
+ YouVersionPlatformConfiguration.readOAuthSession() !== null
+ ) {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ }
return false;
}
}
diff --git a/packages/core/src/YouVersionPlatformConfiguration.ts b/packages/core/src/YouVersionPlatformConfiguration.ts
index e4bbd9bc8..eb1cc8c8c 100644
--- a/packages/core/src/YouVersionPlatformConfiguration.ts
+++ b/packages/core/src/YouVersionPlatformConfiguration.ts
@@ -1,5 +1,11 @@
-import { StoredGrantsSchema } from './schemas/auth';
+import {
+ StoredGrantsSchema,
+ StoredOAuthSessionSchema,
+ type StoredOAuthSession,
+} from './schemas/auth';
import { YouVersionUserInfoJSONSchema, type YouVersionUserInfoJSON } from './schemas/user-info';
+import { parsePermissionList } from './permissions';
+import type { AuthenticationScopes } from './types';
import { versionFilterState } from './version-filter-state';
import { getLocalStorage, removeStorageItem, setStorageItem } from './web-storage';
@@ -57,14 +63,22 @@ export class YouVersionPlatformConfiguration {
accessToken: string | null,
refreshToken: string | null,
expiryDate: Date | null,
+ oauthSession?: Pick,
): boolean {
const storage = getLocalStorage();
let persisted = true;
if (accessToken !== null) {
+ if (oauthSession) {
+ const value = JSON.stringify({ ...oauthSession, accessToken, refreshToken });
+ persisted = setStorageItem(storage, 'youversion-auth-scope', value) && persisted;
+ } else {
+ removeStorageItem(storage, 'youversion-auth-scope');
+ }
persisted = setStorageItem(storage, 'accessToken', accessToken) && persisted;
} else {
removeStorageItem(storage, 'accessToken');
+ removeStorageItem(storage, 'youversion-auth-scope');
}
if (refreshToken !== null) {
@@ -105,6 +119,33 @@ export class YouVersionPlatformConfiguration {
this.saveUserInfo(null);
this.clearGrantedPermissions();
this.clearDataExchangeInitiator();
+ removeStorageItem(getLocalStorage(), 'youversion-auth-state');
+ }
+
+ /** Returns an access token only for the specified account and granted OAuth scope. */
+ public static getOAuthAccessToken(userId: string, scope: AuthenticationScopes): string | null {
+ const session = this.readOAuthSession();
+ return session?.userId === userId && parsePermissionList(session.scope).includes(scope)
+ ? session.accessToken
+ : null;
+ }
+
+ /** @internal Reads the OAuth session for token rotation, or `null` for a mismatched record. */
+ public static readOAuthSession(): StoredOAuthSession | null | undefined {
+ const storage = getLocalStorage();
+ const raw = storage?.getItem('youversion-auth-scope');
+ if (!raw) return undefined;
+ try {
+ const session = StoredOAuthSessionSchema.parse(JSON.parse(raw));
+ // A different tab may be partway through replacing the token or profile.
+ return session.accessToken === storage?.getItem('accessToken') &&
+ session.refreshToken === (storage?.getItem('refreshToken') ?? null) &&
+ session.userId === this.currentUserId
+ ? session
+ : null;
+ } catch {
+ return null;
+ }
}
/**
diff --git a/packages/core/src/__tests__/Users.test.ts b/packages/core/src/__tests__/Users.test.ts
index 1004b75f7..9975db7c1 100644
--- a/packages/core/src/__tests__/Users.test.ts
+++ b/packages/core/src/__tests__/Users.test.ts
@@ -80,6 +80,37 @@ describe('YouVersionAPIUsers', () => {
mocks.btoa.mockReturnValue('mockBase64Value');
}
+ function persistBrowserWrites() {
+ const values = new Map();
+ mocks.localStorage.getItem.mockImplementation((key: string) => values.get(key) ?? null);
+ mocks.localStorage.setItem.mockImplementation((key: string, value: string) => {
+ values.set(key, value);
+ });
+ mocks.localStorage.removeItem.mockImplementation((key: string) => {
+ values.delete(key);
+ });
+ }
+
+ function arriveWithAuthorizationCode(code: string) {
+ const authorizeUrl = new URL(mocks.window.location.href);
+ const redirect = new URL(authorizeUrl.searchParams.get('redirect_uri') ?? '');
+ redirect.searchParams.set('state', authorizeUrl.searchParams.get('state') ?? '');
+ redirect.searchParams.set('code', code);
+ mocks.window.location.href = redirect.href;
+ mocks.window.location.search = redirect.search;
+ vi.mocked(atob).mockReturnValue(JSON.stringify(DEFAULT_CALLBACK_PROFILE));
+ }
+
+ function holdTokenResponse() {
+ let respond!: (response: Response) => void;
+ mockFetch.mockReturnValueOnce(
+ new Promise((resolve) => {
+ respond = resolve;
+ }),
+ );
+ return respond;
+ }
+
/**
* Wires up the shared handleAuthCallback token-exchange setup: callback URL,
* localStorage reads (state/verifier/redirect-uri + optional pending grant),
@@ -127,6 +158,7 @@ describe('YouVersionAPIUsers', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mockFetch.mockReset();
// The code-exchange dedupe map is module-scoped and persists across test
// cases within this file (it only resets on page reload in production).
@@ -155,6 +187,236 @@ describe('YouVersionAPIUsers', () => {
YouVersionPlatformConfiguration.appKey = null;
});
+ it('requests note scopes at authorize and reads the grants from the exchanged token', async () => {
+ persistBrowserWrites();
+ stubSignInCrypto();
+ const redirect = 'https://example.com/callback';
+ const beforeRedirect = vi.fn(() => {
+ expect(mocks.window.location.href).toBe('');
+ });
+
+ await YouVersionAPIUsers.signIn(
+ redirect,
+ ['profile', 'read_notes', 'write_notes'],
+ ['highlights'],
+ beforeRedirect,
+ );
+
+ const authorize = new URL(mocks.window.location.href);
+ expect(authorize.pathname).toBe('/auth/authorize');
+ expect(authorize.searchParams.get('scope')?.split(' ').sort()).toEqual([
+ 'openid',
+ 'profile',
+ 'read_notes',
+ 'write_notes',
+ ]);
+ expect(authorize.searchParams.get('requested_permissions')).toBe('highlights');
+ expect(beforeRedirect).toHaveBeenCalledWith(authorize.searchParams.get('state'));
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'write_notes'),
+ ).toBeNull();
+
+ arriveWithAuthorizationCode('notes-code');
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse(makeTokens('openid profile read_notes write_notes')),
+ );
+ await YouVersionAPIUsers.handleAuthCallback();
+
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'read_notes')).toBe(
+ 'access-token-123',
+ );
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'write_notes')).toBe(
+ 'access-token-123',
+ );
+ expect(YouVersionPlatformConfiguration.grantedPermissions).toEqual(['highlights']);
+ });
+
+ it('retains note scopes when rotation omits scope and replaces them when the response narrows it', async () => {
+ persistBrowserWrites();
+ YouVersionPlatformConfiguration.saveAuthData(
+ 'initial-access-token',
+ 'initial-refresh-token',
+ new Date(0),
+ { scope: 'openid read_notes write_notes', userId: 'notes-account' },
+ );
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'notes-account' });
+ const rotation = { expires_in: 3600, token_type: 'Bearer' };
+ mockFetch
+ .mockResolvedValueOnce(
+ jsonResponse({
+ ...rotation,
+ access_token: 'rotated-access',
+ refresh_token: 'rotated-refresh',
+ }),
+ )
+ .mockResolvedValueOnce(
+ jsonResponse({
+ ...rotation,
+ access_token: 'reduced-access',
+ refresh_token: 'reduced-refresh',
+ scope: 'openid read_notes',
+ }),
+ );
+
+ await YouVersionAPIUsers.refreshTokens();
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken('notes-account', 'read_notes')).toBe(
+ 'rotated-access',
+ );
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('notes-account', 'write_notes'),
+ ).toBe('rotated-access');
+
+ await YouVersionAPIUsers.refreshTokens();
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken('notes-account', 'read_notes')).toBe(
+ 'reduced-access',
+ );
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('notes-account', 'write_notes'),
+ ).toBeNull();
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('notes-account');
+ });
+
+ it('waits for a matching profile instead of refreshing a staged account token', async () => {
+ persistBrowserWrites();
+ const config = YouVersionPlatformConfiguration;
+ config.saveAuthData('old-access', 'old-refresh', new Date(0), {
+ scope: 'read_notes',
+ userId: 'old-account',
+ });
+ config.saveUserInfo({ id: 'old-account' });
+ config.saveAuthData('new-access', 'new-refresh', new Date(0), {
+ scope: 'write_notes',
+ userId: 'new-account',
+ });
+ mockFetch.mockResolvedValueOnce(jsonResponse(makeTokens('openid write_notes')));
+
+ await expect(YouVersionAPIUsers.refreshTokens()).rejects.toThrow();
+ const refreshed = await YouVersionAPIUsers.refreshTokenIfNeeded();
+
+ expect(config.getOAuthAccessToken('old-account', 'write_notes')).toBeNull();
+ expect(config.getOAuthAccessToken('new-account', 'write_notes')).toBeNull();
+ expect(refreshed).toBe(false);
+ expect(mockFetch).not.toHaveBeenCalled();
+ config.saveUserInfo({ id: 'new-account' });
+ expect(config.getOAuthAccessToken('new-account', 'write_notes')).toBe('new-access');
+ });
+
+ it('can complete a newer authorization after an older code exchange fails', async () => {
+ persistBrowserWrites();
+ stubSignInCrypto();
+ const redirect = 'https://example.com/callback';
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+ arriveWithAuthorizationCode('old-code');
+ const releaseOldResponse = holdTokenResponse();
+ const oldCallback = YouVersionAPIUsers.handleAuthCallback();
+ expect(mockFetch).toHaveBeenCalled();
+
+ mocks.btoa.mockReturnValue('new-authorization-value');
+ await YouVersionAPIUsers.signIn(redirect, ['read_notes', 'write_notes']);
+ releaseOldResponse(emptyResponse(400, 'Bad Request'));
+ await expect(oldCallback).rejects.toThrow();
+
+ arriveWithAuthorizationCode('new-code');
+ mockFetch.mockResolvedValueOnce(jsonResponse(makeTokens('openid read_notes')));
+ await YouVersionAPIUsers.handleAuthCallback();
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'read_notes')).toBe(
+ 'access-token-123',
+ );
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'write_notes'),
+ ).toBeNull();
+ });
+
+ it.each([
+ { responseOutcome: 'succeeds', status: 200 },
+ { responseOutcome: 'fails', status: 400 },
+ ])(
+ 'preserves the newer account when an older code exchange $responseOutcome',
+ async ({ status }) => {
+ persistBrowserWrites();
+ stubSignInCrypto();
+ await YouVersionAPIUsers.signIn('https://example.com/callback', ['write_notes']);
+ arriveWithAuthorizationCode('old-code');
+ const releaseOldResponse = holdTokenResponse();
+ const oldCallback = YouVersionAPIUsers.handleAuthCallback();
+ expect(mockFetch).toHaveBeenCalled();
+
+ YouVersionPlatformConfiguration.saveAuthData('new-access', 'new-refresh', null, {
+ scope: 'read_notes',
+ userId: 'new-account',
+ });
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'new-account' });
+ releaseOldResponse(jsonResponse(makeTokens('openid write_notes'), status));
+ await expect(oldCallback).rejects.toThrow();
+
+ expect(YouVersionPlatformConfiguration.accessToken).toBe('new-access');
+ expect(YouVersionPlatformConfiguration.refreshToken).toBe('new-refresh');
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('new-account');
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken('new-account', 'read_notes')).toBe(
+ 'new-access',
+ );
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('new-account', 'write_notes'),
+ ).toBeNull();
+ },
+ );
+
+ it('stays signed out when a canceled sign-in exchange later succeeds', async () => {
+ persistBrowserWrites();
+ stubSignInCrypto();
+ await YouVersionAPIUsers.signIn('https://example.com/callback', ['write_notes']);
+ arriveWithAuthorizationCode('canceled-code');
+ const releaseOldResponse = holdTokenResponse();
+ const oldCallback = YouVersionAPIUsers.handleAuthCallback();
+ expect(mockFetch).toHaveBeenCalled();
+
+ YouVersionAPIUsers.signOut();
+ releaseOldResponse(jsonResponse(makeTokens('openid write_notes')));
+ await expect(oldCallback).rejects.toThrow();
+
+ expect(YouVersionPlatformConfiguration.accessToken).toBeNull();
+ expect(YouVersionAPIUsers.getStoredUserInfo()).toBeNull();
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'write_notes'),
+ ).toBeNull();
+ });
+
+ it.each([
+ { responseOutcome: 'succeeds', status: 200 },
+ { responseOutcome: 'fails', status: 401 },
+ ])(
+ 'preserves the newer account when an older token refresh $responseOutcome',
+ async ({ status }) => {
+ persistBrowserWrites();
+ YouVersionPlatformConfiguration.saveAuthData('old-access', 'old-refresh', new Date(0), {
+ scope: 'write_notes',
+ userId: 'old-account',
+ });
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'old-account' });
+ const releaseOldResponse = holdTokenResponse();
+ const oldRefresh = YouVersionAPIUsers.refreshTokenIfNeeded();
+ expect(mockFetch).toHaveBeenCalled();
+
+ YouVersionPlatformConfiguration.saveAuthData('new-access', 'new-refresh', null, {
+ scope: 'read_notes',
+ userId: 'new-account',
+ });
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'new-account' });
+ releaseOldResponse(jsonResponse(makeTokens('openid write_notes'), status));
+ await expect(oldRefresh).resolves.toBe(false);
+
+ expect(YouVersionPlatformConfiguration.accessToken).toBe('new-access');
+ expect(YouVersionPlatformConfiguration.refreshToken).toBe('new-refresh');
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('new-account');
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken('new-account', 'read_notes')).toBe(
+ 'new-access',
+ );
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('new-account', 'write_notes'),
+ ).toBeNull();
+ },
+ );
+
describe('signIn', () => {
afterEach(() => {
// Restore the crypto spies here so restoration still happens even when an
@@ -220,7 +482,12 @@ describe('YouVersionAPIUsers', () => {
);
// Verify redirect occurred
- expect(mocks.window.location.href).toContain('https://api.youversion.com/auth/authorize');
+ const authorize = new URL(mocks.window.location.href);
+ expect(authorize.origin + authorize.pathname).toBe(
+ 'https://api.youversion.com/auth/authorize',
+ );
+ expect(authorize.searchParams.get('scope')).toBe('openid');
+ expect(authorize.searchParams.has('requested_permissions')).toBe(false);
});
it('should forward requested permissions to the authorize URL', async () => {
@@ -440,11 +707,12 @@ describe('YouVersionAPIUsers', () => {
expect(result?.name).toBe('John Doe');
expect(result?.email).toBe('john@example.com');
- // Verify saveAuthData was called with tokens only (no id token persisted)
+ // Verify the access and refresh tokens and granted scopes are persisted.
expect(saveAuthDataSpy).toHaveBeenCalledWith(
'access-token-123',
'refresh-token-456',
expect.any(Date),
+ { scope: 'bibles highlights openid', userId: '1234567890' },
);
// Verify the decoded profile was persisted instead of the id token
@@ -982,31 +1250,25 @@ describe('YouVersionAPIUsers', () => {
);
});
- it('should successfully rotate the access and refresh tokens', async () => {
+ it('rotates legacy tokens without assigning the returned scope to a stored profile', async () => {
+ persistBrowserWrites();
const originalAccessToken = 'old-access-token';
const originalRefreshToken = 'old-refresh-token';
+ YouVersionPlatformConfiguration.saveAuthData(originalAccessToken, originalRefreshToken, null);
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'legacy-user' });
const mockRefreshResponse = {
access_token: 'new-access-token',
expires_in: 3600,
refresh_token: 'new-refresh-token',
- scope: 'bibles highlights openid',
+ scope: 'openid write_notes',
token_type: 'Bearer',
};
const mockResponse = jsonResponse(mockRefreshResponse);
- mocks.localStorage.getItem.mockImplementation((key: string) => {
- if (key === 'refreshToken') return originalRefreshToken;
- if (key === 'accessToken') return originalAccessToken;
- return null;
- });
-
mockFetch.mockResolvedValue(mockResponse);
- const saveAuthDataSpy = vi.spyOn(YouVersionPlatformConfiguration, 'saveAuthData');
- const saveUserInfoSpy = vi.spyOn(YouVersionPlatformConfiguration, 'saveUserInfo');
-
const result = await YouVersionAPIUsers.refreshTokens();
expect(result).toBeTruthy();
@@ -1038,18 +1300,12 @@ describe('YouVersionAPIUsers', () => {
const body = new URLSearchParams(bodyText);
expect(body.get('grant_type')).toBe('refresh_token');
- // Verify saveAuthData was called with the rotated tokens only
- expect(saveAuthDataSpy).toHaveBeenCalledWith(
- 'new-access-token',
- 'new-refresh-token',
- expect.any(Date),
- );
-
- // The stored profile is left untouched by a refresh
- expect(saveUserInfoSpy).not.toHaveBeenCalled();
-
- saveAuthDataSpy.mockRestore();
- saveUserInfoSpy.mockRestore();
+ expect(YouVersionPlatformConfiguration.accessToken).toBe('new-access-token');
+ expect(YouVersionPlatformConfiguration.refreshToken).toBe('new-refresh-token');
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('legacy-user');
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('legacy-user', 'write_notes'),
+ ).toBeNull();
});
it('should fail the refresh when the rotated tokens cannot be stored', async () => {
@@ -1266,6 +1522,7 @@ describe('YouVersionAPIUsers', () => {
'new-access-token',
'new-refresh-token',
expect.any(Date),
+ undefined,
);
clearAuthTokensSpy.mockRestore();
diff --git a/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts b/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts
index d7897434d..448bb7709 100644
--- a/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts
+++ b/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts
@@ -32,9 +32,12 @@ describe('YouVersionPlatformConfiguration storage contracts', () => {
expect(storage?.getItem('refreshToken')).toBe('refresh-token');
expect(YouVersionPlatformConfiguration.tokenExpiryDate).toEqual(expiryDate);
expect(storage?.getItem('idToken')).toBeNull();
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('user-123', 'write_notes'),
+ ).toBeNull();
});
- it('removes a persisted session and profile on sign-out', () => {
+ it('removes a persisted session, scopes, and profile on sign-out', () => {
const storage = getLocalStorage();
expect(storage).not.toBeNull();
clearStorage(storage);
@@ -42,15 +45,54 @@ describe('YouVersionPlatformConfiguration storage contracts', () => {
'access-token',
'refresh-token',
new Date('2026-01-01T00:00:00Z'),
+ { scope: 'read_notes write_notes', userId: 'user-123' },
);
YouVersionPlatformConfiguration.saveUserInfo({ id: 'user-123' });
const sessionKeys = ['accessToken', 'refreshToken', 'expiryDate', 'userInfo'];
for (const key of sessionKeys) expect(storage?.getItem(key)).not.toBeNull();
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken('user-123', 'read_notes')).toBe(
+ 'access-token',
+ );
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken('user-123', 'write_notes')).toBe(
+ 'access-token',
+ );
YouVersionPlatformConfiguration.clearAuthTokens();
for (const key of sessionKeys) expect(storage?.getItem(key)).toBeNull();
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('user-123', 'read_notes'),
+ ).toBeNull();
+ expect(
+ YouVersionPlatformConfiguration.getOAuthAccessToken('user-123', 'write_notes'),
+ ).toBeNull();
+ });
+
+ it('authorizes note requests only after replacement tokens and profile belong to the same account', () => {
+ clearStorage(getLocalStorage());
+ const config = YouVersionPlatformConfiguration;
+ config.saveAuthData('a-access', 'a-refresh', null, {
+ scope: 'write_notes',
+ userId: 'account-a',
+ });
+ config.saveUserInfo({ id: 'account-a' });
+ expect(config.getOAuthAccessToken('account-a', 'write_notes')).toBe('a-access');
+ expect(config.getOAuthAccessToken('account-b', 'write_notes')).toBeNull();
+
+ config.saveAuthData('b-access', 'b-refresh', null, {
+ scope: 'write_notes',
+ userId: 'account-b',
+ });
+ expect(config.getOAuthAccessToken('account-a', 'write_notes')).toBeNull();
+ expect(config.getOAuthAccessToken('account-b', 'write_notes')).toBeNull();
+
+ config.saveUserInfo({ id: 'account-b' });
+ expect(config.getOAuthAccessToken('account-a', 'write_notes')).toBeNull();
+ expect(config.getOAuthAccessToken('account-b', 'write_notes')).toBe('b-access');
+
+ config.saveAuthData('unbound-access', 'unbound-refresh', null);
+ expect(config.getOAuthAccessToken('account-b', 'write_notes')).toBeNull();
});
it('fails closed when stored user information is malformed or untrusted', () => {
diff --git a/packages/core/src/__tests__/notes.test.ts b/packages/core/src/__tests__/notes.test.ts
index de3f41d36..511e5d2c8 100644
--- a/packages/core/src/__tests__/notes.test.ts
+++ b/packages/core/src/__tests__/notes.test.ts
@@ -143,6 +143,26 @@ it('creates, gets, partially updates, and deletes a note on the regular Notes ro
await expect(client.getNote(updated.id, 'reader').catch(getHttpStatus)).resolves.toBe(404);
});
+it('saves an attached passage without note text', async () => {
+ server.use(
+ http.post(collectionUrl, async ({ request }) => {
+ expect(await request.json()).toEqual({
+ request_id: requestId,
+ content: '',
+ status: 'private',
+ passage: wireNote.passage,
+ });
+ return HttpResponse.json({ ...wireNote, content: '' }, { status: 201 });
+ }),
+ );
+
+ const create = { request_id: requestId, content: '', status: 'private' } as const;
+ await expect(createClient().createNote(create, 'writer')).rejects.toThrow('content');
+ await expect(
+ createClient().createNote({ ...create, passage: note.passage }, 'writer'),
+ ).resolves.toMatchObject({ content: '', passage: note.passage });
+});
+
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 };
diff --git a/packages/core/src/schemas/auth.ts b/packages/core/src/schemas/auth.ts
index 777315fe5..61657ebe5 100644
--- a/packages/core/src/schemas/auth.ts
+++ b/packages/core/src/schemas/auth.ts
@@ -15,6 +15,15 @@ export const StoredGrantsSchema = object({
});
export type StoredGrants = z.infer;
+/** OAuth grants bound to the access token and verified profile that received them. */
+export const StoredOAuthSessionSchema = object({
+ accessToken: z.string(),
+ refreshToken: z.nullable(z.string()),
+ userId: z.string(),
+ scope: z.string(),
+});
+export type StoredOAuthSession = z.infer;
+
/** Claims read from an ID token for UI display. Signature is not verified here. */
export const IdTokenClaimsSchema = object({
sub: z.catch(z.optional(z.string()), undefined),
@@ -44,7 +53,7 @@ export const TokenRefreshResponseSchema = object({
access_token: z.string(),
expires_in: TokenExpiresInSchema,
refresh_token: z.string(),
- scope: z.string(),
+ scope: z.optional(z.string()),
token_type: z.string(),
});
export type TokenRefreshResponse = z.infer;
diff --git a/packages/core/src/schemas/note.ts b/packages/core/src/schemas/note.ts
index 4ba4cfac9..dd4156229 100644
--- a/packages/core/src/schemas/note.ts
+++ b/packages/core/src/schemas/note.ts
@@ -46,11 +46,16 @@ 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,
+ /** Note text. May be empty when saving an attached passage. */
+ content: z.string(),
/** `private` is visible only to the author; `public` is visible to others. */
status,
-});
+}).check(
+ z.refine((note) => note.content.length > 0 || Boolean(note.passage), {
+ path: ['content'],
+ message: 'Content is required without an attached passage',
+ }),
+);
export const UpdateNoteSchema = strictObject({
...optionalWriteFields,
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.test.tsx b/packages/hooks/src/context/YouVersionAuthProvider.test.tsx
index e419819e8..760f8fbb8 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.test.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.test.tsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
-import { StrictMode } from 'react';
-import { render } from '@testing-library/react';
+import { StrictMode, type PropsWithChildren } from 'react';
+import { act, render, renderHook, waitFor } from '@testing-library/react';
import { YouVersionAPIUsers, YouVersionPlatformConfiguration } from '@youversion/platform-core';
import YouVersionAuthProvider from './YouVersionAuthProvider';
import { useYouVersionAuthContext } from './YouVersionAuthContext';
@@ -15,23 +15,20 @@ const mockConfig: AuthConfig = {
const mockUserInfo = createMockUserInfo();
const mockAuthResult = createMockAuthResult();
-// Mock window and location
-const mockWindow = {
- location: {
- href: 'https://example.com',
- search: '',
- },
-};
+function WebAuthWrapper({ children }: PropsWithChildren) {
+ return {children} ;
+}
// Test component to access context
function TestChild() {
- const { userInfo, isLoading, error } = useYouVersionAuthContext();
+ const { userInfo, isLoading, error, oauthCallbackState } = useYouVersionAuthContext();
return (
{userInfo ? JSON.stringify(userInfo) : 'null'}
{isLoading.toString()}
{error ? error.message : 'null'}
+
{oauthCallbackState ?? 'null'}
);
}
@@ -42,9 +39,7 @@ describe('YouVersionAuthProvider', () => {
let refreshTokenIfNeeded: MockInstance;
beforeEach(() => {
- // Setup window mock
- vi.stubGlobal('window', mockWindow);
- mockWindow.location.search = '';
+ window.history.replaceState(null, '', '/');
// Reset configuration
YouVersionPlatformConfiguration.appKey = '';
@@ -60,7 +55,7 @@ describe('YouVersionAuthProvider', () => {
afterEach(() => {
vi.restoreAllMocks();
- vi.unstubAllGlobals();
+ window.history.replaceState(null, '', '/');
});
describe('initialization', () => {
@@ -72,7 +67,7 @@ describe('YouVersionAuthProvider', () => {
);
// Wait for async initialization to complete
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(YouVersionPlatformConfiguration.appKey).toBe(mockConfig.appKey);
expect(YouVersionPlatformConfiguration.apiHost).toBe(mockConfig.apiHost);
});
@@ -90,7 +85,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(YouVersionPlatformConfiguration.appKey).toBe('test-app-key');
expect(YouVersionPlatformConfiguration.installationId).toBeTruthy();
// Since config had no apiHost, component should set default (in real implementation this would be 'api.youversion.com')
@@ -110,15 +105,15 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(YouVersionPlatformConfiguration.installationId).not.toBe(null);
});
});
});
describe('OAuth callback handling', () => {
- it('should detect OAuth callback with state parameter', async () => {
- mockWindow.location.search = '?state=test-state&code=auth-code';
+ it('publishes the verified callback state until another tab changes the session', async () => {
+ window.history.replaceState(null, '', '?state=test-state&code=auth-code');
vi.spyOn(YouVersionAPIUsers, 'getStoredUserInfo').mockReturnValue(mockUserInfo);
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockResolvedValue(mockAuthResult);
@@ -128,17 +123,32 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
expect(handleAuthCallback).toHaveBeenCalled();
expect(getStoredUserInfo).toHaveBeenCalled();
expect(getByTestId('user-info')).toHaveTextContent(JSON.stringify(mockUserInfo));
+ expect(getByTestId('callback-state')).toHaveTextContent('test-state');
+
+ const otherUser = createMockUserInfo({ id: 'other-account' });
+ getStoredUserInfo.mockReturnValue(otherUser);
+ act(() => {
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ });
+ expect(getByTestId('user-info')).toHaveTextContent('other-account');
+ expect(getByTestId('callback-state')).toHaveTextContent('null');
});
it('should detect OAuth callback with error parameter', async () => {
- mockWindow.location.search = '?error=access_denied&error_description=User+denied+access';
+ window.history.replaceState(
+ null,
+ '',
+ '?error=access_denied&error_description=User+denied+access',
+ );
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockResolvedValue(mockAuthResult);
const { getByTestId } = render(
@@ -147,7 +157,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -155,7 +165,7 @@ describe('YouVersionAuthProvider', () => {
});
it('should handle callback error and set error state', async () => {
- mockWindow.location.search = '?state=test-state&code=auth-code';
+ window.history.replaceState(null, '', '?state=test-state&code=auth-code');
const callbackError = new Error('Callback processing failed');
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockRejectedValue(callbackError);
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
@@ -166,10 +176,11 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(getByTestId('error')).toHaveTextContent('Callback processing failed');
expect(getByTestId('is-loading')).toHaveTextContent('false');
expect(getByTestId('user-info')).toHaveTextContent('null');
+ expect(getByTestId('callback-state')).toHaveTextContent('null');
});
expect(errorSpy).not.toHaveBeenCalledWith('Auth callback failed:', callbackError);
});
@@ -180,7 +191,7 @@ describe('YouVersionAuthProvider', () => {
// dedupe (see packages/core Users.test.ts); here we only assert the
// provider effect tolerates the double-invocation and still resolves to an
// authenticated, error-free state.
- mockWindow.location.search = '?state=test-state&code=auth-code';
+ window.history.replaceState(null, '', '?state=test-state&code=auth-code');
vi.spyOn(YouVersionAPIUsers, 'getStoredUserInfo').mockReturnValue(mockUserInfo);
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockResolvedValue(mockAuthResult);
@@ -192,7 +203,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -204,7 +215,7 @@ describe('YouVersionAuthProvider', () => {
});
it('should leave user null when no profile was stored during callback', async () => {
- mockWindow.location.search = '?state=test-state&code=auth-code';
+ window.history.replaceState(null, '', '?state=test-state&code=auth-code');
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockResolvedValue(mockAuthResult);
vi.spyOn(YouVersionAPIUsers, 'getStoredUserInfo').mockReturnValue(null);
@@ -214,7 +225,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -237,7 +248,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -258,7 +269,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -276,7 +287,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await vi.waitFor(() => {
+ await waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -285,3 +296,91 @@ describe('YouVersionAuthProvider', () => {
});
});
});
+
+it('keeps the account synced from another tab when the previous account refresh fails', async () => {
+ YouVersionPlatformConfiguration.saveAuthData(
+ 'old-access-token',
+ 'old-refresh-token',
+ new Date(0),
+ );
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'old-account' });
+ const oldRefresh = Promise.withResolvers();
+ const refresh = vi
+ .spyOn(YouVersionAPIUsers, 'refreshTokenIfNeeded')
+ .mockReturnValue(oldRefresh.promise);
+
+ try {
+ const { result } = renderHook(useYouVersionAuthContext, { wrapper: WebAuthWrapper });
+ expect(result.current.isLoading).toBe(true);
+
+ act(() => {
+ YouVersionPlatformConfiguration.saveAuthData('new-access-token', 'new-refresh-token', null);
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'new-account' });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('new-account');
+
+ await act(async () => {
+ oldRefresh.resolve(false);
+ });
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.userInfo?.userId).toBe('new-account');
+
+ act(() => {
+ YouVersionAPIUsers.signOut();
+ window.dispatchEvent(new StorageEvent('storage', { storageArea: localStorage }));
+ });
+ expect(result.current.userInfo).toBeNull();
+ } finally {
+ refresh.mockRestore();
+ YouVersionAPIUsers.signOut();
+ }
+});
+
+it('takes signed-in and signed-out state from the host across browser auth events', () => {
+ window.history.replaceState(null, '', '?error=access_denied');
+ YouVersionPlatformConfiguration.saveAuthData(
+ 'browser-access-token',
+ 'browser-refresh-token',
+ null,
+ );
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'browser-account' });
+
+ try {
+ const { getByTestId, rerender } = render(
+
+
+ ,
+ );
+ expect(getByTestId('is-loading')).toHaveTextContent('false');
+ expect(getByTestId('user-info')).toHaveTextContent('null');
+
+ rerender(
+
+
+ ,
+ );
+ expect(getByTestId('user-info')).toHaveTextContent('host-account');
+
+ act(() => {
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ });
+ expect(getByTestId('user-info')).toHaveTextContent('host-account');
+ expect(getByTestId('error')).toHaveTextContent('null');
+ expect(getByTestId('callback-state')).toHaveTextContent('null');
+
+ rerender(
+
+
+ ,
+ );
+ expect(getByTestId('user-info')).toHaveTextContent('null');
+ } finally {
+ window.history.replaceState(null, '', '/');
+ YouVersionAPIUsers.signOut();
+ }
+});
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.tsx b/packages/hooks/src/context/YouVersionAuthProvider.tsx
index 7decc1b5c..31f2469bc 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.tsx
@@ -4,6 +4,7 @@ import {
YouVersionAPIUsers,
YouVersionPlatformConfiguration,
YouVersionUserInfo,
+ getLocalStorage,
type YouVersionUserInfoJSON,
} from '@youversion/platform-core';
import React, { useEffect, useState, type ReactNode } from 'react';
@@ -32,6 +33,7 @@ export default function YouVersionAuthProvider({
const [userInfo, setUserInfo] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
+ const [oauthCallbackState, setOAuthCallbackState] = useState(null);
useEffect(() => {
if (!isHostControlled) return;
@@ -42,6 +44,7 @@ export default function YouVersionAuthProvider({
useEffect(() => {
if (isHostControlled) return;
let mounted = true;
+ let sessionChanged = false;
const initAuth = async () => {
// Set configuration
YouVersionPlatformConfiguration.appKey = config.appKey;
@@ -55,10 +58,11 @@ export default function YouVersionAuthProvider({
if (isOAuthCallback) {
try {
const result = await YouVersionAPIUsers.handleAuthCallback();
- if (result) {
+ if (result && !sessionChanged) {
// handleAuthCallback persists the decoded profile; read it back.
if (!mounted) return;
setUserInfo(YouVersionAPIUsers.getStoredUserInfo());
+ setOAuthCallbackState(urlParams.get('state'));
}
} catch (err) {
if (!mounted) return;
@@ -66,7 +70,10 @@ export default function YouVersionAuthProvider({
if (process.env.NODE_ENV === 'development') {
console.error('Auth callback failed:', error);
}
- setError(error);
+ if (!sessionChanged) {
+ setError(error);
+ setUserInfo(YouVersionAPIUsers.getStoredUserInfo());
+ }
}
} else {
// Check for existing token
@@ -77,10 +84,12 @@ export default function YouVersionAuthProvider({
// when the session has expired and cannot be refreshed.
const refreshed = await YouVersionAPIUsers.refreshTokenIfNeeded();
if (!mounted) return;
- setUserInfo(refreshed ? YouVersionAPIUsers.getStoredUserInfo() : null);
+ if (!sessionChanged) {
+ setUserInfo(refreshed ? YouVersionAPIUsers.getStoredUserInfo() : null);
+ }
} catch {
if (!mounted) return;
- setUserInfo(null);
+ if (!sessionChanged) setUserInfo(null);
}
}
}
@@ -90,9 +99,27 @@ export default function YouVersionAuthProvider({
setIsLoading(false);
};
+ function syncSession(event: StorageEvent) {
+ if (
+ event.storageArea !== getLocalStorage() ||
+ (event.key !== null &&
+ event.key !== 'userInfo' &&
+ event.key !== 'accessToken' &&
+ event.key !== 'refreshToken' &&
+ event.key !== 'youversion-auth-scope')
+ ) {
+ return;
+ }
+ sessionChanged = true;
+ setOAuthCallbackState(null);
+ setUserInfo(YouVersionAPIUsers.getStoredUserInfo());
+ }
+
+ globalThis.window?.addEventListener('storage', syncSession);
void initAuth();
return () => {
mounted = false;
+ globalThis.window?.removeEventListener('storage', syncSession);
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
@@ -102,6 +129,8 @@ export default function YouVersionAuthProvider({
isLoading,
error,
redirectUri: config.redirectUri,
+ oauthCallbackState,
+ isHostControlled,
};
return {children} ;
diff --git a/packages/hooks/src/index.ts b/packages/hooks/src/index.ts
index 2b23095f9..6fd87eade 100644
--- a/packages/hooks/src/index.ts
+++ b/packages/hooks/src/index.ts
@@ -20,6 +20,7 @@ export * from './useUnifiedSearch';
export * from './usePassage';
export * from './useVOTD';
export * from './useHighlights';
+export * from './useCreateNote';
export * from './useHighlightAuthActions';
export * from './useLanguages';
export * from './useLanguage';
diff --git a/packages/hooks/src/types/auth.ts b/packages/hooks/src/types/auth.ts
index ca2a500e9..aef341233 100644
--- a/packages/hooks/src/types/auth.ts
+++ b/packages/hooks/src/types/auth.ts
@@ -13,6 +13,10 @@ export interface AuthContextValue {
isLoading: boolean;
error: Error | null;
redirectUri?: string;
+ /** State of the verified OAuth callback handled by this provider. */
+ oauthCallbackState?: string | null;
+ /** Whether the host supplied the profile and owns sign-in. */
+ isHostControlled?: boolean;
}
export interface AuthProviderProps {
diff --git a/packages/hooks/src/useCreateNote.ts b/packages/hooks/src/useCreateNote.ts
new file mode 100644
index 000000000..b31007c95
--- /dev/null
+++ b/packages/hooks/src/useCreateNote.ts
@@ -0,0 +1,12 @@
+'use client';
+
+import { useCallback, useMemo } from 'react';
+import { NotesClient, type CreateNote, type Note } from '@youversion/platform-core';
+import { useApiClient } from './internal/useApiClient';
+
+/** Creates a note using the caller's captured access token. */
+export function useCreateNote(): (note: CreateNote, accessToken: string) => Promise {
+ const apiClient = useApiClient();
+ const client = useMemo(() => new NotesClient(apiClient), [apiClient]);
+ return useCallback((note, accessToken) => client.createNote(note, accessToken), [client]);
+}
diff --git a/packages/hooks/src/useHighlightAuthActions.ts b/packages/hooks/src/useHighlightAuthActions.ts
index 2e675ed20..2863718b8 100644
--- a/packages/hooks/src/useHighlightAuthActions.ts
+++ b/packages/hooks/src/useHighlightAuthActions.ts
@@ -8,6 +8,7 @@ import {
SignInWithYouVersionPermission,
YouVersionAPIUsers,
YouVersionPlatformConfiguration,
+ type AuthenticationScopes,
type DataExchangeCallbackResult,
} from '@youversion/platform-core';
import { YouVersionContext } from './context/YouVersionContext';
@@ -54,7 +55,10 @@ export type UseHighlightAuthActionsResult = {
* permission alongside `profile`. Returns to `redirectUrl` (or the auth
* provider's configured `redirectUri`, falling back to the current URL).
*/
- startSignInForHighlights: (redirectUrl?: string) => Promise;
+ startSignInForHighlights: (
+ redirectUrl?: string,
+ scopes?: AuthenticationScopes[],
+ ) => Promise;
/**
* Just-in-time: mint a data-exchange token then full-page redirect to the
* hosted consent page for the `highlights` permission.
@@ -74,12 +78,12 @@ export function useHighlightAuthActions(): UseHighlightAuthActionsResult {
);
const startSignInForHighlights = useCallback(
- async (redirectUrl?: string) => {
+ async (redirectUrl?: string, scopes: AuthenticationScopes[] = ['profile']) => {
const url = redirectUrl ?? redirectUri ?? globalThis.window?.location.href;
if (!url) {
throw new Error('A redirect URL is required to start sign-in for highlights.');
}
- await YouVersionAPIUsers.signIn(url, ['profile'], [HIGHLIGHTS_PERMISSION]);
+ await YouVersionAPIUsers.signIn(url, scopes, [HIGHLIGHTS_PERMISSION]);
},
[redirectUri],
);
diff --git a/packages/ui/README.md b/packages/ui/README.md
index 9cf87a198..3d6e557b8 100644
--- a/packages/ui/README.md
+++ b/packages/ui/README.md
@@ -52,13 +52,22 @@ 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
+`'highlights'`, `'save'`, `'copy'`, `'share'`, and custom actions. The default
+order is highlights, Save, 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.
+Save opens the Notes composer for the selected verses. A reader with built-in
+sign-in requests `read_notes` and `write_notes` alongside its existing OAuth
+scopes. The composer requires a YouVersion session with `write_notes`. Start
+with `includeAuth` and an `authRedirectUrl` that returns to your reader to let
+the SDK resume the captured selection after sign-in.
+
+An empty note saves its attached passage. The reader also supports a private or
+public note and an optional highlight color.
+
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
diff --git a/packages/ui/scripts/smoke-vite-reader-notes.mjs b/packages/ui/scripts/smoke-vite-reader-notes.mjs
new file mode 100644
index 000000000..df842d906
--- /dev/null
+++ b/packages/ui/scripts/smoke-vite-reader-notes.mjs
@@ -0,0 +1,221 @@
+import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
+import { chromium } from 'playwright';
+import bibles from '../src/test/mock-data/bibles.json' with { type: 'json' };
+import languages from '../src/test/mock-data/languages.json' with { type: 'json' };
+import passages from '../src/test/mock-data/passages.json' with { type: 'json' };
+import { mockBooks } from '../src/test/mock-data/books.ts';
+
+const app = process.argv[2] ?? 'http://127.0.0.1:5176';
+const api = 'https://notes-smoke.example.test';
+const browser = await chromium.launch();
+const context = await browser.newContext({
+ locale: 'en-US',
+ viewport: { width: 1280, height: 900 },
+});
+context.setDefaultTimeout(8_000);
+
+const requestHeaders = {
+ 'access-control-allow-origin': '*',
+ 'access-control-allow-headers': '*',
+ 'access-control-allow-methods': 'GET,POST,OPTIONS',
+};
+const alice = { id: 'alice', name: 'Alice', granted: 'profile read_notes' };
+const bob = { id: 'bob', name: 'Bob', granted: 'profile' };
+const writer = { ...bob, granted: 'profile read_notes write_notes' };
+const responses = new Map();
+const exchanges = new Map();
+const notes = [];
+const page = await context.newPage();
+
+await context.route('https://fonts.googleapis.com/**', (route) => route.fulfill({ body: '' }));
+await context.route(`${api}/**`, async (route) => {
+ const request = route.request();
+ const url = new URL(request.url());
+ const json = (body, status = 200) =>
+ route.fulfill({ json: body, headers: requestHeaders, status });
+ if (request.method() === 'OPTIONS')
+ return route.fulfill({ headers: requestHeaders, status: 204 });
+
+ switch (url.pathname) {
+ case '/auth/authorize': {
+ const source = request.frame().page();
+ const response = responses.get(source);
+ assert.ok(response, 'Expected a hosted auth response');
+ responses.delete(source);
+ await response.pause;
+
+ const destination = new URL(url.searchParams.get('redirect_uri'));
+ assert.equal(destination.origin, new URL(app).origin, 'Expected the local app callback');
+ destination.searchParams.set('state', url.searchParams.get('state'));
+ if (response.account) {
+ const code = randomUUID();
+ exchanges.set(code, response.account);
+ destination.searchParams.set('code', code);
+ } else {
+ destination.searchParams.set('error', 'access_denied');
+ }
+ return route.fulfill({
+ contentType: 'text/html',
+ body: ``,
+ });
+ }
+ case '/auth/token': {
+ const code = new URLSearchParams(request.postData()).get('code');
+ const account = exchanges.get(code);
+ assert.ok(account, 'Expected a token for the issued authorization code');
+ exchanges.delete(code);
+ const claims = Buffer.from(JSON.stringify({ sub: account.id, name: account.name })).toString(
+ 'base64url',
+ );
+ return json({
+ access_token: `token-${account.id}`,
+ refresh_token: `refresh-${account.id}`,
+ expires_in: 3600,
+ id_token: `e30.${claims}.fixture`,
+ token_type: 'Bearer',
+ scope: account.granted,
+ });
+ }
+ case '/v1/bibles/3034':
+ return json({ ...bibles.individual['111'], id: 3034 });
+ case '/v1/bibles':
+ return json({ data: [{ ...bibles.individual['111'], id: 3034 }], next_page_token: null });
+ case '/v1/languages':
+ return json(languages);
+ case '/v1/bibles/3034/books':
+ return json(mockBooks);
+ case '/v1/bibles/3034/passages/JHN.1':
+ return json({ ...passages['JHN.1'], bible_id: 3034 });
+ case '/v1/highlights':
+ return json({ data: [] });
+ case '/v1/notes': {
+ const body = request.postDataJSON();
+ notes.push({ body, authorization: request.headers()['authorization'] });
+ return json({ ...body, id: 'smoke-note' }, 201);
+ }
+ default:
+ return route.fulfill({ body: '', headers: requestHeaders });
+ }
+});
+
+function prepareSignIn(source, account, pause) {
+ responses.set(source, { account, pause });
+ return source
+ .waitForRequest((request) => request.url().startsWith(`${api}/auth/authorize?`))
+ .then((request) => new URL(request.url()).searchParams);
+}
+
+function checkScopes(params, expected) {
+ assert.deepEqual(params.get('scope').split(' ').sort(), [...expected].sort());
+}
+
+const hostedButton = (source) => source.locator('header').getByRole('button', { name: /sign in/i });
+const signedInAs = (source, name) => source.locator('header').getByText(name, { exact: true });
+const menu = (source) => source.getByRole('dialog', { name: 'Verse actions' });
+const editor = (source) => source.getByRole('textbox', { name: 'Add Note…' });
+const composer = (source, reference) =>
+ source.getByRole('dialog', { name: reference, exact: true });
+
+async function selectVerses(source, verses) {
+ for (const verse of verses) await source.locator(`.yv-v[v="${verse}"]`).first().click();
+}
+
+async function beginNote(source) {
+ await menu(source).getByRole('button', { name: 'Save', exact: true }).click();
+}
+
+const readerScopes = ['openid', 'profile', 'read_notes', 'write_notes'];
+const navbarScopes = ['openid', 'profile', 'email'];
+
+try {
+ await page.goto(app);
+ await selectVerses(page, [4, 1]);
+ await beginNote(page);
+ await page
+ .getByText('Save Notes and highlights to your YouVersion account.', { exact: false })
+ .waitFor();
+ await page.getByRole('button', { name: 'No Thanks' }).click();
+ await menu(page).waitFor();
+ assert.equal(await editor(page).count(), 0);
+
+ // A real OAuth decline preserves the selection through the return to the app.
+ await beginNote(page);
+ const declined = prepareSignIn(page, null);
+ await page.getByRole('button', { name: 'Yes Please' }).click();
+ checkScopes(await declined, readerScopes);
+ await page.waitForURL(/error=access_denied/);
+ await menu(page).waitFor();
+ assert.equal(await editor(page).count(), 0);
+
+ const navbar = prepareSignIn(page, alice);
+ await hostedButton(page).click();
+ checkScopes(await navbar, navbarScopes);
+ await signedInAs(page, 'Alice').waitFor();
+ assert.equal(await editor(page).count(), 0);
+
+ // A successful OAuth return that only grants read_notes cannot open a writer.
+ await selectVerses(page, [4, 1]);
+ await beginNote(page);
+ const readOnly = prepareSignIn(page, alice);
+ await page.getByRole('button', { name: 'Yes Please' }).click();
+ checkScopes(await readOnly, readerScopes);
+ await menu(page).waitFor();
+ assert.equal(await editor(page).count(), 0);
+ assert.equal(notes.length, 0);
+
+ // Alice's old authorization comes back after Bob replaces her session in another tab.
+ const other = await context.newPage();
+ await other.goto(app);
+ await signedInAs(other, 'Alice').waitFor();
+ await beginNote(page);
+ const releaseOld = Promise.withResolvers();
+ const stale = prepareSignIn(page, { ...alice, granted: writer.granted }, releaseOld.promise);
+ const continueOld = page.getByRole('button', { name: 'Yes Please' }).click({ noWaitAfter: true });
+ checkScopes(await stale, readerScopes);
+ await other.locator('header').getByRole('button', { name: 'Sign out' }).click();
+ const replacement = prepareSignIn(other, bob);
+ await hostedButton(other).click();
+ checkScopes(await replacement, navbarScopes);
+ await signedInAs(other, 'Bob').waitFor();
+ releaseOld.resolve();
+ await continueOld;
+ await page.waitForURL(/code=/);
+ await signedInAs(page, 'Bob').waitFor();
+ assert.equal(await editor(page).count(), 0);
+ assert.equal(notes.length, 0);
+
+ // Bob's successful grant resumes his exact new selection and waits for Save.
+ await selectVerses(page, [4, 2]);
+ await beginNote(page);
+ const accepted = prepareSignIn(page, writer);
+ await page.getByRole('button', { name: 'Yes Please' }).click();
+ checkScopes(await accepted, readerScopes);
+ await composer(page, 'John 1:2,4').waitFor();
+ assert.equal(notes.length, 0);
+ await editor(page).fill('Notes smoke');
+ await composer(page, 'John 1:2,4').getByRole('button', { name: 'Save', exact: true }).click();
+ await composer(page, 'John 1:2,4').waitFor({ state: 'hidden' });
+ assert.equal(notes.length, 1);
+ assert.equal(notes[0].authorization, 'Bearer token-bob');
+ assert.deepEqual(notes[0].body, {
+ request_id: notes[0].body.request_id,
+ content: 'Notes smoke',
+ status: 'private',
+ passage: { bible_id: 3034, passage_id: 'JHN.1.2+JHN.1.4' },
+ });
+
+ await selectVerses(page, [2]);
+ await beginNote(page);
+ await editor(page).fill('Unsaved Bob draft');
+ await other.locator('header').getByRole('button', { name: 'Sign out' }).click();
+ await editor(page).waitFor({ state: 'hidden' });
+ await hostedButton(page).waitFor();
+ assert.equal(notes.length, 1);
+
+ console.log(
+ 'Reader Notes smoke passed (decline, grant, exact scoped create, stale callback, sign-out, and navbar scopes).',
+ );
+} finally {
+ await browser.close();
+}
diff --git a/packages/ui/src/components/bible-reader-auth.ts b/packages/ui/src/components/bible-reader-auth.ts
new file mode 100644
index 000000000..57e181591
--- /dev/null
+++ b/packages/ui/src/components/bible-reader-auth.ts
@@ -0,0 +1,7 @@
+import type { AuthenticationScopes } from '@youversion/platform-core';
+
+export const READER_SIGN_IN_SCOPES: AuthenticationScopes[] = [
+ 'profile',
+ 'read_notes',
+ 'write_notes',
+];
diff --git a/packages/ui/src/components/bible-reader-notes-composer.tsx b/packages/ui/src/components/bible-reader-notes-composer.tsx
new file mode 100644
index 000000000..ce85cd983
--- /dev/null
+++ b/packages/ui/src/components/bible-reader-notes-composer.tsx
@@ -0,0 +1,150 @@
+'use client';
+
+import { useId, useState, type ReactElement } from 'react';
+import { useTranslation } from 'react-i18next';
+import i18n from '@/i18n';
+import { HIGHLIGHT_COLORS } from '@/lib/highlight-colors';
+import { HighlightColorCircle } from './highlight-color-circle';
+import { Button } from './ui/button';
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from './ui/dialog';
+import { Textarea } from './ui/textarea';
+import type { NoteDraft, NoteDraftFields } from './use-bible-reader-note';
+
+type NotesComposerProps = {
+ draft: NoteDraft;
+ saving: boolean;
+ failed: boolean;
+ onChange: (fields: Partial) => void;
+ onSave: () => void;
+ onDismiss: () => void;
+ theme: 'light' | 'dark';
+};
+
+export function BibleReaderNotesComposer({
+ draft,
+ saving,
+ failed,
+ onChange,
+ onSave,
+ onDismiss,
+ theme,
+}: NotesComposerProps): ReactElement {
+ const { t } = useTranslation(undefined, { i18n });
+ const visibilityName = useId();
+ const [confirmDiscard, setConfirmDiscard] = useState(false);
+
+ function requestDismiss() {
+ if (saving) return;
+ if (draft.text || draft.visibility !== 'private' || draft.color) {
+ setConfirmDiscard(true);
+ } else {
+ onDismiss();
+ }
+ }
+
+ return (
+ {
+ if (!open) requestDismiss();
+ }}
+ >
+
+
+ {draft.selection.reference}
+
+
+
+
+
+ {t('notesDiscardTitle')}
+
+ {t('notesDiscardMessage')}
+
+
+ setConfirmDiscard(false)}>
+ {t('cancel')}
+
+
+ {t('notesDiscard')}
+
+
+
+
+
+
+ );
+}
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
new file mode 100644
index 000000000..11180fa04
--- /dev/null
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -0,0 +1,419 @@
+import type { Meta, StoryObj } from '@storybook/react-vite';
+import {
+ YouVersionAPIUsers,
+ YouVersionPlatformConfiguration,
+ type CreateNote,
+} from '@youversion/platform-core';
+import { http, HttpResponse } from 'msw';
+import { getWorker } from 'msw-storybook-addon';
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+import { globalHandlers } from '@/test/mocks/handlers';
+import { getBackgroundColorChannels, waitForShadowRoot } from '@/test/storybook-dom';
+import { BibleReader } from './bible-reader';
+import { BibleReaderNavigation } from './bible-reader-navigation';
+
+const meta: Meta = {
+ title: 'Components/BibleReader/Notes',
+ parameters: { layout: 'fullscreen' },
+ render: () => (
+
+
+
+
+
+
+ ),
+};
+export default meta;
+type Story = StoryObj;
+
+function readerVerse(root: ShadowRoot, verse: number) {
+ return waitFor(() => {
+ const target = root.querySelector(`.yv-v[v="${verse}"]`);
+ if (!target) throw new Error(`Verse ${verse} is missing`);
+ return target;
+ });
+}
+
+async function selectVerses(root: ShadowRoot, verses: number[]) {
+ for (const verse of verses) await userEvent.click(await readerVerse(root, verse));
+}
+
+async function fillEditor(editor: HTMLTextAreaElement, value: string) {
+ if (__YV_STORYBOOK_VITEST__) {
+ const { userEvent } = await import('vitest/browser');
+ await userEvent.fill(editor, value);
+ return;
+ }
+ await userEvent.type(editor, value || '{Backspace}', {
+ initialSelectionStart: 0,
+ initialSelectionEnd: editor.value.length,
+ });
+}
+
+async function readerOverlays(root: ShadowRoot) {
+ return within(
+ await waitFor(() => {
+ const overlay = root.querySelector('[data-yv-shadow-local-overlay]');
+ if (!overlay) throw new Error('Reader overlay is missing');
+ return overlay;
+ }),
+ );
+}
+
+function tokenResponse(scope: string) {
+ return HttpResponse.json({
+ access_token: 'notes-story-token',
+ expires_in: 3600,
+ id_token: `e30.${btoa(JSON.stringify({ sub: 'notes-story-user', name: 'Reader' }))}.fixture`,
+ refresh_token: 'notes-story-refresh',
+ scope,
+ token_type: 'Bearer',
+ });
+}
+
+function prepareCallback() {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ const url = location.href;
+ const callback = new URL(url);
+ callback.searchParams.set('state', 'notes-story-state');
+ callback.searchParams.set('code', crypto.randomUUID());
+ localStorage.setItem('youversion-auth-state', 'notes-story-state');
+ localStorage.setItem('youversion-auth-code-verifier', 'notes-story-verifier');
+ localStorage.setItem('youversion-auth-redirect-uri', callback.origin);
+ history.replaceState(history.state, '', callback);
+ return () => {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ history.replaceState(history.state, '', url);
+ };
+}
+
+const writableSession = {
+ msw: {
+ handlers: [
+ http.post('*/auth/token', () => tokenResponse('profile read_notes write_notes')),
+ http.get('*/v1/highlights', () => HttpResponse.json({ data: [], next_page_token: null })),
+ ...globalHandlers,
+ ],
+ },
+};
+
+type NoteRequest = Omit & {
+ passage: { bible_id: number; passage_id: string };
+};
+
+const noteResponse = (body: NoteRequest) =>
+ HttpResponse.json({ ...body, id: 'saved-note' }, { status: 201 });
+
+function deferred() {
+ let resolve!: (result: T) => void;
+ const promise = new Promise((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+}
+
+async function openComposer(root: ShadowRoot, reference: string) {
+ const overlays = await readerOverlays(root);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await userEvent.click(actions.getByRole('button', { name: 'Save' }));
+ const composer = await overlays.findByRole('dialog', { name: reference });
+ await waitFor(() => expect(composer).toBeVisible());
+ await waitFor(() => expect(overlays.queryByRole('dialog', { name: 'Verse actions' })).toBeNull());
+ return { overlays, composer: within(composer) };
+}
+
+export const SavePassage: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ beforeEach: prepareCallback,
+ parameters: writableSession,
+ play: async ({ canvasElement }) => {
+ const saved = deferred<{ body: NoteRequest; authorization: string | null }>();
+ getWorker().use(
+ http.post('*/v1/notes', async ({ request }) => {
+ const body = await request.json();
+ saved.resolve({ body, authorization: request.headers.get('authorization') });
+ return noteResponse(body);
+ }),
+ );
+ const root = await waitForShadowRoot(canvasElement);
+ await selectVerses(root, [4, 1, 3]);
+ const overlays = await readerOverlays(root);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await expect(actions.getByRole('button', { name: 'Copy' })).toBeInTheDocument();
+ await expect(actions.getByRole('button', { name: 'Share' })).toBeInTheDocument();
+ const { composer } = await openComposer(root, 'John 1:1,3-4');
+ await expect(composer.getByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
+ await expect(composer.getByRole('radio', { name: 'Private' })).toBeChecked();
+ await expect(composer.getByRole('radio', { name: 'Public' })).not.toBeChecked();
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await expect(await saved.promise).toEqual({
+ authorization: 'Bearer notes-story-token',
+ body: {
+ request_id: expect.stringMatching(/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i),
+ content: '',
+ status: 'private',
+ passage: { bible_id: 111, passage_id: 'JHN.1.1+JHN.1.3-4' },
+ },
+ });
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ },
+};
+
+export const EditAndRetry: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ beforeEach: prepareCallback,
+ globals: { theme: 'dark' },
+ parameters: writableSession,
+ play: async ({ canvasElement }) => {
+ const requests: NoteRequest[] = [];
+ getWorker().use(
+ http.post('*/v1/notes', async ({ request }) => {
+ const body = await request.json();
+ requests.push(body);
+ return requests.length === 1 ? HttpResponse.error() : noteResponse(body);
+ }),
+ );
+ const root = await waitForShadowRoot(canvasElement);
+ await selectVerses(root, [2]);
+ const { overlays, composer } = await openComposer(root, 'John 1:2');
+ const editor = composer.getByRole('textbox', { name: 'Add Note…' });
+ const colors = within(composer.getByRole('group', { name: 'Highlight colors' }));
+ const palette = ['ffec5b', 'b4ffc1', 'bbf4ff', 'ffdca7', 'ffcff8', 'dfdcff'];
+ const colorName = (color: string) => `Apply highlight #${color}`;
+ const selected = colors.getByRole('button', { name: colorName('ffdca7') });
+ const lightSurface = [255, 220, 167, 255];
+ await expect(getBackgroundColorChannels(selected)).not.toEqual(lightSurface);
+
+ async function confirmDirty() {
+ await userEvent.click(composer.getByRole('button', { name: 'Cancel' }));
+ const confirmation = await overlays.findByRole('dialog', { name: 'Discard note?' });
+ await userEvent.click(within(confirmation).getByRole('button', { name: 'Cancel' }));
+ await waitFor(() =>
+ expect(overlays.queryByRole('dialog', { name: 'Discard note?' })).toBeNull(),
+ );
+ }
+
+ await fillEditor(editor, 'First thought');
+ await confirmDirty();
+ await expect(editor).toHaveValue('First thought');
+ await fillEditor(editor, '');
+
+ await userEvent.click(composer.getByRole('radio', { name: 'Public' }));
+ await confirmDirty();
+ await expect(composer.getByRole('radio', { name: 'Public' })).toBeChecked();
+ await userEvent.click(composer.getByRole('radio', { name: 'Private' }));
+
+ await userEvent.click(selected);
+ await confirmDirty();
+ await expect(selected).toHaveAttribute('aria-pressed', 'true');
+ await expect(
+ colors.getAllByRole('button').map((button) => button.getAttribute('aria-label')),
+ ).toEqual(palette.map(colorName));
+
+ await fillEditor(editor, 'First thought');
+ await userEvent.click(composer.getByRole('radio', { name: 'Public' }));
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await expect(await composer.findByRole('alert')).toBeVisible();
+ await expect(editor).toHaveValue('First thought');
+ await expect(selected).toHaveAttribute('aria-pressed', 'true');
+ await expect(composer.getByRole('radio', { name: 'Public' })).toBeChecked();
+ await fillEditor(editor, 'Edited thought');
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+
+ const common = {
+ request_id: expect.stringMatching(/^[\da-f-]{36}$/i),
+ status: 'public',
+ color: 'ffdca7',
+ passage: { bible_id: 111, passage_id: 'JHN.1.2' },
+ };
+ await expect(requests).toEqual([
+ { ...common, content: 'First thought' },
+ { ...common, content: 'Edited thought' },
+ ]);
+ await expect(requests[1]?.request_id).toBe(requests[0]?.request_id);
+ },
+};
+
+const yellow = { bible_id: 111, passage_id: 'JHN.1.1', color: 'ffec5b' };
+const green = { ...yellow, color: 'b4ffc1' };
+const highlightPage = (highlight: typeof yellow) =>
+ HttpResponse.json({ data: [highlight], next_page_token: null });
+
+export const RefreshHighlights: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ beforeEach: prepareCallback,
+ parameters: {
+ msw: {
+ handlers: [
+ http.get('*/v1/highlights', () => highlightPage(yellow)),
+ ...writableSession.msw.handlers,
+ ],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const root = await waitForShadowRoot(canvasElement);
+ const verse = await readerVerse(root, 1);
+ const paint = () => getBackgroundColorChannels(verse);
+ const oldColor = [255, 236, 91, 255];
+ await waitFor(() => expect(paint()).toEqual(oldColor));
+
+ const reads = [HttpResponse.error(), highlightPage(yellow), highlightPage(green)].map(
+ (response) => ({ response, release: deferred(), request: deferred() }),
+ );
+ const queued = reads.slice();
+ getWorker().use(
+ http.post('*/v1/notes', async ({ request }) =>
+ noteResponse(await request.json()),
+ ),
+ http.get('*/v1/highlights', async ({ request }) => {
+ const read = queued.shift();
+ if (!read) return highlightPage(green);
+ read.request.resolve(new URL(request.url));
+ await read.release.promise;
+ return read.response;
+ }),
+ );
+
+ for (const read of reads) {
+ await selectVerses(root, [2]);
+ const { overlays, composer } = await openComposer(root, 'John 1:2');
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ const scope = (await read.request.promise).searchParams;
+ await expect(scope.get('bible_id')).toBe('111');
+ await expect(scope.get('passage_id')).toBe('JHN.1');
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ await expect(paint()).toEqual(oldColor);
+ read.release.resolve();
+ }
+ await waitFor(() => expect(paint()).toEqual([180, 255, 193, 255]));
+ },
+};
+
+const hostNavigation = new BibleReaderNavigation();
+
+export const RefreshDisplayedChapterAfterNavigation: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ beforeEach: prepareCallback,
+ parameters: writableSession,
+ render: () => (
+
+
+
+
+
+ ),
+ play: async ({ canvasElement }) => {
+ const root = await waitForShadowRoot(canvasElement);
+ const noteSent = deferred();
+ const releaseNote = deferred();
+ const chapterReads: string[] = [];
+ getWorker().use(
+ http.post('*/v1/notes', async ({ request }) => {
+ const note = await request.json();
+ noteSent.resolve(note);
+ await releaseNote.promise;
+ return noteResponse(note);
+ }),
+ http.get('*/v1/highlights', ({ request }) => {
+ const { searchParams } = new URL(request.url);
+ chapterReads.push(`${searchParams.get('bible_id')}:${searchParams.get('passage_id')}`);
+ return HttpResponse.json({ data: [], next_page_token: null });
+ }),
+ );
+ await selectVerses(root, [2]);
+ const { overlays, composer } = await openComposer(root, 'John 1:2');
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await expect((await noteSent.promise).passage).toEqual({
+ bible_id: 111,
+ passage_id: 'JHN.1.2',
+ });
+
+ hostNavigation.request({ versionId: 111, passageId: 'JHN.3' });
+ await waitFor(() => expect(chapterReads).toContain('111:JHN.3'));
+ await expect(overlays.getByRole('dialog', { name: 'John 1:2' })).toBeVisible();
+ chapterReads.length = 0;
+ releaseNote.resolve();
+ await waitFor(() => expect(chapterReads).toEqual(['111:JHN.3']));
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ },
+};
+
+export const WritePermissionChangesWhileEditing: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ beforeEach: prepareCallback,
+ parameters: writableSession,
+ play: async ({ canvasElement }) => {
+ const root = await waitForShadowRoot(canvasElement);
+ await selectVerses(root, [1]);
+ const { overlays, composer } = await openComposer(root, 'John 1:1');
+ let creates = 0;
+ getWorker().use(
+ http.post('*/auth/token', () => tokenResponse('profile read_notes')),
+ http.post('*/v1/notes', () => {
+ creates += 1;
+ return HttpResponse.json({}, { status: 403 });
+ }),
+ );
+ await fillEditor(
+ composer.getByRole('textbox', { name: 'Add Note…' }),
+ 'Retained thought',
+ );
+ await YouVersionAPIUsers.refreshTokens();
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await expect(await overlays.findByRole('button', { name: 'Yes Please' })).toBeInTheDocument();
+ await expect(creates).toBe(0);
+ await userEvent.click(overlays.getByRole('button', { name: 'No Thanks' }));
+ await expect(await overlays.findByRole('textbox', { name: 'Add Note…' })).toHaveValue(
+ 'Retained thought',
+ );
+ },
+};
+
+export const NoBuiltInAuth: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ parameters: { includeAuth: false },
+ play: async ({ canvasElement }) => {
+ const root = await waitForShadowRoot(canvasElement);
+ await selectVerses(root, [1]);
+ const overlays = await readerOverlays(root);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await expect(actions.getByRole('button', { name: 'Copy' })).toBeVisible();
+ await expect(actions.queryByRole('button', { name: 'Save' })).toBeNull();
+ await expect(overlays.queryByRole('button', { name: 'Yes Please' })).toBeNull();
+ },
+};
+
+export const SharedCopyAndDiscard: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ beforeEach: prepareCallback,
+ parameters: { ...writableSession, locale: 'es' },
+ play: async ({ canvasElement }) => {
+ const root = await waitForShadowRoot(canvasElement);
+ await selectVerses(root, [1]);
+ const overlays = await readerOverlays(root);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Acciones del versículo' }));
+ await expect(actions.getByRole('button', { name: 'Copiar' })).toBeVisible();
+ await userEvent.click(actions.getByRole('button', { name: 'Save' }));
+ const composer = within(await overlays.findByRole('dialog', { name: 'John 1:1' }));
+ await fillEditor(
+ composer.getByRole('textbox', { name: 'Add Note…' }),
+ 'A saved thought',
+ );
+ await userEvent.click(composer.getByRole('button', { name: 'Cancelar' }));
+ const confirmation = within(await overlays.findByRole('dialog', { name: 'Discard note?' }));
+ await userEvent.click(confirmation.getByRole('button', { name: 'Discard' }));
+ await waitFor(() => expect(overlays.queryByRole('dialog', { name: 'John 1:1' })).toBeNull());
+ const reopened = within(
+ await overlays.findByRole('dialog', { name: 'Acciones del versículo' }),
+ );
+ await userEvent.click(reopened.getByRole('button', { name: 'Save' }));
+ await expect(await overlays.findByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
+ },
+};
diff --git a/packages/ui/src/components/bible-reader-toolbar.tsx b/packages/ui/src/components/bible-reader-toolbar.tsx
index 0242d1620..c64ce4b65 100644
--- a/packages/ui/src/components/bible-reader-toolbar.tsx
+++ b/packages/ui/src/components/bible-reader-toolbar.tsx
@@ -10,6 +10,7 @@ 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 { READER_SIGN_IN_SCOPES } from './bible-reader-auth';
import { BibleChapterPicker } from './bible-chapter-picker';
import { BibleVersionPicker } from './bible-version-picker';
import { BibleReaderSearch } from './bible-reader-search';
@@ -44,7 +45,7 @@ function UserMenu() {
if (onSignInPress) {
onSignInPress();
} else {
- void signIn({ scopes: ['profile'] });
+ void signIn({ scopes: READER_SIGN_IN_SCOPES });
}
};
const handleSignOut = () => {
diff --git a/packages/ui/src/components/bible-reader.stories.tsx b/packages/ui/src/components/bible-reader.stories.tsx
index dc3c25de2..4d1164855 100644
--- a/packages/ui/src/components/bible-reader.stories.tsx
+++ b/packages/ui/src/components/bible-reader.stories.tsx
@@ -564,7 +564,7 @@ export const CustomVerseActions: Story = {
await expect(dialog).toHaveAttribute('data-state', 'closed');
await expect(mark).toBeInTheDocument();
const item = args.verseActionItems?.[1];
- if (!item || item === 'highlights' || item === 'copy' || item === 'share') {
+ if (!item || item === 'highlights' || item === 'save' || item === 'copy' || item === 'share') {
throw new Error('Custom action fixture missing');
}
await expect(item.onSelect).toHaveBeenCalledTimes(1);
@@ -2076,7 +2076,7 @@ export const ChapterChangeLoadingOverlay: Story = {
play: async ({ args, canvasElement }) => {
const { root, reader } = await getReaderStory(canvasElement);
const [mark] = args.verseActionItems ?? [];
- if (!mark || mark === 'highlights' || mark === 'copy' || mark === 'share') {
+ if (!mark || mark === 'highlights' || mark === 'save' || mark === 'copy' || mark === 'share') {
throw new Error('Custom action fixture missing');
}
await waitFor(
diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx
index fc6bb6506..344fb331c 100644
--- a/packages/ui/src/components/bible-reader.tsx
+++ b/packages/ui/src/components/bible-reader.tsx
@@ -33,6 +33,8 @@ import { LoaderIcon } from './icons/loader';
import { ReuseShadowBoundary, ShadowIsolationBoundary } from '@/lib/shadow-isolation';
import { VerseActionPopover } from './verse-action-popover';
import { useBibleReaderHighlights } from './use-bible-reader-highlights';
+import { useBibleReaderNote, type NoteDraft } from './use-bible-reader-note';
+import { BibleReaderNotesComposer } from './bible-reader-notes-composer';
import { HighlightPermissionDialog } from './highlight-permission-dialog';
import { SignInDialog } from './sign-in-dialog';
import {
@@ -193,8 +195,7 @@ export type RootProps = BibleReaderSettingsProps & {
/**
* Which verse-action UI the reader renders over a selection.
*
- * - `'popover'` (default) renders the built-in {@link VerseActionPopover} —
- * today's behavior, unchanged.
+ * - `'popover'` (default) renders the built-in {@link VerseActionPopover}.
* - `'none'` renders **no** verse-action UI while keeping everything else
* intact: verses still select and paint, and {@link onVerseSelect} still
* fires with `reference` and `shareData` populated, so the host can render
@@ -215,8 +216,8 @@ export type RootProps = BibleReaderSettingsProps & {
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"`.
+ * save, copy and share. Omit an item to hide it. Each built-in may appear once.
+ * Respects highlight and Notes 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}.
@@ -492,6 +493,7 @@ function Content() {
onFootnotePress,
onCopy,
onShare,
+ onSignInPress,
highlights,
isHighlightsControlled,
onVerseSelect,
@@ -608,6 +610,7 @@ function Content() {
const {
highlightedVerses,
highlightsInteractive,
+ refresh: refreshHighlights,
apply: applyHighlight,
remove: removeHighlight,
permissionDialogOpen,
@@ -632,6 +635,28 @@ function Content() {
onAuthRedirectFailed: () => highlightRedirectRef.current.onFailed(),
});
+ function clearNoteSelection(selection: NoteDraft['selection']) {
+ if (
+ selection.versionId === versionId &&
+ selection.book === book &&
+ selection.chapter === chapter &&
+ lastSelectionRef.current.length === selection.verses.length &&
+ selection.verses.every((verse) => lastSelectionRef.current.includes(verse))
+ ) {
+ closeAndClearSelection();
+ }
+ }
+
+ const notes = useBibleReaderNote({
+ enabled: verseActions !== 'none' && (!verseActionItems || verseActionItems.includes('save')),
+ hostOwnsSignIn: !!onSignInPress,
+ onSaved: (selection) => {
+ clearNoteSelection(selection);
+ refreshHighlights();
+ },
+ onInvalidated: clearNoteSelection,
+ });
+
// Color row: controlled mode always shows it (YPE-3705 bypasses HIGHLIGHTS_LIVE).
// Self-contained needs the live flag AND an auth provider — without a provider
// the machine is inert (taps noop), so hide dead swatches for copy/share-only.
@@ -813,6 +838,28 @@ function Content() {
setPopoverOpen(true);
}
+ const restoreNoteSelectionRef = useRef(handleVerseSelect);
+ restoreNoteSelectionRef.current = handleVerseSelect;
+ const { restoredSelection: restoredNoteSelection, clearRestoredSelection } = notes;
+ useEffect(() => {
+ if (!restoredNoteSelection || !renderedReference) return;
+ if (
+ restoredNoteSelection.versionId === versionId &&
+ restoredNoteSelection.book === book &&
+ restoredNoteSelection.chapter === chapter &&
+ lastSelectionRef.current.length === 0
+ ) {
+ restoreNoteSelectionRef.current(restoredNoteSelection.verses);
+ }
+ clearRestoredSelection();
+ }, [restoredNoteSelection, clearRestoredSelection, renderedReference, versionId, book, chapter]);
+
+ function handleSaveNote() {
+ if (renderedVerseScope && selectionScopeRef.current === renderedVerseScope) {
+ notes.open(buildVerseSelection(lastSelectionRef.current));
+ }
+ }
+
function handleHighlight(color: string) {
const outcome = applyHighlight(color, selectedVerses);
// Entering the auth flow (sign-in or permission prompt) keeps only the verse
@@ -970,7 +1017,7 @@ function Content() {
setPopoverOpen(true);
return;
}
- if (highlightDialogOpen) return;
+ if (highlightDialogOpen || notes.flow) return;
// Outside click / Escape closes and clears (YPE-642, Resolved round 2).
closeAndClearSelection();
}
@@ -1026,6 +1073,7 @@ function Content() {
className="yv:sticky yv:[inset-block-start:0] yv:z-20 yv:rounded-md yv:bg-background yv:px-4 yv:py-2 yv:empty:sr-only yv:text-center yv:text-destructive"
>
{clipboardFailed ? t('unableToShare') : null}
+ {notes.authorizationFailed ? t('generic.requestErrorBody') : null}
{chapterUnavailable ? (
@@ -1078,6 +1126,7 @@ function Content() {
popoverOpen &&
canShowSelection &&
selectedVerses.length > 0 &&
+ !notes.flow &&
!highlightPromptOpen
}
onOpenChange={handlePopoverOpenChange}
@@ -1089,10 +1138,11 @@ function Content() {
scrollRoot={scrollContainerRef.current}
onHighlight={handleHighlight}
onClearHighlight={handleClearHighlight}
+ onSave={notes.available ? handleSaveNote : undefined}
onCopy={handleCopy}
onShare={handleShare}
actionItems={verseActionItems?.map((item) =>
- item === 'highlights' || item === 'copy' || item === 'share'
+ item === 'highlights' || item === 'save' || item === 'copy' || item === 'share'
? item
: {
...item,
@@ -1135,6 +1185,31 @@ function Content() {
theme={background}
/>
+ {
+ if (!open) notes.cancelAuthorization();
+ }}
+ appName={signInAppName}
+ promptMessage={signInPromptMessage}
+ onConfirm={() => void notes.authorize()}
+ onDecline={notes.cancelAuthorization}
+ theme={background}
+ />
+
+ {(notes.flow?.phase === 'compose' || notes.flow?.phase === 'save') && (
+ void notes.save()}
+ onDismiss={notes.dismiss}
+ theme={background}
+ />
+ )}
+
{showLoadingOverlay ? (
void;
+ theme: 'light' | 'dark';
+};
+
+export function HighlightColorCircle({
+ color,
+ selected,
+ pressed,
+ label,
+ onClick,
+ theme,
+}: HighlightColorCircleProps): ReactElement {
+ const isDark = theme === 'dark';
+ const backgroundColor = highlightFillColorMix(color, 'card') ?? undefined;
+ // A contrasting edge defines pale swatches on light cards and dimmed swatches on dark cards.
+ const border = isDark ? '1px solid rgba(255, 255, 255, 0.2)' : '1px solid rgba(18, 18, 18, 0.2)';
+ return (
+
+ {selected && (
+
+ )}
+
+ );
+}
diff --git a/packages/ui/src/components/use-bible-reader-highlights.auth-flow.integration.test.tsx b/packages/ui/src/components/use-bible-reader-highlights.auth-flow.integration.test.tsx
index 112fd447a..0b6c34890 100644
--- a/packages/ui/src/components/use-bible-reader-highlights.auth-flow.integration.test.tsx
+++ b/packages/ui/src/components/use-bible-reader-highlights.auth-flow.integration.test.tsx
@@ -114,7 +114,7 @@ describe('highlight auth flow — one-fell-swoop (signed out)', () => {
});
expect(signIn).toHaveBeenCalledWith(
'https://host.example/callback',
- ['profile'],
+ ['profile', 'read_notes', 'write_notes'],
['highlights'],
);
diff --git a/packages/ui/src/components/use-bible-reader-highlights.ts b/packages/ui/src/components/use-bible-reader-highlights.ts
index 0c678287d..d88c6916c 100644
--- a/packages/ui/src/components/use-bible-reader-highlights.ts
+++ b/packages/ui/src/components/use-bible-reader-highlights.ts
@@ -5,6 +5,7 @@ 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 { READER_SIGN_IN_SCOPES } from './bible-reader-auth';
import {
bibleReaderHighlightsMachine,
scopesEqual,
@@ -76,6 +77,8 @@ export type UseBibleReaderHighlightsReturn = {
* render the (otherwise inert) color-swatch row.
*/
highlightsInteractive: boolean;
+ /** Revalidates the currently displayed chapter while keeping its cached colors. */
+ refresh: () => void;
/** Whether the just-in-time permission confirm dialog is open. */
permissionDialogOpen: boolean;
/** Controlled open-change for the permission confirm dialog. */
@@ -226,7 +229,7 @@ export function useBibleReaderHighlights({
hasHighlightsPermission,
invalidateHighlightsPermission,
consumeDataExchangeReturn,
- startSignInForHighlights,
+ startSignInForHighlights: () => startSignInForHighlights(undefined, READER_SIGN_IN_SCOPES),
startDataExchangeForHighlights,
onAuthRedirectStarted,
onAuthRedirectFailed,
@@ -270,10 +273,15 @@ export function useBibleReaderHighlights({
//
// If `serverColors` is a new object, `highlightedVerses` is also a new object.
// Then `verse.tsx` runs `useLayoutEffect` again for every verse.
- const serverColors = useMemo(
+ const latestServerColors = useMemo(
() => parseServerColors(highlights, versionId, chapterUsfm),
[highlights, versionId, chapterUsfm],
);
+ const paintedServerColorsRef = useRef(latestServerColors);
+ if (!serverColorsEqual(paintedServerColorsRef.current, latestServerColors)) {
+ paintedServerColorsRef.current = latestServerColors;
+ }
+ const serverColors = paintedServerColorsRef.current;
const lastSentServerColorsRef = useRef
(null);
useEffect(() => {
@@ -408,6 +416,9 @@ export function useBibleReaderHighlights({
// we intentionally exclude here — a signed-out tap still enters the sign-in
// flow, so the row stays interactive.)
highlightsInteractive: hasAuthProvider,
+ refresh: () => {
+ if (live) refetch();
+ },
permissionDialogOpen,
signInDialogOpen,
...api,
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
new file mode 100644
index 000000000..139edb424
--- /dev/null
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -0,0 +1,303 @@
+'use client';
+
+import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import {
+ getHttpStatus,
+ getSessionStorage,
+ removeStorageItem,
+ setStorageItem,
+ YouVersionAPIUsers,
+ YouVersionPlatformConfiguration as config,
+ type CreateNote,
+} from '@youversion/platform-core';
+import { useCreateNote, YouVersionAuthContext } from '@youversion/platform-react-hooks';
+import * as z from 'zod/mini';
+import { buildPassageIds } from '@/lib/usfm-ranges';
+import { READER_SIGN_IN_SCOPES } from './bible-reader-auth';
+
+const selectionSchema = z.object({
+ versionId: z.int().check(z.positive()),
+ book: z.string(),
+ chapter: z.string(),
+ verses: z.array(z.int().check(z.positive())).check(z.minLength(1)),
+ reference: z.string(),
+});
+
+const draftSchema = z.object({
+ selection: selectionSchema,
+ requestId: z.uuid(),
+ ownerId: z.nullable(z.string()),
+ text: z.string(),
+ visibility: z.enum(['private', 'public']),
+ color: z.nullable(z.string().check(z.regex(/^[0-9a-f]{6}$/))),
+});
+
+const handoffSchema = z.object({ draft: draftSchema, state: z.string(), expiresAt: z.number() });
+const HANDOFF_KEY = 'youversion-platform:pending-note';
+const HANDOFF_LIFETIME = 10 * 60 * 1000;
+
+type NoteSelection = z.infer;
+export type NoteDraft = z.infer;
+export type NoteDraftFields = Pick;
+
+type Flow = {
+ draft: NoteDraft;
+ phase: 'authorize' | 'redirect' | 'compose' | 'save';
+ failed?: boolean;
+ editing?: boolean;
+ deniedToken?: string;
+};
+
+type UseBibleReaderNoteResult = {
+ flow: Flow | null;
+ available: boolean;
+ authorizationFailed: boolean;
+ restoredSelection: NoteSelection | null;
+ clearRestoredSelection: () => void;
+ open: (selection: NoteSelection) => void;
+ authorize: () => Promise;
+ cancelAuthorization: () => void;
+ change: (fields: Partial) => void;
+ dismiss: () => void;
+ save: () => Promise;
+};
+
+function consumeNoteHandoff() {
+ const storage = getSessionStorage();
+ const raw = storage?.getItem(HANDOFF_KEY);
+ if (!raw) return null;
+ removeStorageItem(storage, HANDOFF_KEY);
+ try {
+ const parsed = handoffSchema.safeParse(JSON.parse(raw));
+ return parsed.success && parsed.data.expiresAt > Date.now() ? parsed.data : null;
+ } catch {
+ return null;
+ }
+}
+
+function writerToken(account: string | null) {
+ return account ? config.getOAuthAccessToken(account, 'write_notes') : null;
+}
+
+function sameSelection(left: NoteSelection, right: NoteSelection): boolean {
+ return (
+ left.versionId === right.versionId &&
+ left.book === right.book &&
+ left.chapter === right.chapter &&
+ left.verses.length === right.verses.length &&
+ left.verses.every((verse, index) => verse === right.verses[index])
+ );
+}
+
+export function useBibleReaderNote({
+ enabled,
+ hostOwnsSignIn,
+ onSaved,
+ onInvalidated,
+}: {
+ enabled: boolean;
+ hostOwnsSignIn: boolean;
+ onSaved: (selection: NoteSelection) => void;
+ onInvalidated: (selection: NoteSelection) => void;
+}): UseBibleReaderNoteResult {
+ const auth = useContext(YouVersionAuthContext);
+ const account = auth?.userInfo?.userId || null;
+ const authLoading = auth?.isLoading ?? false;
+ const canAuthorize = enabled && auth !== null && !auth.isHostControlled && !hostOwnsSignIn;
+ const createNote = useCreateNote();
+ const [flow, setFlow] = useState(null);
+ const [restoredSelection, setRestoredSelection] = useState(null);
+ const clearRestoredSelection = useCallback(() => setRestoredSelection(null), []);
+ const [authorizationFailed, setAuthorizationFailed] = useState(false);
+ const retainedDraft = useRef(null);
+ const currentFlow = useRef(null);
+ const checkedHandoff = useRef(false);
+ const latest = useRef({ account, authLoading, canAuthorize, onSaved, onInvalidated });
+ latest.current = { account, authLoading, canAuthorize, onSaved, onInvalidated };
+
+ function show(next: Flow | null) {
+ currentFlow.current = next;
+ setFlow(next);
+ }
+
+ useLayoutEffect(() => {
+ if (authLoading) return;
+ const draft = currentFlow.current?.draft ?? retainedDraft.current;
+ if (!draft?.ownerId || draft.ownerId === account) return;
+ retainedDraft.current = null;
+ show(null);
+ latest.current.onInvalidated(draft.selection);
+ }, [account, authLoading]);
+
+ const oauthCallbackState = auth?.oauthCallbackState;
+ useEffect(() => {
+ if (authLoading || !canAuthorize || checkedHandoff.current) return;
+ checkedHandoff.current = true;
+ const handoff = consumeNoteHandoff();
+ if (
+ !handoff ||
+ (oauthCallbackState && oauthCallbackState !== handoff.state) ||
+ (handoff.draft.ownerId && handoff.draft.ownerId !== account)
+ ) {
+ return;
+ }
+ setRestoredSelection(handoff.draft.selection);
+ if (oauthCallbackState === handoff.state && writerToken(account)) {
+ show({ phase: 'compose', draft: { ...handoff.draft, ownerId: account } });
+ } else {
+ retainedDraft.current = handoff.draft;
+ }
+ }, [account, authLoading, canAuthorize, oauthCallbackState]);
+
+ function open(selection: NoteSelection) {
+ if (authLoading || currentFlow.current || selection.verses.length === 0) return;
+ const token = writerToken(account);
+ if (!token && !canAuthorize) return;
+ const retained = retainedDraft.current;
+ retainedDraft.current = null;
+ setAuthorizationFailed(false);
+ const draft =
+ retained && sameSelection(retained.selection, selection)
+ ? { ...retained, ownerId: account }
+ : {
+ selection: selectionSchema.parse(selection),
+ ownerId: account,
+ requestId: crypto.randomUUID(),
+ text: '',
+ visibility: 'private' as const,
+ color: null,
+ };
+ show({ phase: token ? 'compose' : 'authorize', draft });
+ }
+
+ function cancelAuthorization() {
+ const active = currentFlow.current;
+ if (active?.phase !== 'authorize') return;
+ if (active.editing) {
+ show({ ...active, phase: 'compose' });
+ } else {
+ retainedDraft.current = active.draft;
+ show(null);
+ }
+ }
+
+ async function authorize() {
+ const active = currentFlow.current;
+ if (active?.phase !== 'authorize' || !canAuthorize) return;
+ const redirect = { ...active, phase: 'redirect' } as const;
+ show(redirect);
+ let stashed = false;
+ try {
+ await YouVersionAPIUsers.signIn(
+ auth?.redirectUri ?? window.location.href,
+ READER_SIGN_IN_SCOPES,
+ undefined,
+ (state) => {
+ if (
+ currentFlow.current !== redirect ||
+ latest.current.account !== redirect.draft.ownerId ||
+ !latest.current.canAuthorize ||
+ (config.storedUserInfo?.id || null) !== redirect.draft.ownerId
+ ) {
+ throw new Error('The Reader account changed before authorization');
+ }
+ const stored = setStorageItem(
+ getSessionStorage(),
+ HANDOFF_KEY,
+ JSON.stringify({
+ draft: redirect.draft,
+ state,
+ expiresAt: Date.now() + HANDOFF_LIFETIME,
+ }),
+ );
+ if (!stored) throw new Error('The pending note could not be saved for authorization');
+ stashed = true;
+ },
+ );
+ } catch {
+ if (currentFlow.current !== redirect) return;
+ if (stashed) removeStorageItem(getSessionStorage(), HANDOFF_KEY);
+ if (active.editing) {
+ show({ ...active, phase: 'compose', failed: true });
+ } else {
+ retainedDraft.current = active.draft;
+ setAuthorizationFailed(true);
+ show(null);
+ }
+ }
+ }
+
+ function change(fields: Partial) {
+ const active = currentFlow.current;
+ if (active?.phase === 'compose') show({ ...active, draft: { ...active.draft, ...fields } });
+ }
+
+ function dismiss() {
+ if (currentFlow.current?.phase === 'compose') show(null);
+ }
+
+ async function save() {
+ const active = currentFlow.current;
+ if (active?.phase !== 'compose' || authLoading || active.draft.ownerId !== account) return;
+ const token = writerToken(account);
+ if (!token || token === active.deniedToken) {
+ show({
+ ...active,
+ phase: canAuthorize ? 'authorize' : 'compose',
+ editing: true,
+ failed: true,
+ });
+ return;
+ }
+ const saving = { draft: active.draft, phase: 'save' } as const;
+ show(saving);
+ const { selection, text, color, visibility, requestId, ownerId } = active.draft;
+ const isCurrent = () =>
+ currentFlow.current === saving &&
+ latest.current.account === ownerId &&
+ config.storedUserInfo?.id === ownerId;
+ const request: CreateNote = {
+ request_id: requestId,
+ content: text,
+ status: visibility,
+ passage: {
+ version_id: selection.versionId,
+ passage_id: buildPassageIds(selection.book, selection.chapter, selection.verses).join('+'),
+ },
+ };
+ if (color) request.color = color;
+ try {
+ await createNote(request, token);
+ } catch (error) {
+ if (isCurrent()) {
+ const status = getHttpStatus(error);
+ show({
+ phase: 'compose',
+ draft: active.draft,
+ failed: true,
+ deniedToken: status === 401 || status === 403 ? token : undefined,
+ });
+ }
+ return;
+ }
+ if (!isCurrent()) return;
+ show(null);
+ latest.current.onSaved(selection);
+ }
+
+ const visibleFlow =
+ !enabled || (flow?.draft.ownerId && flow.draft.ownerId !== account) ? null : flow;
+ return {
+ flow: visibleFlow,
+ available: enabled && !authLoading && (canAuthorize || !!writerToken(account)),
+ authorizationFailed,
+ restoredSelection,
+ clearRestoredSelection,
+ open,
+ authorize,
+ cancelAuthorization,
+ change,
+ dismiss,
+ save,
+ };
+}
diff --git a/packages/ui/src/components/verse-action-popover.tsx b/packages/ui/src/components/verse-action-popover.tsx
index e3fc1473c..3dbe7c061 100644
--- a/packages/ui/src/components/verse-action-popover.tsx
+++ b/packages/ui/src/components/verse-action-popover.tsx
@@ -17,15 +17,15 @@ import i18n from '@/i18n';
import { cn } from '../lib/utils';
import { BoxStackIcon } from './icons/box-stack';
import { Share } from './icons/share';
-import { CheckIcon } from './icons/check';
+import { BookOpenIcon } from './icons/book-open';
+import { HighlightColorCircle } from './highlight-color-circle';
import { useShadowPortalState } from './ui/use-shadow-portal-state';
-import { buildVerseActionSwatches, highlightFillColorMix } from '@/lib/highlight-colors';
+import { buildVerseActionSwatches } from '@/lib/highlight-colors';
import {
getOwnShadowRoot,
isElementFromOwnerDocument,
useShadowFocusRestoreTarget,
} from '@/lib/shadow-root-host';
-import { isDarkHighlightHex } from './verse';
import { useInterfaceDirection } from '@/lib/direction';
import { YvComponentStyles } from '@/lib/yv-styles-components';
import { useTakeVerseActionPopoverFocusRestoreTarget } from '@/lib/verse-action-popover-focus';
@@ -120,8 +120,8 @@ function isDurableFocusRestoreTarget(
);
}
-/** The SDK-provided actions for highlighting, copying, and sharing a verse selection. */
-export type BuiltInVerseAction = 'highlights' | 'copy' | 'share';
+/** The SDK-provided actions for highlighting, saving, copying, and sharing a verse selection. */
+export type BuiltInVerseAction = 'highlights' | 'save' | 'copy' | 'share';
/** A built-in or host-provided action for a standalone {@link VerseActionPopover}. */
export type VerseActionPopoverItem =
@@ -137,7 +137,7 @@ export type VerseActionPopoverItem =
onSelect: () => void;
};
-const DEFAULT_ACTION_ITEMS: readonly BuiltInVerseAction[] = ['highlights', 'copy', 'share'];
+const DEFAULT_ACTION_ITEMS: readonly BuiltInVerseAction[] = ['highlights', 'save', 'copy', 'share'];
type VerseActionPopoverProps = {
open: boolean;
@@ -161,56 +161,13 @@ type VerseActionPopoverProps = {
actionItems?: readonly VerseActionPopoverItem[];
onHighlight: (color: string) => void;
onClearHighlight: (color: string) => void;
+ /** Enables the Save action. The Reader opens its Notes composer here. */
+ onSave?: () => void;
onCopy: () => void;
onShare: () => void;
theme?: 'light' | 'dark';
};
-type ColorCircleProps = {
- color: string;
- showRemove: boolean;
- label: string;
- onClick: () => void;
- theme: 'light' | 'dark';
-};
-
-function ColorCircle({ color, showRemove, label, onClick, theme }: ColorCircleProps) {
- const isDark = theme === 'dark';
- // Dots sit on `yv:bg-card`. Same `--yv-highlight-mix-p` as the reader;
- // mix against `--yv-card` so a host card override stays authoritative.
- const backgroundColor = highlightFillColorMix(color, 'card') ?? undefined;
- // Inner border matches the Figma "highlight stroke" (#121212 @ 20%), giving
- // pale swatches definition on the light popover. On the dark popover a dark
- // stroke would vanish against the dimmed fill, so flip it to a light stroke.
- const border = isDark ? '1px solid rgba(255, 255, 255, 0.2)' : '1px solid rgba(18, 18, 18, 0.2)';
- return (
-
- {/* Active/remove swatch: a 24px checkmark on the solid color circle. Matches
- iOS (platform-sdk-swift #179), which swapped the earlier X for a check.
- Light mode uses Text/Everdark; dark mode dims the fill, so the check goes
- white to stay legible. Tapping it still removes the highlight. */}
- {showRemove && (
-
- )}
-
- );
-}
-
type ActionButtonProps = {
icon: ReactNode;
label: string;
@@ -251,15 +208,16 @@ export const VerseActionPopover: FC = ({
actionItems = DEFAULT_ACTION_ITEMS,
onHighlight,
onClearHighlight,
+ onSave,
onCopy,
onShare,
theme = 'light',
}) => {
const { t } = useTranslation(undefined, { i18n });
const direction = useInterfaceDirection();
- const visibleActionItems = highlightsEnabled
- ? actionItems
- : actionItems.filter((item) => item !== 'highlights');
+ const visibleActionItems = actionItems.filter(
+ (item) => (item !== 'highlights' || highlightsEnabled) && (item !== 'save' || onSave),
+ );
const open = requestedOpen && visibleActionItems.length > 0;
const portal = useShadowPortalState({ open, onOpenChange });
const getShadowFocusRestoreTarget = useShadowFocusRestoreTarget();
@@ -621,6 +579,19 @@ export const VerseActionPopover: FC = ({
}
>
{view.actionItems.map((item, index) => {
+ if (item === 'save') {
+ return (
+ }
+ label={t('notesSave')}
+ onClick={() => onSave?.()}
+ onClickCapture={() => {
+ customActionActivatedRef.current = true;
+ }}
+ />
+ );
+ }
if (item === 'copy' || item === 'share') {
return (
= ({
aria-label={t('highlightColorsAriaLabel')}
>
{view.colorCircles.map(({ color, showRemove, key }) => (
-
Date: Fri, 27 Nov 2026 08:43:52 -0600
Subject: [PATCH 17/75] fix: recover Reader Notes after interrupted
authorization
Preserve the draft on browser Back and clean up a partially persisted automatic token refresh. Keep the composer within narrow viewports and simplify the shared action and highlight paths.
Ref: YPE-6783
---
packages/core/src/Users.ts | 25 ++++++-
packages/core/src/__tests__/Users.test.ts | 33 +++++++++
.../ui/scripts/smoke-vite-reader-notes.mjs | 7 ++
.../bible-reader-notes-composer.tsx | 6 +-
.../components/bible-reader-notes.stories.tsx | 56 ++++++++++++++-
.../src/components/highlight-color-circle.tsx | 6 +-
.../components/use-bible-reader-highlights.ts | 20 +-----
.../src/components/use-bible-reader-note.ts | 72 +++++++++++++------
.../src/components/verse-action-popover.tsx | 13 ++--
9 files changed, 181 insertions(+), 57 deletions(-)
diff --git a/packages/core/src/Users.ts b/packages/core/src/Users.ts
index 546121a1a..953ccaac2 100644
--- a/packages/core/src/Users.ts
+++ b/packages/core/src/Users.ts
@@ -640,6 +640,12 @@ export class YouVersionAPIUsers {
* @throws An error if refresh fails or no refresh token is available
*/
static async refreshTokens(): Promise {
+ return this.rotateTokens(false);
+ }
+
+ private static async rotateTokens(
+ clearOnPersistenceFailure: boolean,
+ ): Promise {
const accessToken = YouVersionPlatformConfiguration.accessToken;
const refreshToken = YouVersionPlatformConfiguration.refreshToken;
const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
@@ -702,15 +708,28 @@ export class YouVersionAPIUsers {
// Store updated tokens. The rotation already spent the old refresh token,
// so an unpersisted result is a dead session, not a refreshed one.
+ const rotatedAccessToken = result.accessToken || null;
+ const rotatedRefreshToken = result.refreshToken || null;
const persisted = YouVersionPlatformConfiguration.saveAuthData(
- result.accessToken || null,
- result.refreshToken || null,
+ rotatedAccessToken,
+ rotatedRefreshToken,
result.expiryDate || null,
oauthSession
? { scope: tokens.scope ?? oauthSession.scope, userId: oauthSession.userId }
: undefined,
);
if (!persisted) {
+ // A partial write can change the token tuple and expiry, so the regular
+ // stale-result check cannot clean up this failure later.
+ const config = YouVersionPlatformConfiguration;
+ if (
+ clearOnPersistenceFailure &&
+ config.storedUserInfo?.id === userId &&
+ [accessToken, rotatedAccessToken].includes(config.accessToken) &&
+ [refreshToken, rotatedRefreshToken].includes(config.refreshToken)
+ ) {
+ config.clearAuthTokens();
+ }
throw new Error('the rotated tokens could not be saved to browser storage');
}
@@ -783,7 +802,7 @@ export class YouVersionAPIUsers {
const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
if (YouVersionPlatformConfiguration.readOAuthSession() === null) return false;
try {
- const result = await this.refreshTokens();
+ const result = await this.rotateTokens(true);
return !!result;
} catch {
// Refresh failed, clear tokens
diff --git a/packages/core/src/__tests__/Users.test.ts b/packages/core/src/__tests__/Users.test.ts
index 9975db7c1..8d2f755b8 100644
--- a/packages/core/src/__tests__/Users.test.ts
+++ b/packages/core/src/__tests__/Users.test.ts
@@ -89,6 +89,7 @@ describe('YouVersionAPIUsers', () => {
mocks.localStorage.removeItem.mockImplementation((key: string) => {
values.delete(key);
});
+ return values;
}
function arriveWithAuthorizationCode(code: string) {
@@ -417,6 +418,38 @@ describe('YouVersionAPIUsers', () => {
},
);
+ it('clears a partially written refresh session when storage rejects the rotated refresh token', async () => {
+ const stored = persistBrowserWrites();
+ const config = YouVersionPlatformConfiguration;
+ config.saveAuthData('old-access', 'old-refresh', new Date(0));
+ config.saveUserInfo({ id: 'signed-in-user' });
+
+ const rotatedRefreshToken = 'a-longer-rotated-refresh-token';
+ mocks.localStorage.setItem.mockImplementation((key: string, value: string) => {
+ if (value === rotatedRefreshToken)
+ throw new DOMException('Storage quota', 'QuotaExceededError');
+ stored.set(key, value);
+ });
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({
+ access_token: 'new-access',
+ refresh_token: rotatedRefreshToken,
+ expires_in: 3600,
+ scope: 'profile',
+ token_type: 'Bearer',
+ }),
+ );
+
+ await expect(YouVersionAPIUsers.refreshTokenIfNeeded()).resolves.toBe(false);
+ await expect(YouVersionAPIUsers.refreshTokenIfNeeded()).resolves.toBe(false);
+ expect(config.accessToken).toBeNull();
+ expect(config.refreshToken).toBeNull();
+ expect(config.tokenExpiryDate).toBeNull();
+ expect(YouVersionAPIUsers.getStoredUserInfo()).toBeNull();
+ expect(mocks.localStorage.setItem).toHaveBeenCalledWith('refreshToken', rotatedRefreshToken);
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
describe('signIn', () => {
afterEach(() => {
// Restore the crypto spies here so restoration still happens even when an
diff --git a/packages/ui/scripts/smoke-vite-reader-notes.mjs b/packages/ui/scripts/smoke-vite-reader-notes.mjs
index df842d906..8126a9dcd 100644
--- a/packages/ui/scripts/smoke-vite-reader-notes.mjs
+++ b/packages/ui/scripts/smoke-vite-reader-notes.mjs
@@ -194,6 +194,13 @@ try {
await composer(page, 'John 1:2,4').waitFor();
assert.equal(notes.length, 0);
await editor(page).fill('Notes smoke');
+ await page.setViewportSize({ width: 390, height: 844 });
+ const bounds = await composer(page, 'John 1:2,4').boundingBox();
+ assert.ok(
+ bounds && bounds.x >= 12 && bounds.x + bounds.width <= 378,
+ `Expected the composer to fit with viewport margins at 390 px, got ${JSON.stringify(bounds)}`,
+ );
+ await page.setViewportSize({ width: 1280, height: 900 });
await composer(page, 'John 1:2,4').getByRole('button', { name: 'Save', exact: true }).click();
await composer(page, 'John 1:2,4').waitFor({ state: 'hidden' });
assert.equal(notes.length, 1);
diff --git a/packages/ui/src/components/bible-reader-notes-composer.tsx b/packages/ui/src/components/bible-reader-notes-composer.tsx
index ce85cd983..6ba3db6cc 100644
--- a/packages/ui/src/components/bible-reader-notes-composer.tsx
+++ b/packages/ui/src/components/bible-reader-notes-composer.tsx
@@ -52,9 +52,9 @@ export function BibleReaderNotesComposer({
-
+
{draft.selection.reference}
onChange({ color: selected ? null : color })}
theme={theme}
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index 11180fa04..45b837497 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -6,7 +6,7 @@ import {
} from '@youversion/platform-core';
import { http, HttpResponse } from 'msw';
import { getWorker } from 'msw-storybook-addon';
-import { expect, userEvent, waitFor, within } from 'storybook/test';
+import { expect, spyOn, userEvent, waitFor, within } from 'storybook/test';
import { globalHandlers } from '@/test/mocks/handlers';
import { getBackgroundColorChannels, waitForShadowRoot } from '@/test/storybook-dom';
import { BibleReader } from './bible-reader';
@@ -373,6 +373,60 @@ export const WritePermissionChangesWhileEditing: Story = {
await expect(await overlays.findByRole('textbox', { name: 'Add Note…' })).toHaveValue(
'Retained thought',
);
+
+ const signIn = stayOnAuthorizationHandoff();
+ try {
+ await userEvent.click(overlays.getByRole('button', { name: 'Save' }));
+ await userEvent.click(await overlays.findByRole('button', { name: 'Yes Please' }));
+ await waitFor(() =>
+ expect(overlays.queryByRole('button', { name: 'Yes Please' })).toBeNull(),
+ );
+ window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }));
+ await expect(await overlays.findByRole('textbox', { name: 'Add Note…' })).toHaveValue(
+ 'Retained thought',
+ );
+ await expect(creates).toBe(0);
+ } finally {
+ signIn.mockRestore();
+ }
+ },
+};
+
+function stayOnAuthorizationHandoff() {
+ // Intercept only the location change so this test can deliver a browser Back
+ // restoration to the same Reader. The SampleApp smoke exercises real redirects.
+ return spyOn(YouVersionAPIUsers, 'signIn').mockImplementation(
+ async (_url, _scopes, _permissions, beforeRedirect) => {
+ beforeRedirect?.(crypto.randomUUID());
+ },
+ );
+}
+
+export const BackCancelsPendingAuthorization: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ play: async ({ canvasElement }) => {
+ const signIn = stayOnAuthorizationHandoff();
+ try {
+ const root = await waitForShadowRoot(canvasElement);
+ await selectVerses(root, [1, 4]);
+ const overlays = await readerOverlays(root);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await userEvent.click(actions.getByRole('button', { name: 'Save' }));
+ await userEvent.click(await overlays.findByRole('button', { name: 'Yes Please' }));
+ await waitFor(() =>
+ expect(overlays.queryByRole('button', { name: 'Yes Please' })).toBeNull(),
+ );
+ await expect(overlays.queryByRole('dialog', { name: 'Verse actions' })).toBeNull();
+
+ window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }));
+ const restored = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await expect(await readerVerse(root, 1)).toHaveClass('yv-v-selected');
+ await expect(await readerVerse(root, 4)).toHaveClass('yv-v-selected');
+ await userEvent.click(restored.getByRole('button', { name: 'Save' }));
+ await expect(await overlays.findByRole('button', { name: 'Yes Please' })).toBeInTheDocument();
+ } finally {
+ signIn.mockRestore();
+ }
},
};
diff --git a/packages/ui/src/components/highlight-color-circle.tsx b/packages/ui/src/components/highlight-color-circle.tsx
index e23bc6e32..5b3efb054 100644
--- a/packages/ui/src/components/highlight-color-circle.tsx
+++ b/packages/ui/src/components/highlight-color-circle.tsx
@@ -7,7 +7,7 @@ import { isDarkHighlightHex } from './verse';
type HighlightColorCircleProps = {
color: string;
selected: boolean;
- pressed?: boolean;
+ toggle?: boolean;
label: string;
onClick: () => void;
theme: 'light' | 'dark';
@@ -16,7 +16,7 @@ type HighlightColorCircleProps = {
export function HighlightColorCircle({
color,
selected,
- pressed,
+ toggle = false,
label,
onClick,
theme,
@@ -36,7 +36,7 @@ export function HighlightColorCircle({
)}
style={{ backgroundColor, border }}
aria-label={label}
- aria-pressed={pressed}
+ aria-pressed={toggle ? selected : undefined}
>
{selected && (
parseServerColors(highlights, versionId, chapterUsfm),
[highlights, versionId, chapterUsfm],
@@ -283,15 +273,7 @@ export function useBibleReaderHighlights({
}
const serverColors = paintedServerColorsRef.current;
- const lastSentServerColorsRef = useRef(null);
useEffect(() => {
- if (
- lastSentServerColorsRef.current !== null &&
- serverColorsEqual(lastSentServerColorsRef.current, serverColors)
- ) {
- return;
- }
- lastSentServerColorsRef.current = serverColors;
actorRef.send({ type: 'HIGHLIGHTS_UPDATED', serverColors });
}, [actorRef, serverColors]);
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index 139edb424..3a1b950a9 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -62,14 +62,20 @@ type UseBibleReaderNoteResult = {
save: () => Promise;
};
-function consumeNoteHandoff() {
+function consumeNoteHandoff(match?: { state: string; requestId: string }) {
const storage = getSessionStorage();
const raw = storage?.getItem(HANDOFF_KEY);
if (!raw) return null;
- removeStorageItem(storage, HANDOFF_KEY);
+ if (!match) removeStorageItem(storage, HANDOFF_KEY);
try {
const parsed = handoffSchema.safeParse(JSON.parse(raw));
- return parsed.success && parsed.data.expiresAt > Date.now() ? parsed.data : null;
+ if (!parsed.success) return null;
+ const handoff = parsed.data;
+ if (match) {
+ if (handoff.state !== match.state || handoff.draft.requestId !== match.requestId) return null;
+ removeStorageItem(storage, HANDOFF_KEY);
+ }
+ return handoff.expiresAt > Date.now() ? handoff : null;
} catch {
return null;
}
@@ -111,15 +117,26 @@ export function useBibleReaderNote({
const [authorizationFailed, setAuthorizationFailed] = useState(false);
const retainedDraft = useRef(null);
const currentFlow = useRef(null);
+ const handoffState = useRef(null);
const checkedHandoff = useRef(false);
- const latest = useRef({ account, authLoading, canAuthorize, onSaved, onInvalidated });
- latest.current = { account, authLoading, canAuthorize, onSaved, onInvalidated };
+ const latest = useRef({ account, canAuthorize, onSaved, onInvalidated });
+ latest.current = { account, canAuthorize, onSaved, onInvalidated };
function show(next: Flow | null) {
currentFlow.current = next;
setFlow(next);
}
+ function restoreAfterAuthorization(active: Flow, failed = false) {
+ if (active.editing) {
+ show({ ...active, phase: 'compose', failed: failed || active.failed });
+ return;
+ }
+ retainedDraft.current = active.draft;
+ if (failed) setAuthorizationFailed(true);
+ show(null);
+ }
+
useLayoutEffect(() => {
if (authLoading) return;
const draft = currentFlow.current?.draft ?? retainedDraft.current;
@@ -149,6 +166,29 @@ export function useBibleReaderNote({
}
}, [account, authLoading, canAuthorize, oauthCallbackState]);
+ useEffect(() => {
+ // Browser Back can restore this same document without remounting the Reader.
+ function onPageShow(event: PageTransitionEvent) {
+ const active = currentFlow.current;
+ const state = handoffState.current;
+ if (!event.persisted || active?.phase !== 'redirect' || !state) return;
+ handoffState.current = null;
+ const handoff = consumeNoteHandoff({ state, requestId: active.draft.requestId });
+ const ownerId = active.draft.ownerId;
+ if ((config.storedUserInfo?.id || null) !== ownerId || latest.current.account !== ownerId) {
+ show(null);
+ latest.current.onInvalidated(active.draft.selection);
+ } else if (handoff && latest.current.canAuthorize) {
+ restoreAfterAuthorization(active);
+ } else {
+ show(null);
+ }
+ }
+
+ globalThis.window?.addEventListener('pageshow', onPageShow);
+ return () => globalThis.window?.removeEventListener('pageshow', onPageShow);
+ }, []);
+
function open(selection: NoteSelection) {
if (authLoading || currentFlow.current || selection.verses.length === 0) return;
const token = writerToken(account);
@@ -172,13 +212,7 @@ export function useBibleReaderNote({
function cancelAuthorization() {
const active = currentFlow.current;
- if (active?.phase !== 'authorize') return;
- if (active.editing) {
- show({ ...active, phase: 'compose' });
- } else {
- retainedDraft.current = active.draft;
- show(null);
- }
+ if (active?.phase === 'authorize') restoreAfterAuthorization(active);
}
async function authorize() {
@@ -186,7 +220,6 @@ export function useBibleReaderNote({
if (active?.phase !== 'authorize' || !canAuthorize) return;
const redirect = { ...active, phase: 'redirect' } as const;
show(redirect);
- let stashed = false;
try {
await YouVersionAPIUsers.signIn(
auth?.redirectUri ?? window.location.href,
@@ -211,19 +244,16 @@ export function useBibleReaderNote({
}),
);
if (!stored) throw new Error('The pending note could not be saved for authorization');
- stashed = true;
+ handoffState.current = state;
},
);
} catch {
if (currentFlow.current !== redirect) return;
- if (stashed) removeStorageItem(getSessionStorage(), HANDOFF_KEY);
- if (active.editing) {
- show({ ...active, phase: 'compose', failed: true });
- } else {
- retainedDraft.current = active.draft;
- setAuthorizationFailed(true);
- show(null);
+ if (handoffState.current) {
+ consumeNoteHandoff({ state: handoffState.current, requestId: active.draft.requestId });
+ handoffState.current = null;
}
+ restoreAfterAuthorization(active, true);
}
}
diff --git a/packages/ui/src/components/verse-action-popover.tsx b/packages/ui/src/components/verse-action-popover.tsx
index 3dbe7c061..81ce8bc44 100644
--- a/packages/ui/src/components/verse-action-popover.tsx
+++ b/packages/ui/src/components/verse-action-popover.tsx
@@ -237,6 +237,9 @@ export const VerseActionPopover: FC = ({
const versePointerEventsRef = useRef(new WeakSet());
const retainOutsideFocusRef = useRef(false);
const customActionActivatedRef = useRef(false);
+ const markOverlayAction = (): void => {
+ customActionActivatedRef.current = true;
+ };
const allowPriorFocusRestoration = (): void => {
retainOutsideFocusRef.current = false;
customActionActivatedRef.current = false;
@@ -479,7 +482,7 @@ export const VerseActionPopover: FC = ({
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.
+ // Save and custom actions can focus another overlay before Radix finishes closing.
const focusMovedOutside =
customActionActivatedRef.current &&
activeElement?.isConnected &&
@@ -586,9 +589,7 @@ export const VerseActionPopover: FC = ({
icon={ }
label={t('notesSave')}
onClick={() => onSave?.()}
- onClickCapture={() => {
- customActionActivatedRef.current = true;
- }}
+ onClickCapture={markOverlayAction}
/>
);
}
@@ -615,9 +616,7 @@ export const VerseActionPopover: FC = ({
icon={item.icon}
label={item.label}
onClick={item.onSelect}
- onClickCapture={() => {
- customActionActivatedRef.current = true;
- }}
+ onClickCapture={markOverlayAction}
/>
);
}
From 2e454f10a607d35cc450e8bbc80381799aa5e843 Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 09:13:53 -0600
Subject: [PATCH 18/75] fix: preserve Reader Notes through authorization
Keep note handoffs bound to their initiating Reader and authorization attempt. Preserve focus, existing verse actions, and a recoverable draft across OAuth failures and navigation.
Ref: YPE-6783
---
.changeset/reader-saves-notes.md | 3 +
.size-limit.js | 4 +-
packages/core/src/Users.ts | 78 ++-
.../core/src/__tests__/OAuthWorkflows.test.ts | 497 ++++++++++++++++++
packages/core/src/__tests__/Users.test.ts | 483 +----------------
.../YouVersionPlatformConfiguration.test.ts | 2 +-
.../YouVersionAuthProvider.oauth.test.tsx | 194 +++++++
.../context/YouVersionAuthProvider.test.tsx | 161 ++----
.../src/context/YouVersionAuthProvider.tsx | 28 +-
packages/hooks/src/types/auth.ts | 2 +
packages/ui/README.md | 5 +-
.../ui/scripts/smoke-vite-reader-notes.mjs | 48 +-
.../bible-reader-notes-composer.tsx | 54 +-
.../components/bible-reader-notes.stories.tsx | 331 ++++++++++--
packages/ui/src/components/bible-reader.tsx | 7 +-
.../src/components/use-bible-reader-note.ts | 84 ++-
16 files changed, 1242 insertions(+), 739 deletions(-)
create mode 100644 packages/core/src/__tests__/OAuthWorkflows.test.ts
create mode 100644 packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx
diff --git a/.changeset/reader-saves-notes.md b/.changeset/reader-saves-notes.md
index 4907707bb..1254e88ce 100644
--- a/.changeset/reader-saves-notes.md
+++ b/.changeset/reader-saves-notes.md
@@ -9,4 +9,7 @@ selection, including gaps, and saves a passage with optional text, privacy, and
highlight color. Reader sign-in requests Notes scopes. The reader refreshes
chapter highlights after a successful save.
+`'save'` is now a built-in action ID. TypeScript consumers that enumerate built-in
+actions should handle `'save'` alongside `'highlights'`, `'copy'`, and `'share'`.
+
`NotesClient` supports creating a passage-only note with empty `content`.
diff --git a/.size-limit.js b/.size-limit.js
index 11c74cef6..a832fc0a5 100644
--- a/.size-limit.js
+++ b/.size-limit.js
@@ -30,8 +30,8 @@ export default [
{
name: 'hooks / full barrel',
path: 'packages/hooks/dist/index.js',
- // Measured brotlied size 29918 B; set to measured + ~10% per CONTRIBUTING.
- limit: '32.9 KB',
+ // Measured brotlied size 33113 B; set to measured + ~10% per CONTRIBUTING.
+ limit: '36.5 KB',
ignore: ['react', 'react-dom', '@tanstack/react-query'],
},
{
diff --git a/packages/core/src/Users.ts b/packages/core/src/Users.ts
index 953ccaac2..1510c97e7 100644
--- a/packages/core/src/Users.ts
+++ b/packages/core/src/Users.ts
@@ -26,6 +26,13 @@ const MISSING_LOCAL_STORAGE_MESSAGE =
const REJECTED_LOCAL_STORAGE_WRITE_MESSAGE =
'Sign In with YouVersion could not write to localStorage; the store rejected the write (its quota may be full, as it always is in Safari private browsing)';
+const AUTH_STATE_KEY = 'youversion-auth-state';
+
+/** The callback no longer belongs to the active authorization attempt. */
+class OAuthCallbackSupersededError extends Error {
+ override readonly name = 'OAuthCallbackSupersededError';
+}
+
/**
* The OAuth handoff has to survive a full-page redirect, so it cannot fall back
* to memory the way the fail-soft accessors do.
@@ -120,11 +127,21 @@ export function __resetTokenRefreshDedupeForTests(): void {
const clearOAuthHandoff = (storage: Storage | null): void => {
removeStorageItem(storage, 'youversion-auth-code-verifier');
removeStorageItem(storage, 'youversion-auth-redirect-uri');
- removeStorageItem(storage, 'youversion-auth-state');
+ removeStorageItem(storage, AUTH_STATE_KEY);
removeStorageItem(storage, PENDING_GRANTED_PERMISSIONS_KEY);
removeStorageItem(storage, REQUESTED_PERMISSIONS_KEY);
};
+function clearFailedRefreshSession(initialState: string | null) {
+ const currentState = getLocalStorage()?.getItem(AUTH_STATE_KEY) ?? null;
+ if (currentState && currentState !== initialState) {
+ // A newer sign-in needs its PKCE handoff and the initiating profile.
+ YouVersionPlatformConfiguration.saveAuthData(null, null, null);
+ } else {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ }
+}
+
/**
* Persist early grants bound to the OAuth `state` that produced them.
*
@@ -223,7 +240,7 @@ export class YouVersionAPIUsers {
* @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 OAuth scopes.
- * @param beforeRedirect - Called with the authorization state immediately before navigation.
+ * @param beforeRedirect - Called with the authorization state before storing the OAuth handoff and navigating.
* @throws An error if authentication fails or configuration is invalid.
*/
static async signIn(
@@ -258,7 +275,7 @@ export class YouVersionAPIUsers {
? redirectURL.toString().slice(0, -1)
: redirectURL.toString();
persistOrThrow(storage, 'youversion-auth-redirect-uri', redirectUrlString);
- persistOrThrow(storage, 'youversion-auth-state', authorizationRequest.parameters.state);
+ persistOrThrow(storage, AUTH_STATE_KEY, authorizationRequest.parameters.state);
// Clear any stash left by a prior abandoned flow (it's only ever produced later,
// during the callback pre-code hop, and never needs to survive a new signIn).
// Otherwise a previous user's abandoned grants could leak into this flow.
@@ -279,6 +296,11 @@ export class YouVersionAPIUsers {
window.location.href = authorizationRequest.url.toString();
}
+ /** Whether the specified authorization attempt is still pending in this browser. */
+ static isSignInPending(state: string): boolean {
+ return getLocalStorage()?.getItem(AUTH_STATE_KEY) === state;
+ }
+
/**
* Handles the OAuth callback after user authentication.
*
@@ -295,31 +317,25 @@ export class YouVersionAPIUsers {
const state = urlParams.get('state');
const error = urlParams.get('error');
- // Check if this is an OAuth callback
- if (!state && !error) {
- return null;
+ const storage = state ? requireLocalStorage() : null;
+ if (state && state !== storage?.getItem(AUTH_STATE_KEY)) {
+ throw new OAuthCallbackSupersededError('Invalid state parameter - possible CSRF attack');
}
- // Handle OAuth error
if (error) {
+ // Leave a verified denial readable when StrictMode replays this callback.
const errorDescription = urlParams.get('error_description') || error;
throw new Error(`OAuth authentication failed: ${errorDescription}`);
}
- const storage = requireLocalStorage();
-
- // Verify state parameter
- const storedState = storage.getItem('youversion-auth-state');
- if (state !== storedState) {
- throw new Error('Invalid state parameter - possible CSRF attack');
- }
+ if (!state || !storage) return null;
// If we don't have a code, this might be the first callback with user data
// We need to redirect to the server callback to get the authorization code.
// Stash any granted_permissions from this hop first — Swift keeps the original
// callback URL for grants, but the web flow navigates away to /auth/callback
// and the final redirect with `code` may omit them.
- if (!code && state) {
+ if (!code) {
const earlyGrants = parseGrantedPermissions(urlParams);
if (earlyGrants.length > 0) {
stashPendingGrantedPermissions(storage, state, earlyGrants);
@@ -332,7 +348,7 @@ export class YouVersionAPIUsers {
const codeVerifier = storage.getItem('youversion-auth-code-verifier');
const redirectUri = storage.getItem('youversion-auth-redirect-uri');
- if (!code || !codeVerifier || !redirectUri) {
+ if (!codeVerifier || !redirectUri) {
throw new Error('Missing required authentication parameters');
}
@@ -374,13 +390,13 @@ export class YouVersionAPIUsers {
code: string,
codeVerifier: string,
redirectUri: string,
- state: string | null,
+ state: string,
urlParams: URLSearchParams,
storage: Storage,
): Promise {
const initiatingUserId = YouVersionPlatformConfiguration.storedUserInfo?.id;
const isCurrentSignIn = () =>
- storage.getItem('youversion-auth-state') === state &&
+ storage.getItem(AUTH_STATE_KEY) === state &&
YouVersionPlatformConfiguration.storedUserInfo?.id === initiatingUserId;
let savingSession = false;
try {
@@ -404,7 +420,9 @@ export class YouVersionAPIUsers {
throw new Error(`Token exchange response was invalid: ${parsed.error.message}`);
}
const tokens = parsed.data;
- if (!isCurrentSignIn()) throw new Error('The authentication session changed during sign-in');
+ if (!isCurrentSignIn()) {
+ throw new OAuthCallbackSupersededError('The authentication session changed during sign-in');
+ }
// Match Swift: union grants from (1) this URL, (2) stashed pre-code hop,
// (3) token scope — then drop scopes that aren't data-exchange permissions before seeding the
@@ -421,8 +439,8 @@ export class YouVersionAPIUsers {
// (removeGrantedPermission) and the machine's PERMISSION_LOST path re-prompts.
// Same fail-closed state binding as the granted stash; a Set union means a
// future server echo never double-counts.
- const stashedGrants = state ? readPendingGrantedPermissions(storage, state) : [];
- const requestedGrants = state ? readRequestedPermissions(storage, state) : [];
+ const stashedGrants = readPendingGrantedPermissions(storage, state);
+ const requestedGrants = readRequestedPermissions(storage, state);
const grantedPermissions = [
...new Set([
...parseGrantedPermissions(urlParams),
@@ -481,10 +499,18 @@ export class YouVersionAPIUsers {
return result;
} catch (error) {
- if (savingSession || isCurrentSignIn()) {
+ if (error instanceof OAuthCallbackSupersededError) throw error;
+ if (savingSession) {
YouVersionPlatformConfiguration.clearAuthTokens();
- clearOAuthHandoff(storage);
+ } else if (!isCurrentSignIn()) {
+ throw new OAuthCallbackSupersededError(
+ 'The authentication session changed during sign-in',
+ {
+ cause: error,
+ },
+ );
}
+ clearOAuthHandoff(storage);
throw error;
}
}
@@ -651,6 +677,7 @@ export class YouVersionAPIUsers {
const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
const oauthSession = YouVersionPlatformConfiguration.readOAuthSession();
const appKey = YouVersionPlatformConfiguration.appKey;
+ const authState = getLocalStorage()?.getItem(AUTH_STATE_KEY) ?? null;
if (!refreshToken) {
throw new Error('No refresh token available');
@@ -728,7 +755,7 @@ export class YouVersionAPIUsers {
[accessToken, rotatedAccessToken].includes(config.accessToken) &&
[refreshToken, rotatedRefreshToken].includes(config.refreshToken)
) {
- config.clearAuthTokens();
+ clearFailedRefreshSession(authState);
}
throw new Error('the rotated tokens could not be saved to browser storage');
}
@@ -800,6 +827,7 @@ export class YouVersionAPIUsers {
const accessToken = YouVersionPlatformConfiguration.accessToken;
const refreshToken = YouVersionPlatformConfiguration.refreshToken;
const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
+ const authState = getLocalStorage()?.getItem(AUTH_STATE_KEY) ?? null;
if (YouVersionPlatformConfiguration.readOAuthSession() === null) return false;
try {
const result = await this.rotateTokens(true);
@@ -812,7 +840,7 @@ export class YouVersionAPIUsers {
YouVersionPlatformConfiguration.storedUserInfo?.id === userId &&
YouVersionPlatformConfiguration.readOAuthSession() !== null
) {
- YouVersionPlatformConfiguration.clearAuthTokens();
+ clearFailedRefreshSession(authState);
}
return false;
}
diff --git a/packages/core/src/__tests__/OAuthWorkflows.test.ts b/packages/core/src/__tests__/OAuthWorkflows.test.ts
new file mode 100644
index 000000000..5c36ca84f
--- /dev/null
+++ b/packages/core/src/__tests__/OAuthWorkflows.test.ts
@@ -0,0 +1,497 @@
+import { expect, it, onTestFinished, vi } from 'vitest';
+import { YouVersionAPIUsers } from '../Users';
+import { YouVersionPlatformConfiguration as config } from '../YouVersionPlatformConfiguration';
+import { setupBrowserMocks, cleanupBrowserMocks } from './mocks/browser';
+
+const redirect = 'https://example.com/callback';
+
+function createOAuthBrowser() {
+ const browser = setupBrowserMocks();
+ const fetch = vi.fn<(request: Request) => Promise>();
+ vi.stubGlobal('fetch', fetch);
+ const previousAppKey = config.appKey;
+ const previousHost = config.apiHost;
+ config.appKey = 'test-app-key';
+ config.apiHost = 'api.youversion.com';
+ onTestFinished(() => {
+ cleanupBrowserMocks();
+ config.appKey = previousAppKey;
+ config.apiHost = previousHost;
+ });
+
+ const values = new Map();
+ browser.localStorage.getItem.mockImplementation((key: string) => values.get(key) ?? null);
+ browser.localStorage.setItem.mockImplementation((key: string, value: string) => {
+ values.set(key, value);
+ });
+ browser.localStorage.removeItem.mockImplementation((key: string) => {
+ values.delete(key);
+ });
+ browser.crypto.getRandomValues.mockImplementation((array: Uint8Array) => array);
+ browser.crypto.subtle.digest.mockResolvedValue(new Uint8Array(32).buffer);
+ browser.btoa.mockReturnValue('oauth-fixture');
+ browser.atob.mockReturnValue(
+ JSON.stringify({
+ sub: '1234567890',
+ name: 'John Doe',
+ email: 'john@example.com',
+ profile_picture: 'https://example.com/avatar.jpg',
+ }),
+ );
+
+ function arriveWithCode(code: string) {
+ const authorize = new URL(browser.window.location.href);
+ const callback = new URL(redirect);
+ callback.searchParams.set('state', authorize.searchParams.get('state') ?? '');
+ callback.searchParams.set('code', code);
+ browser.window.location.search = callback.search;
+ browser.window.location.href = callback.href;
+ }
+
+ function holdTokenResponse() {
+ let respond!: (response: Response) => void;
+ fetch.mockReturnValueOnce(
+ new Promise((resolve) => {
+ respond = resolve;
+ }),
+ );
+ return respond;
+ }
+
+ return { browser, fetch, values, arriveWithCode, holdTokenResponse };
+}
+
+function makeTokens(scope: string) {
+ return {
+ access_token: 'access-token-123',
+ refresh_token: 'refresh-token-456',
+ id_token: 'e30.e30.fixture',
+ expires_in: 3600,
+ token_type: 'Bearer',
+ scope,
+ };
+}
+
+function tokenResponse(scope: string) {
+ return Response.json({ ...makeTokens(scope), access_token: 'signed-in-access' });
+}
+
+it('keeps the account and newer authorization available when its older refresh fails', async () => {
+ const { browser, fetch, holdTokenResponse, arriveWithCode } = createOAuthBrowser();
+ config.saveAuthData('expired-access', 'old-refresh', new Date(0), {
+ scope: 'profile',
+ userId: 'alice',
+ });
+ config.saveUserInfo({ id: 'alice' });
+ const finishRefresh = holdTokenResponse();
+ const refresh = YouVersionAPIUsers.refreshTokenIfNeeded();
+ expect(fetch).toHaveBeenCalled();
+
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+ finishRefresh(new Response(null, { status: 401 }));
+ await expect(refresh).resolves.toBe(false);
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('alice');
+
+ arriveWithCode('grant-after-prior-refresh');
+ browser.atob.mockReturnValue(JSON.stringify({ sub: 'alice' }));
+ fetch.mockResolvedValueOnce(tokenResponse('write_notes'));
+ await YouVersionAPIUsers.handleAuthCallback();
+ expect(config.getOAuthAccessToken('alice', 'write_notes')).toBe('signed-in-access');
+});
+
+it('reports the same verified denial when StrictMode processes the callback twice', async () => {
+ const { browser, fetch } = createOAuthBrowser();
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+ const authorize = new URL(browser.window.location.href);
+ const callback = new URL(redirect);
+ callback.searchParams.set('state', authorize.searchParams.get('state') ?? '');
+ callback.searchParams.set('error', 'access_denied');
+ browser.window.location = { href: callback.href, search: callback.search };
+
+ const first = YouVersionAPIUsers.handleAuthCallback();
+ const second = YouVersionAPIUsers.handleAuthCallback();
+ await Promise.all([
+ expect(first).rejects.toThrow('OAuth authentication failed: access_denied'),
+ expect(second).rejects.toThrow('OAuth authentication failed: access_denied'),
+ ]);
+ expect(fetch).not.toHaveBeenCalled();
+});
+
+it.each(['network', 'server'] as const)(
+ 'retains the current account and token when reauthorization encounters a %s failure',
+ async (failure) => {
+ const { fetch, arriveWithCode } = createOAuthBrowser();
+ config.saveAuthData('current-access', 'current-refresh', new Date('2100-01-01'), {
+ scope: 'read_notes',
+ userId: 'alice',
+ });
+ config.saveUserInfo({ id: 'alice' });
+ await YouVersionAPIUsers.signIn(redirect, ['read_notes', 'write_notes']);
+ arriveWithCode(`reauthorize-${failure}-failure`);
+
+ if (failure === 'network') fetch.mockRejectedValueOnce(new TypeError('Failed to fetch'));
+ else fetch.mockResolvedValueOnce(new Response(null, { status: 503 }));
+ await expect(YouVersionAPIUsers.handleAuthCallback()).rejects.toMatchObject({
+ name: failure === 'network' ? 'TypeError' : 'Error',
+ });
+
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('alice');
+ expect(config.getOAuthAccessToken('alice', 'read_notes')).toBe('current-access');
+ expect(config.refreshToken).toBe('current-refresh');
+ await expect(YouVersionAPIUsers.handleAuthCallback()).rejects.toThrow(
+ 'Invalid state parameter',
+ );
+ expect(fetch).toHaveBeenCalledTimes(1);
+ },
+);
+
+it.each([
+ { timing: 'before the older callback', pendingExchange: false, tokenRequests: 1 },
+ { timing: 'during the older callback', pendingExchange: true, tokenRequests: 2 },
+])(
+ 'rejects an obsolete grant after signing out and back in $timing',
+ async ({ pendingExchange, tokenRequests }) => {
+ const { browser, fetch, arriveWithCode, holdTokenResponse } = createOAuthBrowser();
+ config.saveAuthData('original-access', 'original-refresh', null);
+ config.saveUserInfo({ id: 'alice' });
+ browser.atob.mockReturnValue(JSON.stringify({ sub: 'alice' }));
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+ arriveWithCode(`old-notes-grant-${pendingExchange}`);
+ const staleCallback = { ...browser.window.location };
+ const state = new URLSearchParams(staleCallback.search).get('state');
+ if (!state) throw new Error('Expected an authorization state');
+ expect(YouVersionAPIUsers.isSignInPending(state)).toBe(true);
+ const finishOld = pendingExchange ? holdTokenResponse() : undefined;
+ const oldCallback = finishOld ? YouVersionAPIUsers.handleAuthCallback() : undefined;
+
+ YouVersionAPIUsers.signOut();
+ expect(YouVersionAPIUsers.isSignInPending(state)).toBe(false);
+ browser.btoa.mockReturnValue('replacement-authorization');
+ await YouVersionAPIUsers.signIn(redirect, ['read_notes']);
+ arriveWithCode(`replacement-sign-in-${pendingExchange}`);
+ fetch.mockResolvedValueOnce(tokenResponse('read_notes'));
+ await YouVersionAPIUsers.handleAuthCallback();
+
+ browser.window.location = staleCallback;
+ finishOld?.(tokenResponse('write_notes'));
+ await expect(oldCallback ?? YouVersionAPIUsers.handleAuthCallback()).rejects.toMatchObject({
+ name: 'OAuthCallbackSupersededError',
+ });
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('alice');
+ expect(config.getOAuthAccessToken('alice', 'read_notes')).toBe('signed-in-access');
+ expect(config.getOAuthAccessToken('alice', 'write_notes')).toBeNull();
+ expect(fetch).toHaveBeenCalledTimes(tokenRequests);
+ },
+);
+
+it('requests note scopes at authorize and reads the grants from the exchanged token', async () => {
+ const { browser, fetch, arriveWithCode } = createOAuthBrowser();
+ const beforeRedirect = vi.fn(() => {
+ expect(browser.window.location.href).toBe('');
+ });
+
+ await YouVersionAPIUsers.signIn(
+ redirect,
+ ['profile', 'read_notes', 'write_notes'],
+ ['highlights'],
+ beforeRedirect,
+ );
+
+ const authorize = new URL(browser.window.location.href);
+ expect(authorize.pathname).toBe('/auth/authorize');
+ expect(authorize.searchParams.get('scope')?.split(' ').sort()).toEqual([
+ 'openid',
+ 'profile',
+ 'read_notes',
+ 'write_notes',
+ ]);
+ expect(authorize.searchParams.get('requested_permissions')).toBe('highlights');
+ expect(beforeRedirect).toHaveBeenCalledWith(authorize.searchParams.get('state'));
+ expect(config.getOAuthAccessToken('1234567890', 'write_notes')).toBeNull();
+
+ arriveWithCode('notes-code');
+ fetch.mockResolvedValueOnce(Response.json(makeTokens('openid profile read_notes write_notes')));
+ const result = await YouVersionAPIUsers.handleAuthCallback();
+ expect(result).toMatchObject({
+ accessToken: 'access-token-123',
+ refreshToken: 'refresh-token-456',
+ yvpUserId: '1234567890',
+ name: 'John Doe',
+ email: 'john@example.com',
+ });
+ expect(config.tokenExpiryDate).toEqual(result?.expiryDate);
+ expect(config.storedUserInfo).toEqual({
+ id: '1234567890',
+ name: 'John Doe',
+ email: 'john@example.com',
+ avatar_url: 'https://example.com/avatar.jpg',
+ });
+ expect(browser.localStorage.getItem('idToken')).toBeNull();
+ expect(browser.window.history.replaceState).toHaveBeenCalledWith({}, '', redirect);
+
+ expect(config.getOAuthAccessToken('1234567890', 'read_notes')).toBe('access-token-123');
+ expect(config.getOAuthAccessToken('1234567890', 'write_notes')).toBe('access-token-123');
+ expect(config.grantedPermissions).toEqual(['highlights']);
+});
+
+it('retains note scopes when rotation omits scope and replaces them when the response narrows it', async () => {
+ const { fetch } = createOAuthBrowser();
+ config.saveAuthData('initial-access-token', 'initial-refresh-token', new Date(0), {
+ scope: 'openid read_notes write_notes',
+ userId: 'notes-account',
+ });
+ config.saveUserInfo({ id: 'notes-account' });
+ const rotation = { expires_in: 3600, token_type: 'Bearer' };
+ fetch
+ .mockResolvedValueOnce(
+ Response.json({
+ ...rotation,
+ access_token: 'rotated-access',
+ refresh_token: 'rotated-refresh',
+ }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ ...rotation,
+ access_token: 'reduced-access',
+ refresh_token: 'reduced-refresh',
+ scope: 'openid read_notes',
+ }),
+ );
+
+ await YouVersionAPIUsers.refreshTokens();
+ expect(config.getOAuthAccessToken('notes-account', 'read_notes')).toBe('rotated-access');
+ expect(config.getOAuthAccessToken('notes-account', 'write_notes')).toBe('rotated-access');
+
+ await YouVersionAPIUsers.refreshTokens();
+ expect(config.getOAuthAccessToken('notes-account', 'read_notes')).toBe('reduced-access');
+ expect(config.getOAuthAccessToken('notes-account', 'write_notes')).toBeNull();
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('notes-account');
+});
+
+it('waits for a matching profile instead of refreshing a staged account token', async () => {
+ const { fetch } = createOAuthBrowser();
+ config.saveAuthData('old-access', 'old-refresh', new Date(0), {
+ scope: 'read_notes',
+ userId: 'old-account',
+ });
+ config.saveUserInfo({ id: 'old-account' });
+ config.saveAuthData('new-access', 'new-refresh', new Date(0), {
+ scope: 'write_notes',
+ userId: 'new-account',
+ });
+ fetch.mockResolvedValueOnce(Response.json(makeTokens('openid write_notes')));
+
+ await expect(YouVersionAPIUsers.refreshTokens()).rejects.toThrow();
+ const refreshed = await YouVersionAPIUsers.refreshTokenIfNeeded();
+
+ expect(config.getOAuthAccessToken('old-account', 'write_notes')).toBeNull();
+ expect(config.getOAuthAccessToken('new-account', 'write_notes')).toBeNull();
+ expect(refreshed).toBe(false);
+ expect(fetch).not.toHaveBeenCalled();
+ config.saveUserInfo({ id: 'new-account' });
+ expect(config.getOAuthAccessToken('new-account', 'write_notes')).toBe('new-access');
+});
+
+it('can complete a newer authorization after an older code exchange fails', async () => {
+ const { browser, fetch, arriveWithCode, holdTokenResponse } = createOAuthBrowser();
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+ arriveWithCode('old-code');
+ const releaseOldResponse = holdTokenResponse();
+ const oldCallback = YouVersionAPIUsers.handleAuthCallback();
+ expect(fetch).toHaveBeenCalled();
+
+ browser.btoa.mockReturnValue('new-authorization-value');
+ await YouVersionAPIUsers.signIn(redirect, ['read_notes', 'write_notes']);
+ releaseOldResponse(new Response(null, { status: 400 }));
+ await expect(oldCallback).rejects.toThrow();
+
+ arriveWithCode('new-code');
+ fetch.mockResolvedValueOnce(Response.json(makeTokens('openid read_notes')));
+ await YouVersionAPIUsers.handleAuthCallback();
+ expect(config.getOAuthAccessToken('1234567890', 'read_notes')).toBe('access-token-123');
+ expect(config.getOAuthAccessToken('1234567890', 'write_notes')).toBeNull();
+});
+
+it.each([
+ { responseOutcome: 'succeeds', status: 200 },
+ { responseOutcome: 'fails', status: 400 },
+])(
+ 'preserves the newer account when an older code exchange $responseOutcome',
+ async ({ status }) => {
+ const { fetch, arriveWithCode, holdTokenResponse } = createOAuthBrowser();
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+ arriveWithCode(`old-account-code-${status}`);
+ const releaseOldResponse = holdTokenResponse();
+ const oldCallback = YouVersionAPIUsers.handleAuthCallback();
+ expect(fetch).toHaveBeenCalled();
+
+ config.saveAuthData('new-access', 'new-refresh', null, {
+ scope: 'read_notes',
+ userId: 'new-account',
+ });
+ config.saveUserInfo({ id: 'new-account' });
+ releaseOldResponse(Response.json(makeTokens('openid write_notes'), { status }));
+ await expect(oldCallback).rejects.toThrow();
+
+ expect(config.accessToken).toBe('new-access');
+ expect(config.refreshToken).toBe('new-refresh');
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('new-account');
+ expect(config.getOAuthAccessToken('new-account', 'read_notes')).toBe('new-access');
+ expect(config.getOAuthAccessToken('new-account', 'write_notes')).toBeNull();
+ },
+);
+
+it('stays signed out when a canceled sign-in exchange later succeeds', async () => {
+ const { fetch, arriveWithCode, holdTokenResponse } = createOAuthBrowser();
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+ arriveWithCode('canceled-code');
+ const releaseOldResponse = holdTokenResponse();
+ const oldCallback = YouVersionAPIUsers.handleAuthCallback();
+ expect(fetch).toHaveBeenCalled();
+
+ YouVersionAPIUsers.signOut();
+ releaseOldResponse(Response.json(makeTokens('openid write_notes')));
+ await expect(oldCallback).rejects.toThrow();
+
+ expect(config.accessToken).toBeNull();
+ expect(YouVersionAPIUsers.getStoredUserInfo()).toBeNull();
+ expect(config.getOAuthAccessToken('1234567890', 'write_notes')).toBeNull();
+});
+
+it.each([
+ { responseOutcome: 'succeeds', status: 200 },
+ { responseOutcome: 'fails', status: 401 },
+])(
+ 'preserves the newer account when an older token refresh $responseOutcome',
+ async ({ status }) => {
+ const { fetch, holdTokenResponse } = createOAuthBrowser();
+ config.saveAuthData('old-access', 'old-refresh', new Date(0), {
+ scope: 'write_notes',
+ userId: 'old-account',
+ });
+ config.saveUserInfo({ id: 'old-account' });
+ const releaseOldResponse = holdTokenResponse();
+ const oldRefresh = YouVersionAPIUsers.refreshTokenIfNeeded();
+ expect(fetch).toHaveBeenCalled();
+
+ config.saveAuthData('new-access', 'new-refresh', null, {
+ scope: 'read_notes',
+ userId: 'new-account',
+ });
+ config.saveUserInfo({ id: 'new-account' });
+ releaseOldResponse(Response.json(makeTokens('openid write_notes'), { status }));
+ await expect(oldRefresh).resolves.toBe(false);
+
+ expect(config.accessToken).toBe('new-access');
+ expect(config.refreshToken).toBe('new-refresh');
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('new-account');
+ expect(config.getOAuthAccessToken('new-account', 'read_notes')).toBe('new-access');
+ expect(config.getOAuthAccessToken('new-account', 'write_notes')).toBeNull();
+ },
+);
+
+it('clears a partially written refresh session when storage rejects the rotated refresh token', async () => {
+ const { browser, fetch, values: stored } = createOAuthBrowser();
+ config.saveAuthData('old-access', 'old-refresh', new Date(0));
+ config.saveUserInfo({ id: 'signed-in-user' });
+
+ const rotatedRefreshToken = 'a-longer-rotated-refresh-token';
+ browser.localStorage.setItem.mockImplementation((key: string, value: string) => {
+ if (value === rotatedRefreshToken)
+ throw new DOMException('Storage quota', 'QuotaExceededError');
+ stored.set(key, value);
+ });
+ fetch.mockResolvedValueOnce(
+ Response.json({
+ access_token: 'new-access',
+ refresh_token: rotatedRefreshToken,
+ expires_in: 3600,
+ scope: 'profile',
+ token_type: 'Bearer',
+ }),
+ );
+
+ await expect(YouVersionAPIUsers.refreshTokenIfNeeded()).resolves.toBe(false);
+ await expect(YouVersionAPIUsers.refreshTokenIfNeeded()).resolves.toBe(false);
+ expect(config.accessToken).toBeNull();
+ expect(config.refreshToken).toBeNull();
+ expect(config.tokenExpiryDate).toBeNull();
+ expect(YouVersionAPIUsers.getStoredUserInfo()).toBeNull();
+ expect(browser.localStorage.setItem).toHaveBeenCalledWith('refreshToken', rotatedRefreshToken);
+ expect(fetch).toHaveBeenCalledTimes(1);
+});
+
+it('rotates legacy tokens without assigning the returned scope to a stored profile', async () => {
+ const { fetch } = createOAuthBrowser();
+ const originalAccessToken = 'old-access-token';
+ const originalRefreshToken = 'old-refresh-token';
+ config.saveAuthData(originalAccessToken, originalRefreshToken, null);
+ config.saveUserInfo({ id: 'legacy-user' });
+
+ const mockRefreshResponse = {
+ access_token: 'new-access-token',
+ expires_in: 3600,
+ refresh_token: 'new-refresh-token',
+ scope: 'openid write_notes',
+ token_type: 'Bearer',
+ };
+
+ const mockResponse = Response.json(mockRefreshResponse);
+
+ fetch.mockResolvedValue(mockResponse);
+
+ const result = await YouVersionAPIUsers.refreshTokens();
+
+ expect(result).toBeTruthy();
+
+ // Assert that access_token and refresh_token are new (different from original)
+ expect(result?.accessToken).toBe('new-access-token');
+ expect(result?.accessToken).not.toBe(originalAccessToken);
+ expect(result?.refreshToken).toBe('new-refresh-token');
+ expect(result?.refreshToken).not.toBe(originalRefreshToken);
+
+ // Verify the refresh token request was made correctly
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ method: 'POST',
+ url: 'https://api.youversion.com/auth/token',
+ }),
+ );
+
+ const calledRequest = fetch.mock.calls[0]?.[0];
+ expect(calledRequest).toBeInstanceOf(Request);
+ if (!(calledRequest instanceof Request)) {
+ throw new Error('expected fetch to be called with a Request');
+ }
+ expect(calledRequest.method).toBe('POST');
+ expect(calledRequest.url).toBe('https://api.youversion.com/auth/token');
+ expect(calledRequest.headers.get('content-type')).toBe('application/x-www-form-urlencoded');
+ const bodyText = await calledRequest.clone().text();
+ const body = new URLSearchParams(bodyText);
+ expect(body.get('grant_type')).toBe('refresh_token');
+
+ expect(config.accessToken).toBe('new-access-token');
+ expect(config.refreshToken).toBe('new-refresh-token');
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('legacy-user');
+ expect(config.getOAuthAccessToken('legacy-user', 'write_notes')).toBeNull();
+});
+
+it('shares one refresh request and keeps the rotated session for simultaneous callers', async () => {
+ const { fetch, holdTokenResponse } = createOAuthBrowser();
+ config.saveAuthData('old-access', 'old-refresh', new Date(0));
+ config.saveUserInfo({ id: 'alice' });
+ const finishRefresh = holdTokenResponse();
+ fetch.mockResolvedValue(new Response(null, { status: 400 }));
+
+ const first = YouVersionAPIUsers.refreshTokenIfNeeded();
+ const second = YouVersionAPIUsers.refreshTokenIfNeeded();
+ finishRefresh(tokenResponse('openid profile'));
+
+ await expect(Promise.all([first, second])).resolves.toEqual([true, true]);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(config.accessToken).toBe('signed-in-access');
+ expect(config.refreshToken).toBe('refresh-token-456');
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('alice');
+});
diff --git a/packages/core/src/__tests__/Users.test.ts b/packages/core/src/__tests__/Users.test.ts
index 8d2f755b8..8631f12f8 100644
--- a/packages/core/src/__tests__/Users.test.ts
+++ b/packages/core/src/__tests__/Users.test.ts
@@ -80,38 +80,6 @@ describe('YouVersionAPIUsers', () => {
mocks.btoa.mockReturnValue('mockBase64Value');
}
- function persistBrowserWrites() {
- const values = new Map();
- mocks.localStorage.getItem.mockImplementation((key: string) => values.get(key) ?? null);
- mocks.localStorage.setItem.mockImplementation((key: string, value: string) => {
- values.set(key, value);
- });
- mocks.localStorage.removeItem.mockImplementation((key: string) => {
- values.delete(key);
- });
- return values;
- }
-
- function arriveWithAuthorizationCode(code: string) {
- const authorizeUrl = new URL(mocks.window.location.href);
- const redirect = new URL(authorizeUrl.searchParams.get('redirect_uri') ?? '');
- redirect.searchParams.set('state', authorizeUrl.searchParams.get('state') ?? '');
- redirect.searchParams.set('code', code);
- mocks.window.location.href = redirect.href;
- mocks.window.location.search = redirect.search;
- vi.mocked(atob).mockReturnValue(JSON.stringify(DEFAULT_CALLBACK_PROFILE));
- }
-
- function holdTokenResponse() {
- let respond!: (response: Response) => void;
- mockFetch.mockReturnValueOnce(
- new Promise((resolve) => {
- respond = resolve;
- }),
- );
- return respond;
- }
-
/**
* Wires up the shared handleAuthCallback token-exchange setup: callback URL,
* localStorage reads (state/verifier/redirect-uri + optional pending grant),
@@ -159,7 +127,6 @@ describe('YouVersionAPIUsers', () => {
beforeEach(() => {
vi.clearAllMocks();
- mockFetch.mockReset();
// The code-exchange dedupe map is module-scoped and persists across test
// cases within this file (it only resets on page reload in production).
@@ -188,268 +155,6 @@ describe('YouVersionAPIUsers', () => {
YouVersionPlatformConfiguration.appKey = null;
});
- it('requests note scopes at authorize and reads the grants from the exchanged token', async () => {
- persistBrowserWrites();
- stubSignInCrypto();
- const redirect = 'https://example.com/callback';
- const beforeRedirect = vi.fn(() => {
- expect(mocks.window.location.href).toBe('');
- });
-
- await YouVersionAPIUsers.signIn(
- redirect,
- ['profile', 'read_notes', 'write_notes'],
- ['highlights'],
- beforeRedirect,
- );
-
- const authorize = new URL(mocks.window.location.href);
- expect(authorize.pathname).toBe('/auth/authorize');
- expect(authorize.searchParams.get('scope')?.split(' ').sort()).toEqual([
- 'openid',
- 'profile',
- 'read_notes',
- 'write_notes',
- ]);
- expect(authorize.searchParams.get('requested_permissions')).toBe('highlights');
- expect(beforeRedirect).toHaveBeenCalledWith(authorize.searchParams.get('state'));
- expect(
- YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'write_notes'),
- ).toBeNull();
-
- arriveWithAuthorizationCode('notes-code');
- mockFetch.mockResolvedValueOnce(
- jsonResponse(makeTokens('openid profile read_notes write_notes')),
- );
- await YouVersionAPIUsers.handleAuthCallback();
-
- expect(YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'read_notes')).toBe(
- 'access-token-123',
- );
- expect(YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'write_notes')).toBe(
- 'access-token-123',
- );
- expect(YouVersionPlatformConfiguration.grantedPermissions).toEqual(['highlights']);
- });
-
- it('retains note scopes when rotation omits scope and replaces them when the response narrows it', async () => {
- persistBrowserWrites();
- YouVersionPlatformConfiguration.saveAuthData(
- 'initial-access-token',
- 'initial-refresh-token',
- new Date(0),
- { scope: 'openid read_notes write_notes', userId: 'notes-account' },
- );
- YouVersionPlatformConfiguration.saveUserInfo({ id: 'notes-account' });
- const rotation = { expires_in: 3600, token_type: 'Bearer' };
- mockFetch
- .mockResolvedValueOnce(
- jsonResponse({
- ...rotation,
- access_token: 'rotated-access',
- refresh_token: 'rotated-refresh',
- }),
- )
- .mockResolvedValueOnce(
- jsonResponse({
- ...rotation,
- access_token: 'reduced-access',
- refresh_token: 'reduced-refresh',
- scope: 'openid read_notes',
- }),
- );
-
- await YouVersionAPIUsers.refreshTokens();
- expect(YouVersionPlatformConfiguration.getOAuthAccessToken('notes-account', 'read_notes')).toBe(
- 'rotated-access',
- );
- expect(
- YouVersionPlatformConfiguration.getOAuthAccessToken('notes-account', 'write_notes'),
- ).toBe('rotated-access');
-
- await YouVersionAPIUsers.refreshTokens();
- expect(YouVersionPlatformConfiguration.getOAuthAccessToken('notes-account', 'read_notes')).toBe(
- 'reduced-access',
- );
- expect(
- YouVersionPlatformConfiguration.getOAuthAccessToken('notes-account', 'write_notes'),
- ).toBeNull();
- expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('notes-account');
- });
-
- it('waits for a matching profile instead of refreshing a staged account token', async () => {
- persistBrowserWrites();
- const config = YouVersionPlatformConfiguration;
- config.saveAuthData('old-access', 'old-refresh', new Date(0), {
- scope: 'read_notes',
- userId: 'old-account',
- });
- config.saveUserInfo({ id: 'old-account' });
- config.saveAuthData('new-access', 'new-refresh', new Date(0), {
- scope: 'write_notes',
- userId: 'new-account',
- });
- mockFetch.mockResolvedValueOnce(jsonResponse(makeTokens('openid write_notes')));
-
- await expect(YouVersionAPIUsers.refreshTokens()).rejects.toThrow();
- const refreshed = await YouVersionAPIUsers.refreshTokenIfNeeded();
-
- expect(config.getOAuthAccessToken('old-account', 'write_notes')).toBeNull();
- expect(config.getOAuthAccessToken('new-account', 'write_notes')).toBeNull();
- expect(refreshed).toBe(false);
- expect(mockFetch).not.toHaveBeenCalled();
- config.saveUserInfo({ id: 'new-account' });
- expect(config.getOAuthAccessToken('new-account', 'write_notes')).toBe('new-access');
- });
-
- it('can complete a newer authorization after an older code exchange fails', async () => {
- persistBrowserWrites();
- stubSignInCrypto();
- const redirect = 'https://example.com/callback';
- await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
- arriveWithAuthorizationCode('old-code');
- const releaseOldResponse = holdTokenResponse();
- const oldCallback = YouVersionAPIUsers.handleAuthCallback();
- expect(mockFetch).toHaveBeenCalled();
-
- mocks.btoa.mockReturnValue('new-authorization-value');
- await YouVersionAPIUsers.signIn(redirect, ['read_notes', 'write_notes']);
- releaseOldResponse(emptyResponse(400, 'Bad Request'));
- await expect(oldCallback).rejects.toThrow();
-
- arriveWithAuthorizationCode('new-code');
- mockFetch.mockResolvedValueOnce(jsonResponse(makeTokens('openid read_notes')));
- await YouVersionAPIUsers.handleAuthCallback();
- expect(YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'read_notes')).toBe(
- 'access-token-123',
- );
- expect(
- YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'write_notes'),
- ).toBeNull();
- });
-
- it.each([
- { responseOutcome: 'succeeds', status: 200 },
- { responseOutcome: 'fails', status: 400 },
- ])(
- 'preserves the newer account when an older code exchange $responseOutcome',
- async ({ status }) => {
- persistBrowserWrites();
- stubSignInCrypto();
- await YouVersionAPIUsers.signIn('https://example.com/callback', ['write_notes']);
- arriveWithAuthorizationCode('old-code');
- const releaseOldResponse = holdTokenResponse();
- const oldCallback = YouVersionAPIUsers.handleAuthCallback();
- expect(mockFetch).toHaveBeenCalled();
-
- YouVersionPlatformConfiguration.saveAuthData('new-access', 'new-refresh', null, {
- scope: 'read_notes',
- userId: 'new-account',
- });
- YouVersionPlatformConfiguration.saveUserInfo({ id: 'new-account' });
- releaseOldResponse(jsonResponse(makeTokens('openid write_notes'), status));
- await expect(oldCallback).rejects.toThrow();
-
- expect(YouVersionPlatformConfiguration.accessToken).toBe('new-access');
- expect(YouVersionPlatformConfiguration.refreshToken).toBe('new-refresh');
- expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('new-account');
- expect(YouVersionPlatformConfiguration.getOAuthAccessToken('new-account', 'read_notes')).toBe(
- 'new-access',
- );
- expect(
- YouVersionPlatformConfiguration.getOAuthAccessToken('new-account', 'write_notes'),
- ).toBeNull();
- },
- );
-
- it('stays signed out when a canceled sign-in exchange later succeeds', async () => {
- persistBrowserWrites();
- stubSignInCrypto();
- await YouVersionAPIUsers.signIn('https://example.com/callback', ['write_notes']);
- arriveWithAuthorizationCode('canceled-code');
- const releaseOldResponse = holdTokenResponse();
- const oldCallback = YouVersionAPIUsers.handleAuthCallback();
- expect(mockFetch).toHaveBeenCalled();
-
- YouVersionAPIUsers.signOut();
- releaseOldResponse(jsonResponse(makeTokens('openid write_notes')));
- await expect(oldCallback).rejects.toThrow();
-
- expect(YouVersionPlatformConfiguration.accessToken).toBeNull();
- expect(YouVersionAPIUsers.getStoredUserInfo()).toBeNull();
- expect(
- YouVersionPlatformConfiguration.getOAuthAccessToken('1234567890', 'write_notes'),
- ).toBeNull();
- });
-
- it.each([
- { responseOutcome: 'succeeds', status: 200 },
- { responseOutcome: 'fails', status: 401 },
- ])(
- 'preserves the newer account when an older token refresh $responseOutcome',
- async ({ status }) => {
- persistBrowserWrites();
- YouVersionPlatformConfiguration.saveAuthData('old-access', 'old-refresh', new Date(0), {
- scope: 'write_notes',
- userId: 'old-account',
- });
- YouVersionPlatformConfiguration.saveUserInfo({ id: 'old-account' });
- const releaseOldResponse = holdTokenResponse();
- const oldRefresh = YouVersionAPIUsers.refreshTokenIfNeeded();
- expect(mockFetch).toHaveBeenCalled();
-
- YouVersionPlatformConfiguration.saveAuthData('new-access', 'new-refresh', null, {
- scope: 'read_notes',
- userId: 'new-account',
- });
- YouVersionPlatformConfiguration.saveUserInfo({ id: 'new-account' });
- releaseOldResponse(jsonResponse(makeTokens('openid write_notes'), status));
- await expect(oldRefresh).resolves.toBe(false);
-
- expect(YouVersionPlatformConfiguration.accessToken).toBe('new-access');
- expect(YouVersionPlatformConfiguration.refreshToken).toBe('new-refresh');
- expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('new-account');
- expect(YouVersionPlatformConfiguration.getOAuthAccessToken('new-account', 'read_notes')).toBe(
- 'new-access',
- );
- expect(
- YouVersionPlatformConfiguration.getOAuthAccessToken('new-account', 'write_notes'),
- ).toBeNull();
- },
- );
-
- it('clears a partially written refresh session when storage rejects the rotated refresh token', async () => {
- const stored = persistBrowserWrites();
- const config = YouVersionPlatformConfiguration;
- config.saveAuthData('old-access', 'old-refresh', new Date(0));
- config.saveUserInfo({ id: 'signed-in-user' });
-
- const rotatedRefreshToken = 'a-longer-rotated-refresh-token';
- mocks.localStorage.setItem.mockImplementation((key: string, value: string) => {
- if (value === rotatedRefreshToken)
- throw new DOMException('Storage quota', 'QuotaExceededError');
- stored.set(key, value);
- });
- mockFetch.mockResolvedValueOnce(
- jsonResponse({
- access_token: 'new-access',
- refresh_token: rotatedRefreshToken,
- expires_in: 3600,
- scope: 'profile',
- token_type: 'Bearer',
- }),
- );
-
- await expect(YouVersionAPIUsers.refreshTokenIfNeeded()).resolves.toBe(false);
- await expect(YouVersionAPIUsers.refreshTokenIfNeeded()).resolves.toBe(false);
- expect(config.accessToken).toBeNull();
- expect(config.refreshToken).toBeNull();
- expect(config.tokenExpiryDate).toBeNull();
- expect(YouVersionAPIUsers.getStoredUserInfo()).toBeNull();
- expect(mocks.localStorage.setItem).toHaveBeenCalledWith('refreshToken', rotatedRefreshToken);
- expect(mockFetch).toHaveBeenCalledTimes(1);
- });
-
describe('signIn', () => {
afterEach(() => {
// Restore the crypto spies here so restoration still happens even when an
@@ -515,12 +220,7 @@ describe('YouVersionAPIUsers', () => {
);
// Verify redirect occurred
- const authorize = new URL(mocks.window.location.href);
- expect(authorize.origin + authorize.pathname).toBe(
- 'https://api.youversion.com/auth/authorize',
- );
- expect(authorize.searchParams.get('scope')).toBe('openid');
- expect(authorize.searchParams.has('requested_permissions')).toBe(false);
+ expect(mocks.window.location.href).toContain('https://api.youversion.com/auth/authorize');
});
it('should forward requested permissions to the authorize URL', async () => {
@@ -717,68 +417,6 @@ describe('YouVersionAPIUsers', () => {
);
});
- it('should successfully exchange code for tokens', async () => {
- setupCallbackFlow({
- scope: 'bibles highlights openid',
- profile: { ...DEFAULT_CALLBACK_PROFILE, profile_picture: 'https://example.com/avatar.jpg' },
- });
-
- // Mock YouVersionPlatformConfiguration persistence
- const saveAuthDataSpy = vi.spyOn(YouVersionPlatformConfiguration, 'saveAuthData');
- const saveUserInfoSpy = vi.spyOn(YouVersionPlatformConfiguration, 'saveUserInfo');
- const saveGrantedPermissionsSpy = vi.spyOn(
- YouVersionPlatformConfiguration,
- 'saveGrantedPermissions',
- );
-
- const result = await YouVersionAPIUsers.handleAuthCallback();
-
- expect(result).toBeTruthy();
- expect(result?.accessToken).toBe('access-token-123');
- expect(result?.refreshToken).toBe('refresh-token-456');
- expect(result?.yvpUserId).toBe('1234567890');
- expect(result?.name).toBe('John Doe');
- expect(result?.email).toBe('john@example.com');
-
- // Verify the access and refresh tokens and granted scopes are persisted.
- expect(saveAuthDataSpy).toHaveBeenCalledWith(
- 'access-token-123',
- 'refresh-token-456',
- expect.any(Date),
- { scope: 'bibles highlights openid', userId: '1234567890' },
- );
-
- // Verify the decoded profile was persisted instead of the id token
- expect(saveUserInfoSpy).toHaveBeenCalledWith({
- id: '1234567890',
- name: 'John Doe',
- email: 'john@example.com',
- avatar_url: 'https://example.com/avatar.jpg',
- });
-
- // Token scope seeds the permission cache (OIDC scopes filtered out)
- expect(saveGrantedPermissionsSpy).toHaveBeenCalledWith(['bibles', 'highlights']);
-
- saveUserInfoSpy.mockRestore();
- saveGrantedPermissionsSpy.mockRestore();
-
- // Verify cleanup
- expect(mocks.localStorage.removeItem).toHaveBeenCalledWith('youversion-auth-code-verifier');
- expect(mocks.localStorage.removeItem).toHaveBeenCalledWith('youversion-auth-redirect-uri');
- expect(mocks.localStorage.removeItem).toHaveBeenCalledWith('youversion-auth-state');
- expect(mocks.localStorage.removeItem).toHaveBeenCalledWith(
- 'youversion-auth-pending-granted-permissions',
- );
-
- expect(mocks.window.history.replaceState).toHaveBeenCalledWith(
- {},
- '',
- 'https://example.com/callback',
- );
-
- saveAuthDataSpy.mockRestore();
- });
-
it('keeps the new session when post-exchange cleanup cannot write to storage', async () => {
// A store can read fine and still throw on every mutation (Safari private
// mode). The tokens are already persisted by the time cleanup runs, so a
@@ -1283,64 +921,6 @@ describe('YouVersionAPIUsers', () => {
);
});
- it('rotates legacy tokens without assigning the returned scope to a stored profile', async () => {
- persistBrowserWrites();
- const originalAccessToken = 'old-access-token';
- const originalRefreshToken = 'old-refresh-token';
- YouVersionPlatformConfiguration.saveAuthData(originalAccessToken, originalRefreshToken, null);
- YouVersionPlatformConfiguration.saveUserInfo({ id: 'legacy-user' });
-
- const mockRefreshResponse = {
- access_token: 'new-access-token',
- expires_in: 3600,
- refresh_token: 'new-refresh-token',
- scope: 'openid write_notes',
- token_type: 'Bearer',
- };
-
- const mockResponse = jsonResponse(mockRefreshResponse);
-
- mockFetch.mockResolvedValue(mockResponse);
-
- const result = await YouVersionAPIUsers.refreshTokens();
-
- expect(result).toBeTruthy();
-
- // Assert that access_token and refresh_token are new (different from original)
- expect(result?.accessToken).toBe('new-access-token');
- expect(result?.accessToken).not.toBe(originalAccessToken);
- expect(result?.refreshToken).toBe('new-refresh-token');
- expect(result?.refreshToken).not.toBe(originalRefreshToken);
-
- // Verify the refresh token request was made correctly
- expect(mockFetch).toHaveBeenCalledTimes(1);
- expect(mockFetch).toHaveBeenCalledWith(
- expect.objectContaining({
- method: 'POST',
- url: 'https://api.youversion.com/auth/token',
- }),
- );
-
- const calledRequest = mockFetch.mock.calls[0]?.[0];
- expect(calledRequest).toBeInstanceOf(Request);
- if (!(calledRequest instanceof Request)) {
- throw new Error('expected fetch to be called with a Request');
- }
- expect(calledRequest.method).toBe('POST');
- expect(calledRequest.url).toBe('https://api.youversion.com/auth/token');
- expect(calledRequest.headers.get('content-type')).toBe('application/x-www-form-urlencoded');
- const bodyText = await calledRequest.clone().text();
- const body = new URLSearchParams(bodyText);
- expect(body.get('grant_type')).toBe('refresh_token');
-
- expect(YouVersionPlatformConfiguration.accessToken).toBe('new-access-token');
- expect(YouVersionPlatformConfiguration.refreshToken).toBe('new-refresh-token');
- expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('legacy-user');
- expect(
- YouVersionPlatformConfiguration.getOAuthAccessToken('legacy-user', 'write_notes'),
- ).toBeNull();
- });
-
it('should fail the refresh when the rotated tokens cannot be stored', async () => {
mocks.localStorage.getItem.mockImplementation((key: string) =>
key === 'refreshToken' ? 'refresh-token-123' : null,
@@ -1501,67 +1081,6 @@ describe('YouVersionAPIUsers', () => {
clearAuthTokensSpy.mockRestore();
});
- it('shares one refresh across concurrent callers so a duplicate cannot wipe the session', async () => {
- const pastDate = new Date(Date.now() - 10 * 60 * 1000);
- mocks.localStorage.getItem.mockImplementation((key: string) => {
- if (key === 'expiryDate') return pastDate.toISOString();
- if (key === 'refreshToken') return 'refresh-token-123';
- if (key === 'idToken') return 'id-token-123';
- return null;
- });
-
- // The refresh token is single-use: the first request succeeds; any second
- // request for the same token 400s on the server. If both concurrent
- // callers spent it, the loser's failure would clear the session.
- let refreshRequestCount = 0;
- mockFetch.mockImplementation(() => {
- refreshRequestCount += 1;
- if (refreshRequestCount === 1) {
- return Promise.resolve(
- jsonResponse({
- access_token: 'new-access-token',
- expires_in: 3600,
- refresh_token: 'new-refresh-token',
- scope: 'bibles highlights openid',
- token_type: 'Bearer',
- }),
- );
- }
- return Promise.resolve(emptyResponse(400, 'Bad Request'));
- });
-
- const clearAuthTokensSpy = vi.spyOn(YouVersionPlatformConfiguration, 'clearAuthTokens');
- const saveAuthDataSpy = vi.spyOn(YouVersionPlatformConfiguration, 'saveAuthData');
-
- // Two concurrent invocations, as StrictMode's double-mount produces.
- const [first, second] = await Promise.all([
- YouVersionAPIUsers.refreshTokenIfNeeded(),
- YouVersionAPIUsers.refreshTokenIfNeeded(),
- ]);
-
- // Exactly one refresh network call despite two concurrent callers.
- expect(refreshRequestCount).toBe(1);
- expect(mockFetch).toHaveBeenCalledTimes(1);
-
- // Both callers resolve true off the single shared refresh.
- expect(first).toBe(true);
- expect(second).toBe(true);
-
- // The destructive clear never ran, so tokens and grants survive; the
- // rotated tokens were persisted exactly once.
- expect(clearAuthTokensSpy).not.toHaveBeenCalled();
- expect(saveAuthDataSpy).toHaveBeenCalledTimes(1);
- expect(saveAuthDataSpy).toHaveBeenCalledWith(
- 'new-access-token',
- 'new-refresh-token',
- expect.any(Date),
- undefined,
- );
-
- clearAuthTokensSpy.mockRestore();
- saveAuthDataSpy.mockRestore();
- });
-
it('clears the shared slot so a later refresh performs a new network call', async () => {
const pastDate = new Date(Date.now() - 10 * 60 * 1000);
mocks.localStorage.getItem.mockImplementation((key: string) => {
diff --git a/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts b/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts
index 448bb7709..4e808e537 100644
--- a/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts
+++ b/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts
@@ -37,7 +37,7 @@ describe('YouVersionPlatformConfiguration storage contracts', () => {
).toBeNull();
});
- it('removes a persisted session, scopes, and profile on sign-out', () => {
+ it('removes the persisted session and profile and disables scoped access on sign-out', () => {
const storage = getLocalStorage();
expect(storage).not.toBeNull();
clearStorage(storage);
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx b/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx
new file mode 100644
index 000000000..40bae62b1
--- /dev/null
+++ b/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx
@@ -0,0 +1,194 @@
+import { expect, it, onTestFinished, vi } from 'vitest';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import {
+ type SignInWithYouVersionResult,
+ type YouVersionUserInfoJSON,
+ YouVersionAPIUsers,
+ YouVersionPlatformConfiguration as config,
+} from '@youversion/platform-core';
+import { createMockAuthResult } from '../__tests__/mocks/auth';
+import { useYouVersionAuthContext } from './YouVersionAuthContext';
+import YouVersionAuthProvider from './YouVersionAuthProvider';
+
+function AuthWrapper({ children }: PropsWithChildren) {
+ return (
+ {children}
+ );
+}
+
+function openCallback(search: string, callback: () => Promise) {
+ YouVersionAPIUsers.signOut();
+ window.history.replaceState(null, '', search);
+ const handleCallback = vi
+ .spyOn(YouVersionAPIUsers, 'handleAuthCallback')
+ .mockImplementation(callback);
+ onTestFinished(() => {
+ handleCallback.mockRestore();
+ window.history.replaceState(null, '', '/');
+ YouVersionAPIUsers.signOut();
+ });
+ return handleCallback;
+}
+
+it('keeps auth pending on the initial OAuth hop without a code', async () => {
+ const intermediate = Promise.withResolvers();
+ const handleCallback = openCallback('?state=first-hop', () => intermediate.promise);
+ const { result } = renderHook(useYouVersionAuthContext, { wrapper: AuthWrapper });
+ expect(result.current.isLoading).toBe(true);
+
+ await act(async () => {
+ intermediate.resolve(null);
+ });
+ expect(handleCallback).toHaveBeenCalled();
+ expect(result.current.error).toBeNull();
+ expect(result.current.isLoading).toBe(true);
+});
+
+it('publishes a verified callback completed after the same account rotates its token', async () => {
+ const callback = Promise.withResolvers();
+ openCallback('?state=notes-grant&code=grant-code', () => callback.promise);
+ config.saveAuthData('old-access', 'old-refresh', null);
+ config.saveUserInfo({ id: 'alice' });
+ const { result } = renderHook(useYouVersionAuthContext, { wrapper: AuthWrapper });
+
+ act(() => {
+ config.saveAuthData('rotated-access', 'rotated-refresh', null);
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'accessToken', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('alice');
+ expect(result.current.isLoading).toBe(true);
+
+ await act(async () => {
+ config.saveAuthData('granted-access', 'granted-refresh', null);
+ callback.resolve(
+ createMockAuthResult({
+ accessToken: 'granted-access',
+ refreshToken: 'granted-refresh',
+ yvpUserId: 'alice',
+ }),
+ );
+ });
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.oauthCallbackState).toBe('notes-grant');
+ expect(result.current.userInfo?.userId).toBe('alice');
+
+ act(() => {
+ config.saveUserInfo({ id: 'other-account' });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('other-account');
+ expect(result.current.oauthCallbackState).toBeNull();
+});
+
+it('ignores a successful callback after another account has already replaced its session', async () => {
+ const callback = Promise.withResolvers();
+ openCallback('?state=notes-grant&code=grant-code', () => callback.promise);
+ const { result } = renderHook(useYouVersionAuthContext, { wrapper: AuthWrapper });
+
+ await act(async () => {
+ config.saveAuthData('replacement-access', 'replacement-refresh', null);
+ config.saveUserInfo({ id: 'bob' });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ callback.resolve(createMockAuthResult({ accessToken: 'old-access', yvpUserId: 'alice' }));
+ });
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.userInfo?.userId).toBe('bob');
+ expect(result.current.oauthCallbackState).toBeNull();
+ expect(result.current.oauthCallbackSuperseded).toBe(true);
+});
+
+it.each([
+ { name: 'OAuthCallbackSupersededError', superseded: true },
+ { name: 'TypeError', superseded: false },
+])('reports whether a failed callback is obsolete after $name', async ({ name, superseded }) => {
+ const error = Object.assign(new Error('Authorization failed'), { name });
+ openCallback('?state=older-grant&code=older-code', () => Promise.reject(error));
+ config.saveAuthData('active-access', 'active-refresh', null);
+ config.saveUserInfo({ id: 'alice' });
+
+ const { result } = renderHook(useYouVersionAuthContext, { wrapper: AuthWrapper });
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.userInfo?.userId).toBe('alice');
+ expect(result.current.oauthCallbackState).toBeNull();
+ expect(result.current.oauthCallbackSuperseded).toBe(superseded);
+});
+
+it('keeps the account synced from another tab when the previous account refresh fails', async () => {
+ config.saveAuthData('old-access-token', 'old-refresh-token', new Date(0));
+ config.saveUserInfo({ id: 'old-account' });
+ const oldRefresh = Promise.withResolvers();
+ const refresh = vi
+ .spyOn(YouVersionAPIUsers, 'refreshTokenIfNeeded')
+ .mockReturnValue(oldRefresh.promise);
+
+ try {
+ const { result } = renderHook(useYouVersionAuthContext, { wrapper: AuthWrapper });
+ expect(result.current.isLoading).toBe(true);
+
+ act(() => {
+ config.saveAuthData('new-access-token', 'new-refresh-token', null);
+ config.saveUserInfo({ id: 'new-account' });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('new-account');
+
+ await act(async () => {
+ oldRefresh.resolve(false);
+ });
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.userInfo?.userId).toBe('new-account');
+
+ act(() => {
+ YouVersionAPIUsers.signOut();
+ window.dispatchEvent(new StorageEvent('storage', { storageArea: localStorage }));
+ });
+ expect(result.current.userInfo).toBeNull();
+ } finally {
+ refresh.mockRestore();
+ YouVersionAPIUsers.signOut();
+ }
+});
+
+it('takes signed-in and signed-out state from the host across browser auth events', () => {
+ openCallback('?error=access_denied', () => Promise.reject(new Error('Browser OAuth was called')));
+ config.saveAuthData('browser-access-token', 'browser-refresh-token', null);
+ config.saveUserInfo({ id: 'browser-account' });
+ let hostUser: YouVersionUserInfoJSON | null = null;
+ function HostAuthWrapper({ children }: PropsWithChildren) {
+ return (
+
+ {children}
+
+ );
+ }
+
+ const { result, rerender } = renderHook(useYouVersionAuthContext, { wrapper: HostAuthWrapper });
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.userInfo).toBeNull();
+
+ hostUser = { id: 'host-account' };
+ rerender();
+ expect(result.current.userInfo?.userId).toBe('host-account');
+
+ act(() => {
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('host-account');
+ expect(result.current.error).toBeNull();
+ expect(result.current.oauthCallbackState).toBeNull();
+
+ hostUser = null;
+ rerender();
+ expect(result.current.userInfo).toBeNull();
+});
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.test.tsx b/packages/hooks/src/context/YouVersionAuthProvider.test.tsx
index 760f8fbb8..e419819e8 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.test.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.test.tsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
-import { StrictMode, type PropsWithChildren } from 'react';
-import { act, render, renderHook, waitFor } from '@testing-library/react';
+import { StrictMode } from 'react';
+import { render } from '@testing-library/react';
import { YouVersionAPIUsers, YouVersionPlatformConfiguration } from '@youversion/platform-core';
import YouVersionAuthProvider from './YouVersionAuthProvider';
import { useYouVersionAuthContext } from './YouVersionAuthContext';
@@ -15,20 +15,23 @@ const mockConfig: AuthConfig = {
const mockUserInfo = createMockUserInfo();
const mockAuthResult = createMockAuthResult();
-function WebAuthWrapper({ children }: PropsWithChildren) {
- return {children} ;
-}
+// Mock window and location
+const mockWindow = {
+ location: {
+ href: 'https://example.com',
+ search: '',
+ },
+};
// Test component to access context
function TestChild() {
- const { userInfo, isLoading, error, oauthCallbackState } = useYouVersionAuthContext();
+ const { userInfo, isLoading, error } = useYouVersionAuthContext();
return (
{userInfo ? JSON.stringify(userInfo) : 'null'}
{isLoading.toString()}
{error ? error.message : 'null'}
-
{oauthCallbackState ?? 'null'}
);
}
@@ -39,7 +42,9 @@ describe('YouVersionAuthProvider', () => {
let refreshTokenIfNeeded: MockInstance;
beforeEach(() => {
- window.history.replaceState(null, '', '/');
+ // Setup window mock
+ vi.stubGlobal('window', mockWindow);
+ mockWindow.location.search = '';
// Reset configuration
YouVersionPlatformConfiguration.appKey = '';
@@ -55,7 +60,7 @@ describe('YouVersionAuthProvider', () => {
afterEach(() => {
vi.restoreAllMocks();
- window.history.replaceState(null, '', '/');
+ vi.unstubAllGlobals();
});
describe('initialization', () => {
@@ -67,7 +72,7 @@ describe('YouVersionAuthProvider', () => {
);
// Wait for async initialization to complete
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(YouVersionPlatformConfiguration.appKey).toBe(mockConfig.appKey);
expect(YouVersionPlatformConfiguration.apiHost).toBe(mockConfig.apiHost);
});
@@ -85,7 +90,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(YouVersionPlatformConfiguration.appKey).toBe('test-app-key');
expect(YouVersionPlatformConfiguration.installationId).toBeTruthy();
// Since config had no apiHost, component should set default (in real implementation this would be 'api.youversion.com')
@@ -105,15 +110,15 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(YouVersionPlatformConfiguration.installationId).not.toBe(null);
});
});
});
describe('OAuth callback handling', () => {
- it('publishes the verified callback state until another tab changes the session', async () => {
- window.history.replaceState(null, '', '?state=test-state&code=auth-code');
+ it('should detect OAuth callback with state parameter', async () => {
+ mockWindow.location.search = '?state=test-state&code=auth-code';
vi.spyOn(YouVersionAPIUsers, 'getStoredUserInfo').mockReturnValue(mockUserInfo);
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockResolvedValue(mockAuthResult);
@@ -123,32 +128,17 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
expect(handleAuthCallback).toHaveBeenCalled();
expect(getStoredUserInfo).toHaveBeenCalled();
expect(getByTestId('user-info')).toHaveTextContent(JSON.stringify(mockUserInfo));
- expect(getByTestId('callback-state')).toHaveTextContent('test-state');
-
- const otherUser = createMockUserInfo({ id: 'other-account' });
- getStoredUserInfo.mockReturnValue(otherUser);
- act(() => {
- window.dispatchEvent(
- new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
- );
- });
- expect(getByTestId('user-info')).toHaveTextContent('other-account');
- expect(getByTestId('callback-state')).toHaveTextContent('null');
});
it('should detect OAuth callback with error parameter', async () => {
- window.history.replaceState(
- null,
- '',
- '?error=access_denied&error_description=User+denied+access',
- );
+ mockWindow.location.search = '?error=access_denied&error_description=User+denied+access';
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockResolvedValue(mockAuthResult);
const { getByTestId } = render(
@@ -157,7 +147,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -165,7 +155,7 @@ describe('YouVersionAuthProvider', () => {
});
it('should handle callback error and set error state', async () => {
- window.history.replaceState(null, '', '?state=test-state&code=auth-code');
+ mockWindow.location.search = '?state=test-state&code=auth-code';
const callbackError = new Error('Callback processing failed');
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockRejectedValue(callbackError);
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
@@ -176,11 +166,10 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(getByTestId('error')).toHaveTextContent('Callback processing failed');
expect(getByTestId('is-loading')).toHaveTextContent('false');
expect(getByTestId('user-info')).toHaveTextContent('null');
- expect(getByTestId('callback-state')).toHaveTextContent('null');
});
expect(errorSpy).not.toHaveBeenCalledWith('Auth callback failed:', callbackError);
});
@@ -191,7 +180,7 @@ describe('YouVersionAuthProvider', () => {
// dedupe (see packages/core Users.test.ts); here we only assert the
// provider effect tolerates the double-invocation and still resolves to an
// authenticated, error-free state.
- window.history.replaceState(null, '', '?state=test-state&code=auth-code');
+ mockWindow.location.search = '?state=test-state&code=auth-code';
vi.spyOn(YouVersionAPIUsers, 'getStoredUserInfo').mockReturnValue(mockUserInfo);
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockResolvedValue(mockAuthResult);
@@ -203,7 +192,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -215,7 +204,7 @@ describe('YouVersionAuthProvider', () => {
});
it('should leave user null when no profile was stored during callback', async () => {
- window.history.replaceState(null, '', '?state=test-state&code=auth-code');
+ mockWindow.location.search = '?state=test-state&code=auth-code';
vi.spyOn(YouVersionAPIUsers, 'handleAuthCallback').mockResolvedValue(mockAuthResult);
vi.spyOn(YouVersionAPIUsers, 'getStoredUserInfo').mockReturnValue(null);
@@ -225,7 +214,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -248,7 +237,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -269,7 +258,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -287,7 +276,7 @@ describe('YouVersionAuthProvider', () => {
,
);
- await waitFor(() => {
+ await vi.waitFor(() => {
expect(getByTestId('is-loading')).toHaveTextContent('false');
});
@@ -296,91 +285,3 @@ describe('YouVersionAuthProvider', () => {
});
});
});
-
-it('keeps the account synced from another tab when the previous account refresh fails', async () => {
- YouVersionPlatformConfiguration.saveAuthData(
- 'old-access-token',
- 'old-refresh-token',
- new Date(0),
- );
- YouVersionPlatformConfiguration.saveUserInfo({ id: 'old-account' });
- const oldRefresh = Promise.withResolvers();
- const refresh = vi
- .spyOn(YouVersionAPIUsers, 'refreshTokenIfNeeded')
- .mockReturnValue(oldRefresh.promise);
-
- try {
- const { result } = renderHook(useYouVersionAuthContext, { wrapper: WebAuthWrapper });
- expect(result.current.isLoading).toBe(true);
-
- act(() => {
- YouVersionPlatformConfiguration.saveAuthData('new-access-token', 'new-refresh-token', null);
- YouVersionPlatformConfiguration.saveUserInfo({ id: 'new-account' });
- window.dispatchEvent(
- new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
- );
- });
- expect(result.current.userInfo?.userId).toBe('new-account');
-
- await act(async () => {
- oldRefresh.resolve(false);
- });
- expect(result.current.isLoading).toBe(false);
- expect(result.current.userInfo?.userId).toBe('new-account');
-
- act(() => {
- YouVersionAPIUsers.signOut();
- window.dispatchEvent(new StorageEvent('storage', { storageArea: localStorage }));
- });
- expect(result.current.userInfo).toBeNull();
- } finally {
- refresh.mockRestore();
- YouVersionAPIUsers.signOut();
- }
-});
-
-it('takes signed-in and signed-out state from the host across browser auth events', () => {
- window.history.replaceState(null, '', '?error=access_denied');
- YouVersionPlatformConfiguration.saveAuthData(
- 'browser-access-token',
- 'browser-refresh-token',
- null,
- );
- YouVersionPlatformConfiguration.saveUserInfo({ id: 'browser-account' });
-
- try {
- const { getByTestId, rerender } = render(
-
-
- ,
- );
- expect(getByTestId('is-loading')).toHaveTextContent('false');
- expect(getByTestId('user-info')).toHaveTextContent('null');
-
- rerender(
-
-
- ,
- );
- expect(getByTestId('user-info')).toHaveTextContent('host-account');
-
- act(() => {
- window.dispatchEvent(
- new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
- );
- });
- expect(getByTestId('user-info')).toHaveTextContent('host-account');
- expect(getByTestId('error')).toHaveTextContent('null');
- expect(getByTestId('callback-state')).toHaveTextContent('null');
-
- rerender(
-
-
- ,
- );
- expect(getByTestId('user-info')).toHaveTextContent('null');
- } finally {
- window.history.replaceState(null, '', '/');
- YouVersionAPIUsers.signOut();
- }
-});
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.tsx b/packages/hooks/src/context/YouVersionAuthProvider.tsx
index 31f2469bc..debb968c3 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.tsx
@@ -34,6 +34,7 @@ export default function YouVersionAuthProvider({
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [oauthCallbackState, setOAuthCallbackState] = useState(null);
+ const [oauthCallbackSuperseded, setOAuthCallbackSuperseded] = useState(false);
useEffect(() => {
if (!isHostControlled) return;
@@ -58,11 +59,24 @@ export default function YouVersionAuthProvider({
if (isOAuthCallback) {
try {
const result = await YouVersionAPIUsers.handleAuthCallback();
- if (result && !sessionChanged) {
- // handleAuthCallback persists the decoded profile; read it back.
+ // A verified state-only callback has already navigated to obtain the code.
+ if (
+ !result &&
+ urlParams.get('state') &&
+ !urlParams.get('code') &&
+ !urlParams.has('error')
+ ) {
+ return;
+ }
+ if (result) {
if (!mounted) return;
- setUserInfo(YouVersionAPIUsers.getStoredUserInfo());
- setOAuthCallbackState(urlParams.get('state'));
+ const storedUser = YouVersionAPIUsers.getStoredUserInfo();
+ const callbackMatchesSession =
+ storedUser?.userId === result.yvpUserId &&
+ result.accessToken === YouVersionPlatformConfiguration.accessToken;
+ if (!sessionChanged || callbackMatchesSession) setUserInfo(storedUser);
+ if (callbackMatchesSession) setOAuthCallbackState(urlParams.get('state'));
+ else if (sessionChanged) setOAuthCallbackSuperseded(true);
}
} catch (err) {
if (!mounted) return;
@@ -70,6 +84,7 @@ export default function YouVersionAuthProvider({
if (process.env.NODE_ENV === 'development') {
console.error('Auth callback failed:', error);
}
+ if (error.name === 'OAuthCallbackSupersededError') setOAuthCallbackSuperseded(true);
if (!sessionChanged) {
setError(error);
setUserInfo(YouVersionAPIUsers.getStoredUserInfo());
@@ -115,11 +130,11 @@ export default function YouVersionAuthProvider({
setUserInfo(YouVersionAPIUsers.getStoredUserInfo());
}
- globalThis.window?.addEventListener('storage', syncSession);
+ globalThis.window?.addEventListener?.('storage', syncSession);
void initAuth();
return () => {
mounted = false;
- globalThis.window?.removeEventListener('storage', syncSession);
+ globalThis.window?.removeEventListener?.('storage', syncSession);
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
@@ -130,6 +145,7 @@ export default function YouVersionAuthProvider({
error,
redirectUri: config.redirectUri,
oauthCallbackState,
+ oauthCallbackSuperseded,
isHostControlled,
};
diff --git a/packages/hooks/src/types/auth.ts b/packages/hooks/src/types/auth.ts
index aef341233..1f5719bd9 100644
--- a/packages/hooks/src/types/auth.ts
+++ b/packages/hooks/src/types/auth.ts
@@ -15,6 +15,8 @@ export interface AuthContextValue {
redirectUri?: string;
/** State of the verified OAuth callback handled by this provider. */
oauthCallbackState?: string | null;
+ /** Whether the OAuth callback was replaced by another authorization attempt or session. */
+ oauthCallbackSuperseded?: boolean;
/** Whether the host supplied the profile and owns sign-in. */
isHostControlled?: boolean;
}
diff --git a/packages/ui/README.md b/packages/ui/README.md
index 3d6e557b8..76d53175c 100644
--- a/packages/ui/README.md
+++ b/packages/ui/README.md
@@ -62,8 +62,9 @@ has gaps.
Save opens the Notes composer for the selected verses. A reader with built-in
sign-in requests `read_notes` and `write_notes` alongside its existing OAuth
scopes. The composer requires a YouVersion session with `write_notes`. Start
-with `includeAuth` and an `authRedirectUrl` that returns to your reader to let
-the SDK resume the captured selection after sign-in.
+with `includeAuth` and an `authRedirectUrl` that returns to the page containing
+the reader in the same position. The SDK resumes the captured selection in
+the reader that initiated sign-in, even when its passage changes.
An empty note saves its attached passage. The reader also supports a private or
public note and an optional highlight color.
diff --git a/packages/ui/scripts/smoke-vite-reader-notes.mjs b/packages/ui/scripts/smoke-vite-reader-notes.mjs
index 8126a9dcd..dbb0866fc 100644
--- a/packages/ui/scripts/smoke-vite-reader-notes.mjs
+++ b/packages/ui/scripts/smoke-vite-reader-notes.mjs
@@ -22,9 +22,10 @@ const requestHeaders = {
};
const alice = { id: 'alice', name: 'Alice', granted: 'profile read_notes' };
const bob = { id: 'bob', name: 'Bob', granted: 'profile' };
-const writer = { ...bob, granted: 'profile read_notes write_notes' };
+const writer = { ...bob, granted: 'profile read_notes write_notes', intermediate: true };
const responses = new Map();
const exchanges = new Map();
+const intermediateReturns = new Map();
const notes = [];
const page = await context.newPage();
@@ -34,6 +35,11 @@ await context.route(`${api}/**`, async (route) => {
const url = new URL(request.url());
const json = (body, status = 200) =>
route.fulfill({ json: body, headers: requestHeaders, status });
+ const navigate = (destination) =>
+ route.fulfill({
+ contentType: 'text/html',
+ body: ``,
+ });
if (request.method() === 'OPTIONS')
return route.fulfill({ headers: requestHeaders, status: 204 });
@@ -47,24 +53,34 @@ await context.route(`${api}/**`, async (route) => {
const destination = new URL(url.searchParams.get('redirect_uri'));
assert.equal(destination.origin, new URL(app).origin, 'Expected the local app callback');
- destination.searchParams.set('state', url.searchParams.get('state'));
+ const state = url.searchParams.get('state');
+ destination.searchParams.set('state', state);
if (response.account) {
const code = randomUUID();
exchanges.set(code, response.account);
destination.searchParams.set('code', code);
+ if (response.account.intermediate) {
+ intermediateReturns.set(state, new URL(destination));
+ destination.searchParams.delete('code');
+ }
} else {
destination.searchParams.set('error', 'access_denied');
}
- return route.fulfill({
- contentType: 'text/html',
- body: ``,
- });
+ return navigate(destination);
+ }
+ case '/auth/callback': {
+ const state = url.searchParams.get('state');
+ const destination = intermediateReturns.get(state);
+ assert.ok(destination, 'Expected the state-only OAuth hop');
+ intermediateReturns.delete(state);
+ return navigate(destination);
}
case '/auth/token': {
const code = new URLSearchParams(request.postData()).get('code');
const account = exchanges.get(code);
assert.ok(account, 'Expected a token for the issued authorization code');
exchanges.delete(code);
+ if (account.tokenStatus) return json({}, account.tokenStatus);
const claims = Buffer.from(JSON.stringify({ sub: account.id, name: account.name })).toString(
'base64url',
);
@@ -121,6 +137,13 @@ async function selectVerses(source, verses) {
for (const verse of verses) await source.locator(`.yv-v[v="${verse}"]`).first().click();
}
+async function selectedVerses(source) {
+ const numbers = await source
+ .locator('.yv-v-selected[v]')
+ .evaluateAll((verses) => verses.map((verse) => Number(verse.getAttribute('v'))));
+ return [...new Set(numbers)].sort((a, b) => a - b);
+}
+
async function beginNote(source) {
await menu(source).getByRole('button', { name: 'Save', exact: true }).click();
}
@@ -146,6 +169,7 @@ try {
checkScopes(await declined, readerScopes);
await page.waitForURL(/error=access_denied/);
await menu(page).waitFor();
+ assert.deepEqual(await selectedVerses(page), [1, 4]);
assert.equal(await editor(page).count(), 0);
const navbar = prepareSignIn(page, alice);
@@ -164,6 +188,16 @@ try {
assert.equal(await editor(page).count(), 0);
assert.equal(notes.length, 0);
+ // A temporary token service failure leaves the prior account and selection intact.
+ await beginNote(page);
+ const unavailable = prepareSignIn(page, { ...alice, tokenStatus: 503 });
+ await page.getByRole('button', { name: 'Yes Please' }).click();
+ checkScopes(await unavailable, readerScopes);
+ await signedInAs(page, 'Alice').waitFor();
+ await menu(page).waitFor();
+ assert.deepEqual(await selectedVerses(page), [1, 4]);
+ assert.equal(notes.length, 0);
+
// Alice's old authorization comes back after Bob replaces her session in another tab.
const other = await context.newPage();
await other.goto(app);
@@ -221,7 +255,7 @@ try {
assert.equal(notes.length, 1);
console.log(
- 'Reader Notes smoke passed (decline, grant, exact scoped create, stale callback, sign-out, and navbar scopes).',
+ 'Reader Notes smoke passed (decline, token-service recovery, two-step grant, exact create, stale callback, sign-out, navbar scopes, and narrow layout).',
);
} finally {
await browser.close();
diff --git a/packages/ui/src/components/bible-reader-notes-composer.tsx b/packages/ui/src/components/bible-reader-notes-composer.tsx
index 6ba3db6cc..22424613c 100644
--- a/packages/ui/src/components/bible-reader-notes-composer.tsx
+++ b/packages/ui/src/components/bible-reader-notes-composer.tsx
@@ -1,9 +1,10 @@
'use client';
-import { useId, useState, type ReactElement } from 'react';
+import { useId, useLayoutEffect, useRef, useState, type ReactElement } from 'react';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
import { HIGHLIGHT_COLORS } from '@/lib/highlight-colors';
+import { getOwnShadowRoot, isElementFromOwnerDocument } from '@/lib/shadow-root-host';
import { HighlightColorCircle } from './highlight-color-circle';
import { Button } from './ui/button';
import { Dialog, DialogContent, DialogDescription, DialogTitle } from './ui/dialog';
@@ -31,11 +32,35 @@ export function BibleReaderNotesComposer({
}: NotesComposerProps): ReactElement {
const { t } = useTranslation(undefined, { i18n });
const visibilityName = useId();
+ const discardDescriptionId = useId();
+ const formRef = useRef(null);
+ const stayButtonRef = useRef(null);
+ const focusBeforeDiscard = useRef(null);
const [confirmDiscard, setConfirmDiscard] = useState(false);
+ useLayoutEffect(() => {
+ if (confirmDiscard) {
+ stayButtonRef.current?.focus({ preventScroll: true });
+ } else {
+ focusBeforeDiscard.current?.focus({ preventScroll: true });
+ focusBeforeDiscard.current = null;
+ }
+ }, [confirmDiscard]);
+
function requestDismiss() {
if (saving) return;
+ if (confirmDiscard) {
+ setConfirmDiscard(false);
+ return;
+ }
if (draft.text || draft.visibility !== 'private' || draft.color) {
+ const form = formRef.current;
+ if (form) {
+ const active = getOwnShadowRoot(form)?.activeElement ?? form.ownerDocument.activeElement;
+ if (isElementFromOwnerDocument(active, form, 'HTMLElement') && form.contains(active)) {
+ focusBeforeDiscard.current = active;
+ }
+ }
setConfirmDiscard(true);
} else {
onDismiss();
@@ -51,15 +76,20 @@ export function BibleReaderNotesComposer({
>
- {draft.selection.reference}
+ {confirmDiscard ? (
+ t('notesDiscardTitle')
+ ) : (
+ {draft.selection.reference}
+ )}
{
event.preventDefault();
onSave();
@@ -128,22 +158,24 @@ export function BibleReaderNotesComposer({
-
-
- {t('notesDiscardTitle')}
-
+ {confirmDiscard && (
+
+
{t('notesDiscardMessage')}
- setConfirmDiscard(false)}>
+
{t('cancel')}
{t('notesDiscard')}
-
-
+
+ )}
);
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index 45b837497..a0001e220 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -6,11 +6,18 @@ import {
} from '@youversion/platform-core';
import { http, HttpResponse } from 'msw';
import { getWorker } from 'msw-storybook-addon';
+import { useState } from 'react';
import { expect, spyOn, userEvent, waitFor, within } from 'storybook/test';
+import * as z from 'zod/mini';
import { globalHandlers } from '@/test/mocks/handlers';
-import { getBackgroundColorChannels, waitForShadowRoot } from '@/test/storybook-dom';
+import {
+ getBackgroundColorChannels,
+ verifyNativeBrowserKey,
+ waitForShadowRoot,
+} from '@/test/storybook-dom';
import { BibleReader } from './bible-reader';
import { BibleReaderNavigation } from './bible-reader-navigation';
+import { YouVersionProvider } from './YouVersionProvider';
const meta: Meta = {
title: 'Components/BibleReader/Notes',
@@ -72,19 +79,34 @@ function tokenResponse(scope: string) {
});
}
-function prepareCallback() {
- YouVersionPlatformConfiguration.clearAuthTokens();
- const url = location.href;
- const callback = new URL(url);
- callback.searchParams.set('state', 'notes-story-state');
+function stageCallback(state: string) {
+ const callback = new URL(location.href);
+ callback.searchParams.set('state', state);
callback.searchParams.set('code', crypto.randomUUID());
- localStorage.setItem('youversion-auth-state', 'notes-story-state');
+ localStorage.setItem('youversion-auth-state', state);
localStorage.setItem('youversion-auth-code-verifier', 'notes-story-verifier');
localStorage.setItem('youversion-auth-redirect-uri', callback.origin);
history.replaceState(history.state, '', callback);
- return () => {
- YouVersionPlatformConfiguration.clearAuthTokens();
- history.replaceState(history.state, '', url);
+}
+
+async function prepareCallback() {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ const originalNotesCallbackUrl = location.href;
+ stageCallback('notes-story-state');
+ return { originalNotesCallbackUrl };
+}
+
+type Play = NonNullable;
+
+function withWritableSession(play: Play): Play {
+ return async (context) => {
+ try {
+ await play(context);
+ } finally {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ const url = z.url().parse(context.loaded.originalNotesCallbackUrl);
+ history.replaceState(history.state, '', url);
+ }
};
}
@@ -125,9 +147,9 @@ async function openComposer(root: ShadowRoot, reference: string) {
export const SavePassage: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
- beforeEach: prepareCallback,
+ loaders: [prepareCallback],
parameters: writableSession,
- play: async ({ canvasElement }) => {
+ play: withWritableSession(async ({ canvasElement }) => {
const saved = deferred<{ body: NoteRequest; authorization: string | null }>();
getWorker().use(
http.post('*/v1/notes', async ({ request }) => {
@@ -157,15 +179,15 @@ export const SavePassage: Story = {
},
});
await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
- },
+ }),
};
export const EditAndRetry: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
- beforeEach: prepareCallback,
+ loaders: [prepareCallback],
globals: { theme: 'dark' },
parameters: writableSession,
- play: async ({ canvasElement }) => {
+ play: withWritableSession(async ({ canvasElement }) => {
const requests: NoteRequest[] = [];
getWorker().use(
http.post('*/v1/notes', async ({ request }) => {
@@ -182,8 +204,7 @@ export const EditAndRetry: Story = {
const palette = ['ffec5b', 'b4ffc1', 'bbf4ff', 'ffdca7', 'ffcff8', 'dfdcff'];
const colorName = (color: string) => `Apply highlight #${color}`;
const selected = colors.getByRole('button', { name: colorName('ffdca7') });
- const lightSurface = [255, 220, 167, 255];
- await expect(getBackgroundColorChannels(selected)).not.toEqual(lightSurface);
+ await expect(getBackgroundColorChannels(selected)).toEqual([79, 70, 60, 255]);
async function confirmDirty() {
await userEvent.click(composer.getByRole('button', { name: 'Cancel' }));
@@ -195,7 +216,30 @@ export const EditAndRetry: Story = {
}
await fillEditor(editor, 'First thought');
- await confirmDirty();
+ editor.focus();
+ await verifyNativeBrowserKey('{Shift>}{Tab}{/Shift}', async () => {
+ await expect(root.activeElement).toBe(composer.getByRole('button', { name: 'Save' }));
+ });
+ await verifyNativeBrowserKey('{Tab}', async () => {
+ await expect(root.activeElement).toBe(editor);
+ });
+ const dismiss = composer.getByRole('button', { name: 'Cancel' });
+ dismiss.focus();
+ const nativeKeys = await verifyNativeBrowserKey('{Enter}', async () => {
+ const confirmation = within(await overlays.findByRole('dialog', { name: 'Discard note?' }));
+ const stay = confirmation.getByRole('button', { name: 'Cancel' });
+ const discard = confirmation.getByRole('button', { name: 'Discard' });
+ await waitFor(() => expect(root.activeElement).toBe(stay));
+ await verifyNativeBrowserKey('{Tab}', async () => expect(root.activeElement).toBe(discard));
+ await verifyNativeBrowserKey('{Tab}', async () => expect(root.activeElement).toBe(stay));
+ await verifyNativeBrowserKey('{Escape}', async () => {
+ await waitFor(() =>
+ expect(overlays.queryByRole('dialog', { name: 'Discard note?' })).toBeNull(),
+ );
+ await waitFor(() => expect(root.activeElement).toBe(dismiss));
+ });
+ });
+ if (!nativeKeys) await confirmDirty();
await expect(editor).toHaveValue('First thought');
await fillEditor(editor, '');
@@ -233,7 +277,7 @@ export const EditAndRetry: Story = {
{ ...common, content: 'Edited thought' },
]);
await expect(requests[1]?.request_id).toBe(requests[0]?.request_id);
- },
+ }),
};
const yellow = { bible_id: 111, passage_id: 'JHN.1.1', color: 'ffec5b' };
@@ -243,7 +287,7 @@ const highlightPage = (highlight: typeof yellow) =>
export const RefreshHighlights: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
- beforeEach: prepareCallback,
+ loaders: [prepareCallback],
parameters: {
msw: {
handlers: [
@@ -252,17 +296,36 @@ export const RefreshHighlights: Story = {
],
},
},
- play: async ({ canvasElement }) => {
+ play: withWritableSession(async ({ canvasElement }) => {
const root = await waitForShadowRoot(canvasElement);
const verse = await readerVerse(root, 1);
const paint = () => getBackgroundColorChannels(verse);
const oldColor = [255, 236, 91, 255];
await waitFor(() => expect(paint()).toEqual(oldColor));
- const reads = [HttpResponse.error(), highlightPage(yellow), highlightPage(green)].map(
- (response) => ({ response, release: deferred(), request: deferred() }),
- );
+ const reads = [
+ new HttpResponse(null, { status: 503 }),
+ highlightPage(yellow),
+ highlightPage(green),
+ ].map((response) => ({
+ response,
+ release: deferred(),
+ request: deferred(),
+ finished: deferred(),
+ }));
const queued = reads.slice();
+ const awaitingFetch = reads.slice();
+ const browserFetch = globalThis.fetch.bind(globalThis);
+ const observedFetch = spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
+ const url = new URL(input instanceof Request ? input.url : input, location.href);
+ const read = url.pathname === '/v1/highlights' ? awaitingFetch.shift() : undefined;
+ const response = await browserFetch(input, init);
+ if (read) {
+ await response.clone().arrayBuffer();
+ read.finished.resolve();
+ }
+ return response;
+ });
getWorker().use(
http.post('*/v1/notes', async ({ request }) =>
noteResponse(await request.json()),
@@ -276,40 +339,94 @@ export const RefreshHighlights: Story = {
}),
);
- for (const read of reads) {
- await selectVerses(root, [2]);
- const { overlays, composer } = await openComposer(root, 'John 1:2');
- await userEvent.click(composer.getByRole('button', { name: 'Save' }));
- const scope = (await read.request.promise).searchParams;
- await expect(scope.get('bible_id')).toBe('111');
- await expect(scope.get('passage_id')).toBe('JHN.1');
- await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
- await expect(paint()).toEqual(oldColor);
- read.release.resolve();
+ try {
+ for (const [index, read] of reads.entries()) {
+ await selectVerses(root, [2]);
+ const { overlays, composer } = await openComposer(root, 'John 1:2');
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ const scope = (await read.request.promise).searchParams;
+ await expect(scope.get('bible_id')).toBe('111');
+ await expect(scope.get('passage_id')).toBe('JHN.1');
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ await expect(paint()).toEqual(oldColor);
+ read.release.resolve();
+ await read.finished.promise;
+ if (index < reads.length - 1) {
+ // The response body has reached fetch. Let the Reader publish the
+ // resulting query state before reading the painted verse.
+ await new Promise((resolve) => setTimeout(() => setTimeout(resolve, 0), 0));
+ await expect(paint()).toEqual(oldColor);
+ }
+ }
+ await waitFor(() => expect(paint()).toEqual([180, 255, 193, 255]));
+ } finally {
+ observedFetch.mockRestore();
}
- await waitFor(() => expect(paint()).toEqual([180, 255, 193, 255]));
- },
+ }),
};
-const hostNavigation = new BibleReaderNavigation();
+const storyNavigation = z.instanceof(BibleReaderNavigation);
+
+export const BuiltInActionsDuringNavigation: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ loaders: [async () => ({ hostNavigation: new BibleReaderNavigation() })],
+ render: (_args, { loaded }) => (
+
+
+
+
+
+ ),
+ play: async ({ canvasElement, loaded }) => {
+ const chapterRequested = deferred();
+ const returnChapter = deferred();
+ getWorker().use(
+ http.get('*/v1/bibles/111/passages/JHN.3', async () => {
+ chapterRequested.resolve();
+ await returnChapter.promise;
+ return new HttpResponse(null, { status: 503 });
+ }),
+ );
+ const root = await waitForShadowRoot(canvasElement);
+ const retainedVerse = await readerVerse(root, 1);
+ storyNavigation.parse(loaded.hostNavigation).request({ versionId: 111, passageId: 'JHN.3' });
+ await chapterRequested.promise;
+ try {
+ await userEvent.click(retainedVerse);
+ const overlays = await readerOverlays(root);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await waitFor(() => expect(actions.getByRole('button', { name: 'Copy' })).toBeVisible());
+ await expect(actions.getByRole('button', { name: 'Share' })).toBeVisible();
+ await expect(actions.queryByRole('button', { name: 'Save' })).toBeNull();
+ } finally {
+ returnChapter.resolve();
+ }
+ },
+};
export const RefreshDisplayedChapterAfterNavigation: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
- beforeEach: prepareCallback,
+ loaders: [prepareCallback, async () => ({ hostNavigation: new BibleReaderNavigation() })],
parameters: writableSession,
- render: () => (
+ render: (_args, { loaded }) => (
),
- play: async ({ canvasElement }) => {
+ play: withWritableSession(async ({ canvasElement, loaded }) => {
const root = await waitForShadowRoot(canvasElement);
const noteSent = deferred();
const releaseNote = deferred();
@@ -335,21 +452,21 @@ export const RefreshDisplayedChapterAfterNavigation: Story = {
passage_id: 'JHN.1.2',
});
- hostNavigation.request({ versionId: 111, passageId: 'JHN.3' });
+ storyNavigation.parse(loaded.hostNavigation).request({ versionId: 111, passageId: 'JHN.3' });
await waitFor(() => expect(chapterReads).toContain('111:JHN.3'));
await expect(overlays.getByRole('dialog', { name: 'John 1:2' })).toBeVisible();
chapterReads.length = 0;
releaseNote.resolve();
await waitFor(() => expect(chapterReads).toEqual(['111:JHN.3']));
await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
- },
+ }),
};
export const WritePermissionChangesWhileEditing: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
- beforeEach: prepareCallback,
+ loaders: [prepareCallback],
parameters: writableSession,
- play: async ({ canvasElement }) => {
+ play: withWritableSession(async ({ canvasElement }) => {
const root = await waitForShadowRoot(canvasElement);
await selectVerses(root, [1]);
const { overlays, composer } = await openComposer(root, 'John 1:1');
@@ -386,18 +503,41 @@ export const WritePermissionChangesWhileEditing: Story = {
'Retained thought',
);
await expect(creates).toBe(0);
+
+ await userEvent.click(overlays.getByRole('button', { name: 'Save' }));
+ await userEvent.click(await overlays.findByRole('button', { name: 'Yes Please' }));
+ await waitFor(() =>
+ expect(overlays.queryByRole('button', { name: 'Yes Please' })).toBeNull(),
+ );
+ const profile = YouVersionPlatformConfiguration.storedUserInfo;
+ if (!profile?.id) throw new Error('Missing initial Reader account');
+ // Sign out and back into the same account while the original page is cached.
+ YouVersionAPIUsers.signOut();
+ YouVersionPlatformConfiguration.saveAuthData('new-access', 'new-refresh', null, {
+ userId: profile.id,
+ scope: 'profile read_notes write_notes',
+ });
+ YouVersionPlatformConfiguration.saveUserInfo(profile);
+ window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }));
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ await selectVerses(root, [2]);
+ const { composer: newDraft } = await openComposer(root, 'John 1:2');
+ await expect(newDraft.getByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
+ await expect(creates).toBe(0);
} finally {
signIn.mockRestore();
}
- },
+ }),
};
function stayOnAuthorizationHandoff() {
- // Intercept only the location change so this test can deliver a browser Back
- // restoration to the same Reader. The SampleApp smoke exercises real redirects.
+ // Simulate sign-in handing off to OAuth without replacing the Reader document.
+ // The SampleApp smoke exercises the actual redirect and token exchange.
return spyOn(YouVersionAPIUsers, 'signIn').mockImplementation(
async (_url, _scopes, _permissions, beforeRedirect) => {
- beforeRedirect?.(crypto.randomUUID());
+ const state = crypto.randomUUID();
+ beforeRedirect?.(state);
+ localStorage.setItem('youversion-auth-state', state);
},
);
}
@@ -426,10 +566,93 @@ export const BackCancelsPendingAuthorization: Story = {
await expect(await overlays.findByRole('button', { name: 'Yes Please' })).toBeInTheDocument();
} finally {
signIn.mockRestore();
+ YouVersionPlatformConfiguration.clearAuthTokens();
}
},
};
+function ParallelReaders() {
+ const [callbackCount, setCallbackCount] = useState(0);
+ return (
+ <>
+ {
+ const state = localStorage.getItem('youversion-auth-state');
+ if (!state) throw new Error('Reader did not start an OAuth handoff');
+ stageCallback(state);
+ setCallbackCount((count) => count + 1);
+ }}
+ >
+ Return from sign-in
+
+
+
+ {['First Reader', 'Second Reader'].map((label) => (
+
+ ))}
+
+
+ >
+ );
+}
+
+export const OAuthReturnsToTheInitiatingReader: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ parameters: { ...writableSession, includeAuth: false },
+ loaders: [
+ async () => {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ return { originalNotesCallbackUrl: location.href };
+ },
+ ],
+ render: () => ,
+ play: withWritableSession(async ({ canvasElement }) => {
+ const signIn = stayOnAuthorizationHandoff();
+ try {
+ const page = within(canvasElement);
+ const second = page.getByRole('region', { name: 'Second Reader' });
+ const secondRoot = await waitForShadowRoot(second);
+ await selectVerses(secondRoot, [1, 4]);
+ const overlays = await readerOverlays(secondRoot);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await userEvent.click(actions.getByRole('button', { name: 'Save' }));
+ await userEvent.click(await overlays.findByRole('button', { name: 'Yes Please' }));
+ await waitFor(() =>
+ expect(overlays.queryByRole('button', { name: 'Yes Please' })).toBeNull(),
+ );
+ await userEvent.click(page.getByRole('button', { name: 'Return from sign-in' }));
+
+ await waitFor(async () =>
+ expect(
+ await waitForShadowRoot(page.getByRole('region', { name: 'Second Reader' })),
+ ).not.toBe(secondRoot),
+ );
+ const returned = await waitForShadowRoot(page.getByRole('region', { name: 'Second Reader' }));
+ const returnedOverlays = await readerOverlays(returned);
+ const note = await returnedOverlays.findByRole('dialog', { name: 'John 1:1,4' });
+ await waitFor(() => expect(note).toBeVisible());
+ const first = canvasElement.querySelector('section[aria-label="First Reader"]');
+ if (!first) throw new Error('The first Reader did not remount');
+ const firstRoot = await waitForShadowRoot(first);
+ await expect(firstRoot.querySelector('[role="dialog"]')).toBeNull();
+ } finally {
+ signIn.mockRestore();
+ }
+ }),
+};
+
export const NoBuiltInAuth: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
parameters: { includeAuth: false },
@@ -438,7 +661,7 @@ export const NoBuiltInAuth: Story = {
await selectVerses(root, [1]);
const overlays = await readerOverlays(root);
const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
- await expect(actions.getByRole('button', { name: 'Copy' })).toBeVisible();
+ await waitFor(() => expect(actions.getByRole('button', { name: 'Copy' })).toBeVisible());
await expect(actions.queryByRole('button', { name: 'Save' })).toBeNull();
await expect(overlays.queryByRole('button', { name: 'Yes Please' })).toBeNull();
},
@@ -446,14 +669,14 @@ export const NoBuiltInAuth: Story = {
export const SharedCopyAndDiscard: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
- beforeEach: prepareCallback,
+ loaders: [prepareCallback],
parameters: { ...writableSession, locale: 'es' },
- play: async ({ canvasElement }) => {
+ play: withWritableSession(async ({ canvasElement }) => {
const root = await waitForShadowRoot(canvasElement);
await selectVerses(root, [1]);
const overlays = await readerOverlays(root);
const actions = within(await overlays.findByRole('dialog', { name: 'Acciones del versículo' }));
- await expect(actions.getByRole('button', { name: 'Copiar' })).toBeVisible();
+ await waitFor(() => expect(actions.getByRole('button', { name: 'Copiar' })).toBeVisible());
await userEvent.click(actions.getByRole('button', { name: 'Save' }));
const composer = within(await overlays.findByRole('dialog', { name: 'John 1:1' }));
await fillEditor(
@@ -469,5 +692,5 @@ export const SharedCopyAndDiscard: Story = {
);
await userEvent.click(reopened.getByRole('button', { name: 'Save' }));
await expect(await overlays.findByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
- },
+ }),
};
diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx
index 344fb331c..e828368d2 100644
--- a/packages/ui/src/components/bible-reader.tsx
+++ b/packages/ui/src/components/bible-reader.tsx
@@ -578,7 +578,9 @@ function Content() {
const selectionScopeRef = useRef(null);
const hasCustomVerseActions =
verseActions === 'popover' &&
- verseActionItems?.some((item) => item !== 'highlights' && item !== 'copy' && item !== 'share');
+ verseActionItems?.some(
+ (item) => item !== 'highlights' && item !== 'save' && 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 =
@@ -648,6 +650,7 @@ function Content() {
}
const notes = useBibleReaderNote({
+ reader: scrollContainerRef,
enabled: verseActions !== 'none' && (!verseActionItems || verseActionItems.includes('save')),
hostOwnsSignIn: !!onSignInPress,
onSaved: (selection) => {
@@ -1138,7 +1141,7 @@ function Content() {
scrollRoot={scrollContainerRef.current}
onHighlight={handleHighlight}
onClearHighlight={handleClearHighlight}
- onSave={notes.available ? handleSaveNote : undefined}
+ onSave={notes.available && selectionMatchesScope ? handleSaveNote : undefined}
onCopy={handleCopy}
onShare={handleShare}
actionItems={verseActionItems?.map((item) =>
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index 3a1b950a9..4117cb39e 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -1,6 +1,14 @@
'use client';
-import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import {
+ useCallback,
+ useContext,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type RefObject,
+} from 'react';
import {
getHttpStatus,
getSessionStorage,
@@ -13,6 +21,7 @@ import {
import { useCreateNote, YouVersionAuthContext } from '@youversion/platform-react-hooks';
import * as z from 'zod/mini';
import { buildPassageIds } from '@/lib/usfm-ranges';
+import { getOwnShadowRoot } from '@/lib/shadow-root-host';
import { READER_SIGN_IN_SCOPES } from './bible-reader-auth';
const selectionSchema = z.object({
@@ -32,7 +41,12 @@ const draftSchema = z.object({
color: z.nullable(z.string().check(z.regex(/^[0-9a-f]{6}$/))),
});
-const handoffSchema = z.object({ draft: draftSchema, state: z.string(), expiresAt: z.number() });
+const handoffSchema = z.object({
+ draft: draftSchema,
+ readerKey: z.string(),
+ state: z.string(),
+ expiresAt: z.number(),
+});
const HANDOFF_KEY = 'youversion-platform:pending-note';
const HANDOFF_LIFETIME = 10 * 60 * 1000;
@@ -62,19 +76,39 @@ type UseBibleReaderNoteResult = {
save: () => Promise;
};
-function consumeNoteHandoff(match?: { state: string; requestId: string }) {
+// An OAuth return remounts the page. The Reader's placement distinguishes
+// multiple instances even when they display the same passage.
+function readerPosition(reader: HTMLElement): string {
+ const path: string[] = [];
+ for (
+ let node: Element | null = reader;
+ node;
+ node = node.parentElement ?? getOwnShadowRoot(node)?.host ?? null
+ ) {
+ if (node.id && !getOwnShadowRoot(node)) {
+ path.unshift(`#${node.id}`);
+ break;
+ }
+ const siblings = Array.from(node.parentNode?.children ?? []).filter(
+ (sibling) => sibling.localName === node?.localName,
+ );
+ path.unshift(`${node.localName}:${siblings.indexOf(node)}`);
+ }
+ return JSON.stringify([reader.ownerDocument.location?.pathname, ...path]);
+}
+
+function consumeNoteHandoff(readerKey: string, match?: { state: string; requestId: string }) {
const storage = getSessionStorage();
const raw = storage?.getItem(HANDOFF_KEY);
if (!raw) return null;
- if (!match) removeStorageItem(storage, HANDOFF_KEY);
try {
const parsed = handoffSchema.safeParse(JSON.parse(raw));
if (!parsed.success) return null;
const handoff = parsed.data;
- if (match) {
- if (handoff.state !== match.state || handoff.draft.requestId !== match.requestId) return null;
- removeStorageItem(storage, HANDOFF_KEY);
- }
+ if (handoff.readerKey !== readerKey) return null;
+ if (match && (handoff.state !== match.state || handoff.draft.requestId !== match.requestId))
+ return null;
+ removeStorageItem(storage, HANDOFF_KEY);
return handoff.expiresAt > Date.now() ? handoff : null;
} catch {
return null;
@@ -96,11 +130,13 @@ function sameSelection(left: NoteSelection, right: NoteSelection): boolean {
}
export function useBibleReaderNote({
+ reader,
enabled,
hostOwnsSignIn,
onSaved,
onInvalidated,
}: {
+ reader: RefObject;
enabled: boolean;
hostOwnsSignIn: boolean;
onSaved: (selection: NoteSelection) => void;
@@ -147,12 +183,14 @@ export function useBibleReaderNote({
}, [account, authLoading]);
const oauthCallbackState = auth?.oauthCallbackState;
+ const oauthCallbackSuperseded = auth?.oauthCallbackSuperseded;
useEffect(() => {
- if (authLoading || !canAuthorize || checkedHandoff.current) return;
+ if (authLoading || !canAuthorize || checkedHandoff.current || !reader.current) return;
checkedHandoff.current = true;
- const handoff = consumeNoteHandoff();
+ const handoff = consumeNoteHandoff(readerPosition(reader.current));
if (
!handoff ||
+ oauthCallbackSuperseded ||
(oauthCallbackState && oauthCallbackState !== handoff.state) ||
(handoff.draft.ownerId && handoff.draft.ownerId !== account)
) {
@@ -164,18 +202,25 @@ export function useBibleReaderNote({
} else {
retainedDraft.current = handoff.draft;
}
- }, [account, authLoading, canAuthorize, oauthCallbackState]);
+ }, [account, authLoading, canAuthorize, oauthCallbackState, oauthCallbackSuperseded, reader]);
useEffect(() => {
// Browser Back can restore this same document without remounting the Reader.
function onPageShow(event: PageTransitionEvent) {
const active = currentFlow.current;
const state = handoffState.current;
- if (!event.persisted || active?.phase !== 'redirect' || !state) return;
+ if (!event.persisted || active?.phase !== 'redirect' || !state || !reader.current) return;
handoffState.current = null;
- const handoff = consumeNoteHandoff({ state, requestId: active.draft.requestId });
+ const handoff = consumeNoteHandoff(readerPosition(reader.current), {
+ state,
+ requestId: active.draft.requestId,
+ });
const ownerId = active.draft.ownerId;
- if ((config.storedUserInfo?.id || null) !== ownerId || latest.current.account !== ownerId) {
+ if (
+ !YouVersionAPIUsers.isSignInPending(state) ||
+ (config.storedUserInfo?.id || null) !== ownerId ||
+ latest.current.account !== ownerId
+ ) {
show(null);
latest.current.onInvalidated(active.draft.selection);
} else if (handoff && latest.current.canAuthorize) {
@@ -187,7 +232,7 @@ export function useBibleReaderNote({
globalThis.window?.addEventListener('pageshow', onPageShow);
return () => globalThis.window?.removeEventListener('pageshow', onPageShow);
- }, []);
+ }, [reader]);
function open(selection: NoteSelection) {
if (authLoading || currentFlow.current || selection.verses.length === 0) return;
@@ -217,7 +262,8 @@ export function useBibleReaderNote({
async function authorize() {
const active = currentFlow.current;
- if (active?.phase !== 'authorize' || !canAuthorize) return;
+ if (active?.phase !== 'authorize' || !canAuthorize || !reader.current) return;
+ const readerKey = readerPosition(reader.current);
const redirect = { ...active, phase: 'redirect' } as const;
show(redirect);
try {
@@ -239,6 +285,7 @@ export function useBibleReaderNote({
HANDOFF_KEY,
JSON.stringify({
draft: redirect.draft,
+ readerKey,
state,
expiresAt: Date.now() + HANDOFF_LIFETIME,
}),
@@ -250,7 +297,10 @@ export function useBibleReaderNote({
} catch {
if (currentFlow.current !== redirect) return;
if (handoffState.current) {
- consumeNoteHandoff({ state: handoffState.current, requestId: active.draft.requestId });
+ consumeNoteHandoff(readerKey, {
+ state: handoffState.current,
+ requestId: active.draft.requestId,
+ });
handoffState.current = null;
}
restoreAfterAuthorization(active, true);
From 24e6dd49e52dd4bd49bbd4e929ebd228ab3992e1 Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 10:04:12 -0600
Subject: [PATCH 19/75] fix: preserve Reader sessions and highlight refresh
Keep OAuth recovery bound to the initiating draft and restore focus around the Notes composer. Refresh highlights for the passage on screen and preserve existing host sign-in behavior.
Ref: YPE-6783
---
.changeset/reader-saves-notes.md | 4 +-
packages/core/src/Users.ts | 13 +-
.../src/YouVersionPlatformConfiguration.ts | 23 +-
.../core/src/__tests__/OAuthWorkflows.test.ts | 106 +++---
.../YouVersionPlatformConfiguration.test.ts | 18 ++
.../YouVersionAuthProvider.oauth.test.tsx | 62 +++-
.../src/context/YouVersionAuthProvider.tsx | 47 ++-
packages/hooks/src/types/auth.ts | 4 +
packages/hooks/src/useApiData.ts | 19 +-
packages/hooks/src/useCreateNote.test.tsx | 26 ++
packages/hooks/src/useCreateNote.ts | 8 +-
packages/hooks/src/useHighlights.ts | 1 +
packages/hooks/src/useYVAuth.test.tsx | 146 ++++++++-
packages/hooks/src/useYVAuth.ts | 24 +-
.../ui/scripts/smoke-vite-reader-notes.mjs | 6 +-
.../bible-reader-notes-composer.tsx | 9 +
.../components/bible-reader-notes.stories.tsx | 306 +++++++++++++++++-
.../src/components/bible-reader-toolbar.tsx | 9 +-
.../src/components/bible-reader.stories.tsx | 6 +-
packages/ui/src/components/bible-reader.tsx | 18 +-
packages/ui/src/components/ui/dialog.tsx | 4 +
.../components/ui/use-shadow-dialog-focus.ts | 9 +-
.../components/use-bible-reader-highlights.ts | 49 ++-
.../src/components/use-bible-reader-note.ts | 88 +++--
.../src/components/verse-action-popover.tsx | 4 +-
25 files changed, 850 insertions(+), 159 deletions(-)
create mode 100644 packages/hooks/src/useCreateNote.test.tsx
diff --git a/.changeset/reader-saves-notes.md b/.changeset/reader-saves-notes.md
index 1254e88ce..ac6ba8290 100644
--- a/.changeset/reader-saves-notes.md
+++ b/.changeset/reader-saves-notes.md
@@ -9,7 +9,7 @@ selection, including gaps, and saves a passage with optional text, privacy, and
highlight color. Reader sign-in requests Notes scopes. The reader refreshes
chapter highlights after a successful save.
-`'save'` is now a built-in action ID. TypeScript consumers that enumerate built-in
-actions should handle `'save'` alongside `'highlights'`, `'copy'`, and `'share'`.
+The configurable verse actions include the built-in IDs `'highlights'`, `'save'`,
+`'copy'`, and `'share'`. Include `'save'` in a custom action order to offer Notes.
`NotesClient` supports creating a passage-only note with empty `content`.
diff --git a/packages/core/src/Users.ts b/packages/core/src/Users.ts
index 1510c97e7..7c6dd501b 100644
--- a/packages/core/src/Users.ts
+++ b/packages/core/src/Users.ts
@@ -132,10 +132,9 @@ const clearOAuthHandoff = (storage: Storage | null): void => {
removeStorageItem(storage, REQUESTED_PERMISSIONS_KEY);
};
-function clearFailedRefreshSession(initialState: string | null) {
- const currentState = getLocalStorage()?.getItem(AUTH_STATE_KEY) ?? null;
- if (currentState && currentState !== initialState) {
- // A newer sign-in needs its PKCE handoff and the initiating profile.
+function clearFailedRefreshSession() {
+ if (getLocalStorage()?.getItem(AUTH_STATE_KEY)) {
+ // A pending sign-in needs its PKCE handoff and the initiating profile.
YouVersionPlatformConfiguration.saveAuthData(null, null, null);
} else {
YouVersionPlatformConfiguration.clearAuthTokens();
@@ -677,7 +676,6 @@ export class YouVersionAPIUsers {
const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
const oauthSession = YouVersionPlatformConfiguration.readOAuthSession();
const appKey = YouVersionPlatformConfiguration.appKey;
- const authState = getLocalStorage()?.getItem(AUTH_STATE_KEY) ?? null;
if (!refreshToken) {
throw new Error('No refresh token available');
@@ -755,7 +753,7 @@ export class YouVersionAPIUsers {
[accessToken, rotatedAccessToken].includes(config.accessToken) &&
[refreshToken, rotatedRefreshToken].includes(config.refreshToken)
) {
- clearFailedRefreshSession(authState);
+ clearFailedRefreshSession();
}
throw new Error('the rotated tokens could not be saved to browser storage');
}
@@ -827,7 +825,6 @@ export class YouVersionAPIUsers {
const accessToken = YouVersionPlatformConfiguration.accessToken;
const refreshToken = YouVersionPlatformConfiguration.refreshToken;
const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
- const authState = getLocalStorage()?.getItem(AUTH_STATE_KEY) ?? null;
if (YouVersionPlatformConfiguration.readOAuthSession() === null) return false;
try {
const result = await this.rotateTokens(true);
@@ -840,7 +837,7 @@ export class YouVersionAPIUsers {
YouVersionPlatformConfiguration.storedUserInfo?.id === userId &&
YouVersionPlatformConfiguration.readOAuthSession() !== null
) {
- clearFailedRefreshSession(authState);
+ clearFailedRefreshSession();
}
return false;
}
diff --git a/packages/core/src/YouVersionPlatformConfiguration.ts b/packages/core/src/YouVersionPlatformConfiguration.ts
index eb1cc8c8c..157819f6f 100644
--- a/packages/core/src/YouVersionPlatformConfiguration.ts
+++ b/packages/core/src/YouVersionPlatformConfiguration.ts
@@ -122,11 +122,24 @@ export class YouVersionPlatformConfiguration {
removeStorageItem(getLocalStorage(), 'youversion-auth-state');
}
- /** Returns an access token only for the specified account and granted OAuth scope. */
- public static getOAuthAccessToken(userId: string, scope: AuthenticationScopes): string | null {
+ /** Returns an account's current access token, verifying the scope or the unchanged legacy session. */
+ public static getOAuthAccessToken(
+ userId: string,
+ scope?: AuthenticationScopes,
+ legacySession?: Pick,
+ ): string | null {
const session = this.readOAuthSession();
- return session?.userId === userId && parsePermissionList(session.scope).includes(scope)
- ? session.accessToken
+ if (session) {
+ return session.userId === userId &&
+ (scope === undefined || parsePermissionList(session.scope).includes(scope))
+ ? session.accessToken
+ : null;
+ }
+ if (session === null || scope !== undefined || legacySession?.userId !== userId) return null;
+ return this.currentUserId === userId &&
+ this.accessToken === legacySession.accessToken &&
+ this.refreshToken === legacySession.refreshToken
+ ? legacySession.accessToken
: null;
}
@@ -134,7 +147,7 @@ export class YouVersionPlatformConfiguration {
public static readOAuthSession(): StoredOAuthSession | null | undefined {
const storage = getLocalStorage();
const raw = storage?.getItem('youversion-auth-scope');
- if (!raw) return undefined;
+ if (raw === null || raw === undefined) return undefined;
try {
const session = StoredOAuthSessionSchema.parse(JSON.parse(raw));
// A different tab may be partway through replacing the token or profile.
diff --git a/packages/core/src/__tests__/OAuthWorkflows.test.ts b/packages/core/src/__tests__/OAuthWorkflows.test.ts
index 5c36ca84f..8bccbccff 100644
--- a/packages/core/src/__tests__/OAuthWorkflows.test.ts
+++ b/packages/core/src/__tests__/OAuthWorkflows.test.ts
@@ -1,14 +1,16 @@
import { expect, it, onTestFinished, vi } from 'vitest';
+import { http, HttpResponse } from 'msw';
import { YouVersionAPIUsers } from '../Users';
import { YouVersionPlatformConfiguration as config } from '../YouVersionPlatformConfiguration';
import { setupBrowserMocks, cleanupBrowserMocks } from './mocks/browser';
+import { server } from './setup';
const redirect = 'https://example.com/callback';
-function createOAuthBrowser() {
+function createOAuthBrowser(transport: 'deferred' | 'msw' = 'deferred') {
const browser = setupBrowserMocks();
const fetch = vi.fn<(request: Request) => Promise>();
- vi.stubGlobal('fetch', fetch);
+ if (transport === 'deferred') vi.stubGlobal('fetch', fetch);
const previousAppKey = config.appKey;
const previousHost = config.apiHost;
config.appKey = 'test-app-key';
@@ -76,23 +78,29 @@ function tokenResponse(scope: string) {
return Response.json({ ...makeTokens(scope), access_token: 'signed-in-access' });
}
-it('keeps the account and newer authorization available when its older refresh fails', async () => {
+it.each([
+ { timing: 'before', signInFirst: true },
+ { timing: 'after', signInFirst: false },
+])('keeps an authorization that started $timing its failed refresh', async ({ signInFirst }) => {
const { browser, fetch, holdTokenResponse, arriveWithCode } = createOAuthBrowser();
config.saveAuthData('expired-access', 'old-refresh', new Date(0), {
scope: 'profile',
userId: 'alice',
});
config.saveUserInfo({ id: 'alice' });
+ if (signInFirst) await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
const finishRefresh = holdTokenResponse();
const refresh = YouVersionAPIUsers.refreshTokenIfNeeded();
expect(fetch).toHaveBeenCalled();
- await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+ if (!signInFirst) await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
finishRefresh(new Response(null, { status: 401 }));
await expect(refresh).resolves.toBe(false);
expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('alice');
+ expect(config.accessToken).toBeNull();
+ expect(config.refreshToken).toBeNull();
- arriveWithCode('grant-after-prior-refresh');
+ arriveWithCode(`grant-after-failed-refresh-${signInFirst}`);
browser.atob.mockReturnValue(JSON.stringify({ sub: 'alice' }));
fetch.mockResolvedValueOnce(tokenResponse('write_notes'));
await YouVersionAPIUsers.handleAuthCallback();
@@ -185,7 +193,7 @@ it.each([
);
it('requests note scopes at authorize and reads the grants from the exchanged token', async () => {
- const { browser, fetch, arriveWithCode } = createOAuthBrowser();
+ const { browser, fetch, values, arriveWithCode } = createOAuthBrowser();
const beforeRedirect = vi.fn(() => {
expect(browser.window.location.href).toBe('');
});
@@ -209,6 +217,20 @@ it('requests note scopes at authorize and reads the grants from the exchanged to
expect(beforeRedirect).toHaveBeenCalledWith(authorize.searchParams.get('state'));
expect(config.getOAuthAccessToken('1234567890', 'write_notes')).toBeNull();
+ const firstHop = new URL(redirect);
+ firstHop.searchParams.set('state', authorize.searchParams.get('state') ?? '');
+ firstHop.searchParams.set('granted_permissions', 'bibles');
+ browser.window.location = { href: firstHop.href, search: firstHop.search };
+ await expect(YouVersionAPIUsers.handleAuthCallback()).resolves.toBeNull();
+ expect(new URL(browser.window.location.href).pathname).toBe('/auth/callback');
+ const handoffKeys = [
+ 'youversion-auth-code-verifier',
+ 'youversion-auth-redirect-uri',
+ 'youversion-auth-state',
+ 'youversion-auth-pending-granted-permissions',
+ ];
+ for (const key of handoffKeys) expect(values.has(key)).toBe(true);
+
arriveWithCode('notes-code');
fetch.mockResolvedValueOnce(Response.json(makeTokens('openid profile read_notes write_notes')));
const result = await YouVersionAPIUsers.handleAuthCallback();
@@ -228,10 +250,11 @@ it('requests note scopes at authorize and reads the grants from the exchanged to
});
expect(browser.localStorage.getItem('idToken')).toBeNull();
expect(browser.window.history.replaceState).toHaveBeenCalledWith({}, '', redirect);
+ for (const key of handoffKeys) expect(values.has(key)).toBe(false);
expect(config.getOAuthAccessToken('1234567890', 'read_notes')).toBe('access-token-123');
expect(config.getOAuthAccessToken('1234567890', 'write_notes')).toBe('access-token-123');
- expect(config.grantedPermissions).toEqual(['highlights']);
+ expect(config.grantedPermissions).toEqual(['bibles', 'highlights']);
});
it('retains note scopes when rotation omits scope and replaces them when the response narrows it', async () => {
@@ -423,54 +446,49 @@ it('clears a partially written refresh session when storage rejects the rotated
});
it('rotates legacy tokens without assigning the returned scope to a stored profile', async () => {
- const { fetch } = createOAuthBrowser();
+ createOAuthBrowser('msw');
const originalAccessToken = 'old-access-token';
const originalRefreshToken = 'old-refresh-token';
config.saveAuthData(originalAccessToken, originalRefreshToken, null);
config.saveUserInfo({ id: 'legacy-user' });
- const mockRefreshResponse = {
- access_token: 'new-access-token',
- expires_in: 3600,
- refresh_token: 'new-refresh-token',
- scope: 'openid write_notes',
- token_type: 'Bearer',
- };
-
- const mockResponse = Response.json(mockRefreshResponse);
-
- fetch.mockResolvedValue(mockResponse);
+ const requests: Request[] = [];
+ if (process.env.INTEGRATION_TESTS) {
+ server.listen();
+ onTestFinished(() => {
+ server.resetHandlers();
+ server.close();
+ });
+ }
+ server.use(
+ http.all('*', ({ request }) => {
+ requests.push(request);
+ return HttpResponse.json({
+ access_token: 'new-access-token',
+ expires_in: 3600,
+ refresh_token: 'new-refresh-token',
+ scope: 'openid write_notes',
+ token_type: 'Bearer',
+ });
+ }),
+ );
const result = await YouVersionAPIUsers.refreshTokens();
- expect(result).toBeTruthy();
-
- // Assert that access_token and refresh_token are new (different from original)
expect(result?.accessToken).toBe('new-access-token');
- expect(result?.accessToken).not.toBe(originalAccessToken);
expect(result?.refreshToken).toBe('new-refresh-token');
- expect(result?.refreshToken).not.toBe(originalRefreshToken);
- // Verify the refresh token request was made correctly
- expect(fetch).toHaveBeenCalledTimes(1);
- expect(fetch).toHaveBeenCalledWith(
- expect.objectContaining({
- method: 'POST',
- url: 'https://api.youversion.com/auth/token',
- }),
- );
-
- const calledRequest = fetch.mock.calls[0]?.[0];
- expect(calledRequest).toBeInstanceOf(Request);
- if (!(calledRequest instanceof Request)) {
- throw new Error('expected fetch to be called with a Request');
- }
- expect(calledRequest.method).toBe('POST');
- expect(calledRequest.url).toBe('https://api.youversion.com/auth/token');
- expect(calledRequest.headers.get('content-type')).toBe('application/x-www-form-urlencoded');
- const bodyText = await calledRequest.clone().text();
- const body = new URLSearchParams(bodyText);
- expect(body.get('grant_type')).toBe('refresh_token');
+ expect(requests).toHaveLength(1);
+ const [request] = requests;
+ if (!request) throw new Error('Expected the token request');
+ expect(request.method).toBe('POST');
+ expect(request.url).toBe('https://api.youversion.com/auth/token');
+ expect(request.headers.get('content-type')).toBe('application/x-www-form-urlencoded');
+ expect(Object.fromEntries(new URLSearchParams(await request.text()))).toEqual({
+ grant_type: 'refresh_token',
+ refresh_token: originalRefreshToken,
+ client_id: 'test-app-key',
+ });
expect(config.accessToken).toBe('new-access-token');
expect(config.refreshToken).toBe('new-refresh-token');
diff --git a/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts b/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts
index 4e808e537..36d74f058 100644
--- a/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts
+++ b/packages/core/src/__tests__/YouVersionPlatformConfiguration.test.ts
@@ -106,6 +106,24 @@ describe('YouVersionPlatformConfiguration storage contracts', () => {
expect(YouVersionPlatformConfiguration.storedUserInfo).toBeNull();
});
+ it('accepts an unchanged legacy session only without a scope or OAuth record', () => {
+ const storage = getLocalStorage();
+ clearStorage(storage);
+ const config = YouVersionPlatformConfiguration;
+ const legacySession = { userId: 'legacy-user', accessToken: 'access', refreshToken: 'refresh' };
+ config.saveAuthData(legacySession.accessToken, legacySession.refreshToken, null);
+ config.saveUserInfo({ id: legacySession.userId });
+ expect(config.getOAuthAccessToken(legacySession.userId, undefined, legacySession)).toBe(
+ 'access',
+ );
+ expect(
+ config.getOAuthAccessToken(legacySession.userId, 'write_notes', legacySession),
+ ).toBeNull();
+
+ expect(setStorageItem(storage, 'youversion-auth-scope', '')).toBe(true);
+ expect(config.getOAuthAccessToken(legacySession.userId, undefined, legacySession)).toBeNull();
+ });
+
it('reports rejected storage writes and degrades safely when storage is unavailable', () => {
try {
vi.stubGlobal('localStorage', {
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx b/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx
index 40bae62b1..57fe1f4bc 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx
@@ -105,20 +105,56 @@ it('ignores a successful callback after another account has already replaced its
});
it.each([
- { name: 'OAuthCallbackSupersededError', superseded: true },
- { name: 'TypeError', superseded: false },
-])('reports whether a failed callback is obsolete after $name', async ({ name, superseded }) => {
- const error = Object.assign(new Error('Authorization failed'), { name });
- openCallback('?state=older-grant&code=older-code', () => Promise.reject(error));
- config.saveAuthData('active-access', 'active-refresh', null);
- config.saveUserInfo({ id: 'alice' });
+ {
+ scenario: 'a matched exchange fails',
+ name: 'TypeError',
+ pendingAtStart: true,
+ superseded: false,
+ recover: true,
+ },
+ {
+ scenario: 'a matched hosted denial returns',
+ name: 'Error',
+ pendingAtStart: true,
+ superseded: false,
+ recover: true,
+ },
+ {
+ scenario: 'the attempt is replaced during exchange',
+ name: 'OAuthCallbackSupersededError',
+ pendingAtStart: true,
+ superseded: true,
+ recover: false,
+ },
+ {
+ scenario: 'the attempt is already absent',
+ name: 'Error',
+ pendingAtStart: false,
+ superseded: false,
+ recover: false,
+ },
+])(
+ 'only identifies recoverable failures when $scenario',
+ async ({ name, pendingAtStart, superseded, recover }) => {
+ const error = Object.assign(new Error('Authorization failed'), { name });
+ const pending = vi.spyOn(YouVersionAPIUsers, 'isSignInPending').mockReturnValue(pendingAtStart);
+ onTestFinished(() => pending.mockRestore());
+ const query = name === 'Error' ? 'error=access_denied' : 'code=grant-code';
+ openCallback(`?state=older-grant&${query}`, () => {
+ pending.mockReturnValue(false);
+ return Promise.reject(error);
+ });
+ config.saveAuthData('active-access', 'active-refresh', null);
+ config.saveUserInfo({ id: 'alice' });
- const { result } = renderHook(useYouVersionAuthContext, { wrapper: AuthWrapper });
- await waitFor(() => expect(result.current.isLoading).toBe(false));
- expect(result.current.userInfo?.userId).toBe('alice');
- expect(result.current.oauthCallbackState).toBeNull();
- expect(result.current.oauthCallbackSuperseded).toBe(superseded);
-});
+ const { result } = renderHook(useYouVersionAuthContext, { wrapper: AuthWrapper });
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.userInfo?.userId).toBe('alice');
+ expect(result.current.oauthCallbackState).toBeNull();
+ expect(result.current.oauthCallbackSuperseded).toBe(superseded);
+ expect(result.current.oauthFailedCallbackState).toBe(recover ? 'older-grant' : null);
+ },
+);
it('keeps the account synced from another tab when the previous account refresh fails', async () => {
config.saveAuthData('old-access-token', 'old-refresh-token', new Date(0));
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.tsx b/packages/hooks/src/context/YouVersionAuthProvider.tsx
index debb968c3..68208c4a8 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.tsx
@@ -24,6 +24,12 @@ interface YouVersionAuthProviderProps {
children: ReactNode;
}
+function getCredentialedUserInfo() {
+ return YouVersionPlatformConfiguration.accessToken || YouVersionPlatformConfiguration.refreshToken
+ ? YouVersionAPIUsers.getStoredUserInfo()
+ : null;
+}
+
export default function YouVersionAuthProvider({
config,
userInfo: controlledUserInfo,
@@ -34,7 +40,13 @@ export default function YouVersionAuthProvider({
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [oauthCallbackState, setOAuthCallbackState] = useState(null);
+ const [oauthFailedCallbackState, setOAuthFailedCallbackState] = useState(null);
const [oauthCallbackSuperseded, setOAuthCallbackSuperseded] = useState(false);
+ const [legacySession, setLegacySession] = useState<{
+ userId: string;
+ accessToken: string;
+ refreshToken: string;
+ } | null>(null);
useEffect(() => {
if (!isHostControlled) return;
@@ -54,18 +66,15 @@ export default function YouVersionAuthProvider({
if (globalThis.window) {
// Check for OAuth callback
const urlParams = new URLSearchParams(globalThis.window.location.search);
+ const state = urlParams.get('state');
const isOAuthCallback = urlParams.has('state') || urlParams.has('error');
if (isOAuthCallback) {
+ const pendingState = state && YouVersionAPIUsers.isSignInPending(state) ? state : null;
try {
const result = await YouVersionAPIUsers.handleAuthCallback();
// A verified state-only callback has already navigated to obtain the code.
- if (
- !result &&
- urlParams.get('state') &&
- !urlParams.get('code') &&
- !urlParams.has('error')
- ) {
+ if (!result && state && !urlParams.get('code') && !urlParams.get('error')) {
return;
}
if (result) {
@@ -75,7 +84,7 @@ export default function YouVersionAuthProvider({
storedUser?.userId === result.yvpUserId &&
result.accessToken === YouVersionPlatformConfiguration.accessToken;
if (!sessionChanged || callbackMatchesSession) setUserInfo(storedUser);
- if (callbackMatchesSession) setOAuthCallbackState(urlParams.get('state'));
+ if (callbackMatchesSession) setOAuthCallbackState(state);
else if (sessionChanged) setOAuthCallbackSuperseded(true);
}
} catch (err) {
@@ -85,22 +94,29 @@ export default function YouVersionAuthProvider({
console.error('Auth callback failed:', error);
}
if (error.name === 'OAuthCallbackSupersededError') setOAuthCallbackSuperseded(true);
+ else setOAuthFailedCallbackState(pendingState);
if (!sessionChanged) {
setError(error);
- setUserInfo(YouVersionAPIUsers.getStoredUserInfo());
+ setUserInfo(getCredentialedUserInfo());
}
}
} else {
// Check for existing token
const refreshToken = YouVersionPlatformConfiguration.refreshToken;
if (refreshToken) {
+ const accessToken = YouVersionPlatformConfiguration.accessToken;
+ const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
try {
// refreshTokenIfNeeded clears tokens (and the stored profile)
// when the session has expired and cannot be refreshed.
const refreshed = await YouVersionAPIUsers.refreshTokenIfNeeded();
if (!mounted) return;
if (!sessionChanged) {
- setUserInfo(refreshed ? YouVersionAPIUsers.getStoredUserInfo() : null);
+ const storedUser = refreshed ? YouVersionAPIUsers.getStoredUserInfo() : null;
+ setUserInfo(storedUser);
+ if (accessToken && userId && storedUser?.userId === userId) {
+ setLegacySession({ userId, accessToken, refreshToken });
+ }
}
} catch {
if (!mounted) return;
@@ -126,8 +142,10 @@ export default function YouVersionAuthProvider({
return;
}
sessionChanged = true;
+ setLegacySession(null);
setOAuthCallbackState(null);
- setUserInfo(YouVersionAPIUsers.getStoredUserInfo());
+ setOAuthFailedCallbackState(null);
+ setUserInfo(getCredentialedUserInfo());
}
globalThis.window?.addEventListener?.('storage', syncSession);
@@ -144,7 +162,16 @@ export default function YouVersionAuthProvider({
isLoading,
error,
redirectUri: config.redirectUri,
+ accessToken:
+ !isHostControlled && userInfo?.userId
+ ? YouVersionPlatformConfiguration.getOAuthAccessToken(
+ userInfo.userId,
+ undefined,
+ legacySession ?? undefined,
+ )
+ : null,
oauthCallbackState,
+ oauthFailedCallbackState,
oauthCallbackSuperseded,
isHostControlled,
};
diff --git a/packages/hooks/src/types/auth.ts b/packages/hooks/src/types/auth.ts
index 1f5719bd9..5ba566804 100644
--- a/packages/hooks/src/types/auth.ts
+++ b/packages/hooks/src/types/auth.ts
@@ -13,8 +13,12 @@ export interface AuthContextValue {
isLoading: boolean;
error: Error | null;
redirectUri?: string;
+ /** Access token checked against the current account in the SDK-managed provider. */
+ accessToken?: string | null;
/** State of the verified OAuth callback handled by this provider. */
oauthCallbackState?: string | null;
+ /** State of a failed OAuth callback that matched the pending authorization attempt. */
+ oauthFailedCallbackState?: string | null;
/** Whether the OAuth callback was replaced by another authorization attempt or session. */
oauthCallbackSuperseded?: boolean;
/** Whether the host supplied the profile and owns sign-in. */
diff --git a/packages/hooks/src/useApiData.ts b/packages/hooks/src/useApiData.ts
index 90a5224ef..a4dca8c02 100644
--- a/packages/hooks/src/useApiData.ts
+++ b/packages/hooks/src/useApiData.ts
@@ -47,9 +47,9 @@ type UseApiDataResult = {
export function useApiData(
queryKey: readonly unknown[],
fetchFn: () => Promise,
- options: UseApiDataOptions = {},
+ options: UseApiDataOptions & { restartInitialFetchOnRefetch?: boolean } = {},
): UseApiDataResult {
- const { enabled = true, keepPreviousData = true } = options;
+ const { enabled = true, keepPreviousData = true, restartInitialFetchOnRefetch } = options;
const queryClient = useInternalQueryClient();
// The client goes to `useQuery` as an explicit argument, so this hook never
@@ -79,8 +79,19 @@ export function useApiData(
// When a component remounts, invalidation still updates the cache.
// `query.refetch()` calls an observer that is no longer active.
const refetch = useCallback(() => {
- void queryClient.invalidateQueries({ queryKey: queryKeyRef.current, exact: true });
- }, [queryClient]);
+ const filters = { queryKey: queryKeyRef.current, exact: true };
+ const state = restartInitialFetchOnRefetch
+ ? queryClient.getQueryState(filters.queryKey)
+ : undefined;
+ if (state?.fetchStatus === 'fetching' && state.data === undefined) {
+ // Invalidation alone reuses an in-flight first fetch, which may predate the write.
+ void queryClient
+ .cancelQueries({ ...filters, type: 'active' })
+ .then(() => queryClient.invalidateQueries(filters));
+ return;
+ }
+ void queryClient.invalidateQueries(filters);
+ }, [queryClient, restartInitialFetchOnRefetch]);
// If `enabled` is false, `data` and `error` are `null`.
// The cache can still hold a value.
diff --git a/packages/hooks/src/useCreateNote.test.tsx b/packages/hooks/src/useCreateNote.test.tsx
new file mode 100644
index 000000000..f58a70ce0
--- /dev/null
+++ b/packages/hooks/src/useCreateNote.test.tsx
@@ -0,0 +1,26 @@
+import { renderHook } from '@testing-library/react';
+import { NotesClient, type CreateNote } from '@youversion/platform-core';
+import { expect, it, onTestFinished, vi } from 'vitest';
+import { createYVWrapper } from './test/utils';
+import { useCreateNote } from './useCreateNote';
+
+it('requires a captured access token before calling the Notes client', async () => {
+ const note: CreateNote = {
+ request_id: 'e6decb7a-f5eb-46ed-ab2d-afc43039e7e4',
+ status: 'private',
+ content: 'My note',
+ };
+ const saved = { id: 'test-note', content: note.content, status: note.status };
+ const create = vi.spyOn(NotesClient.prototype, 'createNote').mockResolvedValue(saved);
+ onTestFinished(() => create.mockRestore());
+ const { result } = renderHook(useCreateNote, { wrapper: createYVWrapper() });
+
+ await expect(result.current(note, '')).rejects.toThrow('access token');
+ await expect(result.current(note, ' ')).rejects.toThrow('access token');
+ // @ts-expect-error -- JavaScript callers can omit the token.
+ await expect(result.current(note)).rejects.toThrow('access token');
+ expect(create).not.toHaveBeenCalled();
+
+ await expect(result.current(note, 'captured-token')).resolves.toEqual(saved);
+ expect(create).toHaveBeenCalledExactlyOnceWith(note, 'captured-token');
+});
diff --git a/packages/hooks/src/useCreateNote.ts b/packages/hooks/src/useCreateNote.ts
index b31007c95..5ac205328 100644
--- a/packages/hooks/src/useCreateNote.ts
+++ b/packages/hooks/src/useCreateNote.ts
@@ -8,5 +8,11 @@ import { useApiClient } from './internal/useApiClient';
export function useCreateNote(): (note: CreateNote, accessToken: string) => Promise {
const apiClient = useApiClient();
const client = useMemo(() => new NotesClient(apiClient), [apiClient]);
- return useCallback((note, accessToken) => client.createNote(note, accessToken), [client]);
+ return useCallback(
+ async (note, accessToken) => {
+ if (!accessToken?.trim()) throw new Error('An access token is required to create a note');
+ return client.createNote(note, accessToken);
+ },
+ [client],
+ );
}
diff --git a/packages/hooks/src/useHighlights.ts b/packages/hooks/src/useHighlights.ts
index d96d2205b..c56157d5e 100644
--- a/packages/hooks/src/useHighlights.ts
+++ b/packages/hooks/src/useHighlights.ts
@@ -65,6 +65,7 @@ export function useHighlights(
// key change would show one account's highlights to another during an
// account switch, so this hook always drops to `null` instead.
keepPreviousData: false,
+ restartInitialFetchOnRefetch: true,
},
);
diff --git a/packages/hooks/src/useYVAuth.test.tsx b/packages/hooks/src/useYVAuth.test.tsx
index 0d984816a..c4968d468 100644
--- a/packages/hooks/src/useYVAuth.test.tsx
+++ b/packages/hooks/src/useYVAuth.test.tsx
@@ -1,7 +1,7 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { YouVersionAPIUsers, YouVersionPlatformConfiguration } from '@youversion/platform-core';
import type { ReactNode } from 'react';
-import { expect, it, vi } from 'vitest';
+import { expect, it, onTestFinished, vi } from 'vitest';
import { createMockAuthResult, createMockUserInfo } from './__tests__/mocks/auth';
import { YouVersionAuthContext } from './context/YouVersionAuthContext';
import { YouVersionProvider } from './context/YouVersionProvider';
@@ -24,6 +24,18 @@ function wrapperWith(redirectUri?: string, setUserInfo = vi.fn()) {
);
}
+function WebAuthWrapper({ children }: { children: ReactNode }) {
+ return (
+
+ {children}
+
+ );
+}
+
it('requires the auth provider boundary', () => {
expect(() => renderHook(() => useYVAuth())).toThrow(
'useYouVersionAuthContext must be used within an auth provider',
@@ -65,6 +77,138 @@ it('derives authentication, loading, token, and error state from its boundaries'
accessToken.mockRestore();
});
+it('pairs a managed access token only with the matching profile across storage updates', async () => {
+ const config = YouVersionPlatformConfiguration;
+ YouVersionAPIUsers.signOut();
+ onTestFinished(() => YouVersionAPIUsers.signOut());
+ const expires = new Date('2100-01-01');
+ config.saveAuthData('alice-access', 'alice-refresh', expires, {
+ scope: 'profile',
+ userId: 'alice',
+ });
+ config.saveUserInfo({ id: 'alice' });
+ const { result } = renderHook(useYVAuth, { wrapper: WebAuthWrapper });
+ await waitFor(() => expect(result.current.userInfo?.userId).toBe('alice'));
+ expect(result.current.auth.accessToken).toBe('alice-access');
+
+ act(() => {
+ config.saveAuthData('bob-access', 'bob-refresh', expires, {
+ scope: 'profile',
+ userId: 'bob',
+ });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'accessToken', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('alice');
+ expect(result.current.auth.accessToken).toBeNull();
+
+ act(() => {
+ config.saveUserInfo({ id: 'bob' });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('bob');
+ expect(result.current.auth.accessToken).toBe('bob-access');
+
+ act(() => {
+ YouVersionAPIUsers.signOut();
+ window.dispatchEvent(new StorageEvent('storage', { storageArea: localStorage }));
+ });
+ expect(result.current.userInfo).toBeNull();
+ expect(result.current.auth.accessToken).toBeNull();
+});
+
+it('keeps an initial legacy token without adopting later unbound credentials', async () => {
+ const config = YouVersionPlatformConfiguration;
+ YouVersionAPIUsers.signOut();
+ onTestFinished(() => YouVersionAPIUsers.signOut());
+ const expires = new Date('2100-01-01');
+ config.saveAuthData('legacy-access', 'legacy-refresh', expires);
+ config.saveUserInfo({ id: 'legacy-alice' });
+
+ const { result } = renderHook(useYVAuth, { wrapper: WebAuthWrapper });
+ await waitFor(() => expect(result.current.auth.isLoading).toBe(false));
+ expect(result.current.userInfo?.userId).toBe('legacy-alice');
+ expect(result.current.auth.accessToken).toBe('legacy-access');
+ expect(config.getOAuthAccessToken('legacy-alice', 'write_notes')).toBeNull();
+
+ act(() => {
+ config.saveAuthData('new-access', 'new-refresh', expires);
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'accessToken', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('legacy-alice');
+ expect(result.current.auth.accessToken).toBeNull();
+
+ act(() => {
+ config.saveUserInfo({ id: 'legacy-bob' });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('legacy-bob');
+ expect(result.current.auth.accessToken).toBeNull();
+
+ act(() => {
+ config.saveAuthData('bound-access', 'bound-refresh', expires, {
+ scope: 'profile',
+ userId: 'legacy-bob',
+ });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'accessToken', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.auth.accessToken).toBe('bound-access');
+});
+
+it('keeps a pending authorization profile signed out on remount and storage updates', async () => {
+ YouVersionAPIUsers.signOut();
+ onTestFinished(() => YouVersionAPIUsers.signOut());
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'pending-alice' });
+ localStorage.setItem('youversion-auth-state', 'pending-note-authorization');
+
+ const { result } = renderHook(useYVAuth, { wrapper: WebAuthWrapper });
+ await waitFor(() => expect(result.current.auth.isLoading).toBe(false));
+ expect(result.current.auth.isAuthenticated).toBe(false);
+ expect(result.current.userInfo).toBeNull();
+ expect(result.current.auth.accessToken).toBeNull();
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('pending-alice');
+ expect(YouVersionAPIUsers.isSignInPending('pending-note-authorization')).toBe(true);
+
+ act(() => {
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'accessToken', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.auth.isAuthenticated).toBe(false);
+ expect(result.current.userInfo).toBeNull();
+ expect(result.current.auth.accessToken).toBeNull();
+});
+
+it('reads the raw token for a host-controlled provider without a profile', async () => {
+ YouVersionAPIUsers.signOut();
+ onTestFinished(() => YouVersionAPIUsers.signOut());
+ YouVersionPlatformConfiguration.saveAuthData('host-access', null, null);
+ const wrapper = ({ children }: { children: ReactNode }) => (
+
+ {children}
+
+ );
+
+ const { result } = renderHook(useYVAuth, { wrapper });
+ await waitFor(() => expect(result.current.auth.isLoading).toBe(false));
+ expect(result.current.userInfo).toBeNull();
+ expect(result.current.auth.accessToken).toBe('host-access');
+});
+
it('forwards scopes and permissions while honoring an explicit redirect URL', async () => {
const signIn = vi.spyOn(YouVersionAPIUsers, 'signIn').mockResolvedValue(undefined);
const { result } = renderHook(() => useYVAuth(), { wrapper: wrapperWith('https://default') });
diff --git a/packages/hooks/src/useYVAuth.ts b/packages/hooks/src/useYVAuth.ts
index 5c7f409da..f9f6eb301 100644
--- a/packages/hooks/src/useYVAuth.ts
+++ b/packages/hooks/src/useYVAuth.ts
@@ -119,18 +119,24 @@ export interface UseYVAuthReturn {
*/
export function useYVAuth(): UseYVAuthReturn {
// Get auth state from provider context
- const { userInfo, setUserInfo, isLoading, error, redirectUri } = useYouVersionAuthContext();
+ const {
+ userInfo,
+ setUserInfo,
+ isLoading,
+ error,
+ redirectUri,
+ isHostControlled,
+ accessToken: managedAccessToken,
+ } = useYouVersionAuthContext();
// Derive authentication state
const isAuthenticated = !!userInfo;
- // Get current tokens for actions
- const authTokens = useMemo(
- () => ({
- accessToken: YouVersionPlatformConfiguration.accessToken,
- }),
- [],
+ const rawAccessToken = useMemo(
+ () => (isHostControlled === false ? null : YouVersionPlatformConfiguration.accessToken),
+ [isHostControlled],
);
+ const accessToken = isHostControlled === false ? (managedAccessToken ?? null) : rawAccessToken;
// Sign in function
const signIn = useCallback(
@@ -158,11 +164,11 @@ export function useYVAuth(): UseYVAuthReturn {
() => ({
isAuthenticated,
isLoading,
- accessToken: authTokens.accessToken,
+ accessToken,
result: null,
error,
}),
- [isAuthenticated, isLoading, authTokens.accessToken, error],
+ [isAuthenticated, isLoading, accessToken, error],
);
// Sign out function
diff --git a/packages/ui/scripts/smoke-vite-reader-notes.mjs b/packages/ui/scripts/smoke-vite-reader-notes.mjs
index dbb0866fc..1284bce27 100644
--- a/packages/ui/scripts/smoke-vite-reader-notes.mjs
+++ b/packages/ui/scripts/smoke-vite-reader-notes.mjs
@@ -72,7 +72,7 @@ await context.route(`${api}/**`, async (route) => {
const state = url.searchParams.get('state');
const destination = intermediateReturns.get(state);
assert.ok(destination, 'Expected the state-only OAuth hop');
- intermediateReturns.delete(state);
+ // Strict Mode can initiate this navigation again before the browser leaves.
return navigate(destination);
}
case '/auth/token': {
@@ -152,7 +152,7 @@ const readerScopes = ['openid', 'profile', 'read_notes', 'write_notes'];
const navbarScopes = ['openid', 'profile', 'email'];
try {
- await page.goto(app);
+ await page.goto(app, { waitUntil: 'domcontentloaded' });
await selectVerses(page, [4, 1]);
await beginNote(page);
await page
@@ -200,7 +200,7 @@ try {
// Alice's old authorization comes back after Bob replaces her session in another tab.
const other = await context.newPage();
- await other.goto(app);
+ await other.goto(app, { waitUntil: 'domcontentloaded' });
await signedInAs(other, 'Alice').waitFor();
await beginNote(page);
const releaseOld = Promise.withResolvers();
diff --git a/packages/ui/src/components/bible-reader-notes-composer.tsx b/packages/ui/src/components/bible-reader-notes-composer.tsx
index 22424613c..d7ffed10b 100644
--- a/packages/ui/src/components/bible-reader-notes-composer.tsx
+++ b/packages/ui/src/components/bible-reader-notes-composer.tsx
@@ -19,6 +19,7 @@ type NotesComposerProps = {
onSave: () => void;
onDismiss: () => void;
theme: 'light' | 'dark';
+ restoreFocusTarget: HTMLElement | null;
};
export function BibleReaderNotesComposer({
@@ -29,11 +30,13 @@ export function BibleReaderNotesComposer({
onSave,
onDismiss,
theme,
+ restoreFocusTarget,
}: NotesComposerProps): ReactElement {
const { t } = useTranslation(undefined, { i18n });
const visibilityName = useId();
const discardDescriptionId = useId();
const formRef = useRef(null);
+ const editorRef = useRef(null);
const stayButtonRef = useRef(null);
const focusBeforeDiscard = useRef(null);
const [confirmDiscard, setConfirmDiscard] = useState(false);
@@ -76,7 +79,12 @@ export function BibleReaderNotesComposer({
>
{
+ event.preventDefault();
+ editorRef.current?.focus({ preventScroll: true });
+ }}
className="yv:box-border yv:max-h-[calc(100dvh-2rem)] yv:max-w-md yv:overflow-y-auto"
>
@@ -96,6 +104,7 @@ export function BibleReaderNotesComposer({
}}
>
('button[aria-label="Settings"]');
+ if (!settings) throw new Error('Reader settings control is missing');
+ settings.focus();
await selectVerses(root, [2]);
const { overlays, composer } = await openComposer(root, 'John 1:2');
const editor = composer.getByRole('textbox', { name: 'Add Note…' });
+ await waitFor(() => expect(root.activeElement).toBe(editor));
const colors = within(composer.getByRole('group', { name: 'Highlight colors' }));
const palette = ['ffec5b', 'b4ffc1', 'bbf4ff', 'ffdca7', 'ffcff8', 'dfdcff'];
const colorName = (color: string) => `Apply highlight #${color}`;
@@ -265,6 +270,7 @@ export const EditAndRetry: Story = {
await fillEditor(editor, 'Edited thought');
await userEvent.click(composer.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ await waitFor(() => expect(root.activeElement).toBe(settings));
const common = {
request_id: expect.stringMatching(/^[\da-f-]{36}$/i),
@@ -369,7 +375,8 @@ const storyNavigation = z.instanceof(BibleReaderNavigation);
export const BuiltInActionsDuringNavigation: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
- loaders: [async () => ({ hostNavigation: new BibleReaderNavigation() })],
+ loaders: [prepareCallback, async () => ({ hostNavigation: new BibleReaderNavigation() })],
+ parameters: writableSession,
render: (_args, { loaded }) => (
),
- play: async ({ canvasElement, loaded }) => {
+ play: withWritableSession(async ({ canvasElement, loaded }) => {
const chapterRequested = deferred();
const returnChapter = deferred();
getWorker().use(
@@ -395,11 +402,14 @@ export const BuiltInActionsDuringNavigation: Story = {
);
const root = await waitForShadowRoot(canvasElement);
const retainedVerse = await readerVerse(root, 1);
+ await userEvent.click(retainedVerse);
+ const overlays = await readerOverlays(root);
+ const activeActions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await waitFor(() => expect(activeActions.getByRole('button', { name: 'Save' })).toBeVisible());
storyNavigation.parse(loaded.hostNavigation).request({ versionId: 111, passageId: 'JHN.3' });
await chapterRequested.promise;
try {
await userEvent.click(retainedVerse);
- const overlays = await readerOverlays(root);
const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
await waitFor(() => expect(actions.getByRole('button', { name: 'Copy' })).toBeVisible());
await expect(actions.getByRole('button', { name: 'Share' })).toBeVisible();
@@ -407,7 +417,7 @@ export const BuiltInActionsDuringNavigation: Story = {
} finally {
returnChapter.resolve();
}
- },
+ }),
};
export const RefreshDisplayedChapterAfterNavigation: Story = {
@@ -430,6 +440,7 @@ export const RefreshDisplayedChapterAfterNavigation: Story = {
const root = await waitForShadowRoot(canvasElement);
const noteSent = deferred();
const releaseNote = deferred();
+ const releaseFirstRead = deferred();
const chapterReads: string[] = [];
getWorker().use(
http.post('*/v1/notes', async ({ request }) => {
@@ -438,9 +449,16 @@ export const RefreshDisplayedChapterAfterNavigation: Story = {
await releaseNote.promise;
return noteResponse(note);
}),
- http.get('*/v1/highlights', ({ request }) => {
+ http.get('*/v1/highlights', async ({ request }) => {
const { searchParams } = new URL(request.url);
- chapterReads.push(`${searchParams.get('bible_id')}:${searchParams.get('passage_id')}`);
+ const scope = `${searchParams.get('bible_id')}:${searchParams.get('passage_id')}`;
+ if (scope === '111:JHN.3') {
+ chapterReads.push(scope);
+ if (chapterReads.length > 1) {
+ return highlightPage({ ...green, passage_id: 'JHN.3.16' });
+ }
+ await releaseFirstRead.promise;
+ }
return HttpResponse.json({ data: [], next_page_token: null });
}),
);
@@ -452,13 +470,81 @@ export const RefreshDisplayedChapterAfterNavigation: Story = {
passage_id: 'JHN.1.2',
});
- storyNavigation.parse(loaded.hostNavigation).request({ versionId: 111, passageId: 'JHN.3' });
- await waitFor(() => expect(chapterReads).toContain('111:JHN.3'));
- await expect(overlays.getByRole('dialog', { name: 'John 1:2' })).toBeVisible();
- chapterReads.length = 0;
- releaseNote.resolve();
- await waitFor(() => expect(chapterReads).toEqual(['111:JHN.3']));
- await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ try {
+ storyNavigation.parse(loaded.hostNavigation).request({ versionId: 111, passageId: 'JHN.3' });
+ await readerVerse(root, 16);
+ await waitFor(() => expect(chapterReads).toEqual(['111:JHN.3']));
+ await expect(overlays.getByRole('dialog', { name: 'John 1:2' })).toBeVisible();
+ releaseNote.resolve();
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ releaseFirstRead.resolve();
+ await waitFor(() => expect(chapterReads).toEqual(['111:JHN.3', '111:JHN.3']));
+ await waitFor(async () =>
+ expect(getBackgroundColorChannels(await readerVerse(root, 16))).toEqual([
+ 180, 255, 193, 255,
+ ]),
+ );
+ } finally {
+ releaseNote.resolve();
+ releaseFirstRead.resolve();
+ }
+ }),
+};
+
+export const RefreshRetainedChapterWhileNavigationLoads: Story = {
+ ...RefreshDisplayedChapterAfterNavigation,
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ play: withWritableSession(async ({ canvasElement, loaded }) => {
+ const root = await waitForShadowRoot(canvasElement);
+ const noteSent = deferred();
+ const releaseNote = deferred();
+ const chapterRequested = deferred();
+ const releaseChapter = deferred();
+ const postSaveReads: string[] = [];
+ let noteSaved = false;
+ getWorker().use(
+ http.post('*/v1/notes', async ({ request }) => {
+ const body = await request.json();
+ noteSent.resolve();
+ await releaseNote.promise;
+ noteSaved = true;
+ return noteResponse(body);
+ }),
+ http.get('*/v1/bibles/111/passages/JHN.3', async () => {
+ chapterRequested.resolve();
+ await releaseChapter.promise;
+ return HttpResponse.json(mockPassages['JHN.3']);
+ }),
+ http.get('*/v1/highlights', ({ request }) => {
+ const scope = new URL(request.url).searchParams.get('passage_id') ?? '';
+ if (noteSaved) postSaveReads.push(scope);
+ return scope === 'JHN.1'
+ ? highlightPage(noteSaved ? green : yellow)
+ : HttpResponse.json({ data: [], next_page_token: null });
+ }),
+ );
+ const retained = await readerVerse(root, 1);
+ await selectVerses(root, [2]);
+ const { overlays, composer } = await openComposer(root, 'John 1:2');
+ try {
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await noteSent.promise;
+ storyNavigation.parse(loaded.hostNavigation).request({ versionId: 111, passageId: 'JHN.3' });
+ await chapterRequested.promise;
+ await expect(retained).toBeVisible();
+ releaseNote.resolve();
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ await waitFor(() =>
+ expect(getBackgroundColorChannels(retained)).toEqual([180, 255, 193, 255]),
+ );
+ await expect(postSaveReads).toEqual(['JHN.1']);
+ releaseChapter.resolve();
+ await waitFor(async () => expect(await readerVerse(root, 16)).toBeVisible());
+ await waitFor(() => expect(postSaveReads).toEqual(['JHN.1', 'JHN.3']));
+ } finally {
+ releaseNote.resolve();
+ releaseChapter.resolve();
+ }
}),
};
@@ -487,9 +573,9 @@ export const WritePermissionChangesWhileEditing: Story = {
await expect(await overlays.findByRole('button', { name: 'Yes Please' })).toBeInTheDocument();
await expect(creates).toBe(0);
await userEvent.click(overlays.getByRole('button', { name: 'No Thanks' }));
- await expect(await overlays.findByRole('textbox', { name: 'Add Note…' })).toHaveValue(
- 'Retained thought',
- );
+ const editor = await overlays.findByRole('textbox', { name: 'Add Note…' });
+ await expect(editor).toHaveValue('Retained thought');
+ await waitFor(() => expect(root.activeElement).toBe(editor));
const signIn = stayOnAuthorizationHandoff();
try {
@@ -530,6 +616,149 @@ export const WritePermissionChangesWhileEditing: Story = {
}),
};
+function ReloadableReader({ withCallback = false }: { withCallback?: boolean }) {
+ const [pageVersion, setPageVersion] = useState(0);
+ return (
+ <>
+ setPageVersion((version) => version + 1)}>
+ Reload Reader
+
+ {withCallback && (
+ {
+ const state = localStorage.getItem('youversion-auth-state');
+ if (!state) throw new Error('Reader did not start an OAuth handoff');
+ stageCallback(state);
+ setPageVersion((version) => version + 1);
+ }}
+ >
+ Return from sign-in
+
+ )}
+
+
+
+
+
+
+
+ >
+ );
+}
+
+export const RemountDropsDraftFromReplacedSession: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ loaders: [prepareCallback],
+ parameters: { ...writableSession, includeAuth: false },
+ render: () => ,
+ play: withWritableSession(async ({ canvasElement }) => {
+ const root = await waitForShadowRoot(canvasElement);
+ await selectVerses(root, [1, 4]);
+ const { overlays, composer } = await openComposer(root, 'John 1:1,4');
+ await fillEditor(
+ composer.getByRole('textbox', { name: 'Add Note…' }),
+ 'A draft from the original session',
+ );
+ getWorker().use(http.post('*/auth/token', () => tokenResponse('profile read_notes')));
+ await YouVersionAPIUsers.refreshTokens();
+ const signIn = stayOnAuthorizationHandoff();
+ try {
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await userEvent.click(await overlays.findByRole('button', { name: 'Yes Please' }));
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ const profile = YouVersionPlatformConfiguration.storedUserInfo;
+ if (!profile?.id) throw new Error('Missing initial Reader account');
+ YouVersionAPIUsers.signOut();
+ YouVersionPlatformConfiguration.saveAuthData(
+ 'new-access',
+ 'new-refresh',
+ new Date(Date.now() + 3_600_000),
+ { userId: profile.id, scope: 'profile read_notes write_notes' },
+ );
+ YouVersionPlatformConfiguration.saveUserInfo(profile);
+
+ await userEvent.click(within(canvasElement).getByRole('button', { name: 'Reload Reader' }));
+ const remounted = await waitForShadowRoot(canvasElement);
+ await expect(remounted).not.toBe(root);
+ await expect(await readerVerse(remounted, 1)).not.toHaveClass('yv-v-selected');
+ await expect(await readerVerse(remounted, 4)).not.toHaveClass('yv-v-selected');
+ await selectVerses(remounted, [1, 4]);
+ const { composer: fresh } = await openComposer(remounted, 'John 1:1,4');
+ await expect(fresh.getByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
+ } finally {
+ signIn.mockRestore();
+ }
+ }),
+};
+
+export const RemountRecoversDraftDuringFailedRefresh: Story = {
+ ...RemountDropsDraftFromReplacedSession,
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ render: () => ,
+ play: withWritableSession(async ({ canvasElement }) => {
+ const page = within(canvasElement);
+ const root = await waitForShadowRoot(canvasElement);
+ await selectVerses(root, [1, 4]);
+ const { overlays, composer } = await openComposer(root, 'John 1:1,4');
+ const draftText = 'A draft held while the session refreshes';
+ await fillEditor(
+ composer.getByRole('textbox', { name: 'Add Note…' }),
+ draftText,
+ );
+ getWorker().use(http.post('*/auth/token', () => tokenResponse('profile read_notes')));
+ await YouVersionAPIUsers.refreshTokens();
+ const signIn = stayOnAuthorizationHandoff();
+ try {
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await userEvent.click(await overlays.findByRole('button', { name: 'Yes Please' }));
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ const profile = YouVersionPlatformConfiguration.storedUserInfo;
+ if (!profile?.id) throw new Error('Missing initial Reader account');
+ YouVersionPlatformConfiguration.saveAuthData(
+ 'notes-story-token',
+ 'notes-story-refresh',
+ new Date(0),
+ {
+ userId: profile.id,
+ scope: 'profile read_notes',
+ },
+ );
+ getWorker().use(http.post('*/auth/token', () => new HttpResponse(null, { status: 503 })));
+ await userEvent.click(page.getByRole('button', { name: 'Reload Reader' }));
+ const remounted = await waitForShadowRoot(canvasElement);
+ await expect(remounted).not.toBe(root);
+ const returnedOverlays = await readerOverlays(remounted);
+ const actions = within(
+ await returnedOverlays.findByRole('dialog', { name: 'Verse actions' }),
+ );
+ await expect(await readerVerse(remounted, 1)).toHaveClass('yv-v-selected');
+ await expect(await readerVerse(remounted, 4)).toHaveClass('yv-v-selected');
+ await userEvent.click(actions.getByRole('button', { name: 'Save' }));
+ await userEvent.click(await returnedOverlays.findByRole('button', { name: 'Yes Please' }));
+ await waitFor(() => expect(returnedOverlays.queryByRole('dialog')).toBeNull());
+
+ getWorker().use(
+ http.post('*/auth/token', () => tokenResponse('profile read_notes write_notes')),
+ );
+ await userEvent.click(page.getByRole('button', { name: 'Return from sign-in' }));
+ const finalRoot = await waitForShadowRoot(canvasElement);
+ const finalOverlays = await readerOverlays(finalRoot);
+ const returned = within(await finalOverlays.findByRole('dialog', { name: 'John 1:1,4' }));
+ await expect(returned.getByRole('textbox', { name: 'Add Note…' })).toHaveValue(draftText);
+ } finally {
+ signIn.mockRestore();
+ }
+ }),
+};
+
function stayOnAuthorizationHandoff() {
// Simulate sign-in handing off to OAuth without replacing the Reader document.
// The SampleApp smoke exercises the actual redirect and token exchange.
@@ -667,6 +896,51 @@ export const NoBuiltInAuth: Story = {
},
};
+export const HostControlledSignIn: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ parameters: { includeAuth: false },
+ render: () => (
+
+
+
+
+
+
+
+
+ ),
+ play: async ({ canvasElement }) => {
+ const signIn = spyOn(YouVersionAPIUsers, 'signIn').mockResolvedValue(undefined);
+ try {
+ const root = await waitForShadowRoot(canvasElement);
+ const toolbar = root.querySelector('button[aria-label="Sign In" i]');
+ if (!toolbar) throw new Error('Reader sign-in control is missing');
+ await userEvent.click(toolbar);
+ const overlays = await readerOverlays(root);
+ await userEvent.click(await overlays.findByRole('button', { name: /sign in/i }));
+ await expect(signIn).toHaveBeenNthCalledWith(1, location.origin, undefined, undefined);
+
+ await selectVerses(root, [1]);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await expect(actions.queryByRole('button', { name: 'Save' })).toBeNull();
+ const [firstColor] = actions.getAllByRole('button', { name: 'Apply highlight' });
+ if (!firstColor) throw new Error('Reader highlight swatches are missing');
+ await userEvent.click(firstColor);
+ await userEvent.click(await overlays.findByRole('button', { name: 'Yes Please' }));
+ await expect(signIn).toHaveBeenNthCalledWith(2, location.origin, ['profile'], ['highlights']);
+ } finally {
+ signIn.mockRestore();
+ }
+ },
+};
+
export const SharedCopyAndDiscard: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
loaders: [prepareCallback],
diff --git a/packages/ui/src/components/bible-reader-toolbar.tsx b/packages/ui/src/components/bible-reader-toolbar.tsx
index c64ce4b65..81d3e80bc 100644
--- a/packages/ui/src/components/bible-reader-toolbar.tsx
+++ b/packages/ui/src/components/bible-reader-toolbar.tsx
@@ -2,7 +2,11 @@
import { useContext, useLayoutEffect, useRef, type JSX } from 'react';
import { useTranslation } from 'react-i18next';
-import { useYVAuth, YouVersionContext } from '@youversion/platform-react-hooks';
+import {
+ useYVAuth,
+ YouVersionAuthContext,
+ YouVersionContext,
+} from '@youversion/platform-react-hooks';
import { getAdjacentChapter } from '@youversion/platform-core';
import i18n from '@/i18n';
import { useInterfaceDirection } from '@/lib/direction';
@@ -37,6 +41,7 @@ function UserMenu() {
const { t } = useTranslation(undefined, { i18n });
const { auth, signIn, signOut, userInfo } = useYVAuth();
const yvContext = useContext(YouVersionContext);
+ const authContext = useContext(YouVersionAuthContext);
const { onSignInPress, onSignOutPress } = useBibleReaderContext();
// Prefer host-supplied native actions (e.g. the Expo DOM wrapper bridges these to
@@ -45,7 +50,7 @@ function UserMenu() {
if (onSignInPress) {
onSignInPress();
} else {
- void signIn({ scopes: READER_SIGN_IN_SCOPES });
+ void signIn(authContext?.isHostControlled ? undefined : { scopes: READER_SIGN_IN_SCOPES });
}
};
const handleSignOut = () => {
diff --git a/packages/ui/src/components/bible-reader.stories.tsx b/packages/ui/src/components/bible-reader.stories.tsx
index 4d1164855..67ceb01e3 100644
--- a/packages/ui/src/components/bible-reader.stories.tsx
+++ b/packages/ui/src/components/bible-reader.stories.tsx
@@ -1507,7 +1507,11 @@ export const SignInFlow: Story = {
const signInButton = overlays.getByRole('button', { name: /sign in/i });
await userEvent.click(signInButton);
- await expect(signInMock).toHaveBeenCalled();
+ await expect(signInMock).toHaveBeenCalledWith(
+ expect.any(String),
+ ['profile', 'read_notes', 'write_notes'],
+ undefined,
+ );
},
};
diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx
index e828368d2..7fcbec699 100644
--- a/packages/ui/src/components/bible-reader.tsx
+++ b/packages/ui/src/components/bible-reader.tsx
@@ -608,6 +608,17 @@ function Content() {
onStarted: () => undefined,
onFailed: () => undefined,
});
+ const displayedHighlightScope = useRef<{
+ versionId: number;
+ book: string;
+ chapter: string;
+ } | null>(null);
+ useLayoutEffect(() => {
+ if (renderedReference) displayedHighlightScope.current = { versionId, book, chapter };
+ }, [renderedReference, versionId, book, chapter]);
+ // While the old passage stays on screen, its highlight read and paint stay with it.
+ const retainedHighlightScope =
+ isRefetching && !isHighlightsControlled ? displayedHighlightScope.current : null;
const {
highlightedVerses,
@@ -626,6 +637,8 @@ function Content() {
versionId,
book,
chapter,
+ retainedScope: retainedHighlightScope,
+ hostOwnsSignIn: !!onSignInPress,
controlled: isHighlightsControlled
? {
highlights: highlights ?? [],
@@ -857,8 +870,10 @@ function Content() {
clearRestoredSelection();
}, [restoredNoteSelection, clearRestoredSelection, renderedReference, versionId, book, chapter]);
- function handleSaveNote() {
+ const noteRestoreFocusTargetRef = useRef(null);
+ function handleSaveNote(restoreFocusTarget: HTMLElement | null) {
if (renderedVerseScope && selectionScopeRef.current === renderedVerseScope) {
+ noteRestoreFocusTargetRef.current = restoreFocusTarget;
notes.open(buildVerseSelection(lastSelectionRef.current));
}
}
@@ -1210,6 +1225,7 @@ function Content() {
onSave={() => void notes.save()}
onDismiss={notes.dismiss}
theme={background}
+ restoreFocusTarget={noteRestoreFocusTargetRef.current}
/>
)}
diff --git a/packages/ui/src/components/ui/dialog.tsx b/packages/ui/src/components/ui/dialog.tsx
index ed112e558..91328c7e4 100644
--- a/packages/ui/src/components/ui/dialog.tsx
+++ b/packages/ui/src/components/ui/dialog.tsx
@@ -60,6 +60,8 @@ const DialogDescription = DialogPrimitive.Description;
type DialogContentProps = React.ComponentProps & {
theme?: 'light' | 'dark';
+ /** Durable focus target when the dialog replaces an overlay that is closing. */
+ restoreFocusTarget?: HTMLElement | null;
};
/**
@@ -75,6 +77,7 @@ function DialogContent({
children,
onCloseAutoFocus,
ref,
+ restoreFocusTarget,
...props
}: DialogContentProps): React.ReactNode {
const direction = useInterfaceDirection();
@@ -88,6 +91,7 @@ function DialogContent({
modal: portal.modal,
open: portal.open,
overlay: overlayNode,
+ restoreFocusTarget,
});
if (portal.awaitingPortalTarget) return null;
diff --git a/packages/ui/src/components/ui/use-shadow-dialog-focus.ts b/packages/ui/src/components/ui/use-shadow-dialog-focus.ts
index 63d009a4a..a3a4def4d 100644
--- a/packages/ui/src/components/ui/use-shadow-dialog-focus.ts
+++ b/packages/ui/src/components/ui/use-shadow-dialog-focus.ts
@@ -14,6 +14,7 @@ interface ShadowDialogFocusOptions {
modal: boolean;
open: boolean;
overlay: HTMLElement | null;
+ restoreFocusTarget?: HTMLElement | null;
}
interface ShadowDialogFocus {
@@ -109,6 +110,7 @@ export function useShadowDialogFocus({
modal,
open,
overlay,
+ restoreFocusTarget,
}: ShadowDialogFocusOptions): ShadowDialogFocus {
const modalPresent = modal && (overlay !== null || content !== null);
useShadowDialogFocusContainment(modalPresent, content, overlay);
@@ -131,9 +133,8 @@ export function useShadowDialogFocus({
}
const shadowRoot = getOwnShadowRoot(container);
- const activeElement = shadowRoot
- ? (shadowRoot.activeElement ?? container.ownerDocument.activeElement)
- : container.ownerDocument.activeElement;
+ const activeElement =
+ restoreFocusTarget ?? shadowRoot?.activeElement ?? container.ownerDocument.activeElement;
if (isElementFromOwnerDocument(activeElement, container, 'HTMLElement')) {
restoreFocusRef.current = {
capturedRoot: activeElement.getRootNode(),
@@ -141,7 +142,7 @@ export function useShadowDialogFocus({
};
}
capturedRestoreFocusRef.current = true;
- }, [container, focusRestoration, open]);
+ }, [container, focusRestoration, open, restoreFocusTarget]);
const onCloseAutoFocus = React.useCallback(
(event: Event): void => {
diff --git a/packages/ui/src/components/use-bible-reader-highlights.ts b/packages/ui/src/components/use-bible-reader-highlights.ts
index 79268641e..300a528e7 100644
--- a/packages/ui/src/components/use-bible-reader-highlights.ts
+++ b/packages/ui/src/components/use-bible-reader-highlights.ts
@@ -39,6 +39,10 @@ export type UseBibleReaderHighlightsOptions = {
versionId: number;
book: string;
chapter: string;
+ /** The chapter still painted during passage navigation. */
+ retainedScope?: HighlightScope | null;
+ /** Retains legacy scopes when a host owns Reader sign-in. */
+ hostOwnsSignIn?: boolean;
/** Presence selects controlled mode (latched by the caller at first mount). */
controlled?: ControlledHighlightsInput;
/** Fires when the sign-in or permission redirect promise fulfills. */
@@ -169,6 +173,8 @@ export function useBibleReaderHighlights({
versionId,
book,
chapter,
+ retainedScope,
+ hostOwnsSignIn,
controlled,
onAuthRedirectStarted,
onAuthRedirectFailed,
@@ -206,9 +212,16 @@ export function useBibleReaderHighlights({
startDataExchangeForHighlights,
} = useHighlightAuthActions();
- const chapterUsfm = `${book}.${chapter}`;
+ const scope: HighlightScope = useMemo(
+ () => ({ versionId, book, chapter }),
+ [versionId, book, chapter],
+ );
+ const displayScope = retainedScope ?? scope;
+ const isDisplayingRetainedChapter = !scopesEqual(scope, displayScope);
+ const displayedVersionId = displayScope.versionId;
+ const displayedChapterUsfm = `${displayScope.book}.${displayScope.chapter}`;
const { highlights, createHighlight, deleteHighlight, refetch } = useHighlights(
- { version_id: versionId, passage_id: chapterUsfm },
+ { version_id: displayedVersionId, passage_id: displayedChapterUsfm },
{ enabled: live },
);
@@ -225,11 +238,18 @@ export function useBibleReaderHighlights({
const services: HighlightServices = {
createHighlight,
deleteHighlight,
- refetch,
+ refetch: () => {
+ // The destination's highlights load when the destination passage is displayed.
+ if (!isDisplayingRetainedChapter) refetch();
+ },
hasHighlightsPermission,
invalidateHighlightsPermission,
consumeDataExchangeReturn,
- startSignInForHighlights: () => startSignInForHighlights(undefined, READER_SIGN_IN_SCOPES),
+ startSignInForHighlights: () =>
+ startSignInForHighlights(
+ undefined,
+ !hostOwnsSignIn && !authContext?.isHostControlled ? READER_SIGN_IN_SCOPES : undefined,
+ ),
startDataExchangeForHighlights,
onAuthRedirectStarted,
onAuthRedirectFailed,
@@ -237,11 +257,6 @@ export function useBibleReaderHighlights({
const servicesRef = useRef(services);
servicesRef.current = services;
- const scope: HighlightScope = useMemo(
- () => ({ versionId, book, chapter }),
- [versionId, book, chapter],
- );
-
const actorRef = useActorRef(bibleReaderHighlightsMachine, {
input: {
services: servicesRef,
@@ -264,8 +279,8 @@ export function useBibleReaderHighlights({
// Keep the same paint and machine input when a refresh returns equivalent verse colors.
const latestServerColors = useMemo(
- () => parseServerColors(highlights, versionId, chapterUsfm),
- [highlights, versionId, chapterUsfm],
+ () => parseServerColors(highlights, displayedVersionId, displayedChapterUsfm),
+ [highlights, displayedVersionId, displayedChapterUsfm],
);
const paintedServerColorsRef = useRef(latestServerColors);
if (!serverColorsEqual(paintedServerColorsRef.current, latestServerColors)) {
@@ -274,8 +289,11 @@ export function useBibleReaderHighlights({
const serverColors = paintedServerColorsRef.current;
useEffect(() => {
- actorRef.send({ type: 'HIGHLIGHTS_UPDATED', serverColors });
- }, [actorRef, serverColors]);
+ actorRef.send({
+ type: 'HIGHLIGHTS_UPDATED',
+ serverColors: isDisplayingRetainedChapter ? {} : serverColors,
+ });
+ }, [actorRef, isDisplayingRetainedChapter, serverColors]);
// ── Rendered verse map ──────────────────────────────────────────────────────
const overlay = useSelector(actorRef, (state) => state.context.overlay);
@@ -295,7 +313,9 @@ export function useBibleReaderHighlights({
// machine scope still points at the old chapter, so the overlay is skipped
// and the new chapter renders from server truth alone — verse numbers
// collide across chapters.
- if (!scopesEqual(machineScope, scope)) return { ...serverColors };
+ if (isDisplayingRetainedChapter || !scopesEqual(machineScope, scope)) {
+ return { ...serverColors };
+ }
// Same window for an account swap: until the AUTH_CHANGED effect runs, the
// machine still holds the previous account's overlay. Skip it, so the new
// account never sees those entries, not even for one paint.
@@ -303,6 +323,7 @@ export function useBibleReaderHighlights({
return selectHighlightedVerses(serverColors, overlay);
}, [
isControlled,
+ isDisplayingRetainedChapter,
controlled?.highlights,
live,
serverColors,
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index 4117cb39e..203a0279e 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -119,6 +119,19 @@ function writerToken(account: string | null) {
return account ? config.getOAuthAccessToken(account, 'write_notes') : null;
}
+function matchesDraftOwner(owner: string | null, account: string | null, state: string | null) {
+ // A failed refresh can clear credentials while leaving an active authorization
+ // attempt and its initiating profile. That identity can recover the draft only.
+ return (
+ owner === account ||
+ (account === null &&
+ owner !== null &&
+ state !== null &&
+ config.storedUserInfo?.id === owner &&
+ YouVersionAPIUsers.isSignInPending(state))
+ );
+}
+
function sameSelection(left: NoteSelection, right: NoteSelection): boolean {
return (
left.versionId === right.versionId &&
@@ -154,6 +167,7 @@ export function useBibleReaderNote({
const retainedDraft = useRef(null);
const currentFlow = useRef(null);
const handoffState = useRef(null);
+ const draftAuthorizationState = useRef(null);
const checkedHandoff = useRef(false);
const latest = useRef({ account, canAuthorize, onSaved, onInvalidated });
latest.current = { account, canAuthorize, onSaved, onInvalidated };
@@ -176,23 +190,32 @@ export function useBibleReaderNote({
useLayoutEffect(() => {
if (authLoading) return;
const draft = currentFlow.current?.draft ?? retainedDraft.current;
- if (!draft?.ownerId || draft.ownerId === account) return;
+ if (
+ !draft?.ownerId ||
+ matchesDraftOwner(draft.ownerId, account, draftAuthorizationState.current)
+ )
+ return;
retainedDraft.current = null;
+ draftAuthorizationState.current = null;
show(null);
latest.current.onInvalidated(draft.selection);
}, [account, authLoading]);
const oauthCallbackState = auth?.oauthCallbackState;
+ const oauthFailedCallbackState = auth?.oauthFailedCallbackState;
const oauthCallbackSuperseded = auth?.oauthCallbackSuperseded;
useEffect(() => {
if (authLoading || !canAuthorize || checkedHandoff.current || !reader.current) return;
checkedHandoff.current = true;
const handoff = consumeNoteHandoff(readerPosition(reader.current));
+ const returnedState = oauthCallbackState ?? oauthFailedCallbackState;
if (
!handoff ||
oauthCallbackSuperseded ||
- (oauthCallbackState && oauthCallbackState !== handoff.state) ||
- (handoff.draft.ownerId && handoff.draft.ownerId !== account)
+ (returnedState
+ ? returnedState !== handoff.state
+ : !YouVersionAPIUsers.isSignInPending(handoff.state)) ||
+ (handoff.draft.ownerId && !matchesDraftOwner(handoff.draft.ownerId, account, handoff.state))
) {
return;
}
@@ -201,8 +224,17 @@ export function useBibleReaderNote({
show({ phase: 'compose', draft: { ...handoff.draft, ownerId: account } });
} else {
retainedDraft.current = handoff.draft;
+ draftAuthorizationState.current = handoff.state;
}
- }, [account, authLoading, canAuthorize, oauthCallbackState, oauthCallbackSuperseded, reader]);
+ }, [
+ account,
+ authLoading,
+ canAuthorize,
+ oauthCallbackState,
+ oauthFailedCallbackState,
+ oauthCallbackSuperseded,
+ reader,
+ ]);
useEffect(() => {
// Browser Back can restore this same document without remounting the Reader.
@@ -219,8 +251,9 @@ export function useBibleReaderNote({
if (
!YouVersionAPIUsers.isSignInPending(state) ||
(config.storedUserInfo?.id || null) !== ownerId ||
- latest.current.account !== ownerId
+ !matchesDraftOwner(ownerId, latest.current.account, state)
) {
+ draftAuthorizationState.current = null;
show(null);
latest.current.onInvalidated(active.draft.selection);
} else if (handoff && latest.current.canAuthorize) {
@@ -239,19 +272,24 @@ export function useBibleReaderNote({
const token = writerToken(account);
if (!token && !canAuthorize) return;
const retained = retainedDraft.current;
+ const sameOwnedSelection =
+ retained &&
+ sameSelection(retained.selection, selection) &&
+ (!retained.ownerId ||
+ matchesDraftOwner(retained.ownerId, account, draftAuthorizationState.current));
retainedDraft.current = null;
+ if (!sameOwnedSelection) draftAuthorizationState.current = null;
setAuthorizationFailed(false);
- const draft =
- retained && sameSelection(retained.selection, selection)
- ? { ...retained, ownerId: account }
- : {
- selection: selectionSchema.parse(selection),
- ownerId: account,
- requestId: crypto.randomUUID(),
- text: '',
- visibility: 'private' as const,
- color: null,
- };
+ const draft = sameOwnedSelection
+ ? { ...retained, ownerId: retained.ownerId ?? account }
+ : {
+ selection: selectionSchema.parse(selection),
+ ownerId: account,
+ requestId: crypto.randomUUID(),
+ text: '',
+ visibility: 'private' as const,
+ color: null,
+ };
show({ phase: token ? 'compose' : 'authorize', draft });
}
@@ -265,6 +303,7 @@ export function useBibleReaderNote({
if (active?.phase !== 'authorize' || !canAuthorize || !reader.current) return;
const readerKey = readerPosition(reader.current);
const redirect = { ...active, phase: 'redirect' } as const;
+ const previousState = draftAuthorizationState.current;
show(redirect);
try {
await YouVersionAPIUsers.signIn(
@@ -274,7 +313,7 @@ export function useBibleReaderNote({
(state) => {
if (
currentFlow.current !== redirect ||
- latest.current.account !== redirect.draft.ownerId ||
+ !matchesDraftOwner(redirect.draft.ownerId, latest.current.account, previousState) ||
!latest.current.canAuthorize ||
(config.storedUserInfo?.id || null) !== redirect.draft.ownerId
) {
@@ -292,10 +331,12 @@ export function useBibleReaderNote({
);
if (!stored) throw new Error('The pending note could not be saved for authorization');
handoffState.current = state;
+ draftAuthorizationState.current = state;
},
);
} catch {
if (currentFlow.current !== redirect) return;
+ draftAuthorizationState.current = previousState;
if (handoffState.current) {
consumeNoteHandoff(readerKey, {
state: handoffState.current,
@@ -318,7 +359,12 @@ export function useBibleReaderNote({
async function save() {
const active = currentFlow.current;
- if (active?.phase !== 'compose' || authLoading || active.draft.ownerId !== account) return;
+ if (
+ active?.phase !== 'compose' ||
+ authLoading ||
+ !matchesDraftOwner(active.draft.ownerId, account, draftAuthorizationState.current)
+ )
+ return;
const token = writerToken(account);
if (!token || token === active.deniedToken) {
show({
@@ -366,7 +412,11 @@ export function useBibleReaderNote({
}
const visibleFlow =
- !enabled || (flow?.draft.ownerId && flow.draft.ownerId !== account) ? null : flow;
+ !enabled ||
+ (flow?.draft.ownerId &&
+ !matchesDraftOwner(flow.draft.ownerId, account, draftAuthorizationState.current))
+ ? null
+ : flow;
return {
flow: visibleFlow,
available: enabled && !authLoading && (canAuthorize || !!writerToken(account)),
diff --git a/packages/ui/src/components/verse-action-popover.tsx b/packages/ui/src/components/verse-action-popover.tsx
index 81ce8bc44..00293d8f9 100644
--- a/packages/ui/src/components/verse-action-popover.tsx
+++ b/packages/ui/src/components/verse-action-popover.tsx
@@ -162,7 +162,7 @@ type VerseActionPopoverProps = {
onHighlight: (color: string) => void;
onClearHighlight: (color: string) => void;
/** Enables the Save action. The Reader opens its Notes composer here. */
- onSave?: () => void;
+ onSave?: (restoreFocusTarget: HTMLElement | null) => void;
onCopy: () => void;
onShare: () => void;
theme?: 'light' | 'dark';
@@ -588,7 +588,7 @@ export const VerseActionPopover: FC = ({
key={item}
icon={ }
label={t('notesSave')}
- onClick={() => onSave?.()}
+ onClick={() => onSave?.(focusRestoreTargetRef.current)}
onClickCapture={markOverlayAction}
/>
);
From 20fe224eacdf2ef7d5c951bceeeffd540e1d5710 Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 11:07:48 -0600
Subject: [PATCH 20/75] fix: preserve Reader draft recovery and auth
compatibility
Keep host-controlled toolbar scopes, restore legacy startup token rotation, and retain the captured draft through a verified failed callback. Verify the workflow with isolated browser fixtures and native Safari.
Ref: YPE-6783
---
packages/core/src/Users.ts | 54 ++++++-----
.../core/src/__tests__/OAuthWorkflows.test.ts | 31 +++++-
.../src/context/YouVersionAuthProvider.tsx | 25 ++++-
packages/hooks/src/useYVAuth.test.tsx | 77 ++++++++++++++-
.../components/bible-reader-notes.stories.tsx | 38 +++++++-
.../src/components/bible-reader-toolbar.tsx | 2 +-
...-highlights.auth-flow.integration.test.tsx | 54 -----------
...e-bible-reader-highlights.sign-in.test.tsx | 95 +++++++++++++++++++
.../src/components/use-bible-reader-note.ts | 74 +++++++++++----
9 files changed, 345 insertions(+), 105 deletions(-)
create mode 100644 packages/ui/src/components/use-bible-reader-highlights.sign-in.test.tsx
diff --git a/packages/core/src/Users.ts b/packages/core/src/Users.ts
index 7c6dd501b..c639824fe 100644
--- a/packages/core/src/Users.ts
+++ b/packages/core/src/Users.ts
@@ -82,6 +82,15 @@ type PendingGrantedPermissionsStash = StatePermissionsStash;
type RequestedPermissionsStash = StatePermissionsStash;
+type TokenRotation = {
+ result: SignInWithYouVersionResult;
+ previousSession: {
+ accessToken: string | null;
+ refreshToken: string;
+ userId: string | undefined;
+ };
+};
+
/**
* Dedupe map for in-flight/settled code-for-token exchanges, keyed by the
* single-use authorization `code`. Under React StrictMode the auth init effect
@@ -112,7 +121,7 @@ export function __resetAuthCallbackDedupeForTests(): void {
* genuine refresh (e.g. the token expiring an hour on) must be able to run.
* Sharing applies only to calls that overlap in time.
*/
-let inFlightRefresh: Promise | null = null;
+let inFlightRefresh: Promise | null = null;
/** Test-only: clears the shared in-flight refresh between test cases. */
export function __resetTokenRefreshDedupeForTests(): void {
@@ -295,9 +304,10 @@ export class YouVersionAPIUsers {
window.location.href = authorizationRequest.url.toString();
}
- /** Whether the specified authorization attempt is still pending in this browser. */
- static isSignInPending(state: string): boolean {
- return getLocalStorage()?.getItem(AUTH_STATE_KEY) === state;
+ /** Whether the specified authorization attempt, or any attempt when omitted, is pending. */
+ static isSignInPending(state?: string): boolean {
+ const pendingState = getLocalStorage()?.getItem(AUTH_STATE_KEY);
+ return !!pendingState && (state === undefined || pendingState === state);
}
/**
@@ -665,12 +675,10 @@ export class YouVersionAPIUsers {
* @throws An error if refresh fails or no refresh token is available
*/
static async refreshTokens(): Promise {
- return this.rotateTokens(false);
+ return (await this.rotateTokens(false)).result;
}
- private static async rotateTokens(
- clearOnPersistenceFailure: boolean,
- ): Promise {
+ private static async rotateTokens(clearOnPersistenceFailure: boolean): Promise {
const accessToken = YouVersionPlatformConfiguration.accessToken;
const refreshToken = YouVersionPlatformConfiguration.refreshToken;
const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
@@ -758,7 +766,7 @@ export class YouVersionAPIUsers {
throw new Error('the rotated tokens could not be saved to browser storage');
}
- return result;
+ return { result, previousSession: { accessToken, refreshToken, userId } };
} catch (error) {
if (error instanceof Error) {
throw new Error(`Token refresh failed: ${error.message}`);
@@ -785,9 +793,12 @@ export class YouVersionAPIUsers {
/**
* Refreshes the access token if it's expired or about to expire.
*
+ * @param onRotation - Receives the persisted rotation and its initiating session when a refresh occurred.
* @returns Promise - true if refresh was successful or not needed, false if failed
*/
- static async refreshTokenIfNeeded(): Promise {
+ static async refreshTokenIfNeeded(
+ onRotation?: (rotation: TokenRotation) => void,
+ ): Promise {
if (!this.isTokenExpired()) {
return true; // Token is still valid
}
@@ -796,16 +807,13 @@ export class YouVersionAPIUsers {
// StrictMode double-invocation) can't spend the single-use refresh token a
// second time and wipe the session on its failure. The get/set here is
// synchronous before the first await, so the check is re-entrancy safe.
- const existingRefresh = inFlightRefresh;
- if (existingRefresh) {
- return existingRefresh;
- }
-
- const refresh = this.performTokenRefresh();
+ const refresh = inFlightRefresh ?? this.performTokenRefresh();
inFlightRefresh = refresh;
try {
- return await refresh;
+ const rotation = await refresh;
+ if (rotation) onRotation?.(rotation);
+ return rotation !== null;
} finally {
// Clear the slot once settled so a later, genuine refresh can run. Guard
// against clobbering a newer refresh that a subsequent call may have set.
@@ -818,17 +826,15 @@ export class YouVersionAPIUsers {
/**
* Performs a single token refresh, clearing the session exactly once on
* failure. Callers must share this via {@link inFlightRefresh} so a duplicate
- * refresh never runs concurrently; a shared failure clears tokens once and
- * resolves false for every caller awaiting it.
+ * refresh never runs concurrently. Each caller receives the same outcome.
*/
- private static async performTokenRefresh(): Promise {
+ private static async performTokenRefresh(): Promise {
const accessToken = YouVersionPlatformConfiguration.accessToken;
const refreshToken = YouVersionPlatformConfiguration.refreshToken;
const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
- if (YouVersionPlatformConfiguration.readOAuthSession() === null) return false;
+ if (YouVersionPlatformConfiguration.readOAuthSession() === null) return null;
try {
- const result = await this.rotateTokens(true);
- return !!result;
+ return await this.rotateTokens(true);
} catch {
// Refresh failed, clear tokens
if (
@@ -839,7 +845,7 @@ export class YouVersionAPIUsers {
) {
clearFailedRefreshSession();
}
- return false;
+ return null;
}
}
}
diff --git a/packages/core/src/__tests__/OAuthWorkflows.test.ts b/packages/core/src/__tests__/OAuthWorkflows.test.ts
index 8bccbccff..3a362f900 100644
--- a/packages/core/src/__tests__/OAuthWorkflows.test.ts
+++ b/packages/core/src/__tests__/OAuthWorkflows.test.ts
@@ -78,6 +78,20 @@ function tokenResponse(scope: string) {
return Response.json({ ...makeTokens(scope), access_token: 'signed-in-access' });
}
+it('reports whether any sign-in or the requested sign-in is pending', async () => {
+ const { browser } = createOAuthBrowser();
+ expect(YouVersionAPIUsers.isSignInPending()).toBe(false);
+ await YouVersionAPIUsers.signIn(redirect);
+ const state = new URL(browser.window.location.href).searchParams.get('state');
+ if (!state) throw new Error('Expected an authorization state');
+ expect(YouVersionAPIUsers.isSignInPending()).toBe(true);
+ expect(YouVersionAPIUsers.isSignInPending(state)).toBe(true);
+ expect(YouVersionAPIUsers.isSignInPending('another-state')).toBe(false);
+ YouVersionAPIUsers.signOut();
+ expect(YouVersionAPIUsers.isSignInPending()).toBe(false);
+ expect(YouVersionAPIUsers.isSignInPending(state)).toBe(false);
+});
+
it.each([
{ timing: 'before', signInFirst: true },
{ timing: 'after', signInFirst: false },
@@ -492,6 +506,8 @@ it('rotates legacy tokens without assigning the returned scope to a stored profi
expect(config.accessToken).toBe('new-access-token');
expect(config.refreshToken).toBe('new-refresh-token');
+ expect(config.tokenExpiryDate).toEqual(result?.expiryDate);
+ expect(config.tokenExpiryDate?.getTime()).toBeGreaterThan(Date.now());
expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('legacy-user');
expect(config.getOAuthAccessToken('legacy-user', 'write_notes')).toBeNull();
});
@@ -503,12 +519,23 @@ it('shares one refresh request and keeps the rotated session for simultaneous ca
const finishRefresh = holdTokenResponse();
fetch.mockResolvedValue(new Response(null, { status: 400 }));
- const first = YouVersionAPIUsers.refreshTokenIfNeeded();
- const second = YouVersionAPIUsers.refreshTokenIfNeeded();
+ const firstRotation = vi.fn();
+ const secondRotation = vi.fn();
+ const first = YouVersionAPIUsers.refreshTokenIfNeeded(firstRotation);
+ const second = YouVersionAPIUsers.refreshTokenIfNeeded(secondRotation);
finishRefresh(tokenResponse('openid profile'));
await expect(Promise.all([first, second])).resolves.toEqual([true, true]);
expect(fetch).toHaveBeenCalledTimes(1);
+ const rotation = {
+ result: expect.objectContaining({
+ accessToken: 'signed-in-access',
+ refreshToken: 'refresh-token-456',
+ }),
+ previousSession: { accessToken: 'old-access', refreshToken: 'old-refresh', userId: 'alice' },
+ };
+ expect(firstRotation).toHaveBeenCalledExactlyOnceWith(rotation);
+ expect(secondRotation).toHaveBeenCalledExactlyOnceWith(rotation);
expect(config.accessToken).toBe('signed-in-access');
expect(config.refreshToken).toBe('refresh-token-456');
expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('alice');
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.tsx b/packages/hooks/src/context/YouVersionAuthProvider.tsx
index 68208c4a8..08d57c37e 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.tsx
@@ -106,16 +106,35 @@ export default function YouVersionAuthProvider({
if (refreshToken) {
const accessToken = YouVersionPlatformConfiguration.accessToken;
const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
+ let initializedAccessToken = accessToken;
+ let initializedRefreshToken = refreshToken;
try {
// refreshTokenIfNeeded clears tokens (and the stored profile)
// when the session has expired and cannot be refreshed.
- const refreshed = await YouVersionAPIUsers.refreshTokenIfNeeded();
+ const refreshed = await YouVersionAPIUsers.refreshTokenIfNeeded(
+ ({ result, previousSession }) => {
+ if (
+ previousSession.accessToken === accessToken &&
+ previousSession.refreshToken === refreshToken &&
+ previousSession.userId === userId &&
+ result.accessToken &&
+ result.refreshToken
+ ) {
+ initializedAccessToken = result.accessToken;
+ initializedRefreshToken = result.refreshToken;
+ }
+ },
+ );
if (!mounted) return;
if (!sessionChanged) {
const storedUser = refreshed ? YouVersionAPIUsers.getStoredUserInfo() : null;
setUserInfo(storedUser);
- if (accessToken && userId && storedUser?.userId === userId) {
- setLegacySession({ userId, accessToken, refreshToken });
+ if (initializedAccessToken && userId && storedUser?.userId === userId) {
+ setLegacySession({
+ userId,
+ accessToken: initializedAccessToken,
+ refreshToken: initializedRefreshToken,
+ });
}
}
} catch {
diff --git a/packages/hooks/src/useYVAuth.test.tsx b/packages/hooks/src/useYVAuth.test.tsx
index c4968d468..931ccbdbd 100644
--- a/packages/hooks/src/useYVAuth.test.tsx
+++ b/packages/hooks/src/useYVAuth.test.tsx
@@ -1,9 +1,9 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { YouVersionAPIUsers, YouVersionPlatformConfiguration } from '@youversion/platform-core';
-import type { ReactNode } from 'react';
+import { StrictMode, type ReactNode } from 'react';
import { expect, it, onTestFinished, vi } from 'vitest';
import { createMockAuthResult, createMockUserInfo } from './__tests__/mocks/auth';
-import { YouVersionAuthContext } from './context/YouVersionAuthContext';
+import { YouVersionAuthContext, useYouVersionAuthContext } from './context/YouVersionAuthContext';
import { YouVersionProvider } from './context/YouVersionProvider';
import type { AuthContextValue } from './types/auth';
import { useYVAuth } from './useYVAuth';
@@ -164,6 +164,79 @@ it('keeps an initial legacy token without adopting later unbound credentials', a
expect(result.current.auth.accessToken).toBe('bound-access');
});
+it.each([
+ { scenario: 'rotates', replacement: null, owner: 'alice', token: 'rotated-access' },
+ { scenario: 'overlaps staged credentials', replacement: 'staged', owner: 'alice', token: null },
+ {
+ scenario: 'is superseded by another account',
+ replacement: 'bob',
+ owner: 'bob',
+ token: 'bob-access',
+ },
+])(
+ 'pairs a late auth consumer with the current account when a legacy session $scenario',
+ async ({ replacement, owner, token }) => {
+ const config = YouVersionPlatformConfiguration;
+ YouVersionAPIUsers.signOut();
+ const reply = Promise.withResolvers();
+ const fetch = vi.fn(() => reply.promise);
+ vi.stubGlobal('fetch', fetch);
+ onTestFinished(() => {
+ vi.unstubAllGlobals();
+ YouVersionAPIUsers.signOut();
+ });
+ config.saveAuthData('expired-access', 'legacy-refresh', new Date(0));
+ config.saveUserInfo({ id: 'alice' });
+
+ function AfterAuth({ children }: { children: ReactNode }) {
+ return useYouVersionAuthContext().isLoading ? null : children;
+ }
+ function Wrapper({ children }: { children: ReactNode }) {
+ return (
+
+
+ {children}
+
+
+ );
+ }
+ const { result } = renderHook(useYVAuth, { wrapper: Wrapper });
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
+ expect(result.current).toBeNull();
+
+ if (replacement) {
+ act(() => {
+ config.saveAuthData(
+ 'bob-access',
+ 'bob-refresh',
+ new Date('2100-01-01'),
+ replacement === 'bob' ? { scope: 'profile', userId: 'bob' } : undefined,
+ );
+ if (replacement === 'bob') config.saveUserInfo({ id: 'bob' });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'accessToken', storageArea: localStorage }),
+ );
+ });
+ }
+ await act(async () => {
+ reply.resolve(
+ Response.json({
+ access_token: 'rotated-access',
+ refresh_token: 'rotated-refresh',
+ expires_in: 3600,
+ scope: 'openid write_notes',
+ token_type: 'Bearer',
+ }),
+ );
+ });
+ await waitFor(() => expect(result.current?.auth.isLoading).toBe(false));
+ expect(result.current.userInfo?.userId).toBe(owner);
+ expect(result.current.auth.accessToken).toBe(token);
+ expect(config.getOAuthAccessToken(owner, 'write_notes')).toBeNull();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ },
+);
+
it('keeps a pending authorization profile signed out on remount and storage updates', async () => {
YouVersionAPIUsers.signOut();
onTestFinished(() => YouVersionAPIUsers.signOut());
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index 5702b3092..b39f0ec20 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -22,6 +22,9 @@ import { YouVersionProvider } from './YouVersionProvider';
const meta: Meta = {
title: 'Components/BibleReader/Notes',
+ // In the shared Firefox process, the Reader's network calls can bypass MSW
+ // after switching preview files. The existing runner isolates tagged files.
+ tags: ['shadow-fresh-process'],
parameters: { layout: 'fullscreen' },
render: () => (
@@ -50,7 +53,10 @@ async function selectVerses(root: ShadowRoot, verses: number[]) {
async function fillEditor(editor: HTMLTextAreaElement, value: string) {
if (__YV_STORYBOOK_VITEST__) {
const { userEvent } = await import('vitest/browser');
- await userEvent.fill(editor, value);
+ // Native keys avoid the WebDriver lookup of an escaped Radix ID in the shadow tree.
+ editor.focus();
+ editor.select();
+ await userEvent.keyboard(value || '{Backspace}');
return;
}
await userEvent.type(editor, value || '{Backspace}', {
@@ -606,6 +612,9 @@ export const WritePermissionChangesWhileEditing: Story = {
YouVersionPlatformConfiguration.saveUserInfo(profile);
window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }));
await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ await waitFor(async () =>
+ expect(await readerVerse(root, 1)).not.toHaveClass('yv-v-selected'),
+ );
await selectVerses(root, [2]);
const { composer: newDraft } = await openComposer(root, 'John 1:2');
await expect(newDraft.getByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
@@ -731,7 +740,14 @@ export const RemountRecoversDraftDuringFailedRefresh: Story = {
scope: 'profile read_notes',
},
);
- getWorker().use(http.post('*/auth/token', () => new HttpResponse(null, { status: 503 })));
+ const failedGrants: string[] = [];
+ getWorker().use(
+ http.post('*/auth/token', async ({ request }) => {
+ const parameters = new URLSearchParams(await request.text());
+ failedGrants.push(parameters.get('grant_type') ?? '');
+ return new HttpResponse(null, { status: 503 });
+ }),
+ );
await userEvent.click(page.getByRole('button', { name: 'Reload Reader' }));
const remounted = await waitForShadowRoot(canvasElement);
await expect(remounted).not.toBe(root);
@@ -745,6 +761,22 @@ export const RemountRecoversDraftDuringFailedRefresh: Story = {
await userEvent.click(await returnedOverlays.findByRole('button', { name: 'Yes Please' }));
await waitFor(() => expect(returnedOverlays.queryByRole('dialog')).toBeNull());
+ await userEvent.click(page.getByRole('button', { name: 'Return from sign-in' }));
+ const failedRoot = await waitForShadowRoot(canvasElement);
+ await expect(failedRoot).not.toBe(remounted);
+ await waitFor(() => expect(failedGrants).toEqual(['refresh_token', 'authorization_code']));
+ await waitFor(async () =>
+ expect(await readerVerse(failedRoot, 1)).toHaveClass('yv-v-selected'),
+ );
+ await expect(await readerVerse(failedRoot, 4)).toHaveClass('yv-v-selected');
+ const failedOverlays = await readerOverlays(failedRoot);
+ const failedActions = within(
+ await failedOverlays.findByRole('dialog', { name: 'Verse actions' }),
+ );
+ await userEvent.click(failedActions.getByRole('button', { name: 'Save' }));
+ await userEvent.click(await failedOverlays.findByRole('button', { name: 'Yes Please' }));
+ await waitFor(() => expect(failedOverlays.queryByRole('dialog')).toBeNull());
+
getWorker().use(
http.post('*/auth/token', () => tokenResponse('profile read_notes write_notes')),
);
@@ -925,7 +957,7 @@ export const HostControlledSignIn: Story = {
await userEvent.click(toolbar);
const overlays = await readerOverlays(root);
await userEvent.click(await overlays.findByRole('button', { name: /sign in/i }));
- await expect(signIn).toHaveBeenNthCalledWith(1, location.origin, undefined, undefined);
+ await expect(signIn).toHaveBeenNthCalledWith(1, location.origin, ['profile'], undefined);
await selectVerses(root, [1]);
const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
diff --git a/packages/ui/src/components/bible-reader-toolbar.tsx b/packages/ui/src/components/bible-reader-toolbar.tsx
index 81d3e80bc..770a51caa 100644
--- a/packages/ui/src/components/bible-reader-toolbar.tsx
+++ b/packages/ui/src/components/bible-reader-toolbar.tsx
@@ -50,7 +50,7 @@ function UserMenu() {
if (onSignInPress) {
onSignInPress();
} else {
- void signIn(authContext?.isHostControlled ? undefined : { scopes: READER_SIGN_IN_SCOPES });
+ void signIn({ scopes: authContext?.isHostControlled ? ['profile'] : READER_SIGN_IN_SCOPES });
}
};
const handleSignOut = () => {
diff --git a/packages/ui/src/components/use-bible-reader-highlights.auth-flow.integration.test.tsx b/packages/ui/src/components/use-bible-reader-highlights.auth-flow.integration.test.tsx
index 0b6c34890..863215a80 100644
--- a/packages/ui/src/components/use-bible-reader-highlights.auth-flow.integration.test.tsx
+++ b/packages/ui/src/components/use-bible-reader-highlights.auth-flow.integration.test.tsx
@@ -84,60 +84,6 @@ afterEach(() => {
sessionStorage.clear();
});
-describe('highlight auth flow — one-fell-swoop (signed out)', () => {
- it('color tap opens the sign-in dialog and stashes pending; confirm starts sign-in; granted return applies', async () => {
- const signIn = vi.spyOn(YouVersionAPIUsers, 'signIn').mockResolvedValue(undefined);
- const createHighlight = vi
- .spyOn(HighlightsClient.prototype, 'createHighlight')
- .mockResolvedValue({ version_id: 111, passage_id: 'JHN.3.16', color: 'ffec5b' });
-
- const { result, unmount } = renderHook(() => useBibleReaderHighlights(options), {
- wrapper: Providers,
- });
-
- // NEW BEHAVIOR (PR-288): a signed-out color tap opens the sign-in dialog
- // instead of redirecting immediately. It stashes the pending intent and does
- // NOT launch OAuth until the user confirms.
- act(() => {
- expect(result.current.apply('FFEC5B', [16])).toBe('flow');
- });
-
- expect(result.current.signInDialogOpen).toBe(true);
- const pending = readPendingHighlights()[0];
- expect(pending).toMatchObject({ verses: [16], color: 'ffec5b', versionId: 111, chapter: '3' });
- expect(signIn).not.toHaveBeenCalled();
- expect(createHighlight).not.toHaveBeenCalled();
-
- // Confirm → launch the full-page sign-in redirect requesting `highlights`.
- act(() => {
- result.current.confirmSignInDialog();
- });
- expect(signIn).toHaveBeenCalledWith(
- 'https://host.example/callback',
- ['profile', 'read_notes', 'write_notes'],
- ['highlights'],
- );
-
- // The confirm triggers a full-page redirect; simulate the reload on the
- // granted return — a fresh mount, now signed in with the permission granted
- // and the pending highlight still in sessionStorage.
- unmount();
- YouVersionPlatformConfiguration.saveGrantedPermissions(['highlights']);
- signedIn = true;
- renderHook(() => useBibleReaderHighlights(options), { wrapper: Providers });
-
- await waitFor(() => {
- expect(createHighlight).toHaveBeenCalledWith({
- version_id: 111,
- passage_id: 'JHN.3.16',
- color: 'ffec5b',
- });
- });
- // Pending consumed (the write is the proof it applied).
- expect(readPendingHighlights()).toEqual([]);
- });
-});
-
describe('highlight auth flow — sign-in dialog (signed out)', () => {
it('a color tap opens the sign-in dialog and stashes pending without launching OAuth', () => {
const signIn = vi.spyOn(YouVersionAPIUsers, 'signIn').mockResolvedValue(undefined);
diff --git a/packages/ui/src/components/use-bible-reader-highlights.sign-in.test.tsx b/packages/ui/src/components/use-bible-reader-highlights.sign-in.test.tsx
new file mode 100644
index 000000000..ee0fb1f9b
--- /dev/null
+++ b/packages/ui/src/components/use-bible-reader-highlights.sign-in.test.tsx
@@ -0,0 +1,95 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import {
+ HighlightsClient,
+ YouVersionAPIUsers,
+ YouVersionPlatformConfiguration,
+} from '@youversion/platform-core';
+import { YouVersionAuthContext, YouVersionContext } from '@youversion/platform-react-hooks';
+import type { ReactNode } from 'react';
+import { expect, it, onTestFinished, vi } from 'vitest';
+import { isHighlightsLive, setHighlightsLive } from '@/lib/feature-flags';
+import { readPendingHighlights } from '@/lib/pending-highlight';
+import { mockUserInfo } from '@/test/highlights-test-utils';
+import { TestQueryClientProvider } from '@/test/hook-overrides';
+import { useBibleReaderHighlights } from './use-bible-reader-highlights';
+
+function withReaderAuth(userInfo: typeof mockUserInfo | null) {
+ const auth = {
+ userInfo,
+ setUserInfo: vi.fn(),
+ isLoading: false,
+ error: null,
+ redirectUri: 'https://host.example/callback',
+ };
+ return function ReaderAuth({ children }: { children: ReactNode }) {
+ return (
+
+
+ {children}
+
+
+ );
+ };
+}
+
+it('requests Notes scopes when confirming highlight sign-in and applies the saved highlight on return', async () => {
+ const highlightsWereLive = isHighlightsLive();
+ setHighlightsLive(true);
+ localStorage.clear();
+ sessionStorage.clear();
+ const read = vi.spyOn(HighlightsClient.prototype, 'getHighlights').mockResolvedValue({
+ data: [],
+ next_page_token: null,
+ });
+ const signIn = vi.spyOn(YouVersionAPIUsers, 'signIn').mockResolvedValue(undefined);
+ const createHighlight = vi
+ .spyOn(HighlightsClient.prototype, 'createHighlight')
+ .mockResolvedValue({ version_id: 111, passage_id: 'JHN.3.16', color: 'ffec5b' });
+ onTestFinished(() => {
+ setHighlightsLive(highlightsWereLive);
+ read.mockRestore();
+ signIn.mockRestore();
+ createHighlight.mockRestore();
+ localStorage.clear();
+ sessionStorage.clear();
+ });
+
+ const options = { versionId: 111, book: 'JHN', chapter: '3' };
+ const { result, unmount } = renderHook(() => useBibleReaderHighlights(options), {
+ wrapper: withReaderAuth(null),
+ });
+ act(() => {
+ expect(result.current.apply('FFEC5B', [16])).toBe('flow');
+ });
+ expect(result.current.signInDialogOpen).toBe(true);
+ expect(readPendingHighlights()[0]).toMatchObject({
+ verses: [16],
+ color: 'ffec5b',
+ versionId: 111,
+ chapter: '3',
+ });
+ expect(signIn).not.toHaveBeenCalled();
+ expect(createHighlight).not.toHaveBeenCalled();
+
+ act(() => result.current.confirmSignInDialog());
+ expect(signIn).toHaveBeenCalledWith(
+ 'https://host.example/callback',
+ ['profile', 'read_notes', 'write_notes'],
+ ['highlights'],
+ );
+ unmount();
+
+ YouVersionPlatformConfiguration.saveUserInfo({ id: mockUserInfo.userId });
+ YouVersionPlatformConfiguration.saveGrantedPermissions(['highlights']);
+ renderHook(() => useBibleReaderHighlights(options), {
+ wrapper: withReaderAuth(mockUserInfo),
+ });
+ await waitFor(() => {
+ expect(createHighlight).toHaveBeenCalledWith({
+ version_id: 111,
+ passage_id: 'JHN.3.16',
+ color: 'ffec5b',
+ });
+ });
+ expect(readPendingHighlights()).toEqual([]);
+});
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index 203a0279e..3485d42d6 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -119,16 +119,26 @@ function writerToken(account: string | null) {
return account ? config.getOAuthAccessToken(account, 'write_notes') : null;
}
-function matchesDraftOwner(owner: string | null, account: string | null, state: string | null) {
- // A failed refresh can clear credentials while leaving an active authorization
- // attempt and its initiating profile. That identity can recover the draft only.
+function matchesDraftOwner(
+ owner: string | null,
+ account: string | null,
+ state: string | null,
+ failedCallbackState?: string | null,
+) {
+ // A failed refresh can leave the initiating profile without credentials.
+ // A verified failed callback can then clear its pending state. That proof is
+ // useful for draft recovery only while the same signed-out attempt owns it.
return (
owner === account ||
(account === null &&
owner !== null &&
state !== null &&
config.storedUserInfo?.id === owner &&
- YouVersionAPIUsers.isSignInPending(state))
+ (YouVersionAPIUsers.isSignInPending(state) ||
+ (state === failedCallbackState &&
+ !config.accessToken &&
+ !config.refreshToken &&
+ !YouVersionAPIUsers.isSignInPending())))
);
}
@@ -158,6 +168,9 @@ export function useBibleReaderNote({
const auth = useContext(YouVersionAuthContext);
const account = auth?.userInfo?.userId || null;
const authLoading = auth?.isLoading ?? false;
+ const oauthCallbackState = auth?.oauthCallbackState;
+ const oauthCallbackSuperseded = auth?.oauthCallbackSuperseded;
+ const oauthFailedCallbackState = oauthCallbackSuperseded ? null : auth?.oauthFailedCallbackState;
const canAuthorize = enabled && auth !== null && !auth.isHostControlled && !hostOwnsSignIn;
const createNote = useCreateNote();
const [flow, setFlow] = useState
(null);
@@ -169,8 +182,14 @@ export function useBibleReaderNote({
const handoffState = useRef(null);
const draftAuthorizationState = useRef(null);
const checkedHandoff = useRef(false);
- const latest = useRef({ account, canAuthorize, onSaved, onInvalidated });
- latest.current = { account, canAuthorize, onSaved, onInvalidated };
+ const latest = useRef({
+ account,
+ canAuthorize,
+ oauthFailedCallbackState,
+ onSaved,
+ onInvalidated,
+ });
+ latest.current = { account, canAuthorize, oauthFailedCallbackState, onSaved, onInvalidated };
function show(next: Flow | null) {
currentFlow.current = next;
@@ -192,18 +211,20 @@ export function useBibleReaderNote({
const draft = currentFlow.current?.draft ?? retainedDraft.current;
if (
!draft?.ownerId ||
- matchesDraftOwner(draft.ownerId, account, draftAuthorizationState.current)
+ matchesDraftOwner(
+ draft.ownerId,
+ account,
+ draftAuthorizationState.current,
+ oauthFailedCallbackState,
+ )
)
return;
retainedDraft.current = null;
draftAuthorizationState.current = null;
show(null);
latest.current.onInvalidated(draft.selection);
- }, [account, authLoading]);
+ }, [account, authLoading, oauthFailedCallbackState]);
- const oauthCallbackState = auth?.oauthCallbackState;
- const oauthFailedCallbackState = auth?.oauthFailedCallbackState;
- const oauthCallbackSuperseded = auth?.oauthCallbackSuperseded;
useEffect(() => {
if (authLoading || !canAuthorize || checkedHandoff.current || !reader.current) return;
checkedHandoff.current = true;
@@ -215,7 +236,8 @@ export function useBibleReaderNote({
(returnedState
? returnedState !== handoff.state
: !YouVersionAPIUsers.isSignInPending(handoff.state)) ||
- (handoff.draft.ownerId && !matchesDraftOwner(handoff.draft.ownerId, account, handoff.state))
+ (handoff.draft.ownerId &&
+ !matchesDraftOwner(handoff.draft.ownerId, account, handoff.state, oauthFailedCallbackState))
) {
return;
}
@@ -276,7 +298,12 @@ export function useBibleReaderNote({
retained &&
sameSelection(retained.selection, selection) &&
(!retained.ownerId ||
- matchesDraftOwner(retained.ownerId, account, draftAuthorizationState.current));
+ matchesDraftOwner(
+ retained.ownerId,
+ account,
+ draftAuthorizationState.current,
+ oauthFailedCallbackState,
+ ));
retainedDraft.current = null;
if (!sameOwnedSelection) draftAuthorizationState.current = null;
setAuthorizationFailed(false);
@@ -313,7 +340,12 @@ export function useBibleReaderNote({
(state) => {
if (
currentFlow.current !== redirect ||
- !matchesDraftOwner(redirect.draft.ownerId, latest.current.account, previousState) ||
+ !matchesDraftOwner(
+ redirect.draft.ownerId,
+ latest.current.account,
+ previousState,
+ latest.current.oauthFailedCallbackState,
+ ) ||
!latest.current.canAuthorize ||
(config.storedUserInfo?.id || null) !== redirect.draft.ownerId
) {
@@ -362,7 +394,12 @@ export function useBibleReaderNote({
if (
active?.phase !== 'compose' ||
authLoading ||
- !matchesDraftOwner(active.draft.ownerId, account, draftAuthorizationState.current)
+ !matchesDraftOwner(
+ active.draft.ownerId,
+ account,
+ draftAuthorizationState.current,
+ oauthFailedCallbackState,
+ )
)
return;
const token = writerToken(account);
@@ -414,7 +451,12 @@ export function useBibleReaderNote({
const visibleFlow =
!enabled ||
(flow?.draft.ownerId &&
- !matchesDraftOwner(flow.draft.ownerId, account, draftAuthorizationState.current))
+ !matchesDraftOwner(
+ flow.draft.ownerId,
+ account,
+ draftAuthorizationState.current,
+ oauthFailedCallbackState,
+ ))
? null
: flow;
return {
From 28e5d2ae7f6dabfe4ce682badae158010b9233d9 Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 11:37:19 -0600
Subject: [PATCH 21/75] fix: preserve Reader auth and passage ownership
Keep verified legacy auth tokens available, discard drafts for ended sessions, restore selection during host takeover, and gate highlight writes to the rendered passage.
Ref: YPE-6783
---
packages/core/src/Users.ts | 30 ++++-
.../src/YouVersionPlatformConfiguration.ts | 42 +++++--
.../core/src/__tests__/OAuthWorkflows.test.ts | 5 +
.../YouVersionAuthProvider.oauth.test.tsx | 86 +++++++++++++
.../src/context/YouVersionAuthProvider.tsx | 102 +++++++++++----
packages/hooks/src/types/auth.ts | 2 +
packages/hooks/src/useYVAuth.test.tsx | 117 +++++++++++++++++-
.../ui/scripts/smoke-vite-reader-notes.mjs | 54 +++++++-
.../components/bible-reader-notes.stories.tsx | 77 ++++++++++++
packages/ui/src/components/bible-reader.tsx | 2 +-
.../src/components/use-bible-reader-note.ts | 38 +++---
11 files changed, 492 insertions(+), 63 deletions(-)
diff --git a/packages/core/src/Users.ts b/packages/core/src/Users.ts
index c639824fe..40d1a265d 100644
--- a/packages/core/src/Users.ts
+++ b/packages/core/src/Users.ts
@@ -83,14 +83,16 @@ type PendingGrantedPermissionsStash = StatePermissionsStash;
type RequestedPermissionsStash = StatePermissionsStash;
type TokenRotation = {
- result: SignInWithYouVersionResult;
- previousSession: {
- accessToken: string | null;
- refreshToken: string;
- userId: string | undefined;
+ readonly result: SignInWithYouVersionResult;
+ readonly previousSession: {
+ readonly accessToken: string | null;
+ readonly refreshToken: string;
+ readonly userId: string | undefined;
};
};
+const tokenRotationObservers = new Set<(rotation: TokenRotation) => void>();
+
/**
* Dedupe map for in-flight/settled code-for-token exchanges, keyed by the
* single-use authorization `code`. Under React StrictMode the auth init effect
@@ -678,6 +680,14 @@ export class YouVersionAPIUsers {
return (await this.rotateTokens(false)).result;
}
+ /** Observes successful token rotations in this SDK instance. Returns an unsubscribe function. */
+ static onTokenRotation(observer: (rotation: TokenRotation) => void): () => void {
+ tokenRotationObservers.add(observer);
+ return () => {
+ tokenRotationObservers.delete(observer);
+ };
+ }
+
private static async rotateTokens(clearOnPersistenceFailure: boolean): Promise {
const accessToken = YouVersionPlatformConfiguration.accessToken;
const refreshToken = YouVersionPlatformConfiguration.refreshToken;
@@ -766,7 +776,15 @@ export class YouVersionAPIUsers {
throw new Error('the rotated tokens could not be saved to browser storage');
}
- return { result, previousSession: { accessToken, refreshToken, userId } };
+ const rotation = { result, previousSession: { accessToken, refreshToken, userId } };
+ for (const observer of tokenRotationObservers) {
+ try {
+ observer(rotation);
+ } catch {
+ // An observer cannot turn an already persisted rotation into an authentication failure.
+ }
+ }
+ return rotation;
} catch (error) {
if (error instanceof Error) {
throw new Error(`Token refresh failed: ${error.message}`);
diff --git a/packages/core/src/YouVersionPlatformConfiguration.ts b/packages/core/src/YouVersionPlatformConfiguration.ts
index 157819f6f..0747757be 100644
--- a/packages/core/src/YouVersionPlatformConfiguration.ts
+++ b/packages/core/src/YouVersionPlatformConfiguration.ts
@@ -9,6 +9,23 @@ import type { AuthenticationScopes } from './types';
import { versionFilterState } from './version-filter-state';
import { getLocalStorage, removeStorageItem, setStorageItem } from './web-storage';
+type LegacyAuthSession = {
+ userId: string | null;
+ accessToken: string;
+ refreshToken: string | null;
+};
+
+function parseStoredUserInfo(raw: string | null | undefined): YouVersionUserInfoJSON | null {
+ if (!raw) return null;
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ const result = YouVersionUserInfoJSONSchema.safeParse(parsed);
+ return result.success ? result.data : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* Security Note: Tokens and the decoded user profile are stored in localStorage
* for persistence. The ID token itself is never persisted — it is decoded once at
@@ -124,9 +141,9 @@ export class YouVersionPlatformConfiguration {
/** Returns an account's current access token, verifying the scope or the unchanged legacy session. */
public static getOAuthAccessToken(
- userId: string,
+ userId: string | null,
scope?: AuthenticationScopes,
- legacySession?: Pick,
+ legacySession?: LegacyAuthSession,
): string | null {
const session = this.readOAuthSession();
if (session) {
@@ -286,18 +303,17 @@ export class YouVersionPlatformConfiguration {
* Returns `null` when nothing is stored or the stored value is malformed.
*/
public static get storedUserInfo(): YouVersionUserInfoJSON | null {
- const raw = getLocalStorage()?.getItem('userInfo');
- if (!raw) {
- return null;
- }
+ return parseStoredUserInfo(getLocalStorage()?.getItem('userInfo'));
+ }
- try {
- const parsed: unknown = JSON.parse(raw);
- const result = YouVersionUserInfoJSONSchema.safeParse(parsed);
- return result.success ? result.data : null;
- } catch {
- return null;
- }
+ /** Whether a storage event records the loss or replacement of a signed-in profile. */
+ public static didStoredAccountChange(
+ event: Pick,
+ ): boolean {
+ if (event.key === null) return true;
+ if (event.key !== 'userInfo') return false;
+ const previousUserId = parseStoredUserInfo(event.oldValue)?.id;
+ return !!previousUserId && previousUserId !== parseStoredUserInfo(event.newValue)?.id;
}
public static get tokenExpiryDate(): Date | null {
diff --git a/packages/core/src/__tests__/OAuthWorkflows.test.ts b/packages/core/src/__tests__/OAuthWorkflows.test.ts
index 3a362f900..dfe041b55 100644
--- a/packages/core/src/__tests__/OAuthWorkflows.test.ts
+++ b/packages/core/src/__tests__/OAuthWorkflows.test.ts
@@ -521,6 +521,10 @@ it('shares one refresh request and keeps the rotated session for simultaneous ca
const firstRotation = vi.fn();
const secondRotation = vi.fn();
+ const failingObserver = vi.fn(() => {
+ throw new Error('A rotation observer failed');
+ });
+ onTestFinished(YouVersionAPIUsers.onTokenRotation(failingObserver));
const first = YouVersionAPIUsers.refreshTokenIfNeeded(firstRotation);
const second = YouVersionAPIUsers.refreshTokenIfNeeded(secondRotation);
finishRefresh(tokenResponse('openid profile'));
@@ -536,6 +540,7 @@ it('shares one refresh request and keeps the rotated session for simultaneous ca
};
expect(firstRotation).toHaveBeenCalledExactlyOnceWith(rotation);
expect(secondRotation).toHaveBeenCalledExactlyOnceWith(rotation);
+ expect(failingObserver).toHaveBeenCalledExactlyOnceWith(rotation);
expect(config.accessToken).toBe('signed-in-access');
expect(config.refreshToken).toBe('refresh-token-456');
expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('alice');
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx b/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx
index 57fe1f4bc..77b67e265 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.oauth.test.tsx
@@ -228,3 +228,89 @@ it('takes signed-in and signed-out state from the host across browser auth event
rerender();
expect(result.current.userInfo).toBeNull();
});
+
+it('keeps the host profile after a mounted web provider switches to host ownership', async () => {
+ YouVersionAPIUsers.signOut();
+ onTestFinished(() => YouVersionAPIUsers.signOut());
+ config.saveAuthData('browser-access', 'browser-refresh', new Date('2100-01-01'), {
+ userId: 'browser-account',
+ scope: 'profile',
+ });
+ config.saveUserInfo({ id: 'browser-account' });
+ let hostUser: YouVersionUserInfoJSON | undefined;
+ function ReaderAuth({ children }: PropsWithChildren) {
+ return (
+
+ {children}
+
+ );
+ }
+
+ const { result, rerender } = renderHook(useYouVersionAuthContext, { wrapper: ReaderAuth });
+ await waitFor(() => expect(result.current.userInfo?.userId).toBe('browser-account'));
+ hostUser = { id: 'host-account' };
+ rerender();
+ expect(result.current.userInfo?.userId).toBe('host-account');
+
+ act(() => {
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'userInfo', storageArea: localStorage }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('host-account');
+});
+
+it.each([
+ { scenario: 'a sign-out', intermediate: null, revision: 1 },
+ { scenario: 'an account replacement', intermediate: { id: 'bob' }, revision: 2 },
+ {
+ scenario: 'only a profile update',
+ intermediate: { id: 'alice', name: 'Updated Alice' },
+ revision: 0,
+ },
+])(
+ 'processes $scenario from queued events after Alice is current again',
+ async ({ intermediate, revision }) => {
+ YouVersionAPIUsers.signOut();
+ onTestFinished(() => YouVersionAPIUsers.signOut());
+ config.saveAuthData('first-access', 'first-refresh', new Date('2100-01-01'), {
+ scope: 'profile',
+ userId: 'alice',
+ });
+ config.saveUserInfo({ id: 'alice' });
+ const { result } = renderHook(useYouVersionAuthContext, { wrapper: AuthWrapper });
+ await waitFor(() => expect(result.current.userInfo?.userId).toBe('alice'));
+ const deletedProfile = localStorage.getItem('userInfo');
+ expect(deletedProfile).not.toBeNull();
+
+ act(() => {
+ if (intermediate) config.saveUserInfo(intermediate);
+ else YouVersionAPIUsers.signOut();
+ const intermediateProfile = localStorage.getItem('userInfo');
+ config.saveAuthData('next-access', 'next-refresh', new Date('2100-01-01'), {
+ scope: 'profile',
+ userId: 'alice',
+ });
+ config.saveUserInfo({ id: 'alice' });
+ window.dispatchEvent(
+ new StorageEvent('storage', {
+ key: 'userInfo',
+ oldValue: deletedProfile,
+ newValue: intermediateProfile,
+ storageArea: localStorage,
+ }),
+ );
+ window.dispatchEvent(
+ new StorageEvent('storage', {
+ key: 'userInfo',
+ oldValue: intermediateProfile,
+ newValue: localStorage.getItem('userInfo'),
+ storageArea: localStorage,
+ }),
+ );
+ });
+ expect(result.current.userInfo?.userId).toBe('alice');
+ expect(result.current.accessToken).toBe('next-access');
+ expect(result.current.accountRevision).toBe(revision);
+ },
+);
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.tsx b/packages/hooks/src/context/YouVersionAuthProvider.tsx
index 08d57c37e..fa1bc2d25 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.tsx
@@ -7,7 +7,7 @@ import {
getLocalStorage,
type YouVersionUserInfoJSON,
} from '@youversion/platform-core';
-import React, { useEffect, useState, type ReactNode } from 'react';
+import React, { useEffect, useRef, useState, type ReactNode } from 'react';
import type { AuthConfig, AuthContextValue } from '../types/auth';
import { YouVersionAuthContext } from './YouVersionAuthContext';
@@ -42,10 +42,11 @@ export default function YouVersionAuthProvider({
const [oauthCallbackState, setOAuthCallbackState] = useState(null);
const [oauthFailedCallbackState, setOAuthFailedCallbackState] = useState(null);
const [oauthCallbackSuperseded, setOAuthCallbackSuperseded] = useState(false);
- const [legacySession, setLegacySession] = useState<{
- userId: string;
+ const [accountRevision, setAccountRevision] = useState(0);
+ const legacySession = useRef<{
+ userId: string | null;
accessToken: string;
- refreshToken: string;
+ refreshToken: string | null;
} | null>(null);
useEffect(() => {
@@ -56,6 +57,8 @@ export default function YouVersionAuthProvider({
useEffect(() => {
if (isHostControlled) return;
+ setIsLoading(true);
+ legacySession.current = null;
let mounted = true;
let sessionChanged = false;
const initAuth = async () => {
@@ -80,12 +83,20 @@ export default function YouVersionAuthProvider({
if (result) {
if (!mounted) return;
const storedUser = YouVersionAPIUsers.getStoredUserInfo();
+ const refreshToken = result.refreshToken || null;
const callbackMatchesSession =
storedUser?.userId === result.yvpUserId &&
- result.accessToken === YouVersionPlatformConfiguration.accessToken;
+ result.accessToken === YouVersionPlatformConfiguration.accessToken &&
+ refreshToken === YouVersionPlatformConfiguration.refreshToken;
if (!sessionChanged || callbackMatchesSession) setUserInfo(storedUser);
- if (callbackMatchesSession) setOAuthCallbackState(state);
- else if (sessionChanged) setOAuthCallbackSuperseded(true);
+ if (callbackMatchesSession && result.accessToken) {
+ legacySession.current = {
+ userId: result.yvpUserId ?? null,
+ accessToken: result.accessToken,
+ refreshToken,
+ };
+ setOAuthCallbackState(state);
+ } else if (sessionChanged) setOAuthCallbackSuperseded(true);
}
} catch (err) {
if (!mounted) return;
@@ -101,11 +112,10 @@ export default function YouVersionAuthProvider({
}
}
} else {
- // Check for existing token
+ const accessToken = YouVersionPlatformConfiguration.accessToken;
const refreshToken = YouVersionPlatformConfiguration.refreshToken;
+ const userId = YouVersionPlatformConfiguration.storedUserInfo?.id ?? null;
if (refreshToken) {
- const accessToken = YouVersionPlatformConfiguration.accessToken;
- const userId = YouVersionPlatformConfiguration.storedUserInfo?.id;
let initializedAccessToken = accessToken;
let initializedRefreshToken = refreshToken;
try {
@@ -116,7 +126,7 @@ export default function YouVersionAuthProvider({
if (
previousSession.accessToken === accessToken &&
previousSession.refreshToken === refreshToken &&
- previousSession.userId === userId &&
+ (previousSession.userId ?? null) === userId &&
result.accessToken &&
result.refreshToken
) {
@@ -129,18 +139,25 @@ export default function YouVersionAuthProvider({
if (!sessionChanged) {
const storedUser = refreshed ? YouVersionAPIUsers.getStoredUserInfo() : null;
setUserInfo(storedUser);
- if (initializedAccessToken && userId && storedUser?.userId === userId) {
- setLegacySession({
+ if (
+ refreshed &&
+ initializedAccessToken &&
+ (storedUser?.userId ?? null) === userId
+ ) {
+ legacySession.current = {
userId,
accessToken: initializedAccessToken,
refreshToken: initializedRefreshToken,
- });
+ };
}
}
} catch {
if (!mounted) return;
if (!sessionChanged) setUserInfo(null);
}
+ } else {
+ setUserInfo(null);
+ if (accessToken) legacySession.current = { userId, accessToken, refreshToken };
}
}
}
@@ -161,19 +178,54 @@ export default function YouVersionAuthProvider({
return;
}
sessionChanged = true;
- setLegacySession(null);
+ const accountChanged = YouVersionPlatformConfiguration.didStoredAccountChange(event);
+ const snapshot = legacySession.current;
+ if (
+ accountChanged ||
+ (snapshot &&
+ (YouVersionPlatformConfiguration.refreshToken !== snapshot.refreshToken ||
+ YouVersionPlatformConfiguration.getOAuthAccessToken(
+ snapshot.userId,
+ undefined,
+ snapshot,
+ ) !== snapshot.accessToken))
+ ) {
+ legacySession.current = null;
+ }
+ if (accountChanged) {
+ setAccountRevision((revision) => revision + 1);
+ }
setOAuthCallbackState(null);
setOAuthFailedCallbackState(null);
setUserInfo(getCredentialedUserInfo());
}
+ const unsubscribeRotation = YouVersionAPIUsers.onTokenRotation(
+ ({ result, previousSession }) => {
+ const current = legacySession.current;
+ if (
+ current &&
+ current.userId === (previousSession.userId ?? null) &&
+ current.accessToken === previousSession.accessToken &&
+ current.refreshToken === previousSession.refreshToken &&
+ result.accessToken
+ ) {
+ legacySession.current = {
+ userId: current.userId,
+ accessToken: result.accessToken,
+ refreshToken: result.refreshToken || null,
+ };
+ }
+ },
+ );
globalThis.window?.addEventListener?.('storage', syncSession);
void initAuth();
return () => {
mounted = false;
+ unsubscribeRotation();
globalThis.window?.removeEventListener?.('storage', syncSession);
};
- }, []); // eslint-disable-line react-hooks/exhaustive-deps
+ }, [isHostControlled]); // eslint-disable-line react-hooks/exhaustive-deps
const value: AuthContextValue = {
userInfo,
@@ -181,14 +233,16 @@ export default function YouVersionAuthProvider({
isLoading,
error,
redirectUri: config.redirectUri,
- accessToken:
- !isHostControlled && userInfo?.userId
- ? YouVersionPlatformConfiguration.getOAuthAccessToken(
- userInfo.userId,
- undefined,
- legacySession ?? undefined,
- )
- : null,
+ get accessToken() {
+ if (isHostControlled) return null;
+ const snapshot = legacySession.current;
+ return YouVersionPlatformConfiguration.getOAuthAccessToken(
+ userInfo?.userId ?? snapshot?.userId ?? null,
+ undefined,
+ snapshot ?? undefined,
+ );
+ },
+ accountRevision,
oauthCallbackState,
oauthFailedCallbackState,
oauthCallbackSuperseded,
diff --git a/packages/hooks/src/types/auth.ts b/packages/hooks/src/types/auth.ts
index 5ba566804..d27991cce 100644
--- a/packages/hooks/src/types/auth.ts
+++ b/packages/hooks/src/types/auth.ts
@@ -15,6 +15,8 @@ export interface AuthContextValue {
redirectUri?: string;
/** Access token checked against the current account in the SDK-managed provider. */
accessToken?: string | null;
+ /** Increments when browser storage records that an account was removed or replaced. */
+ accountRevision?: number;
/** State of the verified OAuth callback handled by this provider. */
oauthCallbackState?: string | null;
/** State of a failed OAuth callback that matched the pending authorization attempt. */
diff --git a/packages/hooks/src/useYVAuth.test.tsx b/packages/hooks/src/useYVAuth.test.tsx
index 931ccbdbd..fec0632c0 100644
--- a/packages/hooks/src/useYVAuth.test.tsx
+++ b/packages/hooks/src/useYVAuth.test.tsx
@@ -1,4 +1,4 @@
-import { act, renderHook, waitFor } from '@testing-library/react';
+import { act, render, renderHook, waitFor } from '@testing-library/react';
import { YouVersionAPIUsers, YouVersionPlatformConfiguration } from '@youversion/platform-core';
import { StrictMode, type ReactNode } from 'react';
import { expect, it, onTestFinished, vi } from 'vitest';
@@ -134,6 +134,21 @@ it('keeps an initial legacy token without adopting later unbound credentials', a
expect(result.current.auth.accessToken).toBe('legacy-access');
expect(config.getOAuthAccessToken('legacy-alice', 'write_notes')).toBeNull();
+ act(() => {
+ const previousProfile = localStorage.getItem('userInfo');
+ config.saveUserInfo({ id: 'legacy-alice', name: 'Updated Alice' });
+ window.dispatchEvent(
+ new StorageEvent('storage', {
+ key: 'userInfo',
+ oldValue: previousProfile,
+ newValue: localStorage.getItem('userInfo'),
+ storageArea: localStorage,
+ }),
+ );
+ });
+ expect(result.current.userInfo?.name).toBe('Updated Alice');
+ expect(result.current.auth.accessToken).toBe('legacy-access');
+
act(() => {
config.saveAuthData('new-access', 'new-refresh', expires);
window.dispatchEvent(
@@ -164,6 +179,106 @@ it('keeps an initial legacy token without adopting later unbound credentials', a
expect(result.current.auth.accessToken).toBe('bound-access');
});
+it.each(['alice', null])(
+ 'exposes an initial access-only token when the stored account is %s',
+ async (userId) => {
+ YouVersionAPIUsers.signOut();
+ onTestFinished(() => YouVersionAPIUsers.signOut());
+ const config = YouVersionPlatformConfiguration;
+ config.saveAuthData('access-only', null, new Date('2100-01-01'));
+ if (userId) config.saveUserInfo({ id: userId });
+ const { result } = renderHook(useYVAuth, { wrapper: WebAuthWrapper });
+ await waitFor(() => expect(result.current.auth.isLoading).toBe(false));
+ expect(result.current.auth.accessToken).toBe('access-only');
+ expect(config.getOAuthAccessToken('alice', 'write_notes')).toBeNull();
+ },
+);
+
+it('exposes an unscoped token from a verified callback with no decoded account', async () => {
+ YouVersionAPIUsers.signOut();
+ onTestFinished(() => {
+ vi.unstubAllGlobals();
+ window.history.replaceState(null, '', '/');
+ YouVersionAPIUsers.signOut();
+ });
+ localStorage.setItem('youversion-auth-state', 'opaque-login');
+ localStorage.setItem('youversion-auth-code-verifier', 'test-verifier');
+ localStorage.setItem('youversion-auth-redirect-uri', 'https://example.com/callback');
+ window.history.replaceState(null, '', '?state=opaque-login&code=opaque-code');
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () =>
+ Response.json({
+ access_token: 'opaque-access',
+ refresh_token: 'opaque-refresh',
+ expires_in: 3600,
+ id_token: 'e30.e30.fixture',
+ scope: 'write_notes',
+ token_type: 'Bearer',
+ }),
+ ),
+ );
+
+ const { result } = renderHook(useYVAuth, { wrapper: WebAuthWrapper });
+ await waitFor(() => expect(result.current.auth.isLoading).toBe(false));
+ expect(result.current.userInfo).toBeNull();
+ expect(result.current.auth.accessToken).toBe('opaque-access');
+ expect(YouVersionPlatformConfiguration.getOAuthAccessToken(null, 'write_notes')).toBeNull();
+});
+
+it('exposes a verified direct rotation to a new consumer in the same Provider', async () => {
+ const config = YouVersionPlatformConfiguration;
+ YouVersionAPIUsers.signOut();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () =>
+ Response.json({
+ access_token: 'after-direct-refresh',
+ refresh_token: 'after-direct-refresh-token',
+ expires_in: 3600,
+ scope: 'write_notes',
+ token_type: 'Bearer',
+ }),
+ ),
+ );
+ onTestFinished(() => {
+ vi.unstubAllGlobals();
+ YouVersionAPIUsers.signOut();
+ });
+ config.saveAuthData('before-direct-refresh', 'old-refresh', new Date('2100-01-01'));
+ config.saveUserInfo({ id: 'alice' });
+
+ function Token() {
+ const { auth } = useYVAuth();
+ return {auth.isLoading ? 'loading' : (auth.accessToken ?? 'no token')} ;
+ }
+
+ const view = render(
+
+
+ ,
+ );
+ await view.findByText('before-direct-refresh');
+ await act(async () => {
+ await YouVersionAPIUsers.refreshTokens();
+ });
+ view.rerender(
+
+
+ ,
+ );
+ await view.findByText('after-direct-refresh');
+ expect(config.getOAuthAccessToken('alice', 'write_notes')).toBeNull();
+
+ config.saveAuthData('unrelated-access', 'unrelated-refresh', new Date('2100-01-01'));
+ view.rerender(
+
+
+ ,
+ );
+ await view.findByText('no token');
+});
+
it.each([
{ scenario: 'rotates', replacement: null, owner: 'alice', token: 'rotated-access' },
{ scenario: 'overlaps staged credentials', replacement: 'staged', owner: 'alice', token: null },
diff --git a/packages/ui/scripts/smoke-vite-reader-notes.mjs b/packages/ui/scripts/smoke-vite-reader-notes.mjs
index 1284bce27..02d2c70b9 100644
--- a/packages/ui/scripts/smoke-vite-reader-notes.mjs
+++ b/packages/ui/scripts/smoke-vite-reader-notes.mjs
@@ -28,6 +28,30 @@ const exchanges = new Map();
const intermediateReturns = new Map();
const notes = [];
const page = await context.newPage();
+await page.addInitScript(() => {
+ let queuedStorageEvents;
+ window.addEventListener('storage', (event) => {
+ if (!queuedStorageEvents || !event.isTrusted) return;
+ event.stopImmediatePropagation();
+ const { key, oldValue, newValue, url, storageArea } = event;
+ queuedStorageEvents.push({ key, oldValue, newValue, url, storageArea });
+ });
+ window.delayStorageEvents = () => {
+ queuedStorageEvents = [];
+ };
+ window.deliverStorageEvents = () => {
+ const queued = queuedStorageEvents;
+ queuedStorageEvents = undefined;
+ for (const event of queued) window.dispatchEvent(new StorageEvent('storage', event));
+ return queued.some(
+ ({ key, oldValue, newValue, storageArea }) =>
+ storageArea === localStorage &&
+ key === 'userInfo' &&
+ newValue === null &&
+ JSON.parse(oldValue)?.id === 'bob',
+ );
+ };
+});
await context.route('https://fonts.googleapis.com/**', (route) => route.fulfill({ body: '' }));
await context.route(`${api}/**`, async (route) => {
@@ -85,8 +109,8 @@ await context.route(`${api}/**`, async (route) => {
'base64url',
);
return json({
- access_token: `token-${account.id}`,
- refresh_token: `refresh-${account.id}`,
+ access_token: account.accessToken ?? `token-${account.id}`,
+ refresh_token: account.refreshToken ?? `refresh-${account.id}`,
expires_in: 3600,
id_token: `e30.${claims}.fixture`,
token_type: 'Bearer',
@@ -246,8 +270,32 @@ try {
passage: { bible_id: 3034, passage_id: 'JHN.1.2+JHN.1.4' },
});
+ // A background tab can process Bob's sign-out only after Bob has signed in again.
+ await selectVerses(page, [2]);
+ await beginNote(page);
+ await editor(page).fill('Draft from the ended Bob session');
+ await page.evaluate(() => window.delayStorageEvents());
+ await other.locator('header').getByRole('button', { name: 'Sign out' }).click();
+ await selectVerses(other, [1]);
+ await beginNote(other);
+ const signedInAgain = prepareSignIn(other, {
+ ...writer,
+ accessToken: 'token-new-bob-session',
+ refreshToken: 'refresh-new-bob-session',
+ });
+ await other.getByRole('button', { name: 'Yes Please' }).click();
+ checkScopes(await signedInAgain, readerScopes);
+ await composer(other, 'John 1:1').waitFor();
+ await composer(other, 'John 1:1').getByRole('button', { name: 'Cancel' }).click();
+ assert.equal(await editor(page).inputValue(), 'Draft from the ended Bob session');
+ assert.ok(await page.evaluate(() => window.deliverStorageEvents()), 'Expected queued sign-out');
+ await editor(page).waitFor({ state: 'hidden' });
+ await signedInAs(page, 'Bob').waitFor();
+ assert.deepEqual(await selectedVerses(page), []);
+
await selectVerses(page, [2]);
await beginNote(page);
+ assert.equal(await editor(page).inputValue(), '');
await editor(page).fill('Unsaved Bob draft');
await other.locator('header').getByRole('button', { name: 'Sign out' }).click();
await editor(page).waitFor({ state: 'hidden' });
@@ -255,7 +303,7 @@ try {
assert.equal(notes.length, 1);
console.log(
- 'Reader Notes smoke passed (decline, token-service recovery, two-step grant, exact create, stale callback, sign-out, navbar scopes, and narrow layout).',
+ 'Reader Notes smoke passed (decline, token-service recovery, two-step grant, exact create, stale callback, same-account re-sign-in, sign-out, navbar scopes, and narrow layout).',
);
} finally {
await browser.close();
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index b39f0ec20..55718f311 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -544,9 +544,21 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = {
expect(getBackgroundColorChannels(retained)).toEqual([180, 255, 193, 255]),
);
await expect(postSaveReads).toEqual(['JHN.1']);
+ await userEvent.click(retained);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await waitFor(() => expect(actions.getByRole('button', { name: 'Copy' })).toBeVisible());
+ await expect(actions.getByRole('button', { name: 'Share' })).toBeVisible();
+ await expect(actions.queryByRole('button', { name: 'Clear highlight' })).toBeNull();
+ await expect(actions.queryAllByRole('button', { name: 'Apply highlight' })).toHaveLength(0);
+ await expect(getBackgroundColorChannels(retained)).toEqual([180, 255, 193, 255]);
releaseChapter.resolve();
await waitFor(async () => expect(await readerVerse(root, 16)).toBeVisible());
await waitFor(() => expect(postSaveReads).toEqual(['JHN.1', 'JHN.3']));
+ await selectVerses(root, [16]);
+ const currentActions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await waitFor(() =>
+ expect(currentActions.getAllByRole('button', { name: 'Apply highlight' })).toHaveLength(6),
+ );
} finally {
releaseNote.resolve();
releaseChapter.resolve();
@@ -973,6 +985,71 @@ export const HostControlledSignIn: Story = {
},
};
+export const HostTakesOverSignIn: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ render: function HostSignInReader() {
+ const [hostOwnsSignIn, setHostOwnsSignIn] = useState(false);
+ const [hostSignInRequested, setHostSignInRequested] = useState(false);
+ return (
+ <>
+ setHostOwnsSignIn(true)}>
+ Use host sign-in
+
+ {hostSignInRequested && Host sign-in requested
}
+
+ setHostSignInRequested(true) : undefined}
+ >
+
+
+
+
+ >
+ );
+ },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement);
+ const signIn = spyOn(YouVersionAPIUsers, 'signIn').mockResolvedValue(undefined);
+ try {
+ const root = await waitForShadowRoot(canvasElement);
+ const takeOver = await page.findByRole('button', { name: 'Use host sign-in' });
+ await selectVerses(root, [1, 4]);
+ const overlays = await readerOverlays(root);
+ const initialActions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await userEvent.click(initialActions.getByRole('button', { name: 'Save' }));
+ await waitFor(() =>
+ expect(overlays.getByRole('button', { name: 'Yes Please' })).toBeVisible(),
+ );
+
+ // A host can take ownership regardless of the open Reader modal.
+ takeOver.click();
+ await waitFor(() =>
+ expect(overlays.queryByRole('button', { name: 'Yes Please' })).toBeNull(),
+ );
+ const restoredActions = within(
+ await overlays.findByRole('dialog', { name: 'Verse actions' }),
+ );
+ await waitFor(() =>
+ expect(restoredActions.getByRole('button', { name: 'Copy' })).toBeVisible(),
+ );
+ await expect(restoredActions.queryByRole('button', { name: 'Save' })).toBeNull();
+ await expect(await readerVerse(root, 1)).toHaveClass('yv-v-selected');
+ await expect(await readerVerse(root, 4)).toHaveClass('yv-v-selected');
+ const toolbar = root.querySelector('button[aria-label="Sign In" i]');
+ if (!toolbar) throw new Error('Reader sign-in control is missing');
+ await userEvent.click(toolbar);
+ await userEvent.click(await overlays.findByRole('button', { name: /sign in/i }));
+ await expect(page.getByRole('status')).toHaveTextContent('Host sign-in requested');
+ await expect(signIn).not.toHaveBeenCalled();
+ } finally {
+ signIn.mockRestore();
+ }
+ },
+};
+
export const SharedCopyAndDiscard: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
loaders: [prepareCallback],
diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx
index 7fcbec699..a2369a3ad 100644
--- a/packages/ui/src/components/bible-reader.tsx
+++ b/packages/ui/src/components/bible-reader.tsx
@@ -1151,7 +1151,7 @@ function Content() {
activeHighlights={activeHighlights}
selectedVerses={selectedVerses}
highlightedVerses={highlightedVerses}
- highlightsEnabled={highlightsEnabled}
+ highlightsEnabled={highlightsEnabled && selectionMatchesScope}
anchorElement={anchorElement}
scrollRoot={scrollContainerRef.current}
onHighlight={handleHighlight}
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index 3485d42d6..b9cf0e1f5 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -167,6 +167,8 @@ export function useBibleReaderNote({
}): UseBibleReaderNoteResult {
const auth = useContext(YouVersionAuthContext);
const account = auth?.userInfo?.userId || null;
+ const accountRevision = auth?.accountRevision ?? 0;
+ const lastAccountRevision = useRef(accountRevision);
const authLoading = auth?.isLoading ?? false;
const oauthCallbackState = auth?.oauthCallbackState;
const oauthCallbackSuperseded = auth?.oauthCallbackSuperseded;
@@ -207,23 +209,29 @@ export function useBibleReaderNote({
}
useLayoutEffect(() => {
- if (authLoading) return;
- const draft = currentFlow.current?.draft ?? retainedDraft.current;
+ const accountChanged = accountRevision !== lastAccountRevision.current;
+ lastAccountRevision.current = accountRevision;
+ if (authLoading && !accountChanged) return;
+ const active = currentFlow.current;
+ const draft = active?.draft ?? retainedDraft.current;
if (
- !draft?.ownerId ||
- matchesDraftOwner(
- draft.ownerId,
- account,
- draftAuthorizationState.current,
- oauthFailedCallbackState,
- )
- )
+ draft?.ownerId &&
+ (accountChanged ||
+ !matchesDraftOwner(
+ draft.ownerId,
+ account,
+ draftAuthorizationState.current,
+ oauthFailedCallbackState,
+ ))
+ ) {
+ retainedDraft.current = null;
+ draftAuthorizationState.current = null;
+ show(null);
+ latest.current.onInvalidated(draft.selection);
return;
- retainedDraft.current = null;
- draftAuthorizationState.current = null;
- show(null);
- latest.current.onInvalidated(draft.selection);
- }, [account, authLoading, oauthFailedCallbackState]);
+ }
+ if (!canAuthorize && active?.phase === 'authorize') restoreAfterAuthorization(active);
+ }, [account, accountRevision, authLoading, canAuthorize, oauthFailedCallbackState]);
useEffect(() => {
if (authLoading || !canAuthorize || checkedHandoff.current || !reader.current) return;
From 1f0a017475eab3788cd2dd302b324c784bcbe1ed Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 12:03:59 -0600
Subject: [PATCH 22/75] fix: preserve Reader drafts and OAuth attempt ownership
Retain clean-canceled drafts across navigation, allow matching-chapter highlight intents, and keep verified auth state bound to its active account and handoff.
Ref: YPE-6783
---
packages/core/src/Users.ts | 32 ++--
.../src/YouVersionPlatformConfiguration.ts | 22 ++-
.../core/src/__tests__/OAuthWorkflows.test.ts | 114 +++++++++++--
packages/core/src/auth-storage-keys.ts | 2 +
.../src/context/YouVersionAuthProvider.tsx | 22 ++-
packages/hooks/src/useHighlightAuthActions.ts | 6 +-
packages/hooks/src/useYVAuth.test.tsx | 66 ++++++++
.../bible-reader-notes-composer.tsx | 6 +-
.../components/bible-reader-notes.stories.tsx | 155 +++++++++++++++++-
packages/ui/src/components/bible-reader.tsx | 14 +-
.../src/components/highlight-color-circle.tsx | 5 +-
.../src/components/use-bible-reader-note.ts | 10 +-
.../components/verse-action-popover.test.tsx | 9 -
packages/ui/src/test/storybook-dom.ts | 12 +-
14 files changed, 406 insertions(+), 69 deletions(-)
create mode 100644 packages/core/src/auth-storage-keys.ts
diff --git a/packages/core/src/Users.ts b/packages/core/src/Users.ts
index 40d1a265d..ba28068fa 100644
--- a/packages/core/src/Users.ts
+++ b/packages/core/src/Users.ts
@@ -14,6 +14,7 @@ import {
type TokenExchangeResponse,
} from './schemas/auth';
import { getLocalStorage, removeStorageItem, setStorageItem } from './web-storage';
+import { AUTH_CODE_VERIFIER_KEY, AUTH_STATE_KEY } from './auth-storage-keys';
const MISSING_LOCAL_STORAGE_MESSAGE =
'Sign In with YouVersion requires localStorage, which is not available in this environment';
@@ -26,13 +27,15 @@ const MISSING_LOCAL_STORAGE_MESSAGE =
const REJECTED_LOCAL_STORAGE_WRITE_MESSAGE =
'Sign In with YouVersion could not write to localStorage; the store rejected the write (its quota may be full, as it always is in Safari private browsing)';
-const AUTH_STATE_KEY = 'youversion-auth-state';
-
/** The callback no longer belongs to the active authorization attempt. */
class OAuthCallbackSupersededError extends Error {
override readonly name = 'OAuthCallbackSupersededError';
}
+class VerifiedOAuthCallbackError extends Error {
+ override readonly name = 'VerifiedOAuthCallbackError';
+}
+
/**
* The OAuth handoff has to survive a full-page redirect, so it cannot fall back
* to memory the way the fail-soft accessors do.
@@ -136,15 +139,20 @@ export function __resetTokenRefreshDedupeForTests(): void {
* failure path of the code exchange.
*/
const clearOAuthHandoff = (storage: Storage | null): void => {
- removeStorageItem(storage, 'youversion-auth-code-verifier');
+ removeStorageItem(storage, AUTH_CODE_VERIFIER_KEY);
removeStorageItem(storage, 'youversion-auth-redirect-uri');
removeStorageItem(storage, AUTH_STATE_KEY);
removeStorageItem(storage, PENDING_GRANTED_PERMISSIONS_KEY);
removeStorageItem(storage, REQUESTED_PERMISSIONS_KEY);
};
+function pendingAuthorizationState(): string | null {
+ const storage = getLocalStorage();
+ return storage?.getItem(AUTH_CODE_VERIFIER_KEY) ? storage.getItem(AUTH_STATE_KEY) : null;
+}
+
function clearFailedRefreshSession() {
- if (getLocalStorage()?.getItem(AUTH_STATE_KEY)) {
+ if (pendingAuthorizationState()) {
// A pending sign-in needs its PKCE handoff and the initiating profile.
YouVersionPlatformConfiguration.saveAuthData(null, null, null);
} else {
@@ -276,11 +284,7 @@ export class YouVersionAPIUsers {
beforeRedirect?.(authorizationRequest.parameters.state);
// Store auth data for callback handler
- persistOrThrow(
- storage,
- 'youversion-auth-code-verifier',
- authorizationRequest.parameters.codeVerifier,
- );
+ persistOrThrow(storage, AUTH_CODE_VERIFIER_KEY, authorizationRequest.parameters.codeVerifier);
const redirectUrlString = redirectURL.toString().endsWith('/')
? redirectURL.toString().slice(0, -1)
: redirectURL.toString();
@@ -308,7 +312,7 @@ export class YouVersionAPIUsers {
/** Whether the specified authorization attempt, or any attempt when omitted, is pending. */
static isSignInPending(state?: string): boolean {
- const pendingState = getLocalStorage()?.getItem(AUTH_STATE_KEY);
+ const pendingState = pendingAuthorizationState();
return !!pendingState && (state === undefined || pendingState === state);
}
@@ -334,8 +338,12 @@ export class YouVersionAPIUsers {
}
if (error) {
- // Leave a verified denial readable when StrictMode replays this callback.
const errorDescription = urlParams.get('error_description') || error;
+ if (state) {
+ // Retain state as proof for a replay of the denial, but end the PKCE attempt.
+ removeStorageItem(storage, AUTH_CODE_VERIFIER_KEY);
+ throw new VerifiedOAuthCallbackError(`OAuth authentication failed: ${errorDescription}`);
+ }
throw new Error(`OAuth authentication failed: ${errorDescription}`);
}
@@ -356,7 +364,7 @@ export class YouVersionAPIUsers {
}
// Get stored auth data
- const codeVerifier = storage.getItem('youversion-auth-code-verifier');
+ const codeVerifier = storage.getItem(AUTH_CODE_VERIFIER_KEY);
const redirectUri = storage.getItem('youversion-auth-redirect-uri');
if (!codeVerifier || !redirectUri) {
diff --git a/packages/core/src/YouVersionPlatformConfiguration.ts b/packages/core/src/YouVersionPlatformConfiguration.ts
index 0747757be..421f21fac 100644
--- a/packages/core/src/YouVersionPlatformConfiguration.ts
+++ b/packages/core/src/YouVersionPlatformConfiguration.ts
@@ -8,6 +8,7 @@ import { parsePermissionList } from './permissions';
import type { AuthenticationScopes } from './types';
import { versionFilterState } from './version-filter-state';
import { getLocalStorage, removeStorageItem, setStorageItem } from './web-storage';
+import { AUTH_STATE_KEY } from './auth-storage-keys';
type LegacyAuthSession = {
userId: string | null;
@@ -26,6 +27,12 @@ function parseStoredUserInfo(raw: string | null | undefined): YouVersionUserInfo
}
}
+function invalidateAuthorization(storage: Storage | null, state: string | null | undefined) {
+ if (state && storage?.getItem(AUTH_STATE_KEY) === state) {
+ removeStorageItem(storage, AUTH_STATE_KEY);
+ }
+}
+
/**
* Security Note: Tokens and the decoded user profile are stored in localStorage
* for persistence. The ID token itself is never persisted — it is decoded once at
@@ -83,6 +90,10 @@ export class YouVersionPlatformConfiguration {
oauthSession?: Pick,
): boolean {
const storage = getLocalStorage();
+ const previousState =
+ accessToken !== null && oauthSession && oauthSession.userId !== this.currentUserId
+ ? storage?.getItem(AUTH_STATE_KEY)
+ : null;
let persisted = true;
if (accessToken !== null) {
@@ -110,6 +121,7 @@ export class YouVersionPlatformConfiguration {
removeStorageItem(storage, 'expiryDate');
}
+ if (persisted) invalidateAuthorization(storage, previousState);
return persisted;
}
@@ -122,13 +134,19 @@ export class YouVersionPlatformConfiguration {
*/
public static saveUserInfo(userInfo: YouVersionUserInfoJSON | null): boolean {
const storage = getLocalStorage();
+ const previousId = parseStoredUserInfo(storage?.getItem('userInfo'))?.id ?? null;
+ const previousState =
+ previousId !== (userInfo?.id ?? null) ? storage?.getItem(AUTH_STATE_KEY) : null;
if (userInfo === null) {
removeStorageItem(storage, 'userInfo');
+ if (!storage?.getItem('userInfo')) invalidateAuthorization(storage, previousState);
return true;
}
- return setStorageItem(storage, 'userInfo', JSON.stringify(userInfo));
+ const persisted = setStorageItem(storage, 'userInfo', JSON.stringify(userInfo));
+ if (persisted) invalidateAuthorization(storage, previousState);
+ return persisted;
}
public static clearAuthTokens(): void {
@@ -136,7 +154,7 @@ export class YouVersionPlatformConfiguration {
this.saveUserInfo(null);
this.clearGrantedPermissions();
this.clearDataExchangeInitiator();
- removeStorageItem(getLocalStorage(), 'youversion-auth-state');
+ removeStorageItem(getLocalStorage(), AUTH_STATE_KEY);
}
/** Returns an account's current access token, verifying the scope or the unchanged legacy session. */
diff --git a/packages/core/src/__tests__/OAuthWorkflows.test.ts b/packages/core/src/__tests__/OAuthWorkflows.test.ts
index dfe041b55..a41540b99 100644
--- a/packages/core/src/__tests__/OAuthWorkflows.test.ts
+++ b/packages/core/src/__tests__/OAuthWorkflows.test.ts
@@ -11,6 +11,13 @@ function createOAuthBrowser(transport: 'deferred' | 'msw' = 'deferred') {
const browser = setupBrowserMocks();
const fetch = vi.fn<(request: Request) => Promise>();
if (transport === 'deferred') vi.stubGlobal('fetch', fetch);
+ else if (process.env.INTEGRATION_TESTS) {
+ server.listen();
+ onTestFinished(() => {
+ server.resetHandlers();
+ server.close();
+ });
+ }
const previousAppKey = config.appKey;
const previousHost = config.apiHost;
config.appKey = 'test-app-key';
@@ -81,10 +88,12 @@ function tokenResponse(scope: string) {
it('reports whether any sign-in or the requested sign-in is pending', async () => {
const { browser } = createOAuthBrowser();
expect(YouVersionAPIUsers.isSignInPending()).toBe(false);
+ config.saveUserInfo({ id: 'alice' });
await YouVersionAPIUsers.signIn(redirect);
const state = new URL(browser.window.location.href).searchParams.get('state');
if (!state) throw new Error('Expected an authorization state');
expect(YouVersionAPIUsers.isSignInPending()).toBe(true);
+ config.saveUserInfo({ id: 'alice', name: 'Updated Alice' });
expect(YouVersionAPIUsers.isSignInPending(state)).toBe(true);
expect(YouVersionAPIUsers.isSignInPending('another-state')).toBe(false);
YouVersionAPIUsers.signOut();
@@ -121,8 +130,8 @@ it.each([
expect(config.getOAuthAccessToken('alice', 'write_notes')).toBe('signed-in-access');
});
-it('reports the same verified denial when StrictMode processes the callback twice', async () => {
- const { browser, fetch } = createOAuthBrowser();
+it('reports a verified denial on replay without keeping the authorization active', async () => {
+ const { browser, fetch, arriveWithCode } = createOAuthBrowser();
await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
const authorize = new URL(browser.window.location.href);
const callback = new URL(redirect);
@@ -136,9 +145,93 @@ it('reports the same verified denial when StrictMode processes the callback twic
expect(first).rejects.toThrow('OAuth authentication failed: access_denied'),
expect(second).rejects.toThrow('OAuth authentication failed: access_denied'),
]);
+ expect(YouVersionAPIUsers.isSignInPending()).toBe(false);
+ expect(YouVersionAPIUsers.isSignInPending(callback.searchParams.get('state') ?? '')).toBe(false);
+
+ arriveWithCode('code-after-denial');
+ await expect(YouVersionAPIUsers.handleAuthCallback()).rejects.toThrow();
expect(fetch).not.toHaveBeenCalled();
});
+it('clears the session on a later refresh failure after a verified OAuth denial', async () => {
+ const { browser } = createOAuthBrowser('msw');
+ config.saveAuthData('alice-access', 'alice-refresh', new Date(0), {
+ scope: 'profile',
+ userId: 'alice',
+ });
+ config.saveUserInfo({ id: 'alice' });
+ config.saveGrantedPermissions(['highlights']);
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+ const state = new URL(browser.window.location.href).searchParams.get('state');
+ if (!state) throw new Error('Expected an authorization state');
+ const callback = new URL(redirect);
+ callback.searchParams.set('state', state);
+ callback.searchParams.set('error', 'access_denied');
+ browser.window.location = { href: callback.href, search: callback.search };
+
+ await expect(YouVersionAPIUsers.handleAuthCallback()).rejects.toThrow('access_denied');
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('alice');
+ browser.window.location = { href: redirect, search: '' };
+ server.use(
+ http.post(
+ 'https://api.youversion.com/auth/token',
+ () => new HttpResponse(null, { status: 401 }),
+ ),
+ );
+ await expect(YouVersionAPIUsers.refreshTokenIfNeeded()).resolves.toBe(false);
+
+ expect(config.accessToken).toBeNull();
+ expect(config.refreshToken).toBeNull();
+ expect(config.storedUserInfo).toBeNull();
+ expect(config.grantedPermissions).toEqual([]);
+ expect(YouVersionAPIUsers.isSignInPending(state)).toBe(false);
+});
+
+it.each(['bob', 'alice'])(
+ 'rejects an earlier callback when the account was replaced before return to %s',
+ async (replacement) => {
+ const { browser, fetch, arriveWithCode } = createOAuthBrowser();
+ config.saveAuthData('alice-access', 'alice-refresh', null);
+ config.saveUserInfo({ id: 'alice' });
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+
+ config.saveAuthData('bob-access', 'bob-refresh', null);
+ config.saveUserInfo({ id: 'bob' });
+ if (replacement === 'alice') {
+ config.saveAuthData('new-alice-access', 'new-alice-refresh', null);
+ config.saveUserInfo({ id: 'alice' });
+ }
+ arriveWithCode(`obsolete-before-return-${replacement}`);
+ browser.atob.mockReturnValue(JSON.stringify({ sub: 'alice' }));
+ fetch.mockResolvedValueOnce(tokenResponse('write_notes'));
+
+ await expect(YouVersionAPIUsers.handleAuthCallback()).rejects.toThrow(
+ 'Invalid state parameter',
+ );
+ expect(fetch).not.toHaveBeenCalled();
+ expect(config.storedUserInfo?.id).toBe(replacement);
+ expect(config.accessToken).toBe(replacement === 'bob' ? 'bob-access' : 'new-alice-access');
+ },
+);
+
+it('rejects an earlier callback once another account has staged its scoped credentials', async () => {
+ const { browser, fetch, arriveWithCode } = createOAuthBrowser();
+ config.saveAuthData('alice-access', 'alice-refresh', null);
+ config.saveUserInfo({ id: 'alice' });
+ await YouVersionAPIUsers.signIn(redirect, ['write_notes']);
+
+ config.saveAuthData('bob-access', 'bob-refresh', null, { scope: 'profile', userId: 'bob' });
+ arriveWithCode('obsolete-after-staging');
+ browser.atob.mockReturnValue(JSON.stringify({ sub: 'alice' }));
+ fetch.mockResolvedValueOnce(tokenResponse('write_notes'));
+
+ await expect(YouVersionAPIUsers.handleAuthCallback()).rejects.toThrow('Invalid state parameter');
+ expect(fetch).not.toHaveBeenCalled();
+ expect(config.accessToken).toBe('bob-access');
+ config.saveUserInfo({ id: 'bob' });
+ expect(config.getOAuthAccessToken('bob', 'profile')).toBe('bob-access');
+});
+
it.each(['network', 'server'] as const)(
'retains the current account and token when reauthorization encounters a %s failure',
async (failure) => {
@@ -464,16 +557,15 @@ it('rotates legacy tokens without assigning the returned scope to a stored profi
const originalAccessToken = 'old-access-token';
const originalRefreshToken = 'old-refresh-token';
config.saveAuthData(originalAccessToken, originalRefreshToken, null);
- config.saveUserInfo({ id: 'legacy-user' });
+ const originalProfile = {
+ id: 'legacy-user',
+ name: 'Legacy Reader',
+ email: 'legacy@example.com',
+ avatar_url: 'https://example.com/legacy-avatar.png',
+ };
+ config.saveUserInfo(originalProfile);
const requests: Request[] = [];
- if (process.env.INTEGRATION_TESTS) {
- server.listen();
- onTestFinished(() => {
- server.resetHandlers();
- server.close();
- });
- }
server.use(
http.all('*', ({ request }) => {
requests.push(request);
@@ -508,7 +600,7 @@ it('rotates legacy tokens without assigning the returned scope to a stored profi
expect(config.refreshToken).toBe('new-refresh-token');
expect(config.tokenExpiryDate).toEqual(result?.expiryDate);
expect(config.tokenExpiryDate?.getTime()).toBeGreaterThan(Date.now());
- expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('legacy-user');
+ expect(config.storedUserInfo).toEqual(originalProfile);
expect(config.getOAuthAccessToken('legacy-user', 'write_notes')).toBeNull();
});
diff --git a/packages/core/src/auth-storage-keys.ts b/packages/core/src/auth-storage-keys.ts
new file mode 100644
index 000000000..8bfb2015f
--- /dev/null
+++ b/packages/core/src/auth-storage-keys.ts
@@ -0,0 +1,2 @@
+export const AUTH_STATE_KEY = 'youversion-auth-state';
+export const AUTH_CODE_VERIFIER_KEY = 'youversion-auth-code-verifier';
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.tsx b/packages/hooks/src/context/YouVersionAuthProvider.tsx
index fa1bc2d25..fd96cb747 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.tsx
@@ -67,6 +67,10 @@ export default function YouVersionAuthProvider({
YouVersionPlatformConfiguration.apiHost = config.apiHost ?? 'api.youversion.com';
if (globalThis.window) {
+ const accessToken = YouVersionPlatformConfiguration.accessToken;
+ const refreshToken = YouVersionPlatformConfiguration.refreshToken;
+ const userId = YouVersionPlatformConfiguration.storedUserInfo?.id ?? null;
+ let legacyFallback = accessToken ? { userId, accessToken, refreshToken } : null;
// Check for OAuth callback
const urlParams = new URLSearchParams(globalThis.window.location.search);
const state = urlParams.get('state');
@@ -82,6 +86,7 @@ export default function YouVersionAuthProvider({
}
if (result) {
if (!mounted) return;
+ legacyFallback = null;
const storedUser = YouVersionAPIUsers.getStoredUserInfo();
const refreshToken = result.refreshToken || null;
const callbackMatchesSession =
@@ -104,18 +109,23 @@ export default function YouVersionAuthProvider({
if (process.env.NODE_ENV === 'development') {
console.error('Auth callback failed:', error);
}
- if (error.name === 'OAuthCallbackSupersededError') setOAuthCallbackSuperseded(true);
- else setOAuthFailedCallbackState(pendingState);
+ if (error.name === 'OAuthCallbackSupersededError') {
+ legacyFallback = null;
+ setOAuthCallbackSuperseded(true);
+ } else {
+ const failedState =
+ error.name === 'VerifiedOAuthCallbackError' ? state : pendingState;
+ if (!failedState) legacyFallback = null;
+ setOAuthFailedCallbackState(failedState);
+ }
if (!sessionChanged) {
setError(error);
setUserInfo(getCredentialedUserInfo());
}
}
} else {
- const accessToken = YouVersionPlatformConfiguration.accessToken;
- const refreshToken = YouVersionPlatformConfiguration.refreshToken;
- const userId = YouVersionPlatformConfiguration.storedUserInfo?.id ?? null;
if (refreshToken) {
+ legacyFallback = null;
let initializedAccessToken = accessToken;
let initializedRefreshToken = refreshToken;
try {
@@ -157,9 +167,9 @@ export default function YouVersionAuthProvider({
}
} else {
setUserInfo(null);
- if (accessToken) legacySession.current = { userId, accessToken, refreshToken };
}
}
+ if (mounted && !sessionChanged && legacyFallback) legacySession.current = legacyFallback;
}
if (!mounted) return;
diff --git a/packages/hooks/src/useHighlightAuthActions.ts b/packages/hooks/src/useHighlightAuthActions.ts
index 2863718b8..b6e75b66c 100644
--- a/packages/hooks/src/useHighlightAuthActions.ts
+++ b/packages/hooks/src/useHighlightAuthActions.ts
@@ -51,9 +51,9 @@ export type UseHighlightAuthActionsResult = {
*/
consumeDataExchangeReturn: () => DataExchangeCallbackResult | null;
/**
- * One-fell-swoop: full-page redirect to sign-in, requesting the `highlights`
- * permission alongside `profile`. Returns to `redirectUrl` (or the auth
- * provider's configured `redirectUri`, falling back to the current URL).
+ * Redirects to sign-in with the `highlights` permission and supplied OAuth
+ * scopes. The scopes default to `profile` when omitted. Returns to `redirectUrl`
+ * or the provider's `redirectUri`, falling back to the current URL.
*/
startSignInForHighlights: (
redirectUrl?: string,
diff --git a/packages/hooks/src/useYVAuth.test.tsx b/packages/hooks/src/useYVAuth.test.tsx
index fec0632c0..5e9e8dcef 100644
--- a/packages/hooks/src/useYVAuth.test.tsx
+++ b/packages/hooks/src/useYVAuth.test.tsx
@@ -226,6 +226,71 @@ it('exposes an unscoped token from a verified callback with no decoded account',
expect(YouVersionPlatformConfiguration.getOAuthAccessToken(null, 'write_notes')).toBeNull();
});
+it.each([
+ {
+ outcome: 'a hosted denial',
+ query: 'state=prior-auth&error=access_denied',
+ exchange: false,
+ token: 'legacy-access',
+ },
+ {
+ outcome: 'an exchange failure',
+ query: 'state=prior-auth&code=temporarily-unavailable',
+ exchange: true,
+ token: 'legacy-access',
+ },
+ {
+ outcome: 'a superseded callback',
+ query: 'state=old-auth&code=old-code',
+ exchange: false,
+ token: null,
+ },
+ {
+ outcome: 'an unverified denial',
+ query: 'error=access_denied',
+ exchange: false,
+ token: null,
+ },
+])(
+ 'preserves only the verified legacy token after $outcome',
+ async ({ query, exchange, token }) => {
+ YouVersionAPIUsers.signOut();
+ onTestFinished(() => {
+ vi.unstubAllGlobals();
+ window.history.replaceState(null, '', '/');
+ YouVersionAPIUsers.signOut();
+ });
+ const config = YouVersionPlatformConfiguration;
+ config.saveAuthData('legacy-access', 'legacy-refresh', new Date('2100-01-01'));
+ config.saveUserInfo({ id: 'legacy-alice' });
+ localStorage.setItem('youversion-auth-state', 'prior-auth');
+ localStorage.setItem('youversion-auth-code-verifier', 'test-verifier');
+ localStorage.setItem('youversion-auth-redirect-uri', 'https://example.com/callback');
+ window.history.replaceState(null, '', `?${query}`);
+ const fetch = vi.fn(async () => new Response(null, { status: 503 }));
+ vi.stubGlobal('fetch', fetch);
+
+ const { result } = renderHook(
+ () => ({ ...useYVAuth(), failedState: useYouVersionAuthContext().oauthFailedCallbackState }),
+ {
+ wrapper: ({ children }) => (
+
+ {children}
+
+ ),
+ },
+ );
+ await waitFor(() => expect(result.current.auth.isLoading).toBe(false));
+ expect(result.current.auth.isAuthenticated).toBe(true);
+ expect(result.current.userInfo?.userId).toBe('legacy-alice');
+ expect(result.current.auth.error).toBeInstanceOf(Error);
+ expect(result.current.auth.accessToken).toBe(token);
+ expect(result.current.failedState).toBe(token ? 'prior-auth' : null);
+ expect(config.getOAuthAccessToken('legacy-alice', 'write_notes')).toBeNull();
+ expect(fetch).toHaveBeenCalledTimes(Number(exchange));
+ },
+);
+
it('exposes a verified direct rotation to a new consumer in the same Provider', async () => {
const config = YouVersionPlatformConfiguration;
YouVersionAPIUsers.signOut();
@@ -357,6 +422,7 @@ it('keeps a pending authorization profile signed out on remount and storage upda
onTestFinished(() => YouVersionAPIUsers.signOut());
YouVersionPlatformConfiguration.saveUserInfo({ id: 'pending-alice' });
localStorage.setItem('youversion-auth-state', 'pending-note-authorization');
+ localStorage.setItem('youversion-auth-code-verifier', 'test-verifier');
const { result } = renderHook(useYVAuth, { wrapper: WebAuthWrapper });
await waitFor(() => expect(result.current.auth.isLoading).toBe(false));
diff --git a/packages/ui/src/components/bible-reader-notes-composer.tsx b/packages/ui/src/components/bible-reader-notes-composer.tsx
index d7ffed10b..5f0e3186d 100644
--- a/packages/ui/src/components/bible-reader-notes-composer.tsx
+++ b/packages/ui/src/components/bible-reader-notes-composer.tsx
@@ -17,7 +17,7 @@ type NotesComposerProps = {
failed: boolean;
onChange: (fields: Partial) => void;
onSave: () => void;
- onDismiss: () => void;
+ onDismiss: (intent: 'cancel' | 'discard') => void;
theme: 'light' | 'dark';
restoreFocusTarget: HTMLElement | null;
};
@@ -66,7 +66,7 @@ export function BibleReaderNotesComposer({
}
setConfirmDiscard(true);
} else {
- onDismiss();
+ onDismiss('cancel');
}
}
@@ -179,7 +179,7 @@ export function BibleReaderNotesComposer({
{t('cancel')}
-
+ onDismiss('discard')}>
{t('notesDiscard')}
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index 55718f311..7927bc321 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -13,6 +13,7 @@ import { globalHandlers } from '@/test/mocks/handlers';
import mockPassages from '@/test/mock-data/passages.json';
import {
getBackgroundColorChannels,
+ getColorChannels,
verifyNativeBrowserKey,
waitForShadowRoot,
} from '@/test/storybook-dom';
@@ -152,6 +153,17 @@ async function openComposer(root: ShadowRoot, reference: string) {
return { overlays, composer: within(composer) };
}
+async function expectSwatchBorder(swatch: HTMLElement | undefined, expectedColor: string) {
+ if (!swatch) throw new Error('Reader highlight swatch is missing');
+ const { ownerDocument } = swatch;
+ const style = getComputedStyle(swatch);
+ await expect(style.borderTopWidth).toBe('1px');
+ await expect(style.borderTopStyle).toBe('solid');
+ await expect(getColorChannels(style.borderTopColor, ownerDocument)).toEqual(
+ getColorChannels(expectedColor, ownerDocument),
+ );
+}
+
export const SavePassage: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
loaders: [prepareCallback],
@@ -171,6 +183,10 @@ export const SavePassage: Story = {
const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
await expect(actions.getByRole('button', { name: 'Copy' })).toBeInTheDocument();
await expect(actions.getByRole('button', { name: 'Share' })).toBeInTheDocument();
+ await expectSwatchBorder(
+ actions.getAllByRole('button', { name: 'Apply highlight' })[0],
+ 'rgba(18, 18, 18, 0.2)',
+ );
const { composer } = await openComposer(root, 'John 1:1,3-4');
await expect(composer.getByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
await expect(composer.getByRole('radio', { name: 'Private' })).toBeChecked();
@@ -208,6 +224,13 @@ export const EditAndRetry: Story = {
if (!settings) throw new Error('Reader settings control is missing');
settings.focus();
await selectVerses(root, [2]);
+ const actions = within(
+ await (await readerOverlays(root)).findByRole('dialog', { name: 'Verse actions' }),
+ );
+ await expectSwatchBorder(
+ actions.getAllByRole('button', { name: 'Apply highlight' })[0],
+ 'rgba(255, 255, 255, 0.2)',
+ );
const { overlays, composer } = await openComposer(root, 'John 1:2');
const editor = composer.getByRole('textbox', { name: 'Add Note…' });
await waitFor(() => expect(root.activeElement).toBe(editor));
@@ -426,6 +449,65 @@ export const BuiltInActionsDuringNavigation: Story = {
}),
};
+export const ControlledHighlightsDuringSameChapterNavigation: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ loaders: [async () => ({ hostNavigation: new BibleReaderNavigation() })],
+ render: function ControlledReader(_args, { loaded }) {
+ const [applied, setApplied] = useState('');
+ return (
+ <>
+ {applied}
+
+
+ setApplied(`${versionId}:${passageIds.join('+')}:${color}`)
+ }
+ >
+
+
+
+ >
+ );
+ },
+ play: async ({ canvasElement, loaded }) => {
+ const passageRequested = deferred();
+ const releasePassage = deferred();
+ getWorker().use(
+ http.get('*/v1/bibles/111/passages/JHN.1.4', async () => {
+ passageRequested.resolve();
+ await releasePassage.promise;
+ return new HttpResponse(null, { status: 503 });
+ }),
+ );
+ const root = await waitForShadowRoot(canvasElement);
+ const retainedVerse = await readerVerse(root, 1);
+ try {
+ storyNavigation
+ .parse(loaded.hostNavigation)
+ .request({ versionId: 111, passageId: 'JHN.1.4' });
+ await passageRequested.promise;
+ await expect(retainedVerse).toBeVisible();
+ await userEvent.click(retainedVerse);
+ const overlays = await readerOverlays(root);
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await waitFor(() => expect(actions.getByRole('button', { name: 'Copy' })).toBeVisible());
+ const [color] = actions.getAllByRole('button', { name: 'Apply highlight' });
+ if (!color) throw new Error('Controlled highlight swatches are missing');
+ await userEvent.click(color);
+ await expect(
+ within(canvasElement).getByRole('status', { name: 'Applied highlight' }),
+ ).toHaveTextContent('111:JHN.1.1:ffec5b');
+ } finally {
+ releasePassage.resolve();
+ }
+ },
+};
+
export const RefreshDisplayedChapterAfterNavigation: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
loaders: [prepareCallback, async () => ({ hostNavigation: new BibleReaderNavigation() })],
@@ -497,6 +579,50 @@ export const RefreshDisplayedChapterAfterNavigation: Story = {
}),
};
+export const CancelRetainsDraftAcrossNavigation: Story = {
+ ...RefreshDisplayedChapterAfterNavigation,
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ play: withWritableSession(async ({ canvasElement, loaded }) => {
+ const attempts: NoteRequest[] = [];
+ getWorker().use(
+ http.post('*/v1/notes', async ({ request }) => {
+ const body = await request.json();
+ attempts.push(body);
+ return attempts.length === 1 ? HttpResponse.error() : noteResponse(body);
+ }),
+ );
+ const root = await waitForShadowRoot(canvasElement);
+ const navigation = storyNavigation.parse(loaded.hostNavigation);
+ const renderedPassage = () => root.querySelector('[data-slot="yv-bible-renderer"]');
+ await selectVerses(root, [1, 4]);
+ const { composer, overlays } = await openComposer(root, 'John 1:1,4');
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(composer.getByRole('alert')).toBeVisible());
+
+ navigation.request({ versionId: 111, passageId: 'JHN.3' });
+ await waitFor(() => expect(renderedPassage()).toHaveTextContent('Nicodemus'));
+ await userEvent.click(composer.getByRole('button', { name: 'Cancel' }));
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ await expect(renderedPassage()).toHaveTextContent('Nicodemus');
+
+ navigation.request({ versionId: 111, passageId: 'JHN.1' });
+ await waitFor(() => expect(renderedPassage()).toHaveTextContent('The Word Became Flesh'));
+ await selectVerses(root, [1, 4]);
+ const { composer: reopened } = await openComposer(root, 'John 1:1,4');
+ await expect(reopened.getByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
+ await userEvent.click(reopened.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ const request = {
+ request_id: expect.stringMatching(/^[\da-f-]{36}$/i),
+ passage: { bible_id: 111, passage_id: 'JHN.1.1+JHN.1.4' },
+ content: '',
+ status: 'private',
+ };
+ await expect(attempts).toEqual([request, request]);
+ await expect(attempts[1]?.request_id).toBe(attempts[0]?.request_id);
+ }),
+};
+
export const RefreshRetainedChapterWhileNavigationLoads: Story = {
...RefreshDisplayedChapterAfterNavigation,
tags: ['integration', 'shadow-dom', 'cross-browser'],
@@ -637,6 +763,19 @@ export const WritePermissionChangesWhileEditing: Story = {
}),
};
+function ReaderPage({ version }: { version: number }) {
+ const [mountedVersion] = useState(version);
+ return {mountedVersion} ;
+}
+
+function waitForReaderPage(container: HTMLElement, version: number) {
+ return waitFor(() =>
+ expect(within(container).getByLabelText('Reader page')).toHaveTextContent(
+ new RegExp(`^${version}$`),
+ ),
+ );
+}
+
function ReloadableReader({ withCallback = false }: { withCallback?: boolean }) {
const [pageVersion, setPageVersion] = useState(0);
return (
@@ -665,6 +804,7 @@ function ReloadableReader({ withCallback = false }: { withCallback?: boolean })
locale="en"
includeAuth
>
+
@@ -707,8 +847,8 @@ export const RemountDropsDraftFromReplacedSession: Story = {
YouVersionPlatformConfiguration.saveUserInfo(profile);
await userEvent.click(within(canvasElement).getByRole('button', { name: 'Reload Reader' }));
+ await waitForReaderPage(canvasElement, 1);
const remounted = await waitForShadowRoot(canvasElement);
- await expect(remounted).not.toBe(root);
await expect(await readerVerse(remounted, 1)).not.toHaveClass('yv-v-selected');
await expect(await readerVerse(remounted, 4)).not.toHaveClass('yv-v-selected');
await selectVerses(remounted, [1, 4]);
@@ -761,8 +901,8 @@ export const RemountRecoversDraftDuringFailedRefresh: Story = {
}),
);
await userEvent.click(page.getByRole('button', { name: 'Reload Reader' }));
+ await waitForReaderPage(canvasElement, 1);
const remounted = await waitForShadowRoot(canvasElement);
- await expect(remounted).not.toBe(root);
const returnedOverlays = await readerOverlays(remounted);
const actions = within(
await returnedOverlays.findByRole('dialog', { name: 'Verse actions' }),
@@ -774,8 +914,8 @@ export const RemountRecoversDraftDuringFailedRefresh: Story = {
await waitFor(() => expect(returnedOverlays.queryByRole('dialog')).toBeNull());
await userEvent.click(page.getByRole('button', { name: 'Return from sign-in' }));
+ await waitForReaderPage(canvasElement, 2);
const failedRoot = await waitForShadowRoot(canvasElement);
- await expect(failedRoot).not.toBe(remounted);
await waitFor(() => expect(failedGrants).toEqual(['refresh_token', 'authorization_code']));
await waitFor(async () =>
expect(await readerVerse(failedRoot, 1)).toHaveClass('yv-v-selected'),
@@ -793,6 +933,7 @@ export const RemountRecoversDraftDuringFailedRefresh: Story = {
http.post('*/auth/token', () => tokenResponse('profile read_notes write_notes')),
);
await userEvent.click(page.getByRole('button', { name: 'Return from sign-in' }));
+ await waitForReaderPage(canvasElement, 3);
const finalRoot = await waitForShadowRoot(canvasElement);
const finalOverlays = await readerOverlays(finalRoot);
const returned = within(await finalOverlays.findByRole('dialog', { name: 'John 1:1,4' }));
@@ -811,6 +952,7 @@ function stayOnAuthorizationHandoff() {
const state = crypto.randomUUID();
beforeRedirect?.(state);
localStorage.setItem('youversion-auth-state', state);
+ localStorage.setItem('youversion-auth-code-verifier', 'notes-story-verifier');
},
);
}
@@ -867,6 +1009,7 @@ function ParallelReaders() {
locale="en"
includeAuth
>
+
{['First Reader', 'Second Reader'].map((label) => (
@@ -907,11 +1050,7 @@ export const OAuthReturnsToTheInitiatingReader: Story = {
);
await userEvent.click(page.getByRole('button', { name: 'Return from sign-in' }));
- await waitFor(async () =>
- expect(
- await waitForShadowRoot(page.getByRole('region', { name: 'Second Reader' })),
- ).not.toBe(secondRoot),
- );
+ await waitForReaderPage(canvasElement, 1);
const returned = await waitForShadowRoot(page.getByRole('region', { name: 'Second Reader' }));
const returnedOverlays = await readerOverlays(returned);
const note = await returnedOverlays.findByRole('dialog', { name: 'John 1:1,4' });
diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx
index a2369a3ad..3469a3681 100644
--- a/packages/ui/src/components/bible-reader.tsx
+++ b/packages/ui/src/components/bible-reader.tsx
@@ -616,9 +616,13 @@ function Content() {
useLayoutEffect(() => {
if (renderedReference) displayedHighlightScope.current = { versionId, book, chapter };
}, [renderedReference, versionId, book, chapter]);
- // While the old passage stays on screen, its highlight read and paint stay with it.
- const retainedHighlightScope =
- isRefetching && !isHighlightsControlled ? displayedHighlightScope.current : null;
+ // Read and paint follow the retained passage. Writes target the selected chapter.
+ const retainedChapter = isRefetching ? displayedHighlightScope.current : null;
+ const highlightSelectionMatchesChapter =
+ selectionMatchesScope ||
+ (retainedChapter?.versionId === versionId &&
+ retainedChapter.book === book &&
+ retainedChapter.chapter === chapter);
const {
highlightedVerses,
@@ -637,7 +641,7 @@ function Content() {
versionId,
book,
chapter,
- retainedScope: retainedHighlightScope,
+ retainedScope: isHighlightsControlled ? null : retainedChapter,
hostOwnsSignIn: !!onSignInPress,
controlled: isHighlightsControlled
? {
@@ -1151,7 +1155,7 @@ function Content() {
activeHighlights={activeHighlights}
selectedVerses={selectedVerses}
highlightedVerses={highlightedVerses}
- highlightsEnabled={highlightsEnabled && selectionMatchesScope}
+ highlightsEnabled={highlightsEnabled && highlightSelectionMatchesChapter}
anchorElement={anchorElement}
scrollRoot={scrollContainerRef.current}
onHighlight={handleHighlight}
diff --git a/packages/ui/src/components/highlight-color-circle.tsx b/packages/ui/src/components/highlight-color-circle.tsx
index 5b3efb054..13f892ae1 100644
--- a/packages/ui/src/components/highlight-color-circle.tsx
+++ b/packages/ui/src/components/highlight-color-circle.tsx
@@ -23,18 +23,17 @@ export function HighlightColorCircle({
}: HighlightColorCircleProps): ReactElement {
const isDark = theme === 'dark';
const backgroundColor = highlightFillColorMix(color, 'card') ?? undefined;
- // A contrasting edge defines pale swatches on light cards and dimmed swatches on dark cards.
- const border = isDark ? '1px solid rgba(255, 255, 255, 0.2)' : '1px solid rgba(18, 18, 18, 0.2)';
return (
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index b9cf0e1f5..73ba8240a 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -72,7 +72,7 @@ type UseBibleReaderNoteResult = {
authorize: () => Promise;
cancelAuthorization: () => void;
change: (fields: Partial) => void;
- dismiss: () => void;
+ dismiss: (intent: 'cancel' | 'discard') => void;
save: () => Promise;
};
@@ -393,8 +393,12 @@ export function useBibleReaderNote({
if (active?.phase === 'compose') show({ ...active, draft: { ...active.draft, ...fields } });
}
- function dismiss() {
- if (currentFlow.current?.phase === 'compose') show(null);
+ function dismiss(intent: 'cancel' | 'discard') {
+ const active = currentFlow.current;
+ if (active?.phase !== 'compose') return;
+ retainedDraft.current = intent === 'cancel' ? active.draft : null;
+ if (intent === 'discard') draftAuthorizationState.current = null;
+ show(null);
}
async function save() {
diff --git a/packages/ui/src/components/verse-action-popover.test.tsx b/packages/ui/src/components/verse-action-popover.test.tsx
index edb066eb7..a80429004 100644
--- a/packages/ui/src/components/verse-action-popover.test.tsx
+++ b/packages/ui/src/components/verse-action-popover.test.tsx
@@ -529,15 +529,6 @@ describe('VerseActionPopover', () => {
expect(firstApplySwatch().style.backgroundColor).toContain('var(--yv-card)');
});
- it('uses a dark inner stroke in light mode and a light one in dark mode', () => {
- const { unmount } = render( );
- expect(firstApplySwatch().style.border).toContain('rgba(18, 18, 18, 0.2)');
- unmount();
-
- render( );
- expect(firstApplySwatch().style.border).toContain('rgba(255, 255, 255, 0.2)');
- });
-
it('keeps the active-swatch checkmark legible on the dimmed dark-mode fill', () => {
render(
{
return waitFor(() => requireShadowContent(root));
}
-/** Resolve computed CSS colors to sRGB bytes across browser serialization formats. */
-export function getBackgroundColorChannels(element: Element): number[] {
- const context = element.ownerDocument.createElement('canvas').getContext('2d');
+/** Resolve CSS colors to sRGB bytes across browser serialization formats. */
+export function getColorChannels(color: string, ownerDocument: Document): number[] {
+ const context = ownerDocument.createElement('canvas').getContext('2d');
if (!context) throw new Error('2D canvas is unavailable');
- context.fillStyle = getComputedStyle(element).backgroundColor;
+ context.fillStyle = color;
context.fillRect(0, 0, 1, 1);
return Array.from(context.getImageData(0, 0, 1, 1).data);
}
+export function getBackgroundColorChannels(element: Element): number[] {
+ return getColorChannels(getComputedStyle(element).backgroundColor, element.ownerDocument);
+}
+
export async function clickStoryElement(element: Element): Promise {
if (__YV_STORYBOOK_VITEST__) {
const { userEvent } = await import('vitest/browser');
From db5916df0dc2ee54acf3dedddffdf09b8fdd260d Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 12:37:44 -0600
Subject: [PATCH 23/75] fix: isolate Reader authorization handoffs
Resume Notes on the verified configured callback, supersede an older pending highlight action, and keep account-bound requests and drafts tied to the right session. Preserve standalone swatch outlines under host styling.
Ref: YPE-6783
---
examples/vite-react/README.md | 2 +-
.../src/YouVersionPlatformConfiguration.ts | 9 +
.../core/src/__tests__/OAuthWorkflows.test.ts | 65 +++--
.../src/context/YouVersionAuthProvider.tsx | 28 +-
packages/hooks/src/internal/useUserScope.ts | 12 +-
packages/hooks/src/types/auth.ts | 2 +-
.../hooks/src/useHighlights.auth.test.tsx | 94 +++++++
packages/hooks/src/useHighlights.ts | 20 +-
packages/hooks/src/useYVAuth.test.tsx | 29 +++
.../ui/scripts/smoke-vite-reader-notes.mjs | 48 +++-
.../bible-reader-highlights-machine.ts | 3 +
.../components/bible-reader-notes.stories.tsx | 242 ++++++++++++++++--
.../src/components/bible-reader.stories.tsx | 50 +---
packages/ui/src/components/bible-reader.tsx | 2 +
.../src/components/highlight-color-circle.tsx | 5 +-
.../components/use-bible-reader-highlights.ts | 4 +
.../src/components/use-bible-reader-note.ts | 114 ++++++---
...ction-popover.shadow-isolation.stories.tsx | 55 +++-
18 files changed, 631 insertions(+), 153 deletions(-)
create mode 100644 packages/hooks/src/useHighlights.auth.test.tsx
diff --git a/examples/vite-react/README.md b/examples/vite-react/README.md
index 4942ddb3b..0433e7418 100644
--- a/examples/vite-react/README.md
+++ b/examples/vite-react/README.md
@@ -38,7 +38,7 @@ Run these commands from the repository root after installing Playwright Chromium
```bash
pnpm build
VITE_YVP_APP_KEY=notes-smoke VITE_YVP_API_HOST=notes-smoke.example.test \
- VITE_YVP_AUTH_REDIRECT_URL=http://127.0.0.1:5176 VITE_YVP_LOCALE=en \
+ VITE_YVP_AUTH_REDIRECT_URL=http://127.0.0.1:5176/callback/ VITE_YVP_LOCALE=en \
pnpm --filter vite-react dev --port 5176 --strictPort
```
diff --git a/packages/core/src/YouVersionPlatformConfiguration.ts b/packages/core/src/YouVersionPlatformConfiguration.ts
index 421f21fac..91a0242b3 100644
--- a/packages/core/src/YouVersionPlatformConfiguration.ts
+++ b/packages/core/src/YouVersionPlatformConfiguration.ts
@@ -178,6 +178,15 @@ export class YouVersionPlatformConfiguration {
: null;
}
+ /**
+ * Whether a persisted OAuth binding is invalid or disagrees with the stored credentials or profile.
+ * An absent legacy binding does not block profile display. Managed account requests still need
+ * a validated token from `getOAuthAccessToken`.
+ */
+ public static get hasMismatchedOAuthSession(): boolean {
+ return this.readOAuthSession() === null;
+ }
+
/** @internal Reads the OAuth session for token rotation, or `null` for a mismatched record. */
public static readOAuthSession(): StoredOAuthSession | null | undefined {
const storage = getLocalStorage();
diff --git a/packages/core/src/__tests__/OAuthWorkflows.test.ts b/packages/core/src/__tests__/OAuthWorkflows.test.ts
index a41540b99..4d5535c3e 100644
--- a/packages/core/src/__tests__/OAuthWorkflows.test.ts
+++ b/packages/core/src/__tests__/OAuthWorkflows.test.ts
@@ -235,7 +235,16 @@ it('rejects an earlier callback once another account has staged its scoped crede
it.each(['network', 'server'] as const)(
'retains the current account and token when reauthorization encounters a %s failure',
async (failure) => {
- const { fetch, arriveWithCode } = createOAuthBrowser();
+ const { arriveWithCode } = createOAuthBrowser('msw');
+ let tokenRequests = 0;
+ server.use(
+ http.post('https://api.youversion.com/auth/token', () => {
+ tokenRequests++;
+ return failure === 'network'
+ ? HttpResponse.error()
+ : new HttpResponse(null, { status: 503 });
+ }),
+ );
config.saveAuthData('current-access', 'current-refresh', new Date('2100-01-01'), {
scope: 'read_notes',
userId: 'alice',
@@ -244,8 +253,6 @@ it.each(['network', 'server'] as const)(
await YouVersionAPIUsers.signIn(redirect, ['read_notes', 'write_notes']);
arriveWithCode(`reauthorize-${failure}-failure`);
- if (failure === 'network') fetch.mockRejectedValueOnce(new TypeError('Failed to fetch'));
- else fetch.mockResolvedValueOnce(new Response(null, { status: 503 }));
await expect(YouVersionAPIUsers.handleAuthCallback()).rejects.toMatchObject({
name: failure === 'network' ? 'TypeError' : 'Error',
});
@@ -256,7 +263,7 @@ it.each(['network', 'server'] as const)(
await expect(YouVersionAPIUsers.handleAuthCallback()).rejects.toThrow(
'Invalid state parameter',
);
- expect(fetch).toHaveBeenCalledTimes(1);
+ expect(tokenRequests).toBe(1);
},
);
@@ -300,7 +307,12 @@ it.each([
);
it('requests note scopes at authorize and reads the grants from the exchanged token', async () => {
- const { browser, fetch, values, arriveWithCode } = createOAuthBrowser();
+ const { browser, values, arriveWithCode } = createOAuthBrowser('msw');
+ server.use(
+ http.post('https://api.youversion.com/auth/token', () =>
+ HttpResponse.json(makeTokens('openid profile read_notes write_notes')),
+ ),
+ );
const beforeRedirect = vi.fn(() => {
expect(browser.window.location.href).toBe('');
});
@@ -339,7 +351,6 @@ it('requests note scopes at authorize and reads the grants from the exchanged to
for (const key of handoffKeys) expect(values.has(key)).toBe(true);
arriveWithCode('notes-code');
- fetch.mockResolvedValueOnce(Response.json(makeTokens('openid profile read_notes write_notes')));
const result = await YouVersionAPIUsers.handleAuthCallback();
expect(result).toMatchObject({
accessToken: 'access-token-123',
@@ -365,29 +376,34 @@ it('requests note scopes at authorize and reads the grants from the exchanged to
});
it('retains note scopes when rotation omits scope and replaces them when the response narrows it', async () => {
- const { fetch } = createOAuthBrowser();
+ createOAuthBrowser('msw');
config.saveAuthData('initial-access-token', 'initial-refresh-token', new Date(0), {
scope: 'openid read_notes write_notes',
userId: 'notes-account',
});
config.saveUserInfo({ id: 'notes-account' });
const rotation = { expires_in: 3600, token_type: 'Bearer' };
- fetch
- .mockResolvedValueOnce(
- Response.json({
- ...rotation,
- access_token: 'rotated-access',
- refresh_token: 'rotated-refresh',
- }),
- )
- .mockResolvedValueOnce(
- Response.json({
- ...rotation,
- access_token: 'reduced-access',
- refresh_token: 'reduced-refresh',
- scope: 'openid read_notes',
- }),
- );
+ server.use(
+ http.post('https://api.youversion.com/auth/token', async ({ request }) => {
+ const body = new URLSearchParams(await request.text());
+ if (body.get('refresh_token') === 'initial-refresh-token') {
+ return HttpResponse.json({
+ ...rotation,
+ access_token: 'rotated-access',
+ refresh_token: 'rotated-refresh',
+ });
+ }
+ if (body.get('refresh_token') === 'rotated-refresh') {
+ return HttpResponse.json({
+ ...rotation,
+ access_token: 'reduced-access',
+ refresh_token: 'reduced-refresh',
+ scope: 'openid read_notes',
+ });
+ }
+ return HttpResponse.json({ error: 'invalid_grant' }, { status: 401 });
+ }),
+ );
await YouVersionAPIUsers.refreshTokens();
expect(config.getOAuthAccessToken('notes-account', 'read_notes')).toBe('rotated-access');
@@ -412,6 +428,7 @@ it('waits for a matching profile instead of refreshing a staged account token',
});
fetch.mockResolvedValueOnce(Response.json(makeTokens('openid write_notes')));
+ expect(config.hasMismatchedOAuthSession).toBe(true);
await expect(YouVersionAPIUsers.refreshTokens()).rejects.toThrow();
const refreshed = await YouVersionAPIUsers.refreshTokenIfNeeded();
@@ -420,6 +437,7 @@ it('waits for a matching profile instead of refreshing a staged account token',
expect(refreshed).toBe(false);
expect(fetch).not.toHaveBeenCalled();
config.saveUserInfo({ id: 'new-account' });
+ expect(config.hasMismatchedOAuthSession).toBe(false);
expect(config.getOAuthAccessToken('new-account', 'write_notes')).toBe('new-access');
});
@@ -601,6 +619,7 @@ it('rotates legacy tokens without assigning the returned scope to a stored profi
expect(config.tokenExpiryDate).toEqual(result?.expiryDate);
expect(config.tokenExpiryDate?.getTime()).toBeGreaterThan(Date.now());
expect(config.storedUserInfo).toEqual(originalProfile);
+ expect(config.hasMismatchedOAuthSession).toBe(false);
expect(config.getOAuthAccessToken('legacy-user', 'write_notes')).toBeNull();
});
diff --git a/packages/hooks/src/context/YouVersionAuthProvider.tsx b/packages/hooks/src/context/YouVersionAuthProvider.tsx
index fd96cb747..f7e6f05c1 100644
--- a/packages/hooks/src/context/YouVersionAuthProvider.tsx
+++ b/packages/hooks/src/context/YouVersionAuthProvider.tsx
@@ -7,7 +7,7 @@ import {
getLocalStorage,
type YouVersionUserInfoJSON,
} from '@youversion/platform-core';
-import React, { useEffect, useRef, useState, type ReactNode } from 'react';
+import React, { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import type { AuthConfig, AuthContextValue } from '../types/auth';
import { YouVersionAuthContext } from './YouVersionAuthContext';
@@ -24,10 +24,19 @@ interface YouVersionAuthProviderProps {
children: ReactNode;
}
-function getCredentialedUserInfo() {
- return YouVersionPlatformConfiguration.accessToken || YouVersionPlatformConfiguration.refreshToken
- ? YouVersionAPIUsers.getStoredUserInfo()
- : null;
+function getCredentialedUserInfo(currentUser: YouVersionUserInfo | null = null) {
+ if (
+ !YouVersionPlatformConfiguration.accessToken &&
+ !YouVersionPlatformConfiguration.refreshToken
+ ) {
+ return null;
+ }
+ const storedUser = YouVersionAPIUsers.getStoredUserInfo();
+ if (!YouVersionPlatformConfiguration.hasMismatchedOAuthSession) {
+ return storedUser;
+ }
+ // A storage event can arrive midway through another tab's account replacement.
+ return currentUser && currentUser.userId === storedUser?.userId ? storedUser : null;
}
export default function YouVersionAuthProvider({
@@ -49,6 +58,11 @@ export default function YouVersionAuthProvider({
refreshToken: string | null;
} | null>(null);
+ const publishUserInfo = useCallback((nextUser) => {
+ if (nextUser === null) setAccountRevision((revision) => revision + 1);
+ setUserInfo(nextUser);
+ }, []);
+
useEffect(() => {
if (!isHostControlled) return;
setUserInfo(controlledUserInfo ? new YouVersionUserInfo(controlledUserInfo) : null);
@@ -207,7 +221,7 @@ export default function YouVersionAuthProvider({
}
setOAuthCallbackState(null);
setOAuthFailedCallbackState(null);
- setUserInfo(getCredentialedUserInfo());
+ setUserInfo(getCredentialedUserInfo);
}
const unsubscribeRotation = YouVersionAPIUsers.onTokenRotation(
@@ -239,7 +253,7 @@ export default function YouVersionAuthProvider({
const value: AuthContextValue = {
userInfo,
- setUserInfo,
+ setUserInfo: publishUserInfo,
isLoading,
error,
redirectUri: config.redirectUri,
diff --git a/packages/hooks/src/internal/useUserScope.ts b/packages/hooks/src/internal/useUserScope.ts
index ecca1eeee..8e3992c8e 100644
--- a/packages/hooks/src/internal/useUserScope.ts
+++ b/packages/hooks/src/internal/useUserScope.ts
@@ -25,13 +25,11 @@ import { YouVersionAuthContext } from '../context/YouVersionAuthContext';
* - an access token is set while no user identity is known (with or without
* an auth context mounted).
*
- * The third state guards the `'anon'` scope. This hook reads identity from
- * the auth context. The request layer reads its token from
- * `YouVersionPlatformConfiguration.accessToken`. When the two disagree, a
- * fetch caches the account data for that token under the shared `'anon'` key.
- * The token read occurs at render time and is not reactive. That is enough:
- * each path that changes the token also changes the auth context, and the
- * context change re-renders this hook.
+ * The third state guards the `'anon'` scope. When auth is unmanaged, the
+ * client can fall back to `YouVersionPlatformConfiguration.accessToken`.
+ * Without an identified user, that could cache private account data under
+ * the shared `'anon'` key. Managed requests also verify the credential for
+ * the identified user before fetching.
*
* This hook reads `YouVersionAuthContext` directly. It does not call
* `useYouVersionAuthContext()`, because that call throws when auth is off,
diff --git a/packages/hooks/src/types/auth.ts b/packages/hooks/src/types/auth.ts
index d27991cce..9b2b8301e 100644
--- a/packages/hooks/src/types/auth.ts
+++ b/packages/hooks/src/types/auth.ts
@@ -15,7 +15,7 @@ export interface AuthContextValue {
redirectUri?: string;
/** Access token checked against the current account in the SDK-managed provider. */
accessToken?: string | null;
- /** Increments when browser storage records that an account was removed or replaced. */
+ /** Increments on explicit sign-out or when browser storage records an account removal or replacement. */
accountRevision?: number;
/** State of the verified OAuth callback handled by this provider. */
oauthCallbackState?: string | null;
diff --git a/packages/hooks/src/useHighlights.auth.test.tsx b/packages/hooks/src/useHighlights.auth.test.tsx
new file mode 100644
index 000000000..ed1aefd79
--- /dev/null
+++ b/packages/hooks/src/useHighlights.auth.test.tsx
@@ -0,0 +1,94 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import {
+ HighlightsClient,
+ YouVersionAPIUsers,
+ YouVersionPlatformConfiguration as config,
+} from '@youversion/platform-core';
+import type { PropsWithChildren } from 'react';
+import { expect, it, onTestFinished, vi } from 'vitest';
+import { YouVersionProvider } from './context/YouVersionProvider';
+import { useHighlights } from './useHighlights';
+import { useYVAuth } from './useYVAuth';
+
+function WebAuthWrapper({ children }: PropsWithChildren) {
+ return (
+
+ {children}
+
+ );
+}
+
+it('loads highlights only after staged credentials and the stored account agree', async () => {
+ YouVersionAPIUsers.signOut();
+ config.saveUserInfo({ id: 'alice' });
+ config.saveAuthData('expired-access', 'expired-refresh', new Date('2000-01-01'));
+ localStorage.setItem('youversion-auth-state', 'alice-notes-grant');
+ localStorage.setItem('youversion-auth-code-verifier', 'test-verifier');
+ const refresh = vi
+ .spyOn(YouVersionAPIUsers, 'refreshTokenIfNeeded')
+ .mockImplementation(async () => {
+ config.saveAuthData(null, null, null);
+ return false;
+ });
+ const highlights = {
+ data: [{ version_id: 111, passage_id: 'JHN.3.16', color: 'fffe00' }],
+ next_page_token: null,
+ };
+ const get = vi.spyOn(HighlightsClient.prototype, 'getHighlights').mockResolvedValue(highlights);
+ onTestFinished(() => {
+ refresh.mockRestore();
+ get.mockRestore();
+ YouVersionAPIUsers.signOut();
+ });
+
+ const options = { version_id: 111, passage_id: 'JHN.3' };
+ const { result } = renderHook(
+ () => ({ session: useYVAuth(), highlights: useHighlights(options) }),
+ { wrapper: WebAuthWrapper },
+ );
+ await waitFor(() => expect(result.current.session.auth.isLoading).toBe(false));
+ expect(result.current.session.userInfo).toBeNull();
+ expect(config.storedUserInfo?.id).toBe('alice');
+ expect(YouVersionAPIUsers.isSignInPending('alice-notes-grant')).toBe(true);
+
+ await act(async () => {
+ config.saveAuthData('bob-access', 'bob-refresh', new Date('2100-01-01'), {
+ scope: 'profile',
+ userId: 'bob',
+ });
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'accessToken', storageArea: localStorage }),
+ );
+ });
+ expect.soft(result.current.session.userInfo).toBeNull();
+ expect.soft(get).not.toHaveBeenCalled();
+ expect(result.current.highlights.highlights).toBeNull();
+
+ await act(async () => {
+ const oldValue = localStorage.getItem('userInfo');
+ config.saveUserInfo({ id: 'bob' });
+ window.dispatchEvent(
+ new StorageEvent('storage', {
+ key: 'userInfo',
+ oldValue,
+ newValue: localStorage.getItem('userInfo'),
+ storageArea: localStorage,
+ }),
+ );
+ });
+ await waitFor(() => expect(result.current.highlights.highlights).toEqual(highlights));
+ expect(result.current.session.userInfo?.userId).toBe('bob');
+ expect(get).toHaveBeenCalledExactlyOnceWith(options, 'bob-access');
+
+ // A refetch can follow a same-account token rotation before a React update.
+ config.saveAuthData('rotated-bob-access', 'rotated-bob-refresh', new Date('2100-01-01'), {
+ scope: 'profile',
+ userId: 'bob',
+ });
+ act(() => result.current.highlights.refetch());
+ await waitFor(() => expect(get).toHaveBeenLastCalledWith(options, 'rotated-bob-access'));
+});
diff --git a/packages/hooks/src/useHighlights.ts b/packages/hooks/src/useHighlights.ts
index c56157d5e..8d9ccbad1 100644
--- a/packages/hooks/src/useHighlights.ts
+++ b/packages/hooks/src/useHighlights.ts
@@ -1,7 +1,8 @@
'use client';
-import { useMemo, useCallback } from 'react';
+import { useMemo, useCallback, useContext } from 'react';
import { HighlightsClient } from '@youversion/platform-core';
+import { YouVersionAuthContext } from './context/YouVersionAuthContext';
import { useApiClient } from './internal/useApiClient';
import { useQueryKeyBase } from './internal/useQueryKeyBase';
import { useUserScope } from './internal/useUserScope';
@@ -39,6 +40,8 @@ export function useHighlights(
const apiClient = useApiClient();
const keyBase = useQueryKeyBase();
const userScope = useUserScope();
+ const auth = useContext(YouVersionAuthContext);
+ const isManaged = auth?.isHostControlled === false;
const highlightsClient = useMemo(() => new HighlightsClient(apiClient), [apiClient]);
@@ -58,9 +61,20 @@ export function useHighlights(
// entry is real.
const { data, loading, error, refetch } = useApiData>(
[...keyBase, 'highlights', userScope, options.version_id, options.passage_id],
- () => highlightsClient.getHighlights(options),
+ () => {
+ if (!isManaged) return highlightsClient.getHighlights(options);
+ const token = auth.userInfo?.userId === userScope ? auth.accessToken : null;
+ if (!token) return Promise.reject(new Error('Authentication required'));
+ // The version check can await HTTP before the client sends the request.
+ // Keep using the credential verified for this query's account.
+ return highlightsClient.getHighlights(options, token);
+ },
{
- enabled: userScope !== null && !override && apiOptions?.enabled !== false,
+ enabled:
+ userScope !== null &&
+ (!isManaged || Boolean(auth.accessToken)) &&
+ !override &&
+ apiOptions?.enabled !== false,
// The `queryKey` carries the user scope. Holding previous data across a
// key change would show one account's highlights to another during an
// account switch, so this hook always drops to `null` instead.
diff --git a/packages/hooks/src/useYVAuth.test.tsx b/packages/hooks/src/useYVAuth.test.tsx
index 5e9e8dcef..37084c296 100644
--- a/packages/hooks/src/useYVAuth.test.tsx
+++ b/packages/hooks/src/useYVAuth.test.tsx
@@ -442,6 +442,35 @@ it('keeps a pending authorization profile signed out on remount and storage upda
expect(result.current.auth.accessToken).toBeNull();
});
+it('publishes explicit sign-out after a failed reauthorization left the profile signed out', async () => {
+ YouVersionAPIUsers.signOut();
+ const previousUrl = window.location.href;
+ onTestFinished(() => {
+ window.history.replaceState(null, '', previousUrl);
+ YouVersionAPIUsers.signOut();
+ });
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'alice' });
+ localStorage.setItem('youversion-auth-state', 'note-authorization');
+ localStorage.setItem('youversion-auth-code-verifier', 'test-verifier');
+ window.history.replaceState(null, '', '?state=note-authorization&error=access_denied');
+
+ const { result } = renderHook(
+ () => ({ session: useYVAuth(), context: useYouVersionAuthContext() }),
+ { wrapper: WebAuthWrapper },
+ );
+ await waitFor(() => expect(result.current.session.auth.isLoading).toBe(false));
+ expect(result.current.context.oauthFailedCallbackState).toBe('note-authorization');
+ expect(result.current.session.userInfo).toBeNull();
+ expect(YouVersionAPIUsers.getStoredUserInfo()?.userId).toBe('alice');
+ expect(result.current.context.accountRevision).toBe(0);
+
+ act(() => result.current.session.signOut());
+
+ expect(YouVersionAPIUsers.getStoredUserInfo()).toBeNull();
+ expect(result.current.session.userInfo).toBeNull();
+ expect(result.current.context.accountRevision).toBe(1);
+});
+
it('reads the raw token for a host-controlled provider without a profile', async () => {
YouVersionAPIUsers.signOut();
onTestFinished(() => YouVersionAPIUsers.signOut());
diff --git a/packages/ui/scripts/smoke-vite-reader-notes.mjs b/packages/ui/scripts/smoke-vite-reader-notes.mjs
index 02d2c70b9..2e1aa9ed3 100644
--- a/packages/ui/scripts/smoke-vite-reader-notes.mjs
+++ b/packages/ui/scripts/smoke-vite-reader-notes.mjs
@@ -7,6 +7,7 @@ import passages from '../src/test/mock-data/passages.json' with { type: 'json' }
import { mockBooks } from '../src/test/mock-data/books.ts';
const app = process.argv[2] ?? 'http://127.0.0.1:5176';
+const callbackPath = process.argv[3] ?? '/callback';
const api = 'https://notes-smoke.example.test';
const browser = await chromium.launch();
const context = await browser.newContext({
@@ -27,6 +28,7 @@ const responses = new Map();
const exchanges = new Map();
const intermediateReturns = new Map();
const notes = [];
+const highlightWrites = [];
const page = await context.newPage();
await page.addInitScript(() => {
let queuedStorageEvents;
@@ -77,6 +79,7 @@ await context.route(`${api}/**`, async (route) => {
const destination = new URL(url.searchParams.get('redirect_uri'));
assert.equal(destination.origin, new URL(app).origin, 'Expected the local app callback');
+ assert.equal(destination.pathname, callbackPath, 'Expected the configured callback path');
const state = url.searchParams.get('state');
destination.searchParams.set('state', state);
if (response.account) {
@@ -128,6 +131,11 @@ await context.route(`${api}/**`, async (route) => {
case '/v1/bibles/3034/passages/JHN.1':
return json({ ...passages['JHN.1'], bible_id: 3034 });
case '/v1/highlights':
+ if (request.method() === 'POST') {
+ const highlight = request.postDataJSON();
+ highlightWrites.push(highlight);
+ return json(highlight, 201);
+ }
return json({ data: [] });
case '/v1/notes': {
const body = request.postDataJSON();
@@ -192,10 +200,48 @@ try {
await page.getByRole('button', { name: 'Yes Please' }).click();
checkScopes(await declined, readerScopes);
await page.waitForURL(/error=access_denied/);
+ assert.equal(new URL(page.url()).pathname, callbackPath);
await menu(page).waitFor();
assert.deepEqual(await selectedVerses(page), [1, 4]);
assert.equal(await editor(page).count(), 0);
+ // A declined highlight attempt must not resume when a new Note is authorized.
+ const competing = await context.newPage();
+ await competing.goto(app, { waitUntil: 'domcontentloaded' });
+ await selectVerses(competing, [1]);
+ await menu(competing).getByRole('button', { name: 'Apply highlight' }).first().click();
+ const highlightDeclined = prepareSignIn(competing, null);
+ await competing.getByRole('button', { name: 'Yes Please' }).click();
+ const highlightParams = await highlightDeclined;
+ checkScopes(highlightParams, readerScopes);
+ assert.equal(highlightParams.get('requested_permissions'), 'highlights');
+ await competing.waitForURL(/error=access_denied/);
+ await hostedButton(competing).and(competing.locator('button:enabled')).waitFor();
+ await competing.goto(app, { waitUntil: 'domcontentloaded' });
+ await hostedButton(competing).waitFor();
+ await selectVerses(competing, [4, 2]);
+ await beginNote(competing);
+ const noteAuthorized = prepareSignIn(competing, writer);
+ const highlightsRead = competing.waitForResponse(
+ (response) => response.url().startsWith(`${api}/v1/highlights?`) && response.ok(),
+ );
+ await competing.getByRole('button', { name: 'Yes Please' }).click();
+ const noteParams = await noteAuthorized;
+ checkScopes(noteParams, readerScopes);
+ assert.equal(noteParams.get('requested_permissions'), null);
+ await highlightsRead;
+ await composer(competing, 'John 1:2,4').waitFor();
+ assert.equal(new URL(competing.url()).pathname, callbackPath);
+ assert.equal(
+ await competing.getByRole('button', { name: 'Continue', includeHidden: true }).count(),
+ 0,
+ );
+ assert.deepEqual(highlightWrites, []);
+ await composer(competing, 'John 1:2,4').getByRole('button', { name: 'Cancel' }).click();
+ await competing.locator('header').getByRole('button', { name: 'Sign out' }).click();
+ await hostedButton(competing).waitFor();
+ await competing.close();
+
const navbar = prepareSignIn(page, alice);
await hostedButton(page).click();
checkScopes(await navbar, navbarScopes);
@@ -303,7 +349,7 @@ try {
assert.equal(notes.length, 1);
console.log(
- 'Reader Notes smoke passed (decline, token-service recovery, two-step grant, exact create, stale callback, same-account re-sign-in, sign-out, navbar scopes, and narrow layout).',
+ 'Reader Notes smoke passed (configured callback route, decline, competing highlight intent, token-service recovery, exact create, stale callback, same-account re-sign-in, sign-out, navbar scopes, and narrow layout).',
);
} finally {
await browser.close();
diff --git a/packages/ui/src/components/bible-reader-highlights-machine.ts b/packages/ui/src/components/bible-reader-highlights-machine.ts
index 18ede76d8..52dc7e8f0 100644
--- a/packages/ui/src/components/bible-reader-highlights-machine.ts
+++ b/packages/ui/src/components/bible-reader-highlights-machine.ts
@@ -172,6 +172,7 @@ export type HighlightsEvent =
| { type: 'DECLINE_SIGN_IN' }
| { type: 'CONFIRM_PERMISSION' }
| { type: 'CANCEL_PERMISSION' }
+ | { type: 'DISCARD_AUTHORIZATION' }
| { type: 'ENQUEUE'; op: WriteOp }
| { type: 'PERMISSION_LOST' };
@@ -759,6 +760,7 @@ export const bibleReaderHighlightsMachine = setup({
AUTH_CHANGED: { actions: ['resetWriteStateOnAccountChange', 'assignAuth'] },
HIGHLIGHTS_UPDATED: { actions: 'reconcileOverlay' },
SCOPE_CHANGED: { guard: 'scopeIsDifferent', actions: 'resetForScopeChange' },
+ DISCARD_AUTHORIZATION: { actions: 'clearPending' },
},
initial: 'booting',
states: {
@@ -783,6 +785,7 @@ export const bibleReaderHighlightsMachine = setup({
flow: {
initial: 'resuming',
on: {
+ DISCARD_AUTHORIZATION: { target: '.idle', actions: 'clearPending' },
// A write's 401/403 (raised by settleWrite) re-opens the JIT dialog.
PERMISSION_LOST: { target: '.permissionDialog' },
// Taps are handled here so any flow substate resolves them.
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index 7927bc321..03afbffd4 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -4,9 +4,10 @@ import {
YouVersionPlatformConfiguration,
type CreateNote,
} from '@youversion/platform-core';
+import { useYVAuth } from '@youversion/platform-react-hooks';
import { http, HttpResponse } from 'msw';
import { getWorker } from 'msw-storybook-addon';
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import { expect, spyOn, userEvent, waitFor, within } from 'storybook/test';
import * as z from 'zod/mini';
import { globalHandlers } from '@/test/mocks/handlers';
@@ -776,6 +777,15 @@ function waitForReaderPage(container: HTMLElement, version: number) {
);
}
+function PendingSessionSignOut() {
+ const { auth, signOut } = useYVAuth();
+ return (
+
+ Sign out the pending session
+
+ );
+}
+
function ReloadableReader({ withCallback = false }: { withCallback?: boolean }) {
const [pageVersion, setPageVersion] = useState(0);
return (
@@ -805,6 +815,7 @@ function ReloadableReader({ withCallback = false }: { withCallback?: boolean })
includeAuth
>
+ {withCallback && }
@@ -860,11 +871,16 @@ export const RemountDropsDraftFromReplacedSession: Story = {
}),
};
-export const RemountRecoversDraftDuringFailedRefresh: Story = {
- ...RemountDropsDraftFromReplacedSession,
- tags: ['integration', 'shadow-dom', 'cross-browser'],
- render: () => ,
- play: withWritableSession(async ({ canvasElement }) => {
+function playFailedRefreshDraft(
+ afterFailure: (result: {
+ canvasElement: HTMLElement;
+ root: ShadowRoot;
+ overlays: ReturnType;
+ draftText: string;
+ ownerId: string;
+ }) => Promise,
+): Play {
+ return withWritableSession(async ({ canvasElement }) => {
const page = within(canvasElement);
const root = await waitForShadowRoot(canvasElement);
await selectVerses(root, [1, 4]);
@@ -925,21 +941,91 @@ export const RemountRecoversDraftDuringFailedRefresh: Story = {
const failedActions = within(
await failedOverlays.findByRole('dialog', { name: 'Verse actions' }),
);
- await userEvent.click(failedActions.getByRole('button', { name: 'Save' }));
- await userEvent.click(await failedOverlays.findByRole('button', { name: 'Yes Please' }));
- await waitFor(() => expect(failedOverlays.queryByRole('dialog')).toBeNull());
+ await expect(failedActions.getByRole('button', { name: 'Save' })).toBeInTheDocument();
+ await afterFailure({
+ canvasElement,
+ root: failedRoot,
+ overlays: failedOverlays,
+ draftText,
+ ownerId: profile.id,
+ });
+ } finally {
+ signIn.mockRestore();
+ }
+ });
+}
- getWorker().use(
- http.post('*/auth/token', () => tokenResponse('profile read_notes write_notes')),
+export const RemountRecoversDraftDuringFailedRefresh: Story = {
+ ...RemountDropsDraftFromReplacedSession,
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ render: () => ,
+ play: playFailedRefreshDraft(async ({ canvasElement, overlays, draftText }) => {
+ const actions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
+ await userEvent.click(actions.getByRole('button', { name: 'Save' }));
+ await userEvent.click(await overlays.findByRole('button', { name: 'Yes Please' }));
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
+ getWorker().use(
+ http.post('*/auth/token', () => tokenResponse('profile read_notes write_notes')),
+ );
+ await userEvent.click(
+ within(canvasElement).getByRole('button', { name: 'Return from sign-in' }),
+ );
+ await waitForReaderPage(canvasElement, 3);
+ const finalRoot = await waitForShadowRoot(canvasElement);
+ const finalOverlays = await readerOverlays(finalRoot);
+ const returned = within(await finalOverlays.findByRole('dialog', { name: 'John 1:1,4' }));
+ await expect(returned.getByRole('textbox', { name: 'Add Note…' })).toHaveValue(draftText);
+ }),
+};
+
+export const ExplicitSignOutClearsTheRecoveredDraft: Story = {
+ ...RemountRecoversDraftDuringFailedRefresh,
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ play: playFailedRefreshDraft(async ({ canvasElement, root, overlays, ownerId }) => {
+ const saved = deferred();
+ getWorker().use(
+ http.post('*/v1/notes', async ({ request }) => {
+ const body = await request.json();
+ saved.resolve(body);
+ return noteResponse(body);
+ }),
+ );
+ const signOut = within(canvasElement).getByRole('button', {
+ name: 'Sign out the pending session',
+ });
+ await waitFor(() => expect(signOut).toBeEnabled());
+ await userEvent.click(signOut);
+
+ const frame = canvasElement.ownerDocument.createElement('iframe');
+ frame.hidden = true;
+ canvasElement.append(frame);
+ try {
+ const storage = frame.contentWindow?.localStorage;
+ if (!storage) throw new Error('Same-origin account writer did not mount');
+ YouVersionPlatformConfiguration.saveAuthData(
+ 'returning-reader-token',
+ 'returning-reader-refresh',
+ new Date('2100-01-01'),
+ { userId: ownerId, scope: 'profile read_notes write_notes' },
);
- await userEvent.click(page.getByRole('button', { name: 'Return from sign-in' }));
- await waitForReaderPage(canvasElement, 3);
- const finalRoot = await waitForShadowRoot(canvasElement);
- const finalOverlays = await readerOverlays(finalRoot);
- const returned = within(await finalOverlays.findByRole('dialog', { name: 'John 1:1,4' }));
- await expect(returned.getByRole('textbox', { name: 'Add Note…' })).toHaveValue(draftText);
+ storage.setItem('userInfo', JSON.stringify({ id: ownerId, name: 'Reader' }));
+ await waitFor(() => expect(signOut).toBeDisabled());
+ for (const verseNumber of [1, 4]) {
+ const verse = await readerVerse(root, verseNumber);
+ if (!verse.classList.contains('yv-v-selected')) await userEvent.click(verse);
+ }
+ const { composer } = await openComposer(root, 'John 1:1,4');
+ await expect(composer.getByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await expect(await saved.promise).toEqual({
+ request_id: expect.stringMatching(/^[\da-f-]{36}$/i),
+ content: '',
+ status: 'private',
+ passage: { bible_id: 111, passage_id: 'JHN.1.1+JHN.1.4' },
+ });
+ await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
} finally {
- signIn.mockRestore();
+ frame.remove();
}
}),
};
@@ -1124,6 +1210,126 @@ export const HostControlledSignIn: Story = {
},
};
+function ReaderAccountStatus() {
+ const { auth, userInfo } = useYVAuth();
+ const [lastEvent, setLastEvent] = useState('ready');
+ useEffect(() => {
+ const observe = (event: StorageEvent) => {
+ if (event.storageArea === localStorage && event.key && event.isTrusted)
+ setLastEvent(event.key);
+ };
+ window.addEventListener('storage', observe);
+ return () => window.removeEventListener('storage', observe);
+ }, []);
+ return (
+
+ {auth.isLoading ? 'Loading' : (userInfo?.name ?? 'Signed out')} / {lastEvent}
+
+ );
+}
+
+export const HighlightsWaitForTheStagedAccount: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ parameters: { includeAuth: false },
+ loaders: [
+ async () => {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ YouVersionPlatformConfiguration.saveUserInfo({ id: 'alice', name: 'Alice' });
+ return {};
+ },
+ ],
+ render: () => (
+
+
+
+
+
+
+
+
+ ),
+ play: async ({ canvasElement }) => {
+ const requests: (string | null)[] = [];
+ getWorker().use(
+ http.get('*/v1/highlights', ({ request }) => {
+ requests.push(request.headers.get('authorization'));
+ return highlightPage(yellow);
+ }),
+ );
+ const status = () => within(canvasElement).getByLabelText('Reader account');
+ const frame = canvasElement.ownerDocument.createElement('iframe');
+ frame.hidden = true;
+ canvasElement.append(frame);
+ try {
+ const storage = frame.contentWindow?.localStorage;
+ if (!storage) throw new Error('Same-origin account writer did not mount');
+ const root = await waitForShadowRoot(canvasElement);
+ const verse = await readerVerse(root, 1);
+ await waitFor(() => expect(status()).toHaveTextContent('Signed out / ready'));
+ YouVersionPlatformConfiguration.saveAuthData(
+ 'bob-access',
+ 'bob-refresh',
+ new Date('2100-01-01'),
+ {
+ userId: 'bob',
+ scope: 'profile read_notes',
+ },
+ );
+ // Stage the bound token in another document while the old profile remains visible in storage.
+ localStorage.removeItem('accessToken');
+ storage.setItem('accessToken', 'bob-access');
+ await waitFor(() => expect(status()).toHaveTextContent('Signed out / accessToken'));
+ await expect(requests).toEqual([]);
+
+ storage.setItem('userInfo', JSON.stringify({ id: 'bob', name: 'Bob' }));
+ await waitFor(() => expect(status()).toHaveTextContent('Bob / userInfo'));
+ await waitFor(() => expect(getBackgroundColorChannels(verse)).toEqual([255, 236, 91, 255]));
+ await expect(requests).toEqual(['Bearer bob-access']);
+ } finally {
+ frame.remove();
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ }
+ },
+};
+
+export const SignInFlow: Story = {
+ tags: ['integration', 'shadow-dom', 'cross-browser'],
+ loaders: [
+ async () => {
+ YouVersionPlatformConfiguration.clearAuthTokens();
+ return {};
+ },
+ ],
+ play: async ({ canvasElement }) => {
+ const signIn = spyOn(YouVersionAPIUsers, 'signIn').mockResolvedValue(undefined);
+ try {
+ const root = await waitForShadowRoot(canvasElement);
+ const trigger = await waitFor(() => {
+ const button = root.querySelector('[data-testid="user-menu-trigger"]');
+ if (!button) throw new Error('Reader sign-in trigger is missing');
+ return button;
+ });
+ await expect(trigger.querySelector('img')).not.toBeInTheDocument();
+ await userEvent.click(trigger);
+ const overlays = await readerOverlays(root);
+ await userEvent.click(await overlays.findByRole('button', { name: /sign in/i }));
+ await expect(signIn).toHaveBeenCalledWith(
+ expect.any(String),
+ ['profile', 'read_notes', 'write_notes'],
+ undefined,
+ );
+ } finally {
+ signIn.mockRestore();
+ }
+ },
+};
+
export const HostTakesOverSignIn: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
render: function HostSignInReader() {
diff --git a/packages/ui/src/components/bible-reader.stories.tsx b/packages/ui/src/components/bible-reader.stories.tsx
index 67ceb01e3..f39a5630a 100644
--- a/packages/ui/src/components/bible-reader.stories.tsx
+++ b/packages/ui/src/components/bible-reader.stories.tsx
@@ -86,7 +86,6 @@ function firstPathParam(value: string | readonly string[] | undefined): string |
return value[0];
}
-let signInMock: ReturnType;
const withShadowRecoveryProvider = (Story: React.ComponentType) => (
@@ -104,7 +103,7 @@ const meta: Meta = {
const { YouVersionAPIUsers } = await import('@youversion/platform-core');
- signInMock = fn().mockImplementation(async () => {
+ const signInMock = fn().mockImplementation(async () => {
await new Promise((resolve) => setTimeout(resolve, 100));
return {
accessToken: 'mock-token',
@@ -1468,53 +1467,6 @@ export const ThemeOverridesProvider: Story = {
},
};
-export const SignInFlow: Story = {
- tags: ['integration'],
- args: {
- defaultVersionId: 111,
- book: 'JHN',
- chapter: '1',
- },
- render: (args) => (
-
-
-
-
-
-
- ),
- play: async ({ canvasElement }) => {
- const { root, reader } = await getReaderStory(canvasElement);
- await waitFor(
- async () => {
- const userMenuTrigger = reader.getByTestId('user-menu-trigger');
- await expect(userMenuTrigger).toBeInTheDocument();
- },
- { timeout: 5000 },
- );
-
- const userMenuTrigger = reader.getByTestId('user-menu-trigger');
- await expect(userMenuTrigger.querySelector('img')).not.toBeInTheDocument();
-
- await userEvent.click(userMenuTrigger);
-
- const overlays = await getReaderOverlay(root);
- await waitFor(async () => {
- const signInButton = await overlays.findByRole('button', { name: /sign in/i });
- await expect(signInButton).toBeInTheDocument();
- });
-
- const signInButton = overlays.getByRole('button', { name: /sign in/i });
- await userEvent.click(signInButton);
-
- await expect(signInMock).toHaveBeenCalledWith(
- expect.any(String),
- ['profile', 'read_notes', 'write_notes'],
- undefined,
- );
- },
-};
-
export const SignOutFlow: Story = {
tags: ['integration'],
args: {
diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx
index 3469a3681..07064239f 100644
--- a/packages/ui/src/components/bible-reader.tsx
+++ b/packages/ui/src/components/bible-reader.tsx
@@ -637,6 +637,7 @@ function Content() {
signInDialogOpen,
confirmSignInDialog,
cancelSignInDialog,
+ discardPendingAuthorization: discardHighlightAuthorization,
} = useBibleReaderHighlights({
versionId,
book,
@@ -675,6 +676,7 @@ function Content() {
refreshHighlights();
},
onInvalidated: clearNoteSelection,
+ onAuthorizationCommitted: discardHighlightAuthorization,
});
// Color row: controlled mode always shows it (YPE-3705 bypasses HIGHLIGHTS_LIVE).
diff --git a/packages/ui/src/components/highlight-color-circle.tsx b/packages/ui/src/components/highlight-color-circle.tsx
index 13f892ae1..54d4ed434 100644
--- a/packages/ui/src/components/highlight-color-circle.tsx
+++ b/packages/ui/src/components/highlight-color-circle.tsx
@@ -23,17 +23,18 @@ export function HighlightColorCircle({
}: HighlightColorCircleProps): ReactElement {
const isDark = theme === 'dark';
const backgroundColor = highlightFillColorMix(color, 'card') ?? undefined;
+ // Keep the swatch outline when the standalone popover shares the host document.
+ const border = '1px solid color-mix(in oklab, var(--yv-card-foreground) 20%, transparent)';
return (
diff --git a/packages/ui/src/components/use-bible-reader-highlights.ts b/packages/ui/src/components/use-bible-reader-highlights.ts
index 300a528e7..5d69c202d 100644
--- a/packages/ui/src/components/use-bible-reader-highlights.ts
+++ b/packages/ui/src/components/use-bible-reader-highlights.ts
@@ -97,6 +97,8 @@ export type UseBibleReaderHighlightsReturn = {
confirmSignInDialog: () => void;
/** User declined/dismissed the sign-in dialog → discard the pending highlight. */
cancelSignInDialog: () => void;
+ /** A new Reader authorization replaces the pending highlight auth intent. */
+ discardPendingAuthorization: () => void;
};
/**
@@ -358,6 +360,7 @@ export function useBibleReaderHighlights({
| 'cancelPermissionDialog'
| 'confirmSignInDialog'
| 'cancelSignInDialog'
+ | 'discardPendingAuthorization'
>
>(
() => ({
@@ -407,6 +410,7 @@ export function useBibleReaderHighlights({
cancelPermissionDialog: () => actorRef.send({ type: 'CANCEL_PERMISSION' }),
confirmSignInDialog: () => actorRef.send({ type: 'CONFIRM_SIGN_IN' }),
cancelSignInDialog: () => actorRef.send({ type: 'DECLINE_SIGN_IN' }),
+ discardPendingAuthorization: () => actorRef.send({ type: 'DISCARD_AUTHORIZATION' }),
}),
[actorRef, scope],
);
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index 73ba8240a..7dbfcbde6 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -44,6 +44,7 @@ const draftSchema = z.object({
const handoffSchema = z.object({
draft: draftSchema,
readerKey: z.string(),
+ callbackReaderKey: z.optional(z.string()),
state: z.string(),
expiresAt: z.number(),
});
@@ -78,7 +79,10 @@ type UseBibleReaderNoteResult = {
// An OAuth return remounts the page. The Reader's placement distinguishes
// multiple instances even when they display the same passage.
-function readerPosition(reader: HTMLElement): string {
+function readerPosition(
+ reader: HTMLElement,
+ pathname = reader.ownerDocument.location?.pathname,
+): string {
const path: string[] = [];
for (
let node: Element | null = reader;
@@ -94,10 +98,14 @@ function readerPosition(reader: HTMLElement): string {
);
path.unshift(`${node.localName}:${siblings.indexOf(node)}`);
}
- return JSON.stringify([reader.ownerDocument.location?.pathname, ...path]);
+ return JSON.stringify([pathname, ...path]);
}
-function consumeNoteHandoff(readerKey: string, match?: { state: string; requestId: string }) {
+function consumeNoteHandoff(
+ readerKey: string,
+ match?: { state: string; requestId: string },
+ callbackState?: string | null,
+) {
const storage = getSessionStorage();
const raw = storage?.getItem(HANDOFF_KEY);
if (!raw) return null;
@@ -105,7 +113,11 @@ function consumeNoteHandoff(readerKey: string, match?: { state: string; requestI
const parsed = handoffSchema.safeParse(JSON.parse(raw));
if (!parsed.success) return null;
const handoff = parsed.data;
- if (handoff.readerKey !== readerKey) return null;
+ if (
+ handoff.readerKey !== readerKey &&
+ (handoff.callbackReaderKey !== readerKey || handoff.state !== callbackState)
+ )
+ return null;
if (match && (handoff.state !== match.state || handoff.draft.requestId !== match.requestId))
return null;
removeStorageItem(storage, HANDOFF_KEY);
@@ -158,12 +170,14 @@ export function useBibleReaderNote({
hostOwnsSignIn,
onSaved,
onInvalidated,
+ onAuthorizationCommitted,
}: {
reader: RefObject;
enabled: boolean;
hostOwnsSignIn: boolean;
onSaved: (selection: NoteSelection) => void;
onInvalidated: (selection: NoteSelection) => void;
+ onAuthorizationCommitted: () => void;
}): UseBibleReaderNoteResult {
const auth = useContext(YouVersionAuthContext);
const account = auth?.userInfo?.userId || null;
@@ -190,8 +204,16 @@ export function useBibleReaderNote({
oauthFailedCallbackState,
onSaved,
onInvalidated,
+ onAuthorizationCommitted,
});
- latest.current = { account, canAuthorize, oauthFailedCallbackState, onSaved, onInvalidated };
+ latest.current = {
+ account,
+ canAuthorize,
+ oauthFailedCallbackState,
+ onSaved,
+ onInvalidated,
+ onAuthorizationCommitted,
+ };
function show(next: Flow | null) {
currentFlow.current = next;
@@ -236,8 +258,12 @@ export function useBibleReaderNote({
useEffect(() => {
if (authLoading || !canAuthorize || checkedHandoff.current || !reader.current) return;
checkedHandoff.current = true;
- const handoff = consumeNoteHandoff(readerPosition(reader.current));
const returnedState = oauthCallbackState ?? oauthFailedCallbackState;
+ const handoff = consumeNoteHandoff(
+ readerPosition(reader.current),
+ undefined,
+ oauthCallbackSuperseded ? null : returnedState,
+ );
if (
!handoff ||
oauthCallbackSuperseded ||
@@ -335,45 +361,53 @@ export function useBibleReaderNote({
async function authorize() {
const active = currentFlow.current;
- if (active?.phase !== 'authorize' || !canAuthorize || !reader.current) return;
- const readerKey = readerPosition(reader.current);
+ const readerElement = reader.current;
+ if (active?.phase !== 'authorize' || !canAuthorize || !readerElement) return;
+ const readerKey = readerPosition(readerElement);
const redirect = { ...active, phase: 'redirect' } as const;
const previousState = draftAuthorizationState.current;
show(redirect);
try {
- await YouVersionAPIUsers.signIn(
- auth?.redirectUri ?? window.location.href,
- READER_SIGN_IN_SCOPES,
- undefined,
- (state) => {
- if (
- currentFlow.current !== redirect ||
- !matchesDraftOwner(
- redirect.draft.ownerId,
- latest.current.account,
- previousState,
- latest.current.oauthFailedCallbackState,
- ) ||
- !latest.current.canAuthorize ||
- (config.storedUserInfo?.id || null) !== redirect.draft.ownerId
- ) {
- throw new Error('The Reader account changed before authorization');
- }
- const stored = setStorageItem(
- getSessionStorage(),
- HANDOFF_KEY,
- JSON.stringify({
- draft: redirect.draft,
- readerKey,
- state,
- expiresAt: Date.now() + HANDOFF_LIFETIME,
- }),
- );
- if (!stored) throw new Error('The pending note could not be saved for authorization');
- handoffState.current = state;
- draftAuthorizationState.current = state;
- },
+ const redirectUri = auth?.redirectUri ?? window.location.href;
+ const callbackHref = new URL(redirectUri).href;
+ // The Core authorize URL removes a trailing slash from the complete URI.
+ const callback = new URL(
+ callbackHref.endsWith('/') ? callbackHref.slice(0, -1) : callbackHref,
);
+ const callbackReaderKey =
+ callback.origin === window.location.origin
+ ? readerPosition(readerElement, callback.pathname)
+ : undefined;
+ await YouVersionAPIUsers.signIn(redirectUri, READER_SIGN_IN_SCOPES, undefined, (state) => {
+ if (
+ currentFlow.current !== redirect ||
+ !matchesDraftOwner(
+ redirect.draft.ownerId,
+ latest.current.account,
+ previousState,
+ latest.current.oauthFailedCallbackState,
+ ) ||
+ !latest.current.canAuthorize ||
+ (config.storedUserInfo?.id || null) !== redirect.draft.ownerId
+ ) {
+ throw new Error('The Reader account changed before authorization');
+ }
+ const stored = setStorageItem(
+ getSessionStorage(),
+ HANDOFF_KEY,
+ JSON.stringify({
+ draft: redirect.draft,
+ readerKey,
+ callbackReaderKey,
+ state,
+ expiresAt: Date.now() + HANDOFF_LIFETIME,
+ }),
+ );
+ if (!stored) throw new Error('The pending note could not be saved for authorization');
+ handoffState.current = state;
+ draftAuthorizationState.current = state;
+ latest.current.onAuthorizationCommitted();
+ });
} catch {
if (currentFlow.current !== redirect) return;
draftAuthorizationState.current = previousState;
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 8debea21c..5686b4780 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
@@ -5,7 +5,12 @@ import { useRef, useState } from 'react';
import { expect, userEvent, within } from 'storybook/test';
import i18n from '../i18n';
import { ShadowRootHost } from '../lib/shadow-root-host';
-import { waitFor, waitForElement, waitForShadowRoot } from '../test/storybook-dom';
+import {
+ getColorChannels,
+ waitFor,
+ waitForElement,
+ waitForShadowRoot,
+} from '../test/storybook-dom';
import { VerseActionPopover } from './verse-action-popover';
function IsolatedVerseActionPopover(): React.ReactNode {
@@ -143,6 +148,54 @@ const meta = {
export default meta;
type Story = StoryObj;
+export const StandaloneSwatchUnderHostReset: Story = {
+ tags: ['cross-browser'],
+ render: function StandalonePopover() {
+ const [anchor, setAnchor] = useState(null);
+ const close = () => setAnchor(null);
+ return (
+ <>
+
+ setAnchor(event.currentTarget)}>
+ Select verse
+
+ {
+ if (!open) close();
+ }}
+ activeHighlights={new Set()}
+ selectedVerses={anchor ? [1] : []}
+ highlightedVerses={{}}
+ anchorElement={anchor}
+ onHighlight={close}
+ onClearHighlight={close}
+ onCopy={close}
+ onShare={close}
+ />
+ >
+ );
+ },
+ play: async ({ canvasElement }) => {
+ const host = await within(canvasElement).findByRole('button', { name: 'Select verse' });
+ await userEvent.click(host);
+ await expect(getComputedStyle(host).borderTopWidth).toBe('0px');
+ const doc = canvasElement.ownerDocument;
+ const popover = await within(doc.body).findByRole('dialog', { name: 'Verse actions' });
+ const [swatch] = within(popover).getAllByRole('button', { name: 'Apply highlight' });
+ if (!swatch) throw new Error('Verse action highlight swatch is missing');
+ await waitFor(async () => {
+ const style = getComputedStyle(swatch);
+ await expect(swatch).toBeVisible();
+ await expect(style.borderTopWidth).toBe('1px');
+ await expect(style.borderTopStyle).toBe('solid');
+ await expect(getColorChannels(style.borderTopColor, doc)).toEqual(
+ getColorChannels('rgba(18, 18, 18, 0.2)', doc),
+ );
+ });
+ },
+};
+
async function waitForClosed(topLayer: HTMLElement): Promise {
await waitFor(async () => {
await expect(topLayer.querySelector('[role="dialog"]')).toBeNull();
From b3d60358747723d19495291e1ba1a2b5d7662635 Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 12:58:08 -0600
Subject: [PATCH 24/75] fix: recover Reader note edits after a lost response
Retry the original create payload, then reconcile the current draft against the recovered note ID using the verified writer token. Keep that ID and draft after a failed update.
Ref: YPE-6783
---
packages/hooks/src/index.ts | 1 +
packages/hooks/src/useUpdateNote.ts | 22 +++++
.../components/bible-reader-notes.stories.tsx | 62 +++++++++++-
.../src/components/use-bible-reader-note.ts | 98 +++++++++++++++----
4 files changed, 161 insertions(+), 22 deletions(-)
create mode 100644 packages/hooks/src/useUpdateNote.ts
diff --git a/packages/hooks/src/index.ts b/packages/hooks/src/index.ts
index 6fd87eade..25e145703 100644
--- a/packages/hooks/src/index.ts
+++ b/packages/hooks/src/index.ts
@@ -21,6 +21,7 @@ export * from './usePassage';
export * from './useVOTD';
export * from './useHighlights';
export * from './useCreateNote';
+export * from './useUpdateNote';
export * from './useHighlightAuthActions';
export * from './useLanguages';
export * from './useLanguage';
diff --git a/packages/hooks/src/useUpdateNote.ts b/packages/hooks/src/useUpdateNote.ts
new file mode 100644
index 000000000..37b4e11ce
--- /dev/null
+++ b/packages/hooks/src/useUpdateNote.ts
@@ -0,0 +1,22 @@
+'use client';
+
+import { useCallback, useMemo } from 'react';
+import { NotesClient, type Note, type UpdateNote } from '@youversion/platform-core';
+import { useApiClient } from './internal/useApiClient';
+
+/** Updates a note using the caller's captured access token. */
+export function useUpdateNote(): (
+ id: string,
+ note: UpdateNote,
+ accessToken: string,
+) => Promise {
+ const apiClient = useApiClient();
+ const client = useMemo(() => new NotesClient(apiClient), [apiClient]);
+ return useCallback(
+ async (id, note, accessToken) => {
+ if (!accessToken?.trim()) throw new Error('An access token is required to update a note');
+ return client.updateNote(id, note, accessToken);
+ },
+ [client],
+ );
+}
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index 03afbffd4..8a0711cd4 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -213,12 +213,26 @@ export const EditAndRetry: Story = {
parameters: writableSession,
play: withWritableSession(async ({ canvasElement }) => {
const requests: NoteRequest[] = [];
+ const updates: Pick[] = [];
+ let stored: NoteRequest | undefined;
getWorker().use(
http.post('*/v1/notes', async ({ request }) => {
const body = await request.json();
requests.push(body);
- return requests.length === 1 ? HttpResponse.error() : noteResponse(body);
+ if (stored) return noteResponse(stored);
+ stored = body;
+ return HttpResponse.error();
}),
+ http.patch>(
+ '*/v1/notes/saved-note',
+ async ({ request }) => {
+ if (!stored) return new HttpResponse(null, { status: 404 });
+ const update = await request.json();
+ updates.push(update);
+ stored = { ...stored, ...update };
+ return updates.length === 1 ? HttpResponse.error() : noteResponse(stored);
+ },
+ ),
);
const root = await waitForShadowRoot(canvasElement);
const settings = root.querySelector('button[aria-label="Settings"]');
@@ -298,6 +312,28 @@ export const EditAndRetry: Story = {
await expect(selected).toHaveAttribute('aria-pressed', 'true');
await expect(composer.getByRole('radio', { name: 'Public' })).toBeChecked();
await fillEditor(editor, 'Edited thought');
+ await userEvent.click(composer.getByRole('radio', { name: 'Private' }));
+ await userEvent.click(selected);
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await waitFor(() =>
+ expect(updates).toEqual([{ content: 'Edited thought', status: 'private', color: null }]),
+ );
+ await waitFor(() => expect(composer.getByRole('alert')).toBeVisible());
+ await expect(editor).toHaveValue('Edited thought');
+ await expect(composer.getByRole('radio', { name: 'Private' })).toBeChecked();
+ await expect(selected).toHaveAttribute('aria-pressed', 'false');
+
+ // PATCH cannot clear already saved text. The empty draft remains editable.
+ await fillEditor(editor, '');
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(composer.getByRole('alert')).toBeVisible());
+ await expect(editor).toHaveValue('');
+
+ // The lost update may have reached the server. Restoring the original fields
+ // still needs an update to that same note.
+ await fillEditor(editor, 'First thought');
+ await userEvent.click(composer.getByRole('radio', { name: 'Public' }));
+ await userEvent.click(selected);
await userEvent.click(composer.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
await waitFor(() => expect(root.activeElement).toBe(settings));
@@ -310,9 +346,14 @@ export const EditAndRetry: Story = {
};
await expect(requests).toEqual([
{ ...common, content: 'First thought' },
- { ...common, content: 'Edited thought' },
+ { ...common, content: 'First thought' },
]);
await expect(requests[1]?.request_id).toBe(requests[0]?.request_id);
+ await expect(updates).toEqual([
+ { content: 'Edited thought', status: 'private', color: null },
+ { content: 'First thought', status: 'public', color: 'ffdca7' },
+ ]);
+ await expect(stored).toEqual(requests[0]);
}),
};
@@ -585,12 +626,25 @@ export const CancelRetainsDraftAcrossNavigation: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
play: withWritableSession(async ({ canvasElement, loaded }) => {
const attempts: NoteRequest[] = [];
+ const updates: { status: NoteRequest['status']; color: NoteRequest['color'] }[] = [];
+ let stored: NoteRequest | undefined;
getWorker().use(
http.post('*/v1/notes', async ({ request }) => {
const body = await request.json();
attempts.push(body);
- return attempts.length === 1 ? HttpResponse.error() : noteResponse(body);
+ if (stored) return noteResponse(stored);
+ stored = body;
+ return HttpResponse.error();
}),
+ http.patch(
+ '*/v1/notes/saved-note',
+ async ({ request }) => {
+ if (!stored) return new HttpResponse(null, { status: 404 });
+ const update = await request.json();
+ updates.push(update);
+ return noteResponse({ ...stored, ...update });
+ },
+ ),
);
const root = await waitForShadowRoot(canvasElement);
const navigation = storyNavigation.parse(loaded.hostNavigation);
@@ -611,6 +665,7 @@ export const CancelRetainsDraftAcrossNavigation: Story = {
await selectVerses(root, [1, 4]);
const { composer: reopened } = await openComposer(root, 'John 1:1,4');
await expect(reopened.getByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
+ await userEvent.click(reopened.getByRole('radio', { name: 'Public' }));
await userEvent.click(reopened.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
const request = {
@@ -621,6 +676,7 @@ export const CancelRetainsDraftAcrossNavigation: Story = {
};
await expect(attempts).toEqual([request, request]);
await expect(attempts[1]?.request_id).toBe(attempts[0]?.request_id);
+ await expect(updates).toEqual([{ status: 'public', color: null }]);
}),
};
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index 7dbfcbde6..3ef9aadec 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -17,8 +17,14 @@ import {
YouVersionAPIUsers,
YouVersionPlatformConfiguration as config,
type CreateNote,
+ type Note,
+ type UpdateNote,
} from '@youversion/platform-core';
-import { useCreateNote, YouVersionAuthContext } from '@youversion/platform-react-hooks';
+import {
+ useCreateNote,
+ useUpdateNote,
+ YouVersionAuthContext,
+} from '@youversion/platform-react-hooks';
import * as z from 'zod/mini';
import { buildPassageIds } from '@/lib/usfm-ranges';
import { getOwnShadowRoot } from '@/lib/shadow-root-host';
@@ -32,13 +38,23 @@ const selectionSchema = z.object({
reference: z.string(),
});
+const editableFields = {
+ text: z.string(),
+ visibility: z.enum(['private', 'public']),
+ color: z.nullable(z.string().check(z.regex(/^[0-9a-f]{6}$/))),
+};
+
const draftSchema = z.object({
selection: selectionSchema,
requestId: z.uuid(),
ownerId: z.nullable(z.string()),
- text: z.string(),
- visibility: z.enum(['private', 'public']),
- color: z.nullable(z.string().check(z.regex(/^[0-9a-f]{6}$/))),
+ ...editableFields,
+ recovery: z.optional(
+ z.object({
+ submitted: z.object(editableFields),
+ savedNote: z.optional(z.object({ id: z.string(), contentMayExist: z.boolean() })),
+ }),
+ ),
});
const handoffSchema = z.object({
@@ -131,6 +147,14 @@ function writerToken(account: string | null) {
return account ? config.getOAuthAccessToken(account, 'write_notes') : null;
}
+function noteMatchesDraft(note: Note, draft: NoteDraftFields) {
+ return (
+ note.content === draft.text &&
+ note.status === draft.visibility &&
+ (note.color?.toLowerCase() ?? null) === draft.color
+ );
+}
+
function matchesDraftOwner(
owner: string | null,
account: string | null,
@@ -189,6 +213,7 @@ export function useBibleReaderNote({
const oauthFailedCallbackState = oauthCallbackSuperseded ? null : auth?.oauthFailedCallbackState;
const canAuthorize = enabled && auth !== null && !auth.isHostControlled && !hostOwnsSignIn;
const createNote = useCreateNote();
+ const updateNote = useUpdateNote();
const [flow, setFlow] = useState(null);
const [restoredSelection, setRestoredSelection] = useState(null);
const clearRestoredSelection = useCallback(() => setRestoredSelection(null), []);
@@ -458,33 +483,68 @@ export function useBibleReaderNote({
});
return;
}
- const saving = { draft: active.draft, phase: 'save' } as const;
+ const draft = active.draft;
+ const saving = { draft, phase: 'save' } as const;
show(saving);
- const { selection, text, color, visibility, requestId, ownerId } = active.draft;
+ const { selection, text, color, visibility, requestId, ownerId, recovery } = draft;
+ const submitted = recovery?.submitted ?? { text, color, visibility };
+ let savedNote = recovery?.savedNote;
+ let patchToken: string | null = null;
const isCurrent = () =>
currentFlow.current === saving &&
latest.current.account === ownerId &&
config.storedUserInfo?.id === ownerId;
- const request: CreateNote = {
- request_id: requestId,
- content: text,
- status: visibility,
- passage: {
- version_id: selection.versionId,
- passage_id: buildPassageIds(selection.book, selection.chapter, selection.verses).join('+'),
- },
- };
- if (color) request.color = color;
try {
- await createNote(request, token);
+ if (!savedNote) {
+ const request: CreateNote = {
+ request_id: requestId,
+ content: submitted.text,
+ status: submitted.visibility,
+ passage: {
+ version_id: selection.versionId,
+ passage_id: buildPassageIds(selection.book, selection.chapter, selection.verses).join(
+ '+',
+ ),
+ },
+ };
+ if (submitted.color) request.color = submitted.color;
+ const note = await createNote(request, token);
+ if (!isCurrent()) return;
+ if (!noteMatchesDraft(note, draft)) {
+ savedNote = { id: note.id, contentMayExist: note.content.length > 0 };
+ }
+ }
+ if (savedNote) {
+ // Recheck the live scope after the create round trip and before updating.
+ patchToken = writerToken(ownerId);
+ if (!patchToken) throw new Error('An access token is required to finish saving the note');
+ if (!text && savedNote.contentMayExist) {
+ throw new Error('The Notes API cannot clear saved note text');
+ }
+ const update: UpdateNote = { status: visibility, color };
+ if (text) update.content = text;
+ const note = await updateNote(savedNote.id, update, patchToken);
+ if (note.id !== savedNote.id || !noteMatchesDraft(note, draft)) {
+ throw new Error('The updated note does not match the draft');
+ }
+ }
} catch (error) {
if (isCurrent()) {
const status = getHttpStatus(error);
+ const deniedToken = status === 401 || status === 403 ? (patchToken ?? token) : undefined;
+ // A lost update may already have changed the note. Retry the desired
+ // fields against this ID, even if the user restored the create values.
+ if (savedNote && patchToken && text && !deniedToken) {
+ savedNote = { ...savedNote, contentMayExist: true };
+ }
show({
phase: 'compose',
- draft: active.draft,
+ draft: {
+ ...draft,
+ recovery: savedNote || recovery || !deniedToken ? { submitted, savedNote } : undefined,
+ },
failed: true,
- deniedToken: status === 401 || status === 403 ? token : undefined,
+ deniedToken,
});
}
return;
From 5f51dcbf33e9a9eea584ed9ded3731d5821bc737 Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 13:05:34 -0600
Subject: [PATCH 25/75] fix: retry Notes writes after definite rejections
Allow corrected create fields and retain known blank content after a definitive HTTP rejection, while preserving recovery from earlier uncertain writes.
Ref: YPE-6783
---
.../components/bible-reader-notes.stories.tsx | 45 +++++++++++++------
.../src/components/use-bible-reader-note.ts | 6 ++-
2 files changed, 35 insertions(+), 16 deletions(-)
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index 8a0711cd4..abc172d71 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -219,6 +219,7 @@ export const EditAndRetry: Story = {
http.post('*/v1/notes', async ({ request }) => {
const body = await request.json();
requests.push(body);
+ if (body.content === 'Rejected thought') return new HttpResponse(null, { status: 413 });
if (stored) return noteResponse(stored);
stored = body;
return HttpResponse.error();
@@ -304,10 +305,17 @@ export const EditAndRetry: Story = {
colors.getAllByRole('button').map((button) => button.getAttribute('aria-label')),
).toEqual(palette.map(colorName));
- await fillEditor(editor, 'First thought');
+ await fillEditor(editor, 'Rejected thought');
await userEvent.click(composer.getByRole('radio', { name: 'Public' }));
await userEvent.click(composer.getByRole('button', { name: 'Save' }));
await expect(await composer.findByRole('alert')).toBeVisible();
+
+ await fillEditor(editor, 'First thought');
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await waitFor(() =>
+ expect(requests.map(({ content }) => content)).toEqual(['Rejected thought', 'First thought']),
+ );
+ await expect(await composer.findByRole('alert')).toBeVisible();
await expect(editor).toHaveValue('First thought');
await expect(selected).toHaveAttribute('aria-pressed', 'true');
await expect(composer.getByRole('radio', { name: 'Public' })).toBeChecked();
@@ -345,15 +353,17 @@ export const EditAndRetry: Story = {
passage: { bible_id: 111, passage_id: 'JHN.1.2' },
};
await expect(requests).toEqual([
+ { ...common, content: 'Rejected thought' },
{ ...common, content: 'First thought' },
{ ...common, content: 'First thought' },
]);
await expect(requests[1]?.request_id).toBe(requests[0]?.request_id);
+ await expect(requests[2]?.request_id).toBe(requests[0]?.request_id);
await expect(updates).toEqual([
{ content: 'Edited thought', status: 'private', color: null },
{ content: 'First thought', status: 'public', color: 'ffdca7' },
]);
- await expect(stored).toEqual(requests[0]);
+ await expect(stored).toEqual(requests[1]);
}),
};
@@ -626,7 +636,8 @@ export const CancelRetainsDraftAcrossNavigation: Story = {
tags: ['integration', 'shadow-dom', 'cross-browser'],
play: withWritableSession(async ({ canvasElement, loaded }) => {
const attempts: NoteRequest[] = [];
- const updates: { status: NoteRequest['status']; color: NoteRequest['color'] }[] = [];
+ type Update = Pick & { content?: string };
+ const updates: Update[] = [];
let stored: NoteRequest | undefined;
getWorker().use(
http.post('*/v1/notes', async ({ request }) => {
@@ -636,15 +647,13 @@ export const CancelRetainsDraftAcrossNavigation: Story = {
stored = body;
return HttpResponse.error();
}),
- http.patch(
- '*/v1/notes/saved-note',
- async ({ request }) => {
- if (!stored) return new HttpResponse(null, { status: 404 });
- const update = await request.json();
- updates.push(update);
- return noteResponse({ ...stored, ...update });
- },
- ),
+ http.patch('*/v1/notes/saved-note', async ({ request }) => {
+ if (!stored) return new HttpResponse(null, { status: 404 });
+ const update = await request.json();
+ updates.push(update);
+ if (update.content !== undefined) return new HttpResponse(null, { status: 429 });
+ return noteResponse({ ...stored, ...update });
+ }),
);
const root = await waitForShadowRoot(canvasElement);
const navigation = storyNavigation.parse(loaded.hostNavigation);
@@ -664,9 +673,18 @@ export const CancelRetainsDraftAcrossNavigation: Story = {
await waitFor(() => expect(renderedPassage()).toHaveTextContent('The Word Became Flesh'));
await selectVerses(root, [1, 4]);
const { composer: reopened } = await openComposer(root, 'John 1:1,4');
- await expect(reopened.getByRole('textbox', { name: 'Add Note…' })).toHaveValue('');
+ const editor = reopened.getByRole('textbox', { name: 'Add Note…' });
+ await expect(editor).toHaveValue('');
await userEvent.click(reopened.getByRole('radio', { name: 'Public' }));
+ await fillEditor(editor, 'Rejected text update');
+ await userEvent.click(reopened.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(reopened.getByRole('alert')).toBeVisible());
+ const rejected = { content: 'Rejected text update', status: 'public', color: null };
+ await expect(updates).toEqual([rejected]);
+
+ await fillEditor(editor, '');
await userEvent.click(reopened.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(updates).toEqual([rejected, { status: 'public', color: null }]));
await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
const request = {
request_id: expect.stringMatching(/^[\da-f-]{36}$/i),
@@ -676,7 +694,6 @@ export const CancelRetainsDraftAcrossNavigation: Story = {
};
await expect(attempts).toEqual([request, request]);
await expect(attempts[1]?.request_id).toBe(attempts[0]?.request_id);
- await expect(updates).toEqual([{ status: 'public', color: null }]);
}),
};
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index 3ef9aadec..22c1223e4 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -66,6 +66,7 @@ const handoffSchema = z.object({
});
const HANDOFF_KEY = 'youversion-platform:pending-note';
const HANDOFF_LIFETIME = 10 * 60 * 1000;
+const NOTE_REJECTION_STATUSES = [400, 401, 403, 404, 412, 413, 422, 429];
type NoteSelection = z.infer;
export type NoteDraft = z.infer;
@@ -532,16 +533,17 @@ export function useBibleReaderNote({
if (isCurrent()) {
const status = getHttpStatus(error);
const deniedToken = status === 401 || status === 403 ? (patchToken ?? token) : undefined;
+ const rejected = status !== undefined && NOTE_REJECTION_STATUSES.includes(status);
// A lost update may already have changed the note. Retry the desired
// fields against this ID, even if the user restored the create values.
- if (savedNote && patchToken && text && !deniedToken) {
+ if (savedNote && patchToken && text && !rejected) {
savedNote = { ...savedNote, contentMayExist: true };
}
show({
phase: 'compose',
draft: {
...draft,
- recovery: savedNote || recovery || !deniedToken ? { submitted, savedNote } : undefined,
+ recovery: savedNote || recovery || !rejected ? { submitted, savedNote } : undefined,
},
failed: true,
deniedToken,
From 7d6cfbd1ee03f682196f5a5a88fe45ff6934bee9 Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 13:20:06 -0600
Subject: [PATCH 26/75] fix: retry corrected Notes payloads after a 413
Release an unresolved create payload after a size rejection. Retain the request UUID and preserve recovery when the note ID is already known.
Ref: YPE-6783
---
.../components/bible-reader-notes.stories.tsx | 27 +++++++++++++++----
.../src/components/use-bible-reader-note.ts | 4 ++-
2 files changed, 25 insertions(+), 6 deletions(-)
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index abc172d71..f982356d5 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -219,7 +219,11 @@ export const EditAndRetry: Story = {
http.post('*/v1/notes', async ({ request }) => {
const body = await request.json();
requests.push(body);
- if (body.content === 'Rejected thought') return new HttpResponse(null, { status: 413 });
+ if (body.content === 'Rejected thought') {
+ return requests.length === 1
+ ? HttpResponse.error()
+ : new HttpResponse(null, { status: 413 });
+ }
if (stored) return noteResponse(stored);
stored = body;
return HttpResponse.error();
@@ -313,7 +317,20 @@ export const EditAndRetry: Story = {
await fillEditor(editor, 'First thought');
await userEvent.click(composer.getByRole('button', { name: 'Save' }));
await waitFor(() =>
- expect(requests.map(({ content }) => content)).toEqual(['Rejected thought', 'First thought']),
+ expect(requests.map(({ content }) => content)).toEqual([
+ 'Rejected thought',
+ 'Rejected thought',
+ ]),
+ );
+ await expect(await composer.findByRole('alert')).toBeVisible();
+
+ await userEvent.click(composer.getByRole('button', { name: 'Save' }));
+ await waitFor(() =>
+ expect(requests.map(({ content }) => content)).toEqual([
+ 'Rejected thought',
+ 'Rejected thought',
+ 'First thought',
+ ]),
);
await expect(await composer.findByRole('alert')).toBeVisible();
await expect(editor).toHaveValue('First thought');
@@ -353,17 +370,17 @@ export const EditAndRetry: Story = {
passage: { bible_id: 111, passage_id: 'JHN.1.2' },
};
await expect(requests).toEqual([
+ { ...common, content: 'Rejected thought' },
{ ...common, content: 'Rejected thought' },
{ ...common, content: 'First thought' },
{ ...common, content: 'First thought' },
]);
- await expect(requests[1]?.request_id).toBe(requests[0]?.request_id);
- await expect(requests[2]?.request_id).toBe(requests[0]?.request_id);
+ await expect(new Set(requests.map(({ request_id }) => request_id)).size).toBe(1);
await expect(updates).toEqual([
{ content: 'Edited thought', status: 'private', color: null },
{ content: 'First thought', status: 'public', color: 'ffdca7' },
]);
- await expect(stored).toEqual(requests[1]);
+ await expect(stored).toEqual(requests[2]);
}),
};
diff --git a/packages/ui/src/components/use-bible-reader-note.ts b/packages/ui/src/components/use-bible-reader-note.ts
index 22c1223e4..1fd2e2f29 100644
--- a/packages/ui/src/components/use-bible-reader-note.ts
+++ b/packages/ui/src/components/use-bible-reader-note.ts
@@ -534,6 +534,8 @@ export function useBibleReaderNote({
const status = getHttpStatus(error);
const deniedToken = status === 401 || status === 403 ? (patchToken ?? token) : undefined;
const rejected = status !== undefined && NOTE_REJECTION_STATUSES.includes(status);
+ // A 413 on create permits corrected fields under the same request ID.
+ const keepSubmission = !rejected || (recovery !== undefined && status !== 413);
// A lost update may already have changed the note. Retry the desired
// fields against this ID, even if the user restored the create values.
if (savedNote && patchToken && text && !rejected) {
@@ -543,7 +545,7 @@ export function useBibleReaderNote({
phase: 'compose',
draft: {
...draft,
- recovery: savedNote || recovery || !rejected ? { submitted, savedNote } : undefined,
+ recovery: savedNote || keepSubmission ? { submitted, savedNote } : undefined,
},
failed: true,
deniedToken,
From bf833d61992a6a6faff64a886851c20925a9e21e Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 16:33:30 -0600
Subject: [PATCH 27/75] fix(ui): preload destination highlights (YPE-6783)
---
.changeset/reader-saves-notes.md | 22 ++++++++++++++++
docs/adr/0006-tanstack-query-read-layer.md | 13 +++++++---
.../components/bible-reader-notes.stories.tsx | 25 +++++++++++++++----
.../components/use-bible-reader-highlights.ts | 12 +++++++--
4 files changed, 62 insertions(+), 10 deletions(-)
diff --git a/.changeset/reader-saves-notes.md b/.changeset/reader-saves-notes.md
index ac6ba8290..3c04b0274 100644
--- a/.changeset/reader-saves-notes.md
+++ b/.changeset/reader-saves-notes.md
@@ -13,3 +13,25 @@ The configurable verse actions include the built-in IDs `'highlights'`, `'save'`
`'copy'`, and `'share'`. Include `'save'` in a custom action order to offer Notes.
`NotesClient` supports creating a passage-only note with empty `content`.
+
+- Hooks exports `useCreateNote` and `useUpdateNote`, which take an explicit access
+ token for the write. The Reader recovers lost create responses with the same
+ request ID and reconciles subsequent edits against the recovered note.
+- Core adds `YouVersionAPIUsers.isSignInPending` and `onTokenRotation`, plus
+ `YouVersionPlatformConfiguration.getOAuthAccessToken`,
+ `hasMismatchedOAuthSession`, and `didStoredAccountChange` for OAuth lifecycle
+ and account-bound credential checks. `signIn` accepts a pre-redirect callback,
+ `refreshTokenIfNeeded` accepts a rotation observer, and `saveAuthData` accepts
+ optional scope/account metadata. Reader sign-in scope overrides are supported
+ by `useHighlightAuthActions().startSignInForHighlights`. `AuthContextValue`
+ exposes verified-token, account-revision, callback-state and auth-ownership
+ fields for managed auth consumers.
+- In SDK-managed auth, `useYVAuth().auth.accessToken` can be `null` even while
+ `isAuthenticated` remains true. Sessions created by version 3.0.0 have no new
+ account/scope binding and are treated as legacy. A normal token refresh in
+ another tab invalidates the receiving tab's legacy token verification; its
+ fetched highlights disappear until that tab reloads, remounts its auth provider,
+ or signs in again. Same-instance SDK refreshes retain legacy verification.
+- Managed `useHighlights` reads are disabled, with data masked to `null`, until
+ both the account and its verified access token are available. Host-controlled
+ auth and highlights retain their existing behavior.
diff --git a/docs/adr/0006-tanstack-query-read-layer.md b/docs/adr/0006-tanstack-query-read-layer.md
index a139e3a5e..8b216e0db 100644
--- a/docs/adr/0006-tanstack-query-read-layer.md
+++ b/docs/adr/0006-tanstack-query-read-layer.md
@@ -29,9 +29,16 @@ stale cached entries still revalidate on mount. Keep the `combine` callback stab
so TanStack Query memoizes it and the returned Map stays referentially stable.
No TanStack Query type reaches the public surface.
-The cache is memory-only. `refetch` performs exact query invalidation. Writes stay
-outside this read layer, owned by the highlights machine, and refresh via
-`refetch` after the write.
+The cache is memory-only. `refetch` performs exact query invalidation. Highlight
+writes stay outside this read layer, owned by the highlights machine, and refresh
+via `refetch` after the write. Reader Notes saves also use `refetch` to refresh the
+displayed chapter's highlights.
+
+Highlight refetch also restarts an active initial read when it has no cached
+result. That read may have started before the write and could return outdated
+data; the restart fetches the post-write state. Settled cached data stays visible
+during revalidation. Other read hooks retain exact invalidation without this
+initial-read restart.
## Why
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index f982356d5..ae09f007e 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -723,6 +723,8 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = {
const releaseNote = deferred();
const chapterRequested = deferred();
const releaseChapter = deferred();
+ const releaseDestinationRevalidation = deferred();
+ let destinationReads = 0;
const postSaveReads: string[] = [];
let noteSaved = false;
getWorker().use(
@@ -738,12 +740,15 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = {
await releaseChapter.promise;
return HttpResponse.json(mockPassages['JHN.3']);
}),
- http.get('*/v1/highlights', ({ request }) => {
+ http.get('*/v1/highlights', async ({ request }) => {
const scope = new URL(request.url).searchParams.get('passage_id') ?? '';
if (noteSaved) postSaveReads.push(scope);
- return scope === 'JHN.1'
- ? highlightPage(noteSaved ? green : yellow)
- : HttpResponse.json({ data: [], next_page_token: null });
+ if (scope === 'JHN.3') {
+ destinationReads += 1;
+ if (destinationReads > 1) await releaseDestinationRevalidation.promise;
+ return highlightPage({ ...green, passage_id: 'JHN.3.16' });
+ }
+ return highlightPage(noteSaved ? green : yellow);
}),
);
const retained = await readerVerse(root, 1);
@@ -755,6 +760,8 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = {
storyNavigation.parse(loaded.hostNavigation).request({ versionId: 111, passageId: 'JHN.3' });
await chapterRequested.promise;
await expect(retained).toBeVisible();
+ await expect(getBackgroundColorChannels(retained)).toEqual([255, 236, 91, 255]);
+ await waitFor(() => expect(destinationReads).toBe(1));
releaseNote.resolve();
await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull());
await waitFor(() =>
@@ -769,7 +776,14 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = {
await expect(actions.queryAllByRole('button', { name: 'Apply highlight' })).toHaveLength(0);
await expect(getBackgroundColorChannels(retained)).toEqual([180, 255, 193, 255]);
releaseChapter.resolve();
- await waitFor(async () => expect(await readerVerse(root, 16)).toBeVisible());
+ await waitFor(() =>
+ expect(root.querySelector('[data-slot="yv-bible-renderer"]')).toHaveTextContent(
+ 'Nicodemus',
+ ),
+ );
+ const destination = await readerVerse(root, 16);
+ await expect(destination).toBeVisible();
+ await expect(getBackgroundColorChannels(destination)).toEqual([180, 255, 193, 255]);
await waitFor(() => expect(postSaveReads).toEqual(['JHN.1', 'JHN.3']));
await selectVerses(root, [16]);
const currentActions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
@@ -779,6 +793,7 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = {
} finally {
releaseNote.resolve();
releaseChapter.resolve();
+ releaseDestinationRevalidation.resolve();
}
}),
};
diff --git a/packages/ui/src/components/use-bible-reader-highlights.ts b/packages/ui/src/components/use-bible-reader-highlights.ts
index 5d69c202d..c93a54ce6 100644
--- a/packages/ui/src/components/use-bible-reader-highlights.ts
+++ b/packages/ui/src/components/use-bible-reader-highlights.ts
@@ -226,6 +226,12 @@ export function useBibleReaderHighlights({
{ version_id: displayedVersionId, passage_id: displayedChapterUsfm },
{ enabled: live },
);
+ // Warm the destination's existing account-scoped cache while the old passage
+ // remains on screen. The display observer shares this request on handoff.
+ const { refetch: refetchDestination } = useHighlights(
+ { version_id: versionId, passage_id: `${book}.${chapter}` },
+ { enabled: live && isDisplayingRetainedChapter },
+ );
// Stable refs so controlled apply/remove close over the latest callbacks
// without re-creating the functions every render.
@@ -241,8 +247,10 @@ export function useBibleReaderHighlights({
createHighlight,
deleteHighlight,
refetch: () => {
- // The destination's highlights load when the destination passage is displayed.
- if (!isDisplayingRetainedChapter) refetch();
+ // Highlight writes target the requested scope; Notes refresh targets the
+ // displayed chapter separately through `refresh` below.
+ if (isDisplayingRetainedChapter) refetchDestination();
+ else refetch();
},
hasHighlightsPermission,
invalidateHighlightsPermission,
From a4a70637bf198cb3f46f5644d0ee7b1d4ba6daa5 Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 16:35:50 -0600
Subject: [PATCH 28/75] docs: clarify legacy auth recovery (YPE-6783)
---
.changeset/reader-saves-notes.md | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/.changeset/reader-saves-notes.md b/.changeset/reader-saves-notes.md
index 3c04b0274..5a0f693cb 100644
--- a/.changeset/reader-saves-notes.md
+++ b/.changeset/reader-saves-notes.md
@@ -30,8 +30,10 @@ The configurable verse actions include the built-in IDs `'highlights'`, `'save'`
`isAuthenticated` remains true. Sessions created by version 3.0.0 have no new
account/scope binding and are treated as legacy. A normal token refresh in
another tab invalidates the receiving tab's legacy token verification; its
- fetched highlights disappear until that tab reloads, remounts its auth provider,
- or signs in again. Same-instance SDK refreshes retain legacy verification.
+ fetched highlights are hidden until credentials can be verified again.
+ Reloading that tab, remounting its auth provider, or a new verified sign-in
+ (including in another tab) can restore them. Same-instance SDK refreshes retain
+ legacy verification.
- Managed `useHighlights` reads are disabled, with data masked to `null`, until
both the account and its verified access token are available. Host-controlled
auth and highlights retain their existing behavior.
From cc1c0619410641f655711195d622b8ee96aa2a1d Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 16:41:51 -0600
Subject: [PATCH 29/75] test(ui): await destination passage before save refresh
(YPE-6783)
---
packages/ui/src/components/bible-reader-notes.stories.tsx | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index ae09f007e..cbbbdc017 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -629,7 +629,11 @@ export const RefreshDisplayedChapterAfterNavigation: Story = {
try {
storyNavigation.parse(loaded.hostNavigation).request({ versionId: 111, passageId: 'JHN.3' });
- await readerVerse(root, 16);
+ await waitFor(() =>
+ expect(root.querySelector('[data-slot="yv-bible-renderer"]')).toHaveTextContent(
+ 'Nicodemus',
+ ),
+ );
await waitFor(() => expect(chapterReads).toEqual(['111:JHN.3']));
await expect(overlays.getByRole('dialog', { name: 'John 1:2' })).toBeVisible();
releaseNote.resolve();
From 3bc1d4487e56d0b19ef47619e7be88d3c8cec8ed Mon Sep 17 00:00:00 2001
From: Austin
Date: Fri, 27 Nov 2026 16:51:49 -0600
Subject: [PATCH 30/75] test(ui): await settled highlight colors (YPE-6783)
---
.../src/components/bible-reader-notes.stories.tsx | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)
diff --git a/packages/ui/src/components/bible-reader-notes.stories.tsx b/packages/ui/src/components/bible-reader-notes.stories.tsx
index cbbbdc017..e427ba6db 100644
--- a/packages/ui/src/components/bible-reader-notes.stories.tsx
+++ b/packages/ui/src/components/bible-reader-notes.stories.tsx
@@ -721,6 +721,14 @@ export const CancelRetainsDraftAcrossNavigation: Story = {
export const RefreshRetainedChapterWhileNavigationLoads: Story = {
...RefreshDisplayedChapterAfterNavigation,
tags: ['integration', 'shadow-dom', 'cross-browser'],
+ parameters: {
+ msw: {
+ handlers: [
+ http.get('*/v1/highlights', () => highlightPage(yellow)),
+ ...writableSession.msw.handlers,
+ ],
+ },
+ },
play: withWritableSession(async ({ canvasElement, loaded }) => {
const root = await waitForShadowRoot(canvasElement);
const noteSent = deferred();
@@ -756,6 +764,7 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = {
}),
);
const retained = await readerVerse(root, 1);
+ await waitFor(() => expect(getBackgroundColorChannels(retained)).toEqual([255, 236, 91, 255]));
await selectVerses(root, [2]);
const { overlays, composer } = await openComposer(root, 'John 1:2');
try {
@@ -787,7 +796,9 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = {
);
const destination = await readerVerse(root, 16);
await expect(destination).toBeVisible();
- await expect(getBackgroundColorChannels(destination)).toEqual([180, 255, 193, 255]);
+ await waitFor(() =>
+ expect(getBackgroundColorChannels(destination)).toEqual([180, 255, 193, 255]),
+ );
await waitFor(() => expect(postSaveReads).toEqual(['JHN.1', 'JHN.3']));
await selectVerses(root, [16]);
const currentActions = within(await overlays.findByRole('dialog', { name: 'Verse actions' }));
From 0b933624c5ddd5cb5c31972993c06fcbfd82d5db Mon Sep 17 00:00:00 2001
From: camrun91 <16566029+camrun91@users.noreply.github.com>
Date: Wed, 25 Nov 2026 21:52:53 +0000
Subject: [PATCH 31/75] chore: sync react localization
---
.changeset/sync-localization-react-3b7e5a8.md | 5 +++++
packages/ui/src/i18n/locales/en.json | 10 +++++++++-
2 files changed, 14 insertions(+), 1 deletion(-)
create mode 100644 .changeset/sync-localization-react-3b7e5a8.md
diff --git a/.changeset/sync-localization-react-3b7e5a8.md b/.changeset/sync-localization-react-3b7e5a8.md
new file mode 100644
index 000000000..86659a231
--- /dev/null
+++ b/.changeset/sync-localization-react-3b7e5a8.md
@@ -0,0 +1,5 @@
+---
+'@youversion/platform-react-ui': patch
+---
+
+Sync localization from platform-localization (3b7e5a8): add Italian (it), Romanian (ro), Swedish (sv); update 89 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 27e0ded28..9636bb7a2 100644
--- a/packages/ui/src/i18n/locales/en.json
+++ b/packages/ui/src/i18n/locales/en.json
@@ -140,5 +140,13 @@
"notesDiscardTitle": "Discard note?",
"notesDiscardMessage": "Your note hasn’t been saved. Discard your changes?",
"notesDiscard": "Discard",
- "notesVerseIndicatorAccessibilityLabel": "Notes {{verse}}"
+ "notesVerseIndicatorAccessibilityLabel": "Notes {{verse}}",
+ "addHighlightAriaLabel": "Add {{color}} highlight",
+ "highlightBlue": "blue",
+ "highlightGreen": "green",
+ "highlightOrange": "orange",
+ "highlightPink": "pink",
+ "highlightPurple": "purple",
+ "highlightYellow": "yellow",
+ "removeHighlightAriaLabel": "Remove {{color}} highlight"
}
From 49bb3d934903736a772ba5e8db216c67af0170f1 Mon Sep 17 00:00:00 2001
From: Austin
Date: Sat, 28 Nov 2026 09:54:44 -0600
Subject: [PATCH 32/75] fix(ui): announce note highlight color names
---
.changeset/reader-saves-notes.md | 3 +++
.../src/components/bible-reader-notes-composer.tsx | 14 +++++++++++++-
.../src/components/bible-reader-notes.stories.tsx | 12 ++++++++----
3 files changed, 24 insertions(+), 5 deletions(-)
diff --git a/.changeset/reader-saves-notes.md b/.changeset/reader-saves-notes.md
index 5a0f693cb..0d17feced 100644
--- a/.changeset/reader-saves-notes.md
+++ b/.changeset/reader-saves-notes.md
@@ -9,6 +9,9 @@ selection, including gaps, and saves a passage with optional text, privacy, and
highlight color. Reader sign-in requests Notes scopes. The reader refreshes
chapter highlights after a successful save.
+Notes composer swatches announce localized color names and whether selecting
+them adds or removes the highlight color.
+
The configurable verse actions include the built-in IDs `'highlights'`, `'save'`,
`'copy'`, and `'share'`. Include `'save'` in a custom action order to offer Notes.
diff --git a/packages/ui/src/components/bible-reader-notes-composer.tsx b/packages/ui/src/components/bible-reader-notes-composer.tsx
index 5f0e3186d..0efe42147 100644
--- a/packages/ui/src/components/bible-reader-notes-composer.tsx
+++ b/packages/ui/src/components/bible-reader-notes-composer.tsx
@@ -40,6 +40,14 @@ export function BibleReaderNotesComposer({
const stayButtonRef = useRef(null);
const focusBeforeDiscard = useRef