diff --git a/.changeset/reader-saved-note-indicators.md b/.changeset/reader-saved-note-indicators.md new file mode 100644 index 00000000..e3fba8e0 --- /dev/null +++ b/.changeset/reader-saved-note-indicators.md @@ -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. diff --git a/docs/adr/0006-tanstack-query-read-layer.md b/docs/adr/0006-tanstack-query-read-layer.md index 3c885424..ee4e4c4e 100644 --- a/docs/adr/0006-tanstack-query-read-layer.md +++ b/docs/adr/0006-tanstack-query-read-layer.md @@ -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 diff --git a/examples/vite-react/src/pages/BibleReaderPage.tsx b/examples/vite-react/src/pages/BibleReaderPage.tsx index 057a8369..ba6a9b74 100644 --- a/examples/vite-react/src/pages/BibleReaderPage.tsx +++ b/examples/vite-react/src/pages/BibleReaderPage.tsx @@ -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(); + const [showCustomMarkers, setShowCustomMarkers] = useState(false); return (
@@ -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.'}

+
, - 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 + } > diff --git a/packages/core/src/YouVersionPlatformConfiguration.ts b/packages/core/src/YouVersionPlatformConfiguration.ts index 5ae10d97..45a222fa 100644 --- a/packages/core/src/YouVersionPlatformConfiguration.ts +++ b/packages/core/src/YouVersionPlatformConfiguration.ts @@ -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 { @@ -129,6 +138,7 @@ export class YouVersionPlatformConfiguration { } if (persisted) invalidateAuthorization(storage, previousState); + notifyAuthSessionChanged(); return persisted; } @@ -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; } @@ -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(); 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 00000000..22a34b89 --- /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__/notes.test.ts b/packages/core/src/__tests__/notes.test.ts index ed535339..6755fcfe 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/notes.ts b/packages/core/src/notes.ts index dec15918..51bfb134 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 615a6205..a754fa10 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 25e14570..1ffb5dfc 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 3d860f42..ff2177a1 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 00000000..d50a006c --- /dev/null +++ b/packages/hooks/src/internal/chapterNotesCache.ts @@ -0,0 +1,38 @@ +import { YouVersionPlatformConfiguration } from '@youversion/platform-core'; +import type { Query, QueryClient } from '@tanstack/react-query'; + +type ChapterNotesGrants = WeakMap; + +// 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; +} diff --git a/packages/hooks/src/internal/useQueryKeyBase.ts b/packages/hooks/src/internal/useQueryKeyBase.ts index 18a9915c..d10b5ad4 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 00000000..08b78464 --- /dev/null +++ b/packages/hooks/src/internal/useRefreshAfterNoteMutation.ts @@ -0,0 +1,43 @@ +'use client'; + +import { useCallback, useContext } from 'react'; +import { YouVersionPlatformConfiguration } from '@youversion/platform-core'; +import { QueryClientContext } from './QueryClientContext'; +import { useQueryKeyBase } from './useQueryKeyBase'; +import { useUserScope } from './useUserScope'; + +/** Capture the provider and account whose active reads a successful write should refresh. */ +export function useRefreshAfterNoteMutation(): (accessToken: string) => (() => 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; + } + + return () => { + // 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 = { queryKey: [...keyBase, resource, account] }; + void queryClient + .cancelQueries({ + ...filters, + type: 'active', + predicate: (query) => + query.state.fetchStatus === 'fetching' && query.state.data === undefined, + }) + .then(() => queryClient.invalidateQueries(filters)); + } + }; + }, + [account, keyBase, queryClient], + ); +} diff --git a/packages/hooks/src/useApiData.ts b/packages/hooks/src/useApiData.ts index a4dca8c0..73251983 100644 --- a/packages/hooks/src/useApiData.ts +++ b/packages/hooks/src/useApiData.ts @@ -46,7 +46,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 +57,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'); diff --git a/packages/hooks/src/useChapterNotes.ts b/packages/hooks/src/useChapterNotes.ts new file mode 100644 index 00000000..0540d68a --- /dev/null +++ b/packages/hooks/src/useChapterNotes.ts @@ -0,0 +1,148 @@ +'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 { chapterNotesGrants } 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 = { version_id: number; passage_id: string }; +export type UseChapterNotesResult = UseNamedQueryResult<'notes', Note[]>; + +function subscribeToAuthSessionChanges(listener: () => void): () => void { + return YouVersionPlatformConfiguration.subscribeToAuthSessionChanges(listener); +} + +/** 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( + 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 accountKey = useMemo(() => [...keyBase, 'chapterNotes', scope], [keyBase, scope]); + const revision = auth?.accountRevision ?? 0; + const chapterKey = useMemo( + () => [...accountKey, revision, version_id, passage_id], + [accountKey, 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; + const filter = { queryKey: chapterKey, exact: true }; + const query = queryClient.getQueryCache().find(filter); + const previous = query && chapterNotesGrants.get(query)?.token; + if (!query || !previous || previous === token) return; + // Cancel an older grant's work without dropping the settled chapter snapshot. + chapterNotesGrants.set(query, { account, token }); + void queryClient.cancelQueries(filter).then(() => { + if (YouVersionPlatformConfiguration.getOAuthAccessToken(account, 'read_notes') === token) { + void queryClient.invalidateQueries(filter, { cancelRefetch: false }); + } + }); + }, [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 filter = { queryKey: chapterKey, exact: true }; + const query = queryClient.getQueryCache().find(filter); + if (query) chapterNotesGrants.set(query, { account, token: requestToken }); + 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) { + signal.throwIfAborted(); + if ( + YouVersionPlatformConfiguration.getOAuthAccessToken(account, 'read_notes') !== + requestToken + ) { + // The retryer discards this outcome while keeping any previously settled data. + void queryClient.cancelQueries(filter); + throw error; + } + const status = getHttpStatus(error); + if (status === 401 || status === 403) { + // A Notes denial clears the account's snapshots. A Bible preflight failure affects one key. + const deniedNotes = error instanceof Error && NotesClient.isListAccessDenied(error); + if (deniedNotes) { + // Cancellation reverts sibling reads synchronously. Clear their data after that revert. + void queryClient.cancelQueries({ + queryKey: accountKey, + predicate: (entry) => entry !== query, + }); + } + queryClient.setQueriesData( + { queryKey: deniedNotes ? accountKey : chapterKey, exact: !deniedNotes }, + [], + ); + } + throw error; + } + 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 5ac20532..6ba1feee 100644 --- a/packages/hooks/src/useCreateNote.ts +++ b/packages/hooks/src/useCreateNote.ts @@ -3,16 +3,21 @@ 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. */ 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?.(); + return saved; }, - [client], + [client, prepareRefresh], ); } diff --git a/packages/hooks/src/useDeleteNote.ts b/packages/hooks/src/useDeleteNote.ts new file mode 100644 index 00000000..7bc86355 --- /dev/null +++ b/packages/hooks/src/useDeleteNote.ts @@ -0,0 +1,22 @@ +'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. */ +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?.(); + }, + [client, prepareRefresh], + ); +} diff --git a/packages/hooks/src/useUpdateNote.ts b/packages/hooks/src/useUpdateNote.ts index 37b4e11c..d5af2d86 100644 --- a/packages/hooks/src/useUpdateNote.ts +++ b/packages/hooks/src/useUpdateNote.ts @@ -3,6 +3,7 @@ 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. */ export function useUpdateNote(): ( @@ -12,11 +13,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?.(); + return saved; }, - [client], + [client, prepareRefresh], ); } diff --git a/packages/ui/README.md b/packages/ui/README.md index c1c79a8b..7b07a7a1 100644 --- a/packages/ui/README.md +++ b/packages/ui/README.md @@ -77,12 +77,18 @@ When upgrading from 3.1.0, include `'save'` in exhaustive `BuiltInVerseAction` maps and string-action guards. The Save action is available by default; hosts can omit it through `verseActionItems`. +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. +`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. ### Limit which Bible versions the SDK uses diff --git a/packages/ui/src/components/bible-reader-notes-composer.tsx b/packages/ui/src/components/bible-reader-notes-composer.tsx index f2132762..76f5db1e 100644 --- a/packages/ui/src/components/bible-reader-notes-composer.tsx +++ b/packages/ui/src/components/bible-reader-notes-composer.tsx @@ -6,10 +6,12 @@ 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 { 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 type { AttachedNote } from './use-bible-note-indicators'; type NotesComposerProps = { draft: NoteDraft; @@ -20,6 +22,8 @@ type NotesComposerProps = { onDismiss: (intent: 'cancel' | 'discard') => void; theme: 'light' | 'dark'; restoreFocusTarget: HTMLElement | null; + savedNotes: AttachedNote[]; + bookName: string; }; export function BibleReaderNotesComposer({ @@ -31,6 +35,8 @@ export function BibleReaderNotesComposer({ onDismiss, theme, restoreFocusTarget, + savedNotes, + bookName, }: NotesComposerProps): ReactElement { const { t } = useTranslation(undefined, { i18n }); const visibilityName = useId(); @@ -40,6 +46,7 @@ export function BibleReaderNotesComposer({ const stayButtonRef = useRef(null); const focusBeforeDiscard = useRef(null); const [confirmDiscard, setConfirmDiscard] = useState(false); + const hasChanges = !!draft.text || draft.visibility !== 'private' || !!draft.color; const colorNames = { ffec5b: t('highlightYellow'), b4ffc1: t('highlightGreen'), @@ -64,7 +71,7 @@ export function BibleReaderNotesComposer({ setConfirmDiscard(false); return; } - if (draft.text || draft.visibility !== 'private' || draft.color) { + if (hasChanges) { const form = formRef.current; if (form) { const active = getOwnShadowRoot(form)?.activeElement ?? form.ownerDocument.activeElement; @@ -183,6 +190,16 @@ export function BibleReaderNotesComposer({
+ {!confirmDiscard && !hasChanges && savedNotes.length > 0 && ( +
+ +
+ )} + {confirmDiscard && (
tokenResponse('profile read_notes write_notes')), http.get('*/v1/highlights', () => HttpResponse.json({ data: [], next_page_token: null })), + http.get('*/v1/notes', () => new HttpResponse(null, { status: 204 })), ...globalHandlers, ], }, @@ -394,54 +404,723 @@ const green = { ...yellow, color: 'b4ffc1' }; const highlightPage = (highlight: typeof yellow) => HttpResponse.json({ data: [highlight], next_page_token: null }); -export const RefreshHighlights: Story = { +const rangeNote = { + id: 'range', + passage: { bible_id: 111, passage_id: 'JHN.1.1-2+JHN.1.4' }, + content: 'One range and one verse', + status: 'private', + color: 'ffec5b', + created_dt: new Date(Date.now() - 3.1 * 86_400_000).toISOString(), +}; +const singleNote = { + id: 'single', + passage: { bible_id: 111, passage_id: 'JHN.1.2' }, + content: 'One verse only', + status: 'public', + created_dt: rangeNote.created_dt, +}; + +export const OpensPreviouslySavedNotes: Story = { tags: ['integration', 'shadow-dom', 'cross-browser'], loaders: [prepareCallback], parameters: { + locale: 'es', msw: { handlers: [ http.get('*/v1/highlights', () => highlightPage(yellow)), + http.get('*/v1/notes', ({ request }) => { + const params = new URL(request.url).searchParams; + if ( + params.get('bible_id') !== '111' || + params.get('passage_id') !== 'JHN.1' || + request.headers.get('authorization') !== 'Bearer notes-story-token' + ) { + return new HttpResponse(null, { status: 403 }); + } + switch (params.get('page_token')) { + case null: + return HttpResponse.json({ data: [rangeNote], next_page_token: 'empty-page' }); + case 'empty-page': + return HttpResponse.json({ data: [], next_page_token: 'last-page' }); + case 'last-page': + return HttpResponse.json({ data: [rangeNote, singleNote] }); + default: + return new HttpResponse(null, { status: 400 }); + } + }), ...writableSession.msw.handlers, ], }, }, 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 first = await readerVerse(root, 1); + const second = await readerVerse(root, 2); + const firstMarker = await within(first).findByRole('button', { name: 'Notas 1' }); + const secondMarker = await within(second).findByRole('button', { name: 'Notas 2' }); + await expect( + within(await readerVerse(root, 4)).getByRole('button', { name: 'Notas 4' }), + ).toBeVisible(); + await expect( + within(await readerVerse(root, 3)).queryByRole('button', { name: 'Notas 3' }), + ).toBeNull(); + const firstMark = firstMarker.querySelector('[data-slot="verse-indicator-mark"]'); + const secondMark = secondMarker.querySelector('[data-slot="verse-indicator-mark"]'); + if (!(firstMark instanceof HTMLElement) || !(secondMark instanceof HTMLElement)) { + throw new Error('Note indicator marks are missing'); + } + await waitFor(async () => { + const [red, green, blue, alpha] = getBackgroundColorChannels(firstMark); + await expect(alpha).toBe(64); + await expect(Math.max(red!, green!, blue!) - Math.min(red!, green!, blue!)).toBeLessThan(6); + }); + await expect(getBackgroundColorChannels(secondMark)).toEqual([61, 121, 194, 255]); + await expect(secondMarker.getBoundingClientRect().width).toBeGreaterThanOrEqual(24); + await expect(secondMarker.getBoundingClientRect().width).toBeGreaterThan( + secondMark.getBoundingClientRect().width, + ); + + await userEvent.click(secondMarker); + const overlays = await readerOverlays(root); + const drawer = within(await overlays.findByRole('dialog', { name: 'John 1:2' })); + const saved = within(drawer.getByRole('region', { name: 'Notas guardadas' })); + const range = within( + saved.getByRole('article', { name: 'Agregaste una nota el John 1:1-2,4' }), + ); + const single = within(saved.getByRole('article', { name: 'Agregaste una nota el John 1:2' })); + await expect(saved.getAllByRole('article')).toHaveLength(2); + await expect(range.getByText('One range and one verse')).toBeVisible(); + await expect(range.getByText('Privada')).toBeVisible(); + await expect(single.getByText('One verse only')).toBeVisible(); + await expect(single.getByText('Pública')).toBeVisible(); + const age = range.getByText('hace 3 días'); + const dot = age.previousElementSibling; + if (!(dot instanceof HTMLElement)) throw new Error('Saved-note color dot is missing'); + await expect(getBackgroundColorChannels(dot)).toEqual([255, 236, 91, 255]); + await expect(single.getByText('hace 3 días').previousElementSibling).toBeNull(); + const editor = drawer.getByRole('textbox', { name: 'Agregar nota…' }); + await fillEditor(editor, 'New thought'); + await expect(drawer.queryByRole('region', { name: 'Notas guardadas' })).toBeNull(); + await fillEditor(editor, ''); + await expect(drawer.getByRole('region', { name: 'Notas guardadas' })).toBeVisible(); + await userEvent.click(drawer.getByRole('button', { name: 'Cancelar' })); + await waitFor(() => expect(root.activeElement).toBe(secondMarker)); + + await userEvent.click(firstMarker); + const firstDrawer = within(await overlays.findByRole('dialog', { name: 'John 1:1' })); + await waitFor(() => + expect( + firstDrawer.getByRole('article', { name: 'Agregaste una nota el John 1:1-2,4' }), + ).toBeVisible(), + ); + await expect(firstDrawer.queryByText('One verse only')).toBeNull(); + }), +}; + +export const StandaloneNoteIndicators: Story = { + ...OpensPreviouslySavedNotes, + tags: ['integration', 'shadow-dom', 'cross-browser'], + args: { onNoteIndicatorPress: fn(), onVerseSelect: fn() }, + render: (args) => ( + + ), + play: withWritableSession(async ({ args, canvasElement }) => { + const root = await waitForShadowRoot(canvasElement); + const marker = await within(await readerVerse(root, 2)).findByRole('button', { + name: 'Notas 2', + }); + marker.focus(); + const ranNative = await verifyNativeBrowserKey('{Enter}', async () => { + await expect(args.onNoteIndicatorPress).toHaveBeenCalledTimes(1); + }); + if (!ranNative) await userEvent.click(marker); + await expect(args.onNoteIndicatorPress).toHaveBeenCalledOnce(); + await expect(args.onNoteIndicatorPress).toHaveBeenCalledWith( + { versionId: 111, passageId: 'JHN.1.2' }, + [expect.objectContaining({ id: 'range' }), expect.objectContaining({ id: 'single' })], + ); + await expect(args.onVerseSelect).not.toHaveBeenCalled(); + await expect(root.querySelector('[role="dialog"]')).toBeNull(); + }), +}; + +function NotesReadHarness({ + chapter, + versionId, + onChapterChange, + onVersionChange, +}: { + chapter: string; + versionId: number; + onChapterChange: (chapter: string) => void; + onVersionChange: (versionId: number) => void; +}) { + const { userInfo } = useYVAuth(); + const [readExcluded, setReadExcluded] = useState(false); + const [readSibling, setReadSibling] = useState(false); + const query = useChapterNotes({ version_id: versionId, passage_id: `JHN.${chapter}` }); + const excluded = useChapterNotes( + { version_id: 3034, passage_id: 'JHN.1' }, + { enabled: readExcluded }, + ); + const sibling = useChapterNotes({ version_id: 1, passage_id: 'JHN.1' }, { enabled: readSibling }); + return ( + <> + + + + + + {getHttpStatus(excluded.error)} + {userInfo?.name} + {query.notes?.map(({ id }) => id).join(',')} + {sibling.notes?.map(({ id }) => id).join(',')} + {getHttpStatus(query.error)} + + {query.loading ? 'Loading' : query.error ? 'Failed' : query.notes ? 'Ready' : 'Unavailable'} + +
+ + + +
+ + ); +} + +const notesHostProfile = { id: 'second-account', name: 'Host Notes profile' }; + +function ScopedNotesStory() { + const [chapter, setChapter] = useState('1'); + const [versionId, setVersionId] = useState(111); + const [showNotes, setShowNotes] = useState(true); + const [hostOwnsProfile, setHostOwnsProfile] = useState(false); + return ( + + + + {showNotes && ( + + )} + + ); +} + +function chapterNote(verse: number, chapter: string, bible_id = 111) { + return { + ...singleNote, + id: `note-${bible_id}-${chapter}-${verse}`, + passage: { bible_id, passage_id: `JHN.${chapter}.${verse}` }, + content: `Saved thought ${bible_id}/${chapter}/${verse}`, + status: 'private', + }; +} + +function stageNotesRead(response: Response, scope: [number, string, string]) { + return { + response, + scope, + request: deferred(), + release: deferred(), + finished: deferred(), + }; +} + +export const NotesFollowChapterVersionAccountAndAccess: Story = { + tags: ['integration', 'shadow-dom', 'cross-browser'], + loaders: [prepareCallback], + parameters: { + includeAuth: false, + msw: { + handlers: [ + http.post('*/auth/token', () => tokenResponse('profile read_notes')), + http.get('*/v1/notes', () => HttpResponse.json({ data: [chapterNote(2, '1')] })), + http.get('*/v1/bibles/1/passages/JHN.3', () => HttpResponse.json(mockPassages['JHN.3'])), + ...writableSession.msw.handlers, + ], + }, + }, + render: () => , + play: withWritableSession(async ({ canvasElement }) => { + let root = await waitForShadowRoot(canvasElement); + const page = within(canvasElement); + const marker = async (verse: number) => { + const element = await readerVerse(root, verse); + return within(element).queryByRole('button', { name: `Notes ${verse}` }); + }; + const refresh = () => userEvent.click(page.getByRole('button', { name: 'Refresh notes' })); + const status = () => page.getByLabelText('Notes read status'); + const ids = () => page.getByLabelText('Notes read IDs'); + const siblingIds = () => page.getByLabelText('Sibling Notes IDs'); + const errorCode = () => page.getByLabelText('Notes read error code'); + const rotate = async (accessToken: string, scope: string): Promise => { + getWorker().use( + http.post('*/auth/token', () => + HttpResponse.json({ + access_token: accessToken, + refresh_token: `${accessToken}-refresh`, + expires_in: 3600, + scope, + token_type: 'Bearer', + }), + ), + ); + await YouVersionAPIUsers.refreshTokens(); + }; + const notePage = (verse: number, chapter: string, version?: number) => + HttpResponse.json({ data: [chapterNote(verse, chapter, version)] }); + const beforeNavigation = [111, 'JHN.1', 'notes-story-token'] satisfies [number, string, string]; + const afterChapter = [111, 'JHN.3', 'notes-story-token'] satisfies [number, string, string]; + const afterVersion = [1, 'JHN.3', 'notes-story-token'] satisfies [number, string, string]; + const otherAccount = [1, 'JHN.3', 'second-account-token'] satisfies [number, string, string]; + const siblingScope = [1, 'JHN.1', 'second-account-token'] satisfies [number, string, string]; + const renewedGrant = [1, 'JHN.3', 'notes-renewed-token'] satisfies [number, string, string]; const reads = [ - new HttpResponse(null, { status: 503 }), - highlightPage(yellow), - highlightPage(green), - ].map((response) => ({ - response, + stageNotesRead(new HttpResponse(null, { status: 503 }), beforeNavigation), + stageNotesRead(notePage(4, '1'), beforeNavigation), + stageNotesRead(notePage(16, '3'), afterChapter), + stageNotesRead(notePage(1, '3', 1), afterVersion), + stageNotesRead(notePage(2, '3', 1), otherAccount), + stageNotesRead(notePage(4, '1', 1), siblingScope), + stageNotesRead(new HttpResponse(null, { status: 403 }), otherAccount), + stageNotesRead(new HttpResponse(null, { status: 503 }), otherAccount), + stageNotesRead(notePage(16, '3', 1), otherAccount), + stageNotesRead(new HttpResponse(null, { status: 401 }), otherAccount), + stageNotesRead( + HttpResponse.json({ data: [{ ...chapterNote(16, '3', 1), id: 'renewed-note' }] }), + renewedGrant, + ), + stageNotesRead(notePage(2, '3', 1), otherAccount), + stageNotesRead(new HttpResponse(null, { status: 503 }), otherAccount), + stageNotesRead(notePage(16, '3', 1), otherAccount), + ] as const; + await waitFor(async () => expect(await marker(2)).toBeVisible()); + await userEvent.click(page.getByRole('button', { name: 'Read excluded version' })); + await waitFor(() => + expect(page.getByLabelText('Excluded version Notes status')).toHaveTextContent('403'), + ); + await expect(await marker(2)).toBeVisible(); + const queue = reads.slice(); + const observedNotes = spyOn(NotesClient.prototype, 'getNotes'); + const matchedCalls = new Set(); + getWorker().use( + http.get('*/v1/notes', async ({ request }) => { + const next = queue.shift(); + if (!next) return new HttpResponse(null, { status: 204 }); + next.request.resolve(request); + await next.release.promise; + return next.response; + }), + ); + async function expectRead(read: (typeof reads)[number]) { + const request = await read.request.promise; + const params = new URL(request.url).searchParams; + const [version, passage, token] = read.scope; + await expect(params.get('bible_id')).toBe(String(version)); + await expect(params.get('passage_id')).toBe(passage); + await expect(request.headers.get('authorization')).toBe(`Bearer ${token}`); + const call = observedNotes.mock.calls.findIndex( + ([options, bearer], index) => + !matchedCalls.has(index) && + options?.version_id === version && + options.passage_id === passage && + bearer === token, + ); + const outcome = observedNotes.mock.results[call]; + if (outcome?.type !== 'return') throw new Error('The Notes client call was not observed'); + matchedCalls.add(call); + const finish = () => read.finished.resolve(); + void outcome.value.then(finish, finish); + } + async function releaseObsoleteRead(read: (typeof reads)[number]) { + read.release.resolve(); + await read.finished.promise; + await new Promise((resolve) => requestAnimationFrame(() => resolve())); + await expect(ids()).toBeEmptyDOMElement(); + } + const [ + failed, + oldChapter, + oldVersion, + oldAccount, + fresh, + sibling, + denied, + failedAfterDenial, + recovered, + oldGrantDenied, + renewed, + regranted, + failedRemount, + hostPrivateRead, + ] = reads; + 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 setSession = (scope: string, name: string) => { + YouVersionPlatformConfiguration.saveAuthData( + 'second-account-token', + 'second-account-refresh', + new Date('2100-01-01'), + { userId: 'second-account', scope }, + ); + storage.setItem('userInfo', JSON.stringify({ id: 'second-account', name })); + }; + + await refresh(); + await expectRead(failed); + const retained = await marker(2); + if (!retained) throw new Error('The current private note indicator is missing'); + await userEvent.click(retained); + const overlays = await readerOverlays(root); + const retainedCard = within(await overlays.findByRole('dialog', { name: 'John 1:2' })); + await expect(retainedCard.getByText('Saved thought 111/1/2')).toBeVisible(); + await expect(retainedCard.getByText('Private')).toBeVisible(); + failed.release.resolve(); + await waitFor(() => expect(status()).toHaveTextContent('Failed')); + await expect(await marker(2)).toBeVisible(); + await expect(ids()).toHaveTextContent('note-111-1-2'); + await expect(retainedCard.getByText('Saved thought 111/1/2')).toBeVisible(); + const usedNativeKeys = await verifyNativeBrowserKey('{Escape}', () => + waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull()), + ); + if (!usedNativeKeys) await userEvent.keyboard('{Escape}'); + await waitFor(() => expect(root.activeElement).toBe(retained)); + + await refresh(); + await expectRead(oldChapter); + await userEvent.click(page.getByRole('button', { name: 'Open John 3' })); + await expectRead(oldVersion); + await waitFor(async () => expect(await marker(2)).toBeNull()); + await releaseObsoleteRead(oldChapter); + await userEvent.click(page.getByRole('button', { name: 'Use KJV' })); + await expectRead(oldAccount); + await releaseObsoleteRead(oldVersion); + setSession('profile read_notes', 'Notes account'); + await expectRead(fresh); + await expect(ids()).toBeEmptyDOMElement(); + await releaseObsoleteRead(oldAccount); + fresh.release.resolve(); + await waitFor(() => expect(ids()).toHaveTextContent(/^note-1-3-2$/)); + await waitFor(async () => expect(await marker(2)).toBeVisible()); + await expect(await marker(16)).toBeNull(); + await expect(await marker(1)).toBeNull(); + + await userEvent.click(page.getByRole('button', { name: 'Read sibling chapter' })); + await expectRead(sibling); + await refresh(); + await expectRead(denied); + const button = await marker(2); + if (!button) throw new Error('The current note indicator is missing'); + await userEvent.click(button); + const viewer = within(await overlays.findByRole('dialog', { name: 'John 3:2' })); + await waitFor(() => expect(viewer.getByText('Saved thought 1/3/2')).toBeVisible()); + await expect(viewer.queryByRole('textbox')).toBeNull(); + denied.release.resolve(); + await waitFor(() => expect(errorCode()).toHaveTextContent('403')); + await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull()); + await expect(await marker(2)).toBeNull(); + + await refresh(); + await expectRead(failedAfterDenial); + sibling.release.resolve(); + await sibling.finished.promise; + failedAfterDenial.release.resolve(); + await waitFor(() => expect(errorCode()).toHaveTextContent('503')); + await expect(ids()).toBeEmptyDOMElement(); + await expect(siblingIds()).toBeEmptyDOMElement(); + await expect(await marker(2)).toBeNull(); + await userEvent.click(page.getByRole('button', { name: 'Stop reading sibling chapter' })); + + await refresh(); + await expectRead(recovered); + recovered.release.resolve(); + await waitFor(async () => expect(await marker(16)).toBeVisible()); + await refresh(); + await expectRead(oldGrantDenied); + const recoveredMarker = await marker(16); + if (!recoveredMarker) throw new Error('The reloaded note indicator is missing'); + await userEvent.click(recoveredMarker); + await overlays.findByRole('dialog', { name: 'John 3:16' }); + await rotate('notes-renewed-token', 'profile read_notes'); + await expectRead(renewed); + await expect(ids()).toHaveTextContent(/^note-1-3-16$/); + await expect(await marker(16)).toBeVisible(); + await expect(overlays.getByRole('dialog', { name: 'John 3:16' })).toBeVisible(); + renewed.release.resolve(); + await waitFor(() => expect(ids()).toHaveTextContent(/^renewed-note$/)); + oldGrantDenied.release.resolve(); + await oldGrantDenied.finished.promise; + // The late denial has reached the Notes client. Observe after the browser's next paint. + await new Promise((resolve) => requestAnimationFrame(() => resolve())); + await expect(ids()).toHaveTextContent(/^renewed-note$/); + await expect(errorCode()).toBeEmptyDOMElement(); + await expect(overlays.getByRole('dialog', { name: 'John 3:16' })).toBeVisible(); + + await rotate('notes-revoked-token', 'profile'); + await waitFor(() => expect(status()).toHaveTextContent('Unavailable')); + await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull()); + await expect(await marker(16)).toBeNull(); + + setSession('profile read_notes', 'Notes access restored'); + await expectRead(regranted); + await expect(await marker(16)).toBeNull(); + await expect(await marker(1)).toBeNull(); + regranted.release.resolve(); + await waitFor(() => expect(ids()).toHaveTextContent(/^note-1-3-2$/)); + await waitFor(async () => expect(await marker(2)).toBeVisible()); + + await userEvent.click(page.getByRole('button', { name: 'Hide Notes reader' })); + await expect(page.queryByLabelText('Notes read IDs')).toBeNull(); + await rotate('hidden-revoked-token', 'profile'); + await rotate('second-account-token', 'profile read_notes'); + await userEvent.click(page.getByRole('button', { name: 'Show Notes reader' })); + root = await waitForShadowRoot(canvasElement); + await expectRead(failedRemount); + await expect(ids()).toBeEmptyDOMElement(); + await expect(await marker(2)).toBeNull(); + failedRemount.release.resolve(); + await waitFor(() => expect(errorCode()).toHaveTextContent('503')); + await expect(ids()).toBeEmptyDOMElement(); + + await userEvent.click(page.getByRole('button', { name: 'Use host Notes profile' })); + const profile = page.getByLabelText('Notes profile'); + await waitFor(() => expect(profile).toHaveTextContent('Host Notes profile')); + await refresh(); + await expectRead(hostPrivateRead); + hostPrivateRead.release.resolve(); + const privateMarker = await waitFor(async () => { + const button = await marker(16); + if (!button) throw new Error('The host note indicator is missing'); + return button; + }); + await userEvent.click(privateMarker); + const hostOverlays = await readerOverlays(root); + const hostDrawer = within(await hostOverlays.findByRole('dialog', { name: 'John 3:16' })); + await expect(hostDrawer.getByText('Saved thought 1/3/16')).toBeVisible(); + storage.setItem( + 'youversion-auth-scope', + JSON.stringify({ + userId: 'second-account', + scope: 'profile', + accessToken: 'second-account-token', + refreshToken: 'second-account-token-refresh', + }), + ); + await waitFor(() => expect(status()).toHaveTextContent('Unavailable')); + await waitFor(() => expect(hostOverlays.queryByRole('dialog')).toBeNull()); + await expect(await marker(16)).toBeNull(); + await expect(profile).toHaveTextContent('Host Notes profile'); + } finally { + for (const read of reads) read.release.resolve(); + observedNotes.mockRestore(); + frame.remove(); + } + }), +}; + +function NotesMutationHarness() { + const { userInfo } = useYVAuth(); + const update = useUpdateNote(); + const remove = useDeleteNote(); + const highlights = useHighlights({ version_id: 111, passage_id: 'JHN.1' }); + const token = YouVersionPlatformConfiguration.getOAuthAccessToken( + userInfo?.userId ?? null, + 'write_notes', + ); + return ( + <> + + {highlights.loading + ? 'Loading' + : (getHttpStatus(highlights.error) ?? (highlights.highlights ? 'Ready' : 'Unavailable'))} + + {token && ( + <> + + + + + )} +
+ + + +
+ + ); +} + +const olderNoteHighlight = { ...yellow, passage_id: 'JHN.1.2', color: 'bbf4ff' }; +const initialHighlightsPage = () => + HttpResponse.json({ data: [yellow, olderNoteHighlight], next_page_token: null }); +const olderNote = { + ...chapterNote(2, '1'), + id: 'older-colored-note', + color: olderNoteHighlight.color, +}; + +export const RefreshHighlights: Story = { + tags: ['integration', 'shadow-dom', 'cross-browser'], + loaders: [prepareCallback], + parameters: { + msw: { + handlers: [ + http.get('*/v1/highlights', initialHighlightsPage), + http.get('*/v1/notes', () => HttpResponse.json({ data: [olderNote] })), + ...writableSession.msw.handlers, + ], + }, + }, + render: () => , + play: withWritableSession(async ({ canvasElement }) => { + const root = await waitForShadowRoot(canvasElement); + const verseOne = await readerVerse(root, 1); + const verseTwo = await readerVerse(root, 2); + const paint = () => [ + getBackgroundColorChannels(verseOne), + getBackgroundColorChannels(verseTwo), + ]; + const yellowPaint = [255, 236, 91, 255]; + const greenPaint = [180, 255, 193, 255]; + const bluePaint = [187, 244, 255, 255]; + const transparent = [0, 0, 0, 0]; + await waitFor(() => expect(paint()).toEqual([yellowPaint, bluePaint])); + await expect(await within(verseTwo).findByRole('button', { name: 'Notes 2' })).toBeVisible(); + + const action = within(canvasElement); + const readStatus = () => action.getByLabelText('Highlights read status'); + const steps = [ + { + press: async () => { + await selectVerses(root, [1]); + const { overlays, composer } = await openComposer(root, 'John 1:1'); + await fillEditor( + composer.getByRole('textbox', { name: 'Add Note…' }), + 'A colored note', + ); + await userEvent.click(composer.getByRole('button', { name: 'Add yellow highlight' })); + await userEvent.click(composer.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(overlays.queryByRole('dialog')).toBeNull()); + }, + response: new HttpResponse(null, { status: 503 }), + settledStatus: '503', + before: [yellowPaint, bluePaint], + after: [yellowPaint, bluePaint], + }, + { + press: () => userEvent.click(action.getByRole('button', { name: 'Change note color' })), + response: initialHighlightsPage(), + pendingStatus: 'Loading', + settledStatus: 'Ready', + before: [yellowPaint, bluePaint], + after: [yellowPaint, bluePaint], + }, + { + press: () => userEvent.click(action.getByRole('button', { name: 'Change note color' })), + response: HttpResponse.json({ data: [green, olderNoteHighlight] }), + settledStatus: 'Ready', + before: [yellowPaint, bluePaint], + after: [greenPaint, bluePaint], + }, + { + press: () => userEvent.click(action.getByRole('button', { name: 'Clear note color' })), + response: highlightPage(olderNoteHighlight), + settledStatus: 'Ready', + before: [greenPaint, bluePaint], + after: [transparent, bluePaint], + }, + { + press: () => userEvent.click(action.getByRole('button', { name: 'Delete colored note' })), + response: HttpResponse.json({ data: [] }), + settledStatus: 'Ready', + before: [transparent, bluePaint], + after: [transparent, transparent], + }, + ]; + const reads = steps.map((step) => ({ + ...step, 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; - }); + const requests: unknown[] = []; + let saved: NoteRequest | undefined; + let olderDeleted = false; getWorker().use( - http.post('*/v1/notes', async ({ request }) => - noteResponse(await request.json()), + http.get('*/v1/notes', () => + HttpResponse.json({ + data: [ + ...(saved ? [{ ...saved, id: 'saved-note' }] : []), + ...(!olderDeleted ? [olderNote] : []), + ], + }), ), + http.post('*/v1/notes', async ({ request }) => { + saved = await request.json(); + requests.push(['create', saved.content, saved.color, saved.passage.passage_id]); + return noteResponse(saved); + }), + http.patch('*/v1/notes/saved-note', async ({ request }) => { + if (!saved) return new HttpResponse(null, { status: 404 }); + const { color } = await request.json(); + requests.push(['update', color]); + saved = { ...saved, color }; + return noteResponse(saved); + }), + http.delete('*/v1/notes/older-colored-note', () => { + requests.push(['delete', 'older-colored-note']); + olderDeleted = true; + return new HttpResponse(null, { status: 204 }); + }), http.get('*/v1/highlights', async ({ request }) => { const read = queued.shift(); - if (!read) return highlightPage(green); + if (!read) return HttpResponse.json({ data: [] }); read.request.resolve(new URL(request.url)); await read.release.promise; return read.response; @@ -449,27 +1128,32 @@ export const RefreshHighlights: Story = { ); 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' })); + for (const read of reads) { + await read.press(); 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); + const { pendingStatus } = read; + if (pendingStatus) + await waitFor(() => expect(readStatus()).toHaveTextContent(pendingStatus)); + await expect(paint()).toEqual(read.before); 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(readStatus()).toHaveTextContent(read.settledStatus)); + await waitFor(() => expect(paint()).toEqual(read.after)); } - await waitFor(() => expect(paint()).toEqual([180, 255, 193, 255])); + await expect(requests).toEqual([ + ['create', 'A colored note', 'ffec5b', 'JHN.1.1'], + ['update', 'b4ffc1'], + ['update', 'b4ffc1'], + ['update', null], + ['delete', 'older-colored-note'], + ]); + await expect(within(verseOne).getByRole('button', { name: 'Notes 1' })).toBeVisible(); + await waitFor(() => + expect(within(verseTwo).queryByRole('button', { name: 'Notes 2' })).toBeNull(), + ); } finally { - observedFetch.mockRestore(); + for (const read of reads) read.release.resolve(); } }), }; @@ -739,7 +1423,7 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = { await waitFor(() => expect(getBackgroundColorChannels(retained)).toEqual([180, 255, 193, 255]), ); - await expect(postSaveReads).toEqual(['JHN.1']); + await expect(postSaveReads).toContain('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()); @@ -759,7 +1443,7 @@ export const RefreshRetainedChapterWhileNavigationLoads: Story = { await waitFor(() => expect(getBackgroundColorChannels(destination)).toEqual([180, 255, 193, 255]), ); - await waitFor(() => expect(postSaveReads).toEqual(['JHN.1', 'JHN.3'])); + await waitFor(() => expect(postSaveReads).toContain('JHN.3')); await selectVerses(root, [16]); const currentActions = within(await overlays.findByRole('dialog', { name: 'Verse actions' })); await waitFor(() => diff --git a/packages/ui/src/components/bible-reader-saved-notes.tsx b/packages/ui/src/components/bible-reader-saved-notes.tsx new file mode 100644 index 00000000..8d4fb5b4 --- /dev/null +++ b/packages/ui/src/components/bible-reader-saved-notes.tsx @@ -0,0 +1,139 @@ +'use client'; + +import { useId, type ReactElement } from 'react'; +import { useTranslation } from 'react-i18next'; +import i18n from '@/i18n'; +import { highlightFillColorMix } from '@/lib/highlight-colors'; +import { buildVerseReference } from '@/lib/verse-share'; +import { Button } from './ui/button'; +import { Dialog, DialogContent, DialogTitle } from './ui/dialog'; +import type { AttachedNote } from './use-bible-note-indicators'; + +type SavedNotesProps = { + notes: AttachedNote[]; + bookName: string; + chapter: string; +}; + +function relativeAge(created: string, locale: string) { + const elapsedMinutes = Math.max(0, Math.floor((Date.now() - Date.parse(created)) / 60_000)); + const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }); + if (elapsedMinutes >= 1_440) return formatter.format(-Math.floor(elapsedMinutes / 1_440), 'day'); + if (elapsedMinutes >= 60) return formatter.format(-Math.floor(elapsedMinutes / 60), 'hour'); + if (elapsedMinutes > 0) return formatter.format(-elapsedMinutes, 'minute'); + return formatter.format(0, 'second'); +} + +function SavedNoteCard({ + attachment, + bookName, + chapter, +}: { + attachment: AttachedNote; + bookName: string; + chapter: string; +}) { + const { t, i18n: translation } = useTranslation(undefined, { i18n }); + const titleId = useId(); + const { note, verses } = attachment; + const passage = buildVerseReference({ bookName, chapter, verses, versionAbbreviation: '' }); + return ( +
+
+

+ {t('notesAddedNoteOn', { date: passage })} +

+ + {note.status === 'public' ? t('notesPublic') : t('notesPrivate')} + +
+ {note.content && ( +

+ {note.content} +

+ )} + {(note.color || note.created_dt) && ( +
+ {note.color && ( +
+ )} +
+ ); +} + +export function BibleReaderSavedNotes({ notes, bookName, chapter }: SavedNotesProps): ReactElement { + const { t } = useTranslation(undefined, { i18n }); + const headingId = useId(); + return ( +
+

+ {t('notesPreviouslySaved')} +

+ {notes.map((attachment) => ( + + ))} +
+ ); +} + +export function BibleReaderSavedNotesDrawer({ + reference, + theme, + restoreFocusTarget, + onDismiss, + ...savedNotes +}: SavedNotesProps & { + reference: string; + theme: 'light' | 'dark'; + restoreFocusTarget: HTMLElement | null; + onDismiss: () => void; +}): ReactElement { + const { t } = useTranslation(undefined, { i18n }); + return ( + { + if (!open) onDismiss(); + }} + > + + + {reference} + + +
+ +
+
+
+ ); +} diff --git a/packages/ui/src/components/bible-reader.tsx b/packages/ui/src/components/bible-reader.tsx index b06b5f57..93bdcea5 100644 --- a/packages/ui/src/components/bible-reader.tsx +++ b/packages/ui/src/components/bible-reader.tsx @@ -17,9 +17,16 @@ import { type Highlight, type TextDirection, } from '@youversion/platform-core'; -import { useBooks, usePassage, useTheme, useVersion } from '@youversion/platform-react-hooks'; +import { + useBooks, + usePassage, + useTheme, + useVersion, + YouVersionAuthContext, +} from '@youversion/platform-react-hooks'; import { useCallback, + useContext, useEffect, useLayoutEffect, useMemo, @@ -38,6 +45,8 @@ import { useBibleReaderHighlights } from './use-bible-reader-highlights'; import { scopesEqual } from './bible-reader-highlights-machine'; import { useBibleReaderNote, type NoteDraft } from './use-bible-reader-note'; import { BibleReaderNotesComposer } from './bible-reader-notes-composer'; +import { BibleReaderSavedNotesDrawer } from './bible-reader-saved-notes'; +import { getIndicatorVerse, useBibleNoteIndicators } from './use-bible-note-indicators'; import { HighlightPermissionDialog } from './highlight-permission-dialog'; import { SignInDialog } from './sign-in-dialog'; import { @@ -54,6 +63,7 @@ import { useTransientVerseFocus, type VerseFocusRequest } from '@/lib/use-transi import { BibleReaderNavigation, type BibleReaderNavigationRequest, + type BibleReaderReference, } from './bible-reader-navigation'; import { VerseActionPopoverFocusRestoreProvider } from '@/lib/verse-action-popover-focus'; import { isElementFromOwnerDocument } from '@/lib/shadow-root-host'; @@ -483,6 +493,7 @@ function Root({ function Content() { const { t } = useTranslation(undefined, { i18n }); + const auth = useContext(YouVersionAuthContext); const { background, book, @@ -625,7 +636,6 @@ function Content() { const { highlightedVerses, highlightsInteractive, - refresh: refreshHighlights, apply: applyHighlight, remove: removeHighlight, permissionDialogOpen, @@ -667,13 +677,34 @@ function Content() { reader: scrollContainerRef, enabled: verseActions !== 'none' && (!verseActionItems || verseActionItems.includes('save')), hostOwnsSignIn: !!onSignInPress, - onSaved: (selection) => { - clearNoteSelection(selection); - refreshHighlights(); - }, + onSaved: clearNoteSelection, onInvalidated: clearNoteSelection, onAuthorizationCommitted: discardHighlightAuthorization, }); + const noteIndicators = useBibleNoteIndicators({ + versionId, + chapterPassageId: chapterReference, + highlightedVerses, + enabled: verseActions !== 'none' && !chapterUnavailable, + }); + const noteScope = JSON.stringify([ + auth?.userInfo?.userId, + auth?.accountRevision, + versionId, + chapterReference, + ]); + const [viewedNoteVerse, setViewedNoteVerse] = useState<{ + scope: string; + verse: number; + focusTarget: HTMLElement | null; + } | null>(null); + const viewedNotes = + viewedNoteVerse?.scope === noteScope && renderedReference + ? noteIndicators.getSavedNotes([viewedNoteVerse.verse]) + : []; + useLayoutEffect(() => { + if (viewedNoteVerse && viewedNotes.length === 0) setViewedNoteVerse(null); + }, [viewedNoteVerse, viewedNotes.length]); // 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 @@ -882,6 +913,23 @@ function Content() { } } + function handleNoteIndicatorPress(reference: BibleReaderReference) { + if (!renderedReference || notes.flow) return; + const verse = getIndicatorVerse(reference); + if (noteIndicators.getSavedNotes([verse]).length === 0) return; + const focusTarget = + readerRef.current?.querySelector( + `.yv-v[v="${verse}"] [data-slot="verse-indicator"]`, + ) ?? null; + closeAndClearSelection(); + if (notes.canCompose) { + noteRestoreFocusTargetRef.current = focusTarget; + notes.open(buildVerseSelection([verse])); + } else { + setViewedNoteVerse({ scope: noteScope, verse, focusTarget }); + } + } + function handleHighlight(color: string) { const outcome = applyHighlight(color, selectedVerses); // Entering the auth flow (sign-in or permission prompt) keeps only the verse @@ -1132,8 +1180,12 @@ function Content() { scriptureDirection={scriptureDirection} selectedVerses={canShowSelection ? selectedVerses : undefined} onVerseSelect={handleVerseSelect} - getVerseIndicator={isRefetching ? undefined : getVerseIndicator} - onVerseIndicatorPress={onVerseIndicatorPress} + getVerseIndicator={ + isRefetching ? undefined : (getVerseIndicator ?? noteIndicators.getVerseIndicator) + } + onVerseIndicatorPress={ + getVerseIndicator ? onVerseIndicatorPress : handleNoteIndicatorPress + } highlightedVerses={highlightedVerses} passageState={{ passage, @@ -1237,6 +1289,24 @@ function Content() { onDismiss={notes.dismiss} theme={background} restoreFocusTarget={noteRestoreFocusTargetRef.current} + savedNotes={ + scopesEqual(notes.flow.draft.selection, { versionId, book, chapter }) + ? noteIndicators.getSavedNotes(notes.flow.draft.selection.verses) + : [] + } + bookName={bookData?.title ?? book} + /> + )} + + {viewedNoteVerse && viewedNotes.length > 0 && ( + setViewedNoteVerse(null)} /> )} diff --git a/packages/ui/src/components/use-bible-note-indicators.ts b/packages/ui/src/components/use-bible-note-indicators.ts new file mode 100644 index 00000000..47f81460 --- /dev/null +++ b/packages/ui/src/components/use-bible-note-indicators.ts @@ -0,0 +1,74 @@ +'use client'; + +import { useMemo } from 'react'; +import { parseUsfmReference, type Note } from '@youversion/platform-core'; +import { useChapterNotes } from '@youversion/platform-react-hooks'; +import { useTranslation } from 'react-i18next'; +import i18n from '@/i18n'; +import type { BibleReaderReference } from './bible-reader-navigation'; +import type { VerseIndicatorProps } from './verse'; + +export type AttachedNote = { note: Note; verses: number[] }; + +type BibleNoteIndicators = { + getVerseIndicator: VerseIndicatorProps['getVerseIndicator']; + getSavedNotes: (verses: readonly number[]) => AttachedNote[]; +}; + +export function useBibleNoteIndicators({ + versionId, + chapterPassageId, + highlightedVerses, + enabled, +}: { + versionId: number; + chapterPassageId: string; + highlightedVerses: Record; + enabled: boolean; +}): BibleNoteIndicators { + const { t } = useTranslation(undefined, { i18n }); + const { notes } = useChapterNotes( + { version_id: versionId, passage_id: chapterPassageId }, + { enabled }, + ); + const { attachments, markedVerses } = useMemo(() => { + const attachments: AttachedNote[] = []; + const markedVerses = new Set(); + for (const note of notes ?? []) { + if (!note.passage || note.passage.version_id !== versionId) continue; + const verses = note.passage.passage_id.split('+').flatMap((id) => { + const reference = parseUsfmReference(id); + return reference && `${reference.book}.${reference.chapter}` === chapterPassageId + ? reference.verses + : []; + }); + if (verses.length === 0) continue; + attachments.push({ note, verses }); + for (const verse of verses) markedVerses.add(verse); + } + return { attachments, markedVerses }; + }, [notes, chapterPassageId, versionId]); + + const getVerseIndicator: NonNullable = (reference) => { + const verse = getIndicatorVerse(reference); + if (!markedVerses.has(verse)) return undefined; + return { + label: t('notesVerseIndicatorAccessibilityLabel', { verse }), + style: { + backgroundColor: highlightedVerses[verse] + ? 'color-mix(in srgb, var(--yv-muted-foreground) 25%, transparent)' + : 'var(--yv-ring)', + }, + }; + }; + + return { + getVerseIndicator: markedVerses.size > 0 ? getVerseIndicator : undefined, + getSavedNotes: (verses: readonly number[]): AttachedNote[] => + attachments.filter((attachment) => attachment.verses.some((verse) => verses.includes(verse))), + }; +} + +export function getIndicatorVerse(reference: BibleReaderReference): number { + return Number(reference.passageId.split('.').pop()); +} diff --git a/packages/ui/src/components/use-bible-reader-highlights.ts b/packages/ui/src/components/use-bible-reader-highlights.ts index 2d247db3..3ba3ef4c 100644 --- a/packages/ui/src/components/use-bible-reader-highlights.ts +++ b/packages/ui/src/components/use-bible-reader-highlights.ts @@ -81,8 +81,6 @@ 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. */ @@ -247,8 +245,7 @@ export function useBibleReaderHighlights({ createHighlight, deleteHighlight, refetch: () => { - // Highlight writes target the requested scope; Notes refresh targets the - // displayed chapter separately through `refresh` below. + // Highlight writes target the requested scope even during navigation. if (isDisplayingRetainedChapter) refetchDestination(); else refetch(); }, @@ -432,9 +429,6 @@ 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 index abcfe254..0d41f04b 100644 --- a/packages/ui/src/components/use-bible-reader-note.ts +++ b/packages/ui/src/components/use-bible-reader-note.ts @@ -85,6 +85,7 @@ type Flow = { type UseBibleReaderNoteResult = { flow: Flow | null; available: boolean; + canCompose: boolean; authorizationFailed: boolean; restoredSelection: NoteSelection | null; clearRestoredSelection: () => void; @@ -578,9 +579,11 @@ export function useBibleReaderNote({ )) ? null : flow; + const canCompose = enabled && !authLoading && !!writerToken(account); return { flow: visibleFlow, - available: enabled && !authLoading && (canAuthorize || !!writerToken(account)), + available: canCompose || (!authLoading && canAuthorize), + canCompose, authorizationFailed, restoredSelection, clearRestoredSelection, diff --git a/packages/ui/src/components/verse.tsx b/packages/ui/src/components/verse.tsx index 5090e65b..30039206 100644 --- a/packages/ui/src/components/verse.tsx +++ b/packages/ui/src/components/verse.tsx @@ -25,7 +25,7 @@ import { YvReaderStyles } from '@/lib/yv-styles-reader'; import { cn } from '@/lib/utils'; import { type FontFamily } from '@/lib/verse-html-utils'; -import type { Highlight, TextDirection } from '@youversion/platform-core'; +import type { Highlight, Note, TextDirection } from '@youversion/platform-core'; import { transformBibleHtml } from '@youversion/platform-core/browser'; import { chapterScopeForHighlightPaint, @@ -39,6 +39,7 @@ 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'; +import { getIndicatorVerse, useBibleNoteIndicators } from './use-bible-note-indicators'; const LETTERS = 'abcdefghijklmnopqrstuvwxyz'; type ResolvedScriptureDirection = TextDirection | 'auto'; @@ -369,6 +370,7 @@ function VerseNumberIndicator({ return (