Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .changeset/reader-saved-note-indicators.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
'@youversion/platform-core': patch
'@youversion/platform-react-hooks': minor
'@youversion/platform-react-ui': minor
---

Show saved Notes on their attached verses in BibleReader. The Notes drawer
shows matching passages, text, visibility, relative ages, and note colors.
Standalone BibleTextView supports Notes indicators through
`onNoteIndicatorPress`, which receives the verse and its matching notes.

The hooks package adds `useChapterNotes` and `useDeleteNote`. Successful Notes
writes with the signed-in account's captured token refresh active Notes and
highlights in the same provider, preserving settled data during refresh.

`NotesClient.isListAccessDenied` identifies 401 and 403 responses from the
Notes collection so a Bible version refusal only clears Notes for its own query.
`YouVersionPlatformConfiguration.subscribeToAuthSessionChanges` lets consumers
re-read the verified session after SDK credential or profile writes and auth
storage changes from other documents. Chapter Notes revalidate on credential
rotation and clear cached Notes when read access is lost, including while the
Reader is unmounted.
10 changes: 6 additions & 4 deletions docs/adr/0006-tanstack-query-read-layer.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,16 @@ No TanStack Query type reaches the public surface.

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.
via `refetch` after the write. Successful Notes mutations for the signed-in account
invalidate its chapter Notes and highlights in the provider's cache, refreshing
active reads for the displayed chapter and Bible version.

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.
during revalidation. Chapter Notes use the same restart after a mutation or
refetch. The chapter Notes query publishes the complete paginated snapshot and
clears it on loss of Notes read access.

## Why

Expand Down
34 changes: 25 additions & 9 deletions examples/vite-react/src/pages/BibleReaderPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ 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<string>();
const [showCustomMarkers, setShowCustomMarkers] = useState(false);

