diff --git a/.changeset/reader-saved-note-indicators.md b/.changeset/reader-saved-note-indicators.md new file mode 100644 index 000000000..a1e12ab3a --- /dev/null +++ b/.changeset/reader-saved-note-indicators.md @@ -0,0 +1,25 @@ +--- +'@youversion/platform-core': patch +'@youversion/platform-react-hooks': minor +'@youversion/platform-react-ui': minor +--- + +Show saved notes with rounded indicator backgrounds behind verse numbers, using +25% gray over highlights and 55% blue otherwise to match the native SDKs, and in a drawer +with passage, visibility, localized age, color, and expandable six-line previews. Standalone BibleTextView +callers can handle note indicators with `onNoteIndicatorPress`. +Preserve contrasting verse-number text over dark highlights. + +Add `useChapterNotes` and `useDeleteNote`. Successful note writes refresh +highlights while preserving settled data. Creates update matching chapter Notes +directly; later complete reads replace that snapshot. Updates and deletes re-read Notes. Clear private notes when read access is lost. + +Keep one swatch per color and check existing selection colors in place. Make the +unused `VerseActionPopover` props `selectedVerses` and `highlightedVerses` optional +and deprecated; use `activeHighlights` for checked colors. The Save +composer retains history while editing, caps the editor at three lines, supports +modal scrolling, and disables Save until a draft changes. Keep shared dialogs within +narrow viewports by including padding in their declared width. + +Expose auth-session change subscriptions and identify Notes collection access +denials separately from Bible preflight failures. diff --git a/docs/adr/0006-tanstack-query-read-layer.md b/docs/adr/0006-tanstack-query-read-layer.md index 3c8854246..499052195 100644 --- a/docs/adr/0006-tanstack-query-read-layer.md +++ b/docs/adr/0006-tanstack-query-read-layer.md @@ -31,14 +31,20 @@ 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 +refresh its active highlights in the provider's cache for the displayed chapter +and Bible version. A successful create updates matching chapter Notes directly +and marks them stale for the next read. Updates and deletes refresh Notes too. +Complete chapter reads remain authoritative; no separate retained-create list +overrides later successful snapshots. 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 an update, delete, or +explicit refetch. An initial paged read can finish alongside a create and merges +that confirmed Note once, so earlier saved Notes are still collected. The chapter Notes query publishes the complete paginated snapshot and +clears it on loss of Notes read access. ## Why diff --git a/examples/vite-react/scripts/smoke-reader-notes.mjs b/examples/vite-react/scripts/smoke-reader-notes.mjs index 87436ad96..37d8be54c 100644 --- a/examples/vite-react/scripts/smoke-reader-notes.mjs +++ b/examples/vite-react/scripts/smoke-reader-notes.mjs @@ -167,6 +167,8 @@ await context.route(`${api}/**`, async (route) => { } return json({ data: [] }); case '/v1/notes': { + if (request.method() === 'GET') return json({ data: [] }); + assert.equal(request.method(), 'POST', 'Expected a supported Notes operation'); const body = request.postDataJSON(); notes.push({ body, authorization: request.headers()['authorization'] }); return json({ ...body, id: 'smoke-note' }, 201); @@ -413,9 +415,15 @@ try { passage: { bible_id: 3034, passage_id: 'JHN.1.2+JHN.1.4' }, }); + // A confirmed save is immediately available even while the list endpoint is stale. + await page.getByRole('button', { name: 'Notes 2', exact: true }).click(); + await composer(page, 'John 1:2').waitFor(); + assert.equal( + await composer(page, 'John 1:2').getByText('Notes smoke', { exact: true }).count(), + 1, + ); + // 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 signOut(other); diff --git a/packages/core/src/YouVersionPlatformConfiguration.ts b/packages/core/src/YouVersionPlatformConfiguration.ts index 845dc137d..c8dc8c4d6 100644 --- a/packages/core/src/YouVersionPlatformConfiguration.ts +++ b/packages/core/src/YouVersionPlatformConfiguration.ts @@ -19,6 +19,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 { @@ -107,6 +116,7 @@ export class YouVersionPlatformConfiguration { } if (persisted) invalidateAuthorization(storage, previousState); + notifyAuthSessionChanged(); return persisted; } @@ -126,11 +136,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; } @@ -185,6 +197,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(this: void, 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(); diff --git a/packages/core/src/__tests__/auth-session-events.test.ts b/packages/core/src/__tests__/auth-session-events.test.ts new file mode 100644 index 000000000..22a34b898 --- /dev/null +++ b/packages/core/src/__tests__/auth-session-events.test.ts @@ -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(); + } +}); diff --git a/packages/core/src/__tests__/client.test.ts b/packages/core/src/__tests__/client.test.ts index 8871310f4..9748261ac 100644 --- a/packages/core/src/__tests__/client.test.ts +++ b/packages/core/src/__tests__/client.test.ts @@ -78,6 +78,7 @@ describe('ApiClient contracts', () => { }); YouVersionPlatformConfiguration.installationId = null; expect(await installId()).toBe('persisted-id'); + expect(new ApiClient({ appKey: 'k' }).config.installationId).toBe('persisted-id'); } finally { vi.unstubAllGlobals(); YouVersionPlatformConfiguration.installationId = null; diff --git a/packages/core/src/__tests__/notes.test.ts b/packages/core/src/__tests__/notes.test.ts index ed5353394..6755fcfee 100644 --- a/packages/core/src/__tests__/notes.test.ts +++ b/packages/core/src/__tests__/notes.test.ts @@ -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), + ); } } }); @@ -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), diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index 993480962..3c4541760 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -67,6 +67,7 @@ export class ApiClient { this.baseURL = 'https://' + apiHost; this.timeout = config.timeout || 10000; const installationId = config.installationId || getInstallationId(); + this.config.installationId = installationId ?? undefined; this.defaultHeaders = { 'Content-Type': 'application/json', 'X-YVP-App-Key': this.config.appKey, diff --git a/packages/core/src/notes.ts b/packages/core/src/notes.ts index dec15918b..51bfb1344 100644 --- a/packages/core/src/notes.ts +++ b/packages/core/src/notes.ts @@ -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, @@ -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(); const GetNotesOptionsSchema = object({ /** Filter by Bible version. Sent on the wire as `bible_id`. */ @@ -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. @@ -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(NOTES_PATH, query, headers); + let response: ApiResponse; + try { + response = await this.client.getWithStatus(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 }; } diff --git a/packages/hooks/src/hook-overrides.ts b/packages/hooks/src/hook-overrides.ts index 615a62058..a754fa104 100644 --- a/packages/hooks/src/hook-overrides.ts +++ b/packages/hooks/src/hook-overrides.ts @@ -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'; @@ -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, diff --git a/packages/hooks/src/index.ts b/packages/hooks/src/index.ts index 25e145703..1ffb5dfc6 100644 --- a/packages/hooks/src/index.ts +++ b/packages/hooks/src/index.ts @@ -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'; diff --git a/packages/hooks/src/internal/QueryClientContext.tsx b/packages/hooks/src/internal/QueryClientContext.tsx index 3d860f429..ff2177a19 100644 --- a/packages/hooks/src/internal/QueryClientContext.tsx +++ b/packages/hooks/src/internal/QueryClientContext.tsx @@ -9,6 +9,7 @@ import { type ReactNode, } from 'react'; import type { QueryClient } from '@tanstack/react-query'; +import { subscribeToChapterNotesRevocation } from './chapterNotesCache'; /** * @internal @@ -62,7 +63,11 @@ export function InternalQueryClientProvider({ }): ReactElement { useEffect(() => { client.mount(); - return () => client.unmount(); + const unsubscribe = subscribeToChapterNotesRevocation(client); + return () => { + unsubscribe(); + client.unmount(); + }; }, [client]); return {children}; } diff --git a/packages/hooks/src/internal/chapterNotesCache.ts b/packages/hooks/src/internal/chapterNotesCache.ts new file mode 100644 index 000000000..5c33b84fe --- /dev/null +++ b/packages/hooks/src/internal/chapterNotesCache.ts @@ -0,0 +1,229 @@ +import { + getHttpStatus, + NotesClient, + parseUsfmReference, + YouVersionPlatformConfiguration, + type ApiConfig, + type Note, +} from '@youversion/platform-core'; +import type { Query, QueryClient, QueryFilters, QueryKey } from '@tanstack/react-query'; + +type ChapterNotesGrants = WeakMap< + Query, + { + account: string; + token: string; + context: string; + startedWithoutSnapshot: boolean; + denied?: boolean; + } +>; + +// Both bundles use the same private query client. Keep their tracking state on +// that client so CommonJS providers can revoke Notes read by ESM hooks. +const CHAPTER_NOTES_GRANTS_KEY = Symbol.for('@youversion/platform-react-hooks/chapterNotesGrants'); + +type ChapterNotesQueryClient = QueryClient & { + [CHAPTER_NOTES_GRANTS_KEY]?: ChapterNotesGrants; +}; + +function getChapterNotesGrants(client: QueryClient): ChapterNotesGrants { + // SAFETY: only this private symbol is attached to the SDK-owned client, and + // every bundle stores the same WeakMap type there. + const owner = client as ChapterNotesQueryClient; + return (owner[CHAPTER_NOTES_GRANTS_KEY] ??= new WeakMap()); +} + +/** Publish the confirmed create; the next complete read remains authoritative. */ +export async function publishCreatedChapterNote( + client: QueryClient, + filters: QueryFilters, + note: Note, +): Promise { + const chapterNotesGrants = getChapterNotesGrants(client); + // Let an initial paged read finish collecting older notes. The read merges + // confirmed creates published while it was pending; settled refreshes cancel. + await client.cancelQueries({ + ...filters, + predicate: (query) => + (!filters.predicate || filters.predicate(query)) && + !chapterNotesGrants.get(query)?.startedWithoutSnapshot, + }); + for (const query of client.getQueryCache().findAll(filters)) { + const grant = chapterNotesGrants.get(query); + if ( + !grant || + grant.denied || + YouVersionPlatformConfiguration.getOAuthAccessToken(grant.account, 'read_notes') !== + grant.token + ) + continue; + const overlaps = + note.passage?.version_id === query.queryKey.at(-2) && + note.passage?.passage_id.split('+').some((id) => { + const reference = parseUsfmReference(id); + return reference && `${reference.book}.${reference.chapter}` === query.queryKey.at(-1); + }); + if (!overlaps) continue; + client.setQueryData(query.queryKey, (notes = []) => [ + note, + ...notes.filter((entry) => entry.id !== note.id), + ]); + } + await client.invalidateQueries({ ...filters, refetchType: 'none' }); +} + +/** Revalidate a tracked chapter when its verified token rotates, retaining settled data. */ +export function revalidateChapterNotesOnTokenChange( + client: QueryClient, + queryKey: QueryKey, + account: string, + token: string, +): void { + const chapterNotesGrants = getChapterNotesGrants(client); + const filter = { queryKey, exact: true }; + const query = client.getQueryCache().find(filter); + const previous = query && chapterNotesGrants.get(query); + if (!query || !previous || previous.token === token) return; + chapterNotesGrants.set(query, { ...previous, token }); + void client.cancelQueries(filter).then(() => { + if (YouVersionPlatformConfiguration.getOAuthAccessToken(account, 'read_notes') === token) { + void client.invalidateQueries(filter, { cancelRefetch: false }); + } + }); +} + +interface ChapterNotesRead { + account: string; + token: string; + config: ApiConfig; + revision: number; +} + +interface TrackedChapterNotesRead { + complete(): void; + handleReadError(cause: unknown, signal: AbortSignal): Promise | undefined; +} + +/** Track one read and bind its error cleanup to the originating query and authorization. */ +export function trackChapterNotesRead( + client: QueryClient, + queryKey: QueryKey, + { account, token, config, revision }: ChapterNotesRead, +): TrackedChapterNotesRead { + const chapterNotesGrants = getChapterNotesGrants(client); + // Match effective request identity, including supported header overrides. + // Locale and Bible filters partition results without granting Notes access. + const headers = new Headers({ + 'X-YVP-App-Key': config.appKey, + ...(config.installationId && { 'X-YVP-Installation-Id': config.installationId }), + ...config.additionalHeaders, + }); + const context = JSON.stringify([ + headers.get('X-YVP-App-Key'), + // Normalize host case/default HTTPS port without merging distinct base paths. + new URL(`https://${config.apiHost || 'api.youversion.com'}/`).href, + headers.get('X-YVP-Installation-Id'), + revision, + ]); + const filter = { queryKey, exact: true }; + const query = client.getQueryCache().find(filter); + const previous = query && chapterNotesGrants.get(query); + if (query) + chapterNotesGrants.set(query, { + account, + token, + context, + startedWithoutSnapshot: query.state.data === undefined, + denied: + previous?.account === account && previous.context === context ? previous.denied : undefined, + }); + const isRetired = () => + query !== undefined && + (client.getQueryCache().get(query.queryHash) !== query || !chapterNotesGrants.has(query)); + + return { + complete() { + const grant = query && !isRetired() && chapterNotesGrants.get(query); + if (grant) grant.denied = false; + }, + handleReadError(cause: unknown, signal: AbortSignal) { + const status = getHttpStatus(cause); + const deniedNotes = cause instanceof Error && NotesClient.isListAccessDenied(cause); + // Transport may finish after cancellation. A current grant's Notes denial still clears it. + if (!deniedNotes) signal.throwIfAborted(); + if (isRetired()) return; + if (YouVersionPlatformConfiguration.getOAuthAccessToken(account, 'read_notes') !== token) { + // The retryer discards this outcome while keeping any previously settled data. + if (!signal.aborted) void client.cancelQueries(filter); + return; + } + if (status === 401 || status === 403) { + // A Notes denial clears matching snapshots. A Bible preflight failure affects one key. + const matchesAuthorization = (entry: Query) => { + const grant = chapterNotesGrants.get(entry); + return grant?.account === account && grant.context === context; + }; + if (deniedNotes) { + // A fulfilled sibling can still be committing its result. Cancel and + // settle matching reads before clearing, then recheck the authorization. + return client + .cancelQueries({ + // A replacement fetch reuses the Query after this attempt is canceled. + predicate: (entry) => + (entry !== query || signal.aborted) && matchesAuthorization(entry), + }) + .then(() => { + if (isRetired()) return; + if ( + YouVersionPlatformConfiguration.getOAuthAccessToken(account, 'read_notes') !== token + ) { + if (!signal.aborted) void client.cancelQueries(filter); + return; + } + for (const entry of client + .getQueryCache() + .findAll({ predicate: matchesAuthorization })) { + const grant = chapterNotesGrants.get(entry); + if (grant) { + grant.denied = true; + } + } + client.setQueriesData({ predicate: matchesAuthorization }, []); + }); + } + const grant = query && chapterNotesGrants.get(query); + if (grant) { + grant.denied = true; + } + client.setQueriesData(filter, []); + } + return; + }, + }; +} + +/** Evict private Notes even when the provider has no mounted Notes readers. */ +export function subscribeToChapterNotesRevocation(client: QueryClient): () => void { + const chapterNotesGrants = getChapterNotesGrants(client); + function removeRevokedNotes(): void { + client.removeQueries({ + predicate: (query) => { + const grant = chapterNotesGrants.get(query); + if ( + !grant || + YouVersionPlatformConfiguration.getOAuthAccessToken(grant.account, 'read_notes') + ) + return false; + // Retire old reads even if a later authorization reuses the same token. + chapterNotesGrants.delete(query); + return true; + }, + }); + } + + const unsubscribe = + YouVersionPlatformConfiguration.subscribeToAuthSessionChanges(removeRevokedNotes); + removeRevokedNotes(); + return unsubscribe; +} diff --git a/packages/hooks/src/internal/refreshQueries.ts b/packages/hooks/src/internal/refreshQueries.ts new file mode 100644 index 000000000..3a5484995 --- /dev/null +++ b/packages/hooks/src/internal/refreshQueries.ts @@ -0,0 +1,21 @@ +import type { QueryClient, QueryFilters } from '@tanstack/react-query'; + +/** Keep settled data while replacing initial reads that may predate a write. */ +export function refreshQueries( + client: QueryClient, + filters: QueryFilters, + restartInitialFetch = false, +): Promise { + const initialReads: QueryFilters = { + ...filters, + type: 'active', + predicate: (query) => + (!filters.predicate || filters.predicate(query)) && + query.state.fetchStatus === 'fetching' && + query.state.data === undefined, + }; + if (restartInitialFetch && client.getQueryCache().findAll(initialReads).length > 0) { + return client.cancelQueries(initialReads).then(() => client.invalidateQueries(filters)); + } + return client.invalidateQueries(filters); +} diff --git a/packages/hooks/src/internal/useQueryKeyBase.ts b/packages/hooks/src/internal/useQueryKeyBase.ts index 18a9915c0..d10b5ad4b 100644 --- a/packages/hooks/src/internal/useQueryKeyBase.ts +++ b/packages/hooks/src/internal/useQueryKeyBase.ts @@ -41,11 +41,12 @@ export function useQueryKeyBase(): readonly unknown[] { [additionalHeaders], ); - return [ - context?.appKey, - context?.apiHost, - context?.installationId, - additionalHeadersKey, - serializeVersionFilters(), - ]; + const appKey = context?.appKey; + const apiHost = context?.apiHost; + const installationId = context?.installationId; + const versionFilters = serializeVersionFilters(); + return useMemo( + () => [appKey, apiHost, installationId, additionalHeadersKey, versionFilters], + [appKey, apiHost, installationId, additionalHeadersKey, versionFilters], + ); } diff --git a/packages/hooks/src/internal/useRefreshAfterNoteMutation.ts b/packages/hooks/src/internal/useRefreshAfterNoteMutation.ts new file mode 100644 index 000000000..46933b3ca --- /dev/null +++ b/packages/hooks/src/internal/useRefreshAfterNoteMutation.ts @@ -0,0 +1,66 @@ +'use client'; + +import { useCallback, useContext } from 'react'; +import { YouVersionPlatformConfiguration, type Note } from '@youversion/platform-core'; +import { QueryClientContext } from './QueryClientContext'; +import { useQueryKeyBase } from './useQueryKeyBase'; +import { useUserScope } from './useUserScope'; +import { refreshQueries } from './refreshQueries'; +import { publishCreatedChapterNote } from './chapterNotesCache'; + +type ChapterNotesMutation = { type: 'create'; note: Note } | { type: 'update' | 'delete' }; + +// Locale and Bible filters change a read's representation, not which account's +// writes it reflects. Keep all other headers in the match, including app and +// installation overrides. These keys are produced by useQueryKeyBase. +function refreshScope(key: readonly unknown[]): string { + // SAFETY: Matching SDK resource keys use useQueryKeyBase, whose fourth + // segment is serializeAdditionalHeaders output (JSON text or null). + const serializedHeaders = key[3] as string | null; + const headers: [string, string][] = JSON.parse(serializedHeaders ?? '[]'); + return JSON.stringify([ + ...key.slice(0, 3), + headers.filter(([name]) => name.toLowerCase() !== 'accept-language'), + ]); +} + +/** Capture the provider and account whose active reads a successful write should refresh. */ +export function useRefreshAfterNoteMutation(): ( + accessToken: string, +) => ((mutation: ChapterNotesMutation) => void) | undefined { + const queryClient = useContext(QueryClientContext); + const keyBase = useQueryKeyBase(); + const account = useUserScope(); + + return useCallback( + (accessToken: string) => { + if ( + !queryClient || + account === null || + YouVersionPlatformConfiguration.getOAuthAccessToken(account, 'write_notes') !== accessToken + ) { + return undefined; + } + + const scope = refreshScope(keyBase); + return (mutation) => { + // Writes can move or remove attachments. Refresh each displayed scope for + // this account and mark any previously visited scopes stale. + for (const resource of ['chapterNotes', 'highlights']) { + const filters = { + predicate: (query: { queryKey: readonly unknown[] }) => + query.queryKey[keyBase.length] === resource && + query.queryKey[keyBase.length + 1] === account && + refreshScope(query.queryKey) === scope, + }; + if (resource === 'chapterNotes' && mutation.type === 'create') { + void publishCreatedChapterNote(queryClient, filters, mutation.note); + } else { + void refreshQueries(queryClient, filters, true); + } + } + }; + }, + [account, keyBase, queryClient], + ); +} diff --git a/packages/hooks/src/useApiData.ts b/packages/hooks/src/useApiData.ts index a4dca8c02..b4049c7e0 100644 --- a/packages/hooks/src/useApiData.ts +++ b/packages/hooks/src/useApiData.ts @@ -3,6 +3,7 @@ import { useCallback, useRef } from 'react'; import { keepPreviousData as keepPreviousDataPlaceholder, useQuery } from '@tanstack/react-query'; import { useInternalQueryClient } from './internal/QueryClientContext'; +import { refreshQueries } from './internal/refreshQueries'; export type UseApiDataOptions = { enabled?: boolean; @@ -46,7 +47,7 @@ type UseApiDataResult = { */ export function useApiData( queryKey: readonly unknown[], - fetchFn: () => Promise, + fetchFn: (context: { signal: AbortSignal }) => Promise, options: UseApiDataOptions & { restartInitialFetchOnRefetch?: boolean } = {}, ): UseApiDataResult { const { enabled = true, keepPreviousData = true, restartInitialFetchOnRefetch } = options; @@ -57,9 +58,9 @@ export function useApiData( const query = useQuery( { queryKey, - queryFn: async () => { + queryFn: async (context) => { try { - return await fetchFn(); + return await fetchFn(context); } catch (err) { // Consumers are promised `Error | null`; normalize non-Error throws. throw err instanceof Error ? err : new Error('Request failed'); @@ -80,17 +81,7 @@ export function useApiData( // `query.refetch()` calls an observer that is no longer active. const refetch = useCallback(() => { 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); + void refreshQueries(queryClient, filters, restartInitialFetchOnRefetch); }, [queryClient, restartInitialFetchOnRefetch]); // If `enabled` is false, `data` and `error` are `null`. diff --git a/packages/hooks/src/useChapterNotes.test.tsx b/packages/hooks/src/useChapterNotes.test.tsx new file mode 100644 index 000000000..d6138e847 --- /dev/null +++ b/packages/hooks/src/useChapterNotes.test.tsx @@ -0,0 +1,510 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryClient } from '@tanstack/react-query'; +import { + HighlightsClient, + NotesClient, + YouVersionPlatformConfiguration as config, + YouVersionUserInfo, + type Collection, + type Note, +} from '@youversion/platform-core'; +import type { ReactNode } from 'react'; +import { expect, it, onTestFinished, vi } from 'vitest'; +import { YouVersionAuthContext, YouVersionContext } from './context'; +import type { YouVersionContextData } from './context/YouVersionContext'; +import { queryClientDefaultOptions, TestQueryClientProvider } from './test-utils'; +import { useChapterNotes } from './useChapterNotes'; +import { useCreateNote } from './useCreateNote'; +import { useUpdateNote } from './useUpdateNote'; +import { useDeleteNote } from './useDeleteNote'; +import { useHighlights } from './useHighlights'; + +function notesSession() { + config.saveUserInfo({ id: 'notes-reader' }); + config.saveAuthData('notes-token', 'notes-refresh', new Date('2100-01-01'), { + userId: 'notes-reader', + scope: 'profile read_notes write_notes', + }); + const client = new QueryClient({ defaultOptions: queryClientDefaultOptions }); + const context: Pick = { + additionalHeaders: { 'Accept-Language': 'en' }, + }; + const auth = { + userInfo: new YouVersionUserInfo({ id: 'notes-reader' }), + setUserInfo: vi.fn(), + isLoading: false, + error: null, + accountRevision: 0, + }; + function Wrapper({ children }: { children: ReactNode }) { + return ( + + + {children} + + + ); + } + onTestFinished(() => { + client.clear(); + vi.restoreAllMocks(); + config.clearAuthTokens(); + }); + return { client, context, Wrapper }; +} + +const privatePage: Collection = { + data: [{ id: 'private-note', content: 'Private note text', status: 'private' }], + next_page_token: null, +}; + +it('clears a sibling response that has resolved just before the Notes denial', async () => { + const { client, Wrapper } = notesSession(); + const sibling = Promise.withResolvers>(); + const denied = Promise.withResolvers>(); + const denial = Object.assign(new Error('Notes access denied'), { status: 403 }); + vi.spyOn(NotesClient, 'isListAccessDenied').mockImplementation((error) => error === denial); + const read = vi + .spyOn(NotesClient.prototype, 'getNotes') + .mockImplementation((options) => + options?.passage_id === 'JHN.1' ? sibling.promise : denied.promise, + ); + const { result } = renderHook( + () => ({ + sibling: useChapterNotes({ version_id: 111, passage_id: 'JHN.1' }), + denied: useChapterNotes({ version_id: 111, passage_id: 'JHN.2' }), + }), + { wrapper: Wrapper }, + ); + await waitFor(() => expect(read).toHaveBeenCalledTimes(2)); + const outcomes = client + .getQueryCache() + .getAll() + .flatMap((entry) => (entry.promise ? [entry.promise] : [])); + await act(async () => { + sibling.resolve(privatePage); + await Promise.resolve(); + await Promise.resolve(); + denied.reject(denial); + await Promise.allSettled(outcomes); + }); + await waitFor(() => expect(result.current.denied.error).toBe(denial)); + expect(result.current.sibling.notes).toEqual([]); + expect(result.current.denied.notes).toBeNull(); +}); + +it('keeps cached Notes isolated by effective app and installation header overrides', async () => { + const { context, Wrapper } = notesSession(); + const firstReturn = Promise.withResolvers>(); + const secondReturn = Promise.withResolvers>(); + const appDenied = Object.assign(new Error('Other app denied'), { status: 401 }); + const installationDenied = Object.assign(new Error('Other installation denied'), { status: 403 }); + vi.spyOn(NotesClient, 'isListAccessDenied').mockImplementation( + (error) => error === appDenied || error === installationDenied, + ); + const read = vi + .spyOn(NotesClient.prototype, 'getNotes') + .mockResolvedValueOnce(privatePage) + .mockRejectedValueOnce(appDenied) + .mockReturnValueOnce(firstReturn.promise) + .mockRejectedValueOnce(installationDenied) + .mockReturnValueOnce(secondReturn.promise); + context.additionalHeaders = { + 'Accept-Language': 'en', + 'X-YVP-App-Key': 'app-a', + 'X-YVP-Installation-Id': 'installation-a', + }; + const original = context.additionalHeaders; + const { result, rerender } = renderHook( + () => useChapterNotes({ version_id: 111, passage_id: 'JHN.1' }), + { wrapper: Wrapper }, + ); + await waitFor(() => expect(result.current.notes).toEqual(privatePage.data)); + context.additionalHeaders = { ...original, 'X-YVP-App-Key': 'app-b' }; + rerender(); + await waitFor(() => expect(result.current.error).toBe(appDenied)); + context.additionalHeaders = original; + rerender(); + expect(result.current.notes).toEqual(privatePage.data); + await waitFor(() => expect(read).toHaveBeenCalledTimes(3)); + context.additionalHeaders = { ...original, 'X-YVP-Installation-Id': 'installation-b' }; + rerender(); + await waitFor(() => expect(result.current.error).toBe(installationDenied)); + context.additionalHeaders = original; + rerender(); + expect(result.current.notes).toEqual(privatePage.data); + await waitFor(() => expect(read).toHaveBeenCalledTimes(5)); +}); + +it.each(['before', 'after'] as const)( + 'clears cached Notes when a same-session refresh replaces the request %s its denial', + async (replacementTiming) => { + const { Wrapper } = notesSession(); + const denied = Promise.withResolvers>(); + const restarted = Promise.withResolvers>(); + const denial = Object.assign(new Error('Notes access denied'), { status: 403 }); + const unavailable = Object.assign(new Error('Notes unavailable'), { status: 503 }); + vi.spyOn(NotesClient, 'isListAccessDenied').mockImplementation((error) => error === denial); + const read = vi + .spyOn(NotesClient.prototype, 'getNotes') + .mockResolvedValueOnce(privatePage) + .mockReturnValueOnce(denied.promise) + .mockReturnValueOnce(restarted.promise); + const { result } = renderHook(() => useChapterNotes({ version_id: 111, passage_id: 'JHN.1' }), { + wrapper: Wrapper, + }); + await waitFor(() => expect(result.current.notes).toEqual(privatePage.data)); + act(() => result.current.refetch()); + await waitFor(() => expect(read).toHaveBeenCalledTimes(2)); + if (replacementTiming === 'before') { + act(() => result.current.refetch()); + await waitFor(() => expect(read).toHaveBeenCalledTimes(3)); + } + await act(async () => { + denied.reject(denial); + await Promise.resolve(); + if (replacementTiming === 'after') result.current.refetch(); + restarted.reject(unavailable); + }); + // Pre-denial replacements are canceled; a later refetch is a new recovery read. + await waitFor(() => + expect(result.current.error).toBe(replacementTiming === 'before' ? null : unavailable), + ); + expect(read).toHaveBeenCalledTimes(3); + expect(result.current.notes).toEqual([]); + }, +); + +it('discards a pre-denial replacement response and recovers with a new read', async () => { + const { client, Wrapper } = notesSession(); + const denied = Promise.withResolvers>(); + const replacement = Promise.withResolvers>(); + const recovery = Promise.withResolvers>(); + const denial = Object.assign(new Error('Notes access denied'), { status: 403 }); + vi.spyOn(NotesClient, 'isListAccessDenied').mockImplementation((error) => error === denial); + const read = vi + .spyOn(NotesClient.prototype, 'getNotes') + .mockResolvedValueOnce(privatePage) + .mockReturnValueOnce(denied.promise) + .mockReturnValueOnce(replacement.promise) + .mockReturnValueOnce(recovery.promise); + const { result, rerender } = renderHook( + () => useChapterNotes({ version_id: 111, passage_id: 'JHN.1' }), + { wrapper: Wrapper }, + ); + await waitFor(() => expect(result.current.notes).toEqual(privatePage.data)); + act(() => result.current.refetch()); + await waitFor(() => expect(read).toHaveBeenCalledTimes(2)); + act(() => result.current.refetch()); + await waitFor(() => expect(read).toHaveBeenCalledTimes(3)); + const replacementSettled = Promise.allSettled( + client + .getQueryCache() + .getAll() + .flatMap((entry) => (entry.promise ? [entry.promise] : [])), + ); + await act(async () => denied.reject(denial)); + await waitFor(() => expect(result.current.notes).toEqual([])); + await act(async () => { + replacement.resolve(privatePage); + await replacementSettled; + }); + rerender(); + expect(result.current.notes).toEqual([]); + + act(() => result.current.refetch()); + await waitFor(() => expect(read).toHaveBeenCalledTimes(4)); + expect(result.current.notes).toEqual([]); + await act(async () => recovery.resolve(privatePage)); + await waitFor(() => expect(result.current.notes).toEqual(privatePage.data)); +}); + +it.each(['cached', 'evicted'] as const)( + 'keeps restored Notes when an earlier revoked read denies the reused token (%s query)', + async (originState) => { + const { client, Wrapper } = notesSession(); + if (originState === 'evicted') client.setQueryDefaults([], { gcTime: 0 }); + let passage = 'JHN.1'; + const oldRead = Promise.withResolvers>(); + const denial = Object.assign(new Error('Old Notes access denied'), { status: 403 }); + const restoredPage: Collection = { + data: [{ id: 'restored-note', content: 'Newly restored Notes', status: 'private' }], + next_page_token: null, + }; + vi.spyOn(NotesClient, 'isListAccessDenied').mockImplementation((error) => error === denial); + const read = vi + .spyOn(NotesClient.prototype, 'getNotes') + .mockResolvedValue(privatePage) + .mockResolvedValueOnce(privatePage) + .mockReturnValueOnce(oldRead.promise); + const { result, rerender } = renderHook( + () => useChapterNotes({ version_id: 111, passage_id: passage }), + { wrapper: Wrapper }, + ); + await waitFor(() => expect(result.current.notes).toEqual(privatePage.data)); + act(() => result.current.refetch()); + await waitFor(() => expect(read).toHaveBeenCalledTimes(2)); + if (originState === 'evicted') { + passage = 'JHN.2'; + rerender(); + await waitFor(() => expect(read).toHaveBeenCalledTimes(3)); + await waitFor(() => expect(client.getQueryCache().getAll()).toHaveLength(1)); + } + act(() => { + config.saveAuthData('notes-token', 'notes-refresh', new Date('2100-01-01'), { + userId: 'notes-reader', + scope: 'profile', + }); + }); + await waitFor(() => expect(result.current.notes).toBeNull()); + read.mockResolvedValueOnce(restoredPage); + act(() => { + config.saveAuthData('notes-token', 'notes-refresh', new Date('2100-01-01'), { + userId: 'notes-reader', + scope: 'profile read_notes', + }); + }); + await waitFor(() => expect(result.current.notes).toEqual(restoredPage.data)); + await act(async () => oldRead.reject(denial)); + rerender(); + expect(read).toHaveBeenCalledTimes(originState === 'evicted' ? 4 : 3); + expect(result.current.notes).toEqual(restoredPage.data); + expect(result.current.error).toBeNull(); + }, +); + +it('clears equivalent server partitions after denial while preserving a distinct server', async () => { + const { context, Wrapper } = notesSession(); + const homeReturn = Promise.withResolvers>(); + const otherReturn = Promise.withResolvers>(); + const otherPage: Collection = { + data: [{ id: 'other-server-note', content: 'Another server', status: 'private' }], + next_page_token: null, + }; + const denial = Object.assign(new Error('Notes access denied'), { status: 403 }); + const unavailable = Object.assign(new Error('Notes unavailable'), { status: 503 }); + vi.spyOn(NotesClient, 'isListAccessDenied').mockImplementation((error) => error === denial); + const read = vi + .spyOn(NotesClient.prototype, 'getNotes') + .mockResolvedValueOnce(otherPage) + .mockResolvedValueOnce(privatePage) + .mockRejectedValueOnce(denial) + .mockReturnValueOnce(homeReturn.promise) + .mockReturnValueOnce(otherReturn.promise); + context.apiHost = 'other-api.example.test'; + const { result, rerender } = renderHook( + () => useChapterNotes({ version_id: 111, passage_id: 'JHN.1' }), + { wrapper: Wrapper }, + ); + await waitFor(() => expect(result.current.notes).toEqual(otherPage.data)); + context.apiHost = 'api.example.test'; + rerender(); + await waitFor(() => expect(result.current.notes).toEqual(privatePage.data)); + context.apiHost = 'API.EXAMPLE.TEST:443'; + rerender(); + await waitFor(() => expect(result.current.error).toBe(denial)); + context.apiHost = 'api.example.test'; + rerender(); + await waitFor(() => expect(read).toHaveBeenCalledTimes(4)); + expect(result.current.notes).toEqual([]); + await act(async () => homeReturn.reject(unavailable)); + await waitFor(() => expect(result.current.error).toBe(unavailable)); + expect(result.current.notes).toEqual([]); + + context.apiHost = 'other-api.example.test'; + rerender(); + await waitFor(() => expect(read).toHaveBeenCalledTimes(5)); + expect(result.current.notes).toEqual(otherPage.data); + await act(async () => otherReturn.resolve(otherPage)); +}); + +// Existing Reader journeys keep language/filter settings fixed during writes. +// Exercise the hooks' shared invalidation when those cache partitions change. +it.each(['create', 'update', 'delete'] as const)( + 'refreshes current Notes and highlights when %s finishes after language and filter changes', + async (operation) => { + const { client, context, Wrapper } = notesSession(); + const pending = Promise.withResolvers(); + let saved = false; + const write = async () => { + await pending.promise; + saved = true; + return privatePage.data[0]!; + }; + vi.spyOn(NotesClient.prototype, 'createNote').mockImplementation(write); + vi.spyOn(NotesClient.prototype, 'updateNote').mockImplementation(write); + vi.spyOn(NotesClient.prototype, 'deleteNote').mockImplementation(async () => { + await write(); + }); + const readNotes = vi + .spyOn(NotesClient.prototype, 'getNotes') + .mockImplementation(async () => (saved ? privatePage : { data: [], next_page_token: null })); + const readHighlights = vi.spyOn(HighlightsClient.prototype, 'getHighlights').mockResolvedValue({ + data: [], + next_page_token: null, + }); + onTestFinished(() => { + config.permittedVersionIds = undefined; + }); + let displayed = { version_id: 111, passage_id: 'JHN.1' }; + const { result, rerender } = renderHook( + () => ({ + notes: useChapterNotes(displayed), + highlights: useHighlights(displayed), + create: useCreateNote(), + update: useUpdateNote(), + delete: useDeleteNote(), + }), + { wrapper: Wrapper }, + ); + await waitFor(() => expect(result.current.notes.notes).toEqual([])); + await waitFor(() => expect(result.current.highlights.highlights).not.toBeNull()); + let mutation: Promise; + act(() => { + mutation = + operation === 'create' + ? result.current.create( + { request_id: 'refresh-test', status: 'private', content: 'Test' }, + 'notes-token', + ) + : operation === 'update' + ? result.current.update('private-note', { content: 'Test' }, 'notes-token') + : result.current.delete('private-note', 'notes-token'); + }); + context.additionalHeaders = { 'Accept-Language': 'es' }; + rerender(); + await waitFor(() => expect(readNotes).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(result.current.notes.notes).toEqual([])); + config.permittedVersionIds = [1]; + displayed = { version_id: 1, passage_id: 'JHN.3' }; + rerender(); + await waitFor(() => expect(readNotes).toHaveBeenCalledTimes(3)); + await waitFor(() => expect(result.current.notes.notes).toEqual([])); + await waitFor(() => expect(readHighlights).toHaveBeenCalledTimes(3)); + + // Inactive caches for another identity must not be invalidated by this write. + const currentKey = client + .getQueryCache() + .getAll() + .find( + (query) => query.queryKey[3] === '[["Accept-Language","es"]]' && query.queryKey[4] !== null, + )!.queryKey; + const isolatedKeys = [ + currentKey.map((value, index) => (index === 0 ? 'other-app' : value)), + currentKey.map((value, index) => (index === 1 ? 'other.example.com' : value)), + currentKey.map((value, index) => (index === 2 ? 'other-installation' : value)), + currentKey.map((value, index) => (index === 3 ? '[["X-YVP-App-Key","other-app"]]' : value)), + currentKey.map((value, index) => + index === 3 ? '[["X-YVP-Installation-Id","other-installation"]]' : value, + ), + currentKey.map((value, index) => (index === 6 ? 'other-account' : value)), + ]; + for (const key of isolatedKeys) client.setQueryData(key, []); + await act(async () => { + pending.resolve(); + await mutation; + }); + await waitFor(() => + expect(result.current.notes.notes).toEqual(operation === 'create' ? [] : privatePage.data), + ); + await waitFor(() => expect(readHighlights).toHaveBeenCalledTimes(4)); + expect(readHighlights).toHaveBeenLastCalledWith(displayed); + for (const key of isolatedKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(false); + // Previously visited language/filter partitions are stale for the next visit. + expect( + client + .getQueryCache() + .getAll() + .filter((query) => query.queryKey[3] === '[["Accept-Language","en"]]') + .every((query) => query.state.isInvalidated), + ).toBe(true); + }, +); + +// Browser journeys start with settled reads; cover a save during the initial request here. +it.each(['success', 'failure'] as const)( + 'keeps two saves through initial paged read %s and accepts the next complete snapshot', + async (outcome) => { + const { client, Wrapper } = notesSession(); + const pending = Promise.withResolvers>(); + const created: Note = { + id: 'new-note', + content: 'Just saved', + status: 'private', + passage: { version_id: 111, passage_id: 'JHN.1.1+JHN.1.4' }, + }; + const second = { ...created, id: 'second-note', content: 'Saved again' }; + const olderPage: Collection = { + data: [{ ...privatePage.data[0]!, id: 'older-note' }], + next_page_token: null, + }; + const empty = { data: [], next_page_token: null }; + let initialPageSent = false; + const read = vi + .spyOn(NotesClient.prototype, 'getNotes') + .mockImplementation(async ({ passage_id, page_token } = {}) => { + if (page_token === 'older-page') return pending.promise; + if (passage_id === 'JHN.1' && !initialPageSent) { + initialPageSent = true; + return { ...privatePage, next_page_token: 'older-page' }; + } + return empty; + }); + vi.spyOn(NotesClient.prototype, 'createNote') + .mockResolvedValueOnce(created) + .mockResolvedValueOnce(second); + const { result } = renderHook( + () => ({ + chapter: useChapterNotes({ version_id: 111, passage_id: 'JHN.1' }), + sibling: useChapterNotes({ version_id: 111, passage_id: 'JHN.2' }), + create: useCreateNote(), + }), + { wrapper: Wrapper }, + ); + await waitFor(() => expect(read).toHaveBeenCalledTimes(3)); + await act(async () => { + await result.current.create( + { + request_id: 'cache-create', + content: created.content, + status: 'private', + passage: created.passage, + }, + 'notes-token', + ); + }); + await waitFor(() => expect(result.current.chapter.notes).toEqual([created])); + await act(async () => { + await result.current.create( + { + request_id: 'second-create', + content: second.content, + status: 'private', + passage: second.passage, + }, + 'notes-token', + ); + }); + await waitFor(() => expect(result.current.chapter.notes).toEqual([second, created])); + expect(result.current.sibling.notes).toEqual([]); + expect(read).toHaveBeenCalledTimes(3); + // An older in-flight response must not undo the confirmed save. + await act(async () => { + if (outcome === 'failure') pending.reject(new Error('initial read failed')); + else pending.resolve(olderPage); + }); + const expected = + outcome === 'failure' + ? [second, created] + : [...privatePage.data, ...olderPage.data, second, created]; + await waitFor(() => expect(result.current.chapter.notes).toEqual(expected)); + read.mockRejectedValueOnce(Object.assign(new Error('offline'), { status: 503 })); + act(() => result.current.chapter.refetch()); + await waitFor(() => expect(result.current.chapter.error?.message).toBe('offline')); + expect(result.current.chapter.notes).toEqual(expected); + // A later successful read is authoritative, including deletion elsewhere. + act(() => result.current.chapter.refetch()); + await waitFor(() => expect(result.current.chapter.notes).toEqual([])); + expect(client.isFetching()).toBe(0); + }, +); diff --git a/packages/hooks/src/useChapterNotes.ts b/packages/hooks/src/useChapterNotes.ts new file mode 100644 index 000000000..03bc97a42 --- /dev/null +++ b/packages/hooks/src/useChapterNotes.ts @@ -0,0 +1,129 @@ +'use client'; + +import { useContext, useEffect, useMemo, useSyncExternalStore } from 'react'; +import { + getHttpStatus, + NotesClient, + parseUsfmReference, + YouVersionPlatformConfiguration, + type Note, +} from '@youversion/platform-core'; +import { YouVersionAuthContext } from './context/YouVersionAuthContext'; +import { + revalidateChapterNotesOnTokenChange, + trackChapterNotesRead, +} from './internal/chapterNotesCache'; +import { useInternalQueryClient } from './internal/QueryClientContext'; +import { useApiClient } from './internal/useApiClient'; +import { useQueryKeyBase } from './internal/useQueryKeyBase'; +import { useUserScope } from './internal/useUserScope'; +import { useApiData, type UseApiDataOptions } from './useApiData'; +import { useHookOverride } from './useHookOverride'; +import type { UseNamedQueryResult } from './useQueryResult'; + +export type ChapterNotesOptions = { + /** Bible version whose chapter Notes should be loaded. */ + version_id: number; + /** Chapter-only USFM reference, e.g. `JHN.1`. Verse, range, or malformed references leave reads idle. */ + passage_id: string; +}; +export type UseChapterNotesResult = UseNamedQueryResult<'notes', Note[]>; + +/** Reads a complete chapter's Notes snapshot for the identified account with `read_notes`. */ +export function useChapterNotes( + { version_id, passage_id }: ChapterNotesOptions, + options?: UseApiDataOptions, +): UseChapterNotesResult { + const override = useHookOverride('useChapterNotes'); + const auth = useContext(YouVersionAuthContext); + const scope = useUserScope(); + const account = auth?.userInfo?.userId || null; + const token = useSyncExternalStore( + YouVersionPlatformConfiguration.subscribeToAuthSessionChanges, + () => account && YouVersionPlatformConfiguration.getOAuthAccessToken(account, 'read_notes'), + () => null, + ); + const keyBase = useQueryKeyBase(); + const queryClient = useInternalQueryClient(); + const apiClient = useApiClient(); + const client = useMemo(() => new NotesClient(apiClient), [apiClient]); + const chapter = parseUsfmReference(passage_id); + const revision = auth?.accountRevision ?? 0; + const chapterKey = useMemo( + () => [...keyBase, 'chapterNotes', scope, revision, version_id, passage_id], + [keyBase, scope, revision, version_id, passage_id], + ); + const enabled = + !override && + !!token && + scope !== null && + chapter !== null && + chapter.verses.length === 0 && + version_id > 0 && + options?.enabled !== false; + + useEffect(() => { + if (!enabled || !account || !token) return; + revalidateChapterNotesOnTokenChange(queryClient, chapterKey, account, token); + }, [account, token, queryClient, chapterKey, enabled]); + + const { data, error, loading, refetch } = useApiData( + chapterKey, + async ({ signal }) => { + const requestToken = + account && YouVersionPlatformConfiguration.getOAuthAccessToken(account, 'read_notes'); + if (!requestToken || !account) throw new Error('Read Notes access is required'); + const read = trackChapterNotesRead(queryClient, chapterKey, { + account, + token: requestToken, + config: apiClient.config, + revision, + }); + const initialSnapshot = queryClient.getQueryData(chapterKey); + const notes = new Map(); + const visited = new Set(); + let page_token: string | null = null; + try { + do { + const page = await client.getNotes({ version_id, passage_id, page_token }, requestToken); + signal.throwIfAborted(); + if ( + YouVersionPlatformConfiguration.getOAuthAccessToken(account, 'read_notes') !== + requestToken + ) { + throw new Error('Read Notes access changed during the request'); + } + for (const note of page.data) { + if (!notes.has(note.id)) notes.set(note.id, note); + } + page_token = page.next_page_token; + if (page_token !== null) { + if (visited.has(page_token)) throw new Error('Repeated Notes page token'); + visited.add(page_token); + } + } while (page_token !== null); + } catch (error) { + const cleanup = read.handleReadError(error, signal); + if (cleanup) await cleanup; + throw error; + } + // A save can publish a confirmed create before this initial read finishes. + // Merge that one read with the cache; later complete reads replace it normally. + if (initialSnapshot === undefined) { + for (const note of queryClient.getQueryData(chapterKey) ?? []) + notes.set(note.id, note); + } + read.complete(); + return Array.from(notes.values()); + }, + { + enabled, + keepPreviousData: false, + restartInitialFetchOnRefetch: true, + }, + ); + + if (override) return override({ version_id, passage_id }, options); + const status = getHttpStatus(error); + return { notes: status === 401 || status === 403 ? null : data, error, loading, refetch }; +} diff --git a/packages/hooks/src/useCreateNote.ts b/packages/hooks/src/useCreateNote.ts index 5ac205328..10fe856dc 100644 --- a/packages/hooks/src/useCreateNote.ts +++ b/packages/hooks/src/useCreateNote.ts @@ -3,16 +3,28 @@ import { useCallback, useMemo } from 'react'; import { NotesClient, type CreateNote, type Note } from '@youversion/platform-core'; import { useApiClient } from './internal/useApiClient'; +import { useRefreshAfterNoteMutation } from './internal/useRefreshAfterNoteMutation'; -/** Creates a note using the caller's captured access token. */ +/** + * Creates a note using the caller's captured access token. + * Successful writes refresh matching highlights. Creates update chapter Notes + * directly; updates and deletes re-read them. Requires verified account access. + */ export function useCreateNote(): (note: CreateNote, accessToken: string) => Promise { const apiClient = useApiClient(); const client = useMemo(() => new NotesClient(apiClient), [apiClient]); + const prepareRefresh = useRefreshAfterNoteMutation(); 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); + const refresh = prepareRefresh(accessToken); + const saved = await client.createNote(note, accessToken); + refresh?.({ + type: 'create', + note: { ...saved, passage: saved.passage === undefined ? note.passage : saved.passage }, + }); + return saved; }, - [client], + [client, prepareRefresh], ); } diff --git a/packages/hooks/src/useDeleteNote.ts b/packages/hooks/src/useDeleteNote.ts new file mode 100644 index 000000000..f1fed54c5 --- /dev/null +++ b/packages/hooks/src/useDeleteNote.ts @@ -0,0 +1,26 @@ +'use client'; + +import { useCallback, useMemo } from 'react'; +import { NotesClient } from '@youversion/platform-core'; +import { useApiClient } from './internal/useApiClient'; +import { useRefreshAfterNoteMutation } from './internal/useRefreshAfterNoteMutation'; + +/** + * Deletes a note using the caller's captured access token. + * Successful writes refresh matching highlights. Creates update chapter Notes + * directly; updates and deletes re-read them. Requires verified account access. + */ +export function useDeleteNote(): (id: string, accessToken: string) => Promise { + const apiClient = useApiClient(); + const client = useMemo(() => new NotesClient(apiClient), [apiClient]); + const prepareRefresh = useRefreshAfterNoteMutation(); + return useCallback( + async (id, accessToken) => { + if (!accessToken?.trim()) throw new Error('An access token is required to delete a note'); + const refresh = prepareRefresh(accessToken); + await client.deleteNote(id, accessToken); + refresh?.({ type: 'delete' }); + }, + [client, prepareRefresh], + ); +} diff --git a/packages/hooks/src/useUpdateNote.ts b/packages/hooks/src/useUpdateNote.ts index 37b4e11ce..b4210a5de 100644 --- a/packages/hooks/src/useUpdateNote.ts +++ b/packages/hooks/src/useUpdateNote.ts @@ -3,8 +3,13 @@ import { useCallback, useMemo } from 'react'; import { NotesClient, type Note, type UpdateNote } from '@youversion/platform-core'; import { useApiClient } from './internal/useApiClient'; +import { useRefreshAfterNoteMutation } from './internal/useRefreshAfterNoteMutation'; -/** Updates a note using the caller's captured access token. */ +/** + * Updates a note using the caller's captured access token. + * Successful writes refresh matching highlights. Creates update chapter Notes + * directly; updates and deletes re-read them. Requires verified account access. + */ export function useUpdateNote(): ( id: string, note: UpdateNote, @@ -12,11 +17,15 @@ export function useUpdateNote(): ( ) => Promise { const apiClient = useApiClient(); const client = useMemo(() => new NotesClient(apiClient), [apiClient]); + const prepareRefresh = useRefreshAfterNoteMutation(); 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); + const refresh = prepareRefresh(accessToken); + const saved = await client.updateNote(id, note, accessToken); + refresh?.({ type: 'update' }); + return saved; }, - [client], + [client, prepareRefresh], ); } diff --git a/packages/ui/README.md b/packages/ui/README.md index b73a0f393..6a63e0976 100644 --- a/packages/ui/README.md +++ b/packages/ui/README.md @@ -80,12 +80,22 @@ when Notes are available. Existing action types, exhaustive maps, and string-act guards remain compatible. Signed-in readers missing `write_notes` start OAuth directly; signed-out readers first see the sign-in introduction. +For a signed-in account with `read_notes`, BibleReader marks verses with saved +notes. Activate a marker to open the matching saved notes in the Notes drawer. +A custom action list without `includeSave` still permits Notes markers, which +open a read-only drawer. Setting `verseActions="none"` disables built-in Notes markers. +`BibleTextView` can opt into the same markers with `onNoteIndicatorPress`. The +callback receives the tapped verse reference and all notes attached to it. + 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. +Supplying `getVerseIndicator` takes precedence over the built-in Notes marks. +In BibleReader, this replaces the markers while Notes loading continues to supply +the composer's previously saved Notes list. ### Limit which Bible versions the SDK uses diff --git a/packages/ui/src/components/bible-reader-controlled.test.tsx b/packages/ui/src/components/bible-reader-controlled.test.tsx index 059e891d7..adc18ab1c 100644 --- a/packages/ui/src/components/bible-reader-controlled.test.tsx +++ b/packages/ui/src/components/bible-reader-controlled.test.tsx @@ -290,6 +290,42 @@ function selectVerse(container: HTMLElement, verse: number) { const APPLY_LABEL = /^(Add \w+|Apply) highlight$/; const REMOVE_LABEL = /^(Remove \w+|Clear) highlight$/; +it('keeps one swatch per color while selecting and deselecting highlighted verses', async () => { + const { container } = renderReader({ + highlights: [ + { version_id: 111, passage_id: 'JHN.1.1', color: YELLOW }, + { version_id: 111, passage_id: 'JHN.1.2', color: GREEN }, + ], + }); + + selectVerse(container, 1); + await screen.findByRole('group', { name: 'Highlight colors' }); + + function expectSwatches(activeColors: string[]) { + const group = screen.getByRole('group', { name: 'Highlight colors' }); + const buttons = Array.from(group.querySelectorAll('button')); + expect(buttons).toHaveLength(HIGHLIGHT_COLORS.length); + expect(buttons.map((button) => button.style.backgroundColor)).toEqual( + HIGHLIGHT_COLORS.map((color) => fillFor(color, 'card')), + ); + for (const [index, color] of HIGHLIGHT_COLORS.entries()) { + const button = buttons[index]!; + expect(REMOVE_LABEL.test(button.getAttribute('aria-label') ?? '')).toBe( + activeColors.includes(color), + ); + expect(button.querySelector('svg') !== null).toBe(activeColors.includes(color)); + } + } + + expectSwatches([YELLOW]); + selectVerse(container, 2); + expectSwatches([YELLOW, GREEN]); + selectVerse(container, 1); + expectSwatches([GREEN]); + selectVerse(container, 3); + expectSwatches([GREEN]); +}); + function getApplyButtons() { return screen .getAllByRole('button') diff --git a/packages/ui/src/components/bible-reader-notes-composer.tsx b/packages/ui/src/components/bible-reader-notes-composer.tsx index 13052eddf..6510e25ad 100644 --- a/packages/ui/src/components/bible-reader-notes-composer.tsx +++ b/packages/ui/src/components/bible-reader-notes-composer.tsx @@ -5,13 +5,15 @@ import { useTranslation } from 'react-i18next'; import i18n from '@/i18n'; import { BookmarkIcon } from './icons/bookmark'; import { GlobeIcon } from './icons/globe'; -import { HIGHLIGHT_COLORS } from '@/lib/highlight-colors'; +import { HIGHLIGHT_COLORS, isPaletteHighlightColor } from '@/lib/highlight-colors'; import { getOwnShadowRoot, isElementFromOwnerDocument } from '@/lib/shadow-root-host'; import { HighlightColorCircle } from './highlight-color-circle'; +import { BibleReaderSavedNotes } from './bible-reader-saved-notes'; 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'; +import { hasNoteDraftChanges, type NoteDraft, type NoteDraftFields } from './use-bible-reader-note'; +import type { AttachedNote } from './use-bible-note-indicators'; type NotesComposerProps = { draft: NoteDraft; @@ -22,6 +24,8 @@ type NotesComposerProps = { onDismiss: (intent: 'cancel' | 'discard') => void; theme: 'light' | 'dark'; restoreFocusTarget: HTMLElement | null; + savedNotes: AttachedNote[]; + bookName: string; }; export function BibleReaderNotesComposer({ @@ -33,6 +37,8 @@ export function BibleReaderNotesComposer({ onDismiss, theme, restoreFocusTarget, + savedNotes, + bookName, }: NotesComposerProps): ReactElement { const { t } = useTranslation(undefined, { i18n }); const referenceId = useId(); @@ -43,6 +49,13 @@ export function BibleReaderNotesComposer({ const stayButtonRef = useRef(null); const focusBeforeDiscard = useRef(null); const [confirmDiscard, setConfirmDiscard] = useState(false); + const hasChanges = hasNoteDraftChanges(draft); + // An interrupted save may already exist on the server and still needs a retry. + const canSave = hasChanges || draft.recovery !== undefined; + const showInheritedColors = !draft.colorChanged && draft.color === (draft.initialColor ?? null); + const selectedColors = new Set( + (showInheritedColors ? draft.initialColors : undefined) ?? (draft.color ? [draft.color] : []), + ); const colorNames = { ffec5b: t('highlightYellow'), b4ffc1: t('highlightGreen'), @@ -52,6 +65,17 @@ export function BibleReaderNotesComposer({ dfdcff: t('highlightPurple'), }; + useLayoutEffect(() => { + const editor = editorRef.current; + if (!editor || globalThis.CSS?.supports?.('field-sizing', 'content')) { + return; + } + const scrollTop = editor.scrollTop; + editor.style.blockSize = 'auto'; + editor.style.blockSize = `${editor.scrollHeight}px`; + editor.scrollTop = scrollTop; + }, [draft.text]); + useLayoutEffect(() => { if (confirmDiscard) { stayButtonRef.current?.focus({ preventScroll: true }); @@ -67,7 +91,7 @@ export function BibleReaderNotesComposer({ setConfirmDiscard(false); return; } - if (draft.text || draft.visibility !== 'private' || draft.color) { + if (hasChanges) { const content = formRef.current?.parentElement; if (content) { const active = @@ -101,7 +125,7 @@ export function BibleReaderNotesComposer({ event.preventDefault(); editorRef.current?.focus({ preventScroll: true }); }} - className="yv:box-border yv:[max-block-size:calc(100dvh-2rem)] yv:[max-inline-size:31.25rem] yv:overflow-y-auto" + className="yv:box-border yv:[max-block-size:calc(100dvh-2rem)] yv:[max-inline-size:31.25rem] yv:rounded-[24px] yv:overflow-y-auto" >
{!confirmDiscard &&