return (
<div className="flex h-[calc(100vh-3.5rem)] flex-col">
Expand All @@ -18,6 +19,14 @@ export function BibleReaderPage() {
? `Opened marker for ${openedMarker}.`
: 'Select verses and choose Save to add a note or Mark verses to add a marker.'}
</p>
<label className="flex items-center gap-2 px-4 py-1 text-sm">
<input
type="checkbox"
checked={showCustomMarkers}
onChange={(event) => setShowCustomMarkers(event.currentTarget.checked)}
/>
Show custom markers instead of note indicators
</label>
<div className="min-h-0 flex-1">
<BibleReader.Root
defaultBook="JHN"
Expand All @@ -31,27 +40,34 @@ export function BibleReaderPage() {
id: 'mark',
label: 'Mark verses',
icon: <BookmarkPlus size={20} />,
onSelect: ({ versionId, passageIds }) =>
onSelect: ({ versionId, passageIds }) => {
setShowCustomMarkers(true);
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' },
}
getVerseIndicator={
showCustomMarkers
? (reference) =>
markers.has(markerKey(reference))
? {
label: `Open marker for ${reference.passageId}`,
style: { backgroundColor: '#a855f7' },
}
: undefined
: undefined
}
onVerseIndicatorPress={({ passageId }) => setOpenedMarker(passageId)}
onVerseIndicatorPress={
showCustomMarkers ? ({ passageId }) => setOpenedMarker(passageId) : undefined
}
>
<BibleReader.Content />
<BibleReader.Toolbar />
Expand Down
31 changes: 31 additions & 0 deletions packages/core/src/YouVersionPlatformConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ import {
AUTH_SCOPE_KEY,
} from './auth-storage-keys';

const AUTH_SESSION_CHANGED_EVENT = 'youversion:auth-session-changed';

function notifyAuthSessionChanged(): void {
const browser = globalThis.window;
if (browser?.Event) {
browser.dispatchEvent?.(new browser.Event(AUTH_SESSION_CHANGED_EVENT));
}
}

function parseStoredUserInfo(raw: string | null | undefined): YouVersionUserInfoJSON | null {
if (!raw) return null;
try {
Expand Down Expand Up @@ -129,6 +138,7 @@ export class YouVersionPlatformConfiguration {
}

if (persisted) invalidateAuthorization(storage, previousState);
notifyAuthSessionChanged();
return persisted;
}

Expand All @@ -148,11 +158,13 @@ export class YouVersionPlatformConfiguration {
if (userInfo === null) {
removeStorageItem(storage, AUTH_USER_INFO_KEY);
if (!storage?.getItem(AUTH_USER_INFO_KEY)) invalidateAuthorization(storage, previousState);
notifyAuthSessionChanged();
return true;
}

const persisted = setStorageItem(storage, AUTH_USER_INFO_KEY, JSON.stringify(userInfo));
if (persisted) invalidateAuthorization(storage, previousState);
notifyAuthSessionChanged();
return persisted;
}

Expand Down Expand Up @@ -207,6 +219,25 @@ export class YouVersionPlatformConfiguration {
);
}

/**
* Subscribes to SDK credential or profile writes in this document and auth
* storage changes from other documents. Re-read the current session in the
* callback, which receives no credentials.
* Returns an unsubscribe function.
*/
public static subscribeToAuthSessionChanges(listener: () => void): () => void {
const browser = globalThis.window;
const onStorage = (event: StorageEvent) => {
if (YouVersionPlatformConfiguration.isAuthSessionEvent(event)) listener();
};
browser?.addEventListener?.(AUTH_SESSION_CHANGED_EVENT, listener);
browser?.addEventListener?.('storage', onStorage);
return () => {
browser?.removeEventListener?.(AUTH_SESSION_CHANGED_EVENT, listener);
browser?.removeEventListener?.('storage', onStorage);
};
}

/** @internal A legacy rotation completed after this account's scoped binding was written. */
public static get hasExpiredLegacyRotation(): boolean {
const storage = getLocalStorage();
Expand Down
38 changes: 38 additions & 0 deletions packages/core/src/__tests__/auth-session-events.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { expect, it, vi } from 'vitest';
import { JSDOM } from 'jsdom';
import { YouVersionPlatformConfiguration } from '../YouVersionPlatformConfiguration';

it('keeps auth writes and notifications working in a grafted DOM window', () => {
const embedded = new JSDOM('', { url: 'https://sdk.example' });
expect(embedded.window.Event).not.toBe(Event);
vi.stubGlobal('window', embedded.window);
const observed: (string | null)[] = [];
const unsubscribe = YouVersionPlatformConfiguration.subscribeToAuthSessionChanges(() => {
observed.push(YouVersionPlatformConfiguration.getOAuthAccessToken('realm-user', 'read_notes'));
});

try {
expect(
YouVersionPlatformConfiguration.saveAuthData('realm-access', 'realm-refresh', null, {
scope: 'read_notes',
userId: 'realm-user',
}),
).toBe(true);
expect(YouVersionPlatformConfiguration.saveUserInfo({ id: 'realm-user' })).toBe(true);
expect(observed).toEqual([null, 'realm-access']);
expect(YouVersionPlatformConfiguration.getOAuthAccessToken('realm-user', 'read_notes')).toBe(
'realm-access',
);

unsubscribe();
YouVersionPlatformConfiguration.clearAuthTokens();
expect(observed).toEqual([null, 'realm-access']);
expect(
YouVersionPlatformConfiguration.getOAuthAccessToken('realm-user', 'read_notes'),
).toBeNull();
} finally {
unsubscribe();
vi.unstubAllGlobals();
embedded.window.close();
}
});
24 changes: 18 additions & 6 deletions packages/core/src/__tests__/notes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,17 +225,27 @@ describe.skipIf(Boolean(process.env.INTEGRATION_TESTS))('NotesClient', () => {
const client = createClient();
const create = { request_id: requestId, content: note.content, status: note.status };
for (const status of [401, 403]) {
const statusText = status === 401 ? 'Unauthorized' : 'Forbidden';
server.use(
http.all(`${collectionUrl}*`, () => HttpResponse.json({ message: 'Denied' }, { status })),
http.all(`${collectionUrl}*`, () =>
HttpResponse.json({ message: 'Denied' }, { status, statusText }),
),
);
const list = client.getNotes({}, 'token');
await expect(list.catch(getHttpStatus)).resolves.toBe(status);
await expect(list).rejects.toMatchObject({ statusText });
await expect(list).rejects.toSatisfy((error: Error) => NotesClient.isListAccessDenied(error));
for (const operation of [
() => client.getNotes({}, 'token'),
() => client.getNote(noteId, 'token'),
() => client.createNote(create, 'token'),
() => client.updateNote(noteId, { title: null }, 'token'),
() => client.deleteNote(noteId, 'token'),
]) {
await expect(operation().catch(getHttpStatus)).resolves.toBe(status);
const denied = operation();
await expect(denied.catch(getHttpStatus)).resolves.toBe(status);
await expect(denied).rejects.not.toSatisfy((error: Error) =>
NotesClient.isListAccessDenied(error),
);
}
}
});
Expand Down Expand Up @@ -388,9 +398,11 @@ describe.skipIf(Boolean(process.env.INTEGRATION_TESTS))('NotesClient', () => {
},
]) {
Object.assign(config, filters);
await expect(
client.getNotes({ version_id: 3034 }, 'reader').catch(getHttpStatus),
).resolves.toBe(403);
const refused = client.getNotes({ version_id: 3034 }, 'reader');
await expect(refused.catch(getHttpStatus)).resolves.toBe(403);
await expect(refused).rejects.not.toSatisfy((error: Error) =>
NotesClient.isListAccessDenied(error),
);
await expect(client.createNote(create, 'writer').catch(getHttpStatus)).resolves.toBe(403);
await expect(
client.updateNote(noteId, { passage: note.passage }, 'writer').catch(getHttpStatus),
Expand Down
20 changes: 18 additions & 2 deletions packages/core/src/notes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as z from 'zod/mini';
import { resolveAuthToken } from './auth-token';
import { assertUsableVersion } from './bible-chapter';
import type { ApiClient } from './client';
import { getHttpStatus, type ApiClient, type ApiResponse } from './client';
import {
CreateNoteSchema,
NoteIdSchema,
Expand All @@ -15,6 +15,7 @@ import { object } from './schemas/object';
import type { Collection, CreateNote, Note, NotePassage, UpdateNote } from './types';

const NOTES_PATH = '/v1/notes';
const listAccessDenials = new WeakSet<Error>();

const GetNotesOptionsSchema = object({
/** Filter by Bible version. Sent on the wire as `bible_id`. */
Expand Down Expand Up @@ -71,6 +72,11 @@ export class NotesClient {
this.client = client;
}

/** True for an HTTP 401 or 403 received from the Notes collection by `getNotes`. */
static isListAccessDenied(error: Error): boolean {
return listAccessDenials.has(error);
}

/**
* Lists one page of notes with `read_notes` access. An empty page can still have a continuation token.
* Malformed notes are skipped without discarding the page's continuation token.
Expand All @@ -88,7 +94,17 @@ export class NotesClient {
if (passage_id !== undefined) query.passage_id = passage_id;
if (page_size !== undefined) query.page_size = page_size;
if (page_token != null) query.page_token = page_token;
const { status, data } = await this.client.getWithStatus<unknown>(NOTES_PATH, query, headers);
let response: ApiResponse<unknown>;
try {
response = await this.client.getWithStatus<unknown>(NOTES_PATH, query, headers);
} catch (error) {
const status = getHttpStatus(error);
if (error instanceof Error && (status === 401 || status === 403)) {
listAccessDenials.add(error);
}
throw error;
}
const { status, data } = response;
if (status === 204) {
return { data: [], next_page_token: null };
}
Expand Down
5 changes: 5 additions & 0 deletions packages/hooks/src/hook-overrides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
} from '@youversion/platform-core';
import type { UseApiDataOptions } from './useApiData';
import type { UseBooksResult } from './useBooks';
import type { ChapterNotesOptions, UseChapterNotesResult } from './useChapterNotes';
import type { UseHighlightsResult } from './useHighlights';
import type { UseLanguageResult } from './useLanguage';
import type { UseLanguagesResult } from './useLanguages';
Expand All @@ -24,6 +25,10 @@ import type { UseVerseOfTheDayResult } from './useVOTD';
*/
export type HookOverrides = {
useBooks?: (versionId: number, options?: UseApiDataOptions) => UseBooksResult;
useChapterNotes?: (
options: ChapterNotesOptions,
apiOptions?: UseApiDataOptions,
) => UseChapterNotesResult;
useFilteredVersions?: (
versions: BibleVersion[],
searchTerm: string,
Expand Down
2 changes: 2 additions & 0 deletions packages/hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ export * from './useUnifiedSearch';
export * from './usePassage';
export * from './useVOTD';
export * from './useHighlights';
export * from './useChapterNotes';
export * from './useCreateNote';
export * from './useDeleteNote';
export * from './useUpdateNote';
export * from './useHighlightAuthActions';
export * from './useLanguages';
Expand Down
7 changes: 6 additions & 1 deletion packages/hooks/src/internal/QueryClientContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
type ReactNode,
} from 'react';
import type { QueryClient } from '@tanstack/react-query';
import { subscribeToChapterNotesRevocation } from './chapterNotesCache';

/**
* @internal
Expand Down Expand Up @@ -62,7 +63,11 @@ export function InternalQueryClientProvider({
}): ReactElement {
useEffect(() => {
client.mount();
return () => client.unmount();
const unsubscribe = subscribeToChapterNotesRevocation(client);
return () => {
unsubscribe();
client.unmount();
};
}, [client]);
return <QueryClientContext.Provider value={client}>{children}</QueryClientContext.Provider>;
}
Expand Down
38 changes: 38 additions & 0 deletions packages/hooks/src/internal/chapterNotesCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { YouVersionPlatformConfiguration } from '@youversion/platform-core';
import type { Query, QueryClient } from '@tanstack/react-query';

type ChapterNotesGrants = WeakMap<Query, { account: string; token: string }>;

// The CommonJS hook and test-utils provider bundles share a query client. They
// also need the same grant map so the provider can evict Notes fetched by the hook.
const CHAPTER_NOTES_GRANTS_KEY = Symbol.for('@youversion/platform-react-hooks/chapterNotesGrants');

interface ChapterNotesGrantsRegistry {
[key: symbol]: ChapterNotesGrants | undefined;
}

// SAFETY: only the private symbol above is read and written on this registry.
const registry = globalThis as ChapterNotesGrantsRegistry;
export const chapterNotesGrants: ChapterNotesGrants =
registry[CHAPTER_NOTES_GRANTS_KEY] ?? new WeakMap();
registry[CHAPTER_NOTES_GRANTS_KEY] = chapterNotesGrants;

/** Evict private Notes even when the provider has no mounted Notes readers. */
export function subscribeToChapterNotesRevocation(client: QueryClient): () => void {
function removeRevokedNotes(): void {
client.removeQueries({
predicate: (query) => {
const grant = chapterNotesGrants.get(query);
return (
grant !== undefined &&
!YouVersionPlatformConfiguration.getOAuthAccessToken(grant.account, 'read_notes')
);
},
});
}

const unsubscribe =
YouVersionPlatformConfiguration.subscribeToAuthSessionChanges(removeRevokedNotes);
removeRevokedNotes();
return unsubscribe;
}
Loading
Loading