diff --git a/.changeset/ype-6539-dimmed-chapter-highlights.md b/.changeset/ype-6539-dimmed-chapter-highlights.md new file mode 100644 index 00000000..034e1599 --- /dev/null +++ b/.changeset/ype-6539-dimmed-chapter-highlights.md @@ -0,0 +1,5 @@ +--- +'@youversion/platform-react-native-expo-ui': patch +--- + +Keep highlight fills on the dimmed outgoing passage while the next chapter or reference loads (YPE-6539). diff --git a/packages/ui/src/native/__tests__/bible-reader-native.test.tsx b/packages/ui/src/native/__tests__/bible-reader-native.test.tsx index 4e6060bf..38f2e583 100644 --- a/packages/ui/src/native/__tests__/bible-reader-native.test.tsx +++ b/packages/ui/src/native/__tests__/bible-reader-native.test.tsx @@ -858,6 +858,96 @@ describe('BibleReaderNative', () => { }) }) + describe('dimmed chapter highlights', () => { + function layoutParagraph(sentence: string): void { + const paragraph = screen.UNSAFE_getAllByType(Text).find((node) => node.props.onTextLayout) + if (paragraph === undefined) { + throw new Error('missing paragraph layout') + } + fireEvent(paragraph, 'textLayout', { + nativeEvent: { + lines: [ + { + text: sentence, + x: 0, + y: 0, + width: 240, + height: 32, + ascender: 24, + descender: -6, + capHeight: 18, + xHeight: 12, + }, + ], + }, + }) + } + + function hasHighlightFill(color: string): boolean { + return screen.UNSAFE_getAllByType(Text).some((node) => { + return StyleSheet.flatten(node.props.style)?.backgroundColor === color + }) + } + + it('keeps highlight fills on the dimmed outgoing chapter while the next chapter loads', async () => { + const chapter1 = fetchChapters({ '1': { status: 200, sentence: 'In the beginning' } }) + let resolveChapter2!: (response: { + status: number + body: string + contentType: string + }) => void + const chapter2Pending = new Promise<{ status: number; body: string; contentType: string }>( + (resolve) => { + resolveChapter2 = resolve + }, + ) + + const reader = mount({ + fetchBibleContent: (request) => + request.path.includes('/passages/JHN.2') ? chapter2Pending : chapter1(request), + highlights: [{ version_id: VERSION_ID, passage_id: 'JHN.1.1', color: 'fffe00' }], + }) + + await screen.findByText('In the beginning') + layoutParagraph('In the beginning') + await waitFor(() => expect(hasHighlightFill('#fffe00')).toBe(true)) + + reader.update({ + chapter: '2', + highlights: [{ version_id: VERSION_ID, passage_id: 'JHN.2.1', color: '5dff79' }], + }) + + expect(screen.getByText('In the beginning')).toBeTruthy() + expect(hasHighlightFill('#fffe00')).toBe(true) + expect(hasHighlightFill('#5dff79')).toBe(false) + + resolveChapter2({ + status: 200, + body: chapterBody('The earth was'), + contentType: 'application/json', + }) + + await screen.findByText('The earth was') + layoutParagraph('The earth was') + await waitFor(() => expect(hasHighlightFill('#5dff79')).toBe(true)) + expect(hasHighlightFill('#fffe00')).toBe(false) + }) + + it('clears highlight fills when highlights are removed on the current chapter', async () => { + const reader = mount({ + highlights: [{ version_id: VERSION_ID, passage_id: 'JHN.1.1', color: 'fffe00' }], + }) + + await screen.findByText('In the beginning') + layoutParagraph('In the beginning') + await waitFor(() => expect(hasHighlightFill('#fffe00')).toBe(true)) + + reader.update({ highlights: [] }) + + await waitFor(() => expect(hasHighlightFill('#fffe00')).toBe(false)) + }) + }) + it('shows scripture when the version language is on the provider list', async () => { const restore = stubVersionNames({ [VERSION_ID]: 'BSB' }, { [VERSION_ID]: 'en' }) try { diff --git a/packages/ui/src/native/__tests__/bible-text-view.test.tsx b/packages/ui/src/native/__tests__/bible-text-view.test.tsx index 9a3fcbc5..9b94e9c7 100644 --- a/packages/ui/src/native/__tests__/bible-text-view.test.tsx +++ b/packages/ui/src/native/__tests__/bible-text-view.test.tsx @@ -516,6 +516,52 @@ describe('BibleTextView', () => { }) }) + it('keeps highlight fills on the dimmed outgoing passage while the next reference loads', async () => { + useHighlightsMock.mockImplementation((options: UseHighlightsOptions) => ({ + ...emptyHighlights(options), + highlights: + options.enabled !== false && options.book === 'JHN' && options.chapter === '3' + ? [{ version_id: 3034, passage_id: 'JHN.3.16', color: 'fffe00' }] + : [], + })) + let resolveNext!: (response: Response) => void + const pending = new Promise((resolve) => { + resolveNext = resolve + }) + installFetch((requested) => + requested === 'JHN.3.16' + ? jsonPassage(passageHtml(verseBlock(16, JOHN)), 'John 3:16') + : pending, + ) + const view = render(, { + wrapper: highlightWrapper(), + }) + + await screen.findByText(JOHN) + paintHighlight(JOHN) + await waitFor(() => { + const painted = screen.UNSAFE_getAllByType(Text).some((node) => { + return StyleSheet.flatten(node.props.style)?.backgroundColor === '#fffe00' + }) + expect(painted).toBe(true) + }) + + view.rerender() + + expect(screen.getByText(JOHN)).toBeTruthy() + const stillPainted = screen.UNSAFE_getAllByType(Text).some((node) => { + return StyleSheet.flatten(node.props.style)?.backgroundColor === '#fffe00' + }) + expect(stillPainted).toBe(true) + + resolveNext(jsonPassage(passageHtml(verseBlock(1, 'Now when Jesus learned')), 'John 4:1')) + await screen.findByText('Now when Jesus learned') + const oldPaintRemains = screen.UNSAFE_getAllByType(Text).some((node) => { + return StyleSheet.flatten(node.props.style)?.backgroundColor === '#fffe00' + }) + expect(oldPaintRemains).toBe(false) + }) + it('draws dark ink when theme is dark inside a light provider', async () => { serveOnly('JHN.3.16', passageHtml(verseBlock(16, JOHN)), 'John 3:16') render(, { diff --git a/packages/ui/src/native/bible-reader-native.tsx b/packages/ui/src/native/bible-reader-native.tsx index f1bacd33..4254e206 100644 --- a/packages/ui/src/native/bible-reader-native.tsx +++ b/packages/ui/src/native/bible-reader-native.tsx @@ -151,6 +151,7 @@ export function BibleReaderNative(props: BibleReaderNativeProps): ReactNode { direction: versionDirection, ink, background, + isCurrent, }) // ---- Selection ---- diff --git a/packages/ui/src/native/bible-text-view-native.tsx b/packages/ui/src/native/bible-text-view-native.tsx index f6d67b3a..cad979e7 100644 --- a/packages/ui/src/native/bible-text-view-native.tsx +++ b/packages/ui/src/native/bible-text-view-native.tsx @@ -96,18 +96,23 @@ export function BibleTextViewNative({ ? { content: hostHtml.content, reference: hostHtml.reference } : null const load = usePassage(fetchBibleContent, versionId, address, supplied) + // Supplied mode never paints a retained fetch: the host owns passage, loading, and error. + const passage = suppliedMode && (hostHtml === null || address === null) ? null : load.passage + const currentKey = address === null ? null : passageKey(versionId, address) + const isCurrent = passage !== null && currentKey !== null && passage.key === currentKey // Intros load as passages but have no numeric chapter for paint. const highlights = useHighlightPaint(highlightScopeFor(reference, versionId)) const multiple = resolvedLineMultiple(lineHeight) // By the rendered passage's version: dimmed old text keeps its direction while the next loads. - const versionDirection = load.passage ? versionDirections?.get(load.passage.versionId) : undefined + const versionDirection = passage ? versionDirections?.get(passage.versionId) : undefined const { look, paint } = usePassageStyle({ - passage: load.passage, + passage, highlights, fontSize, lineMultiple: multiple, fontFamily, direction: scriptureDirection ?? versionDirection, + isCurrent, }) const selected = useMemo(() => new Set(selectedVerses ?? []), [selectedVerses]) const drawNotes = renderNotes && onFootnotePress !== undefined @@ -142,11 +147,7 @@ export function BibleTextViewNative({ Promise.resolve(now.onFootnotePress(footnoteFor(now.passage, verse, html))).catch(console.error) }, []) - // Supplied mode never paints a retained fetch: the host owns passage, loading, and error. - const passage = suppliedMode && (hostHtml === null || address === null) ? null : load.passage const hostLoading = suppliedMode && (passageState?.loading ?? false) - const currentKey = address === null ? null : passageKey(versionId, address) - const isCurrent = passage !== null && currentKey !== null && passage.key === currentKey let message: string | null = null let onRetry: (() => void) | null = null if (suppliedMode) { diff --git a/packages/ui/src/native/scripture/__tests__/passage-style.test.tsx b/packages/ui/src/native/scripture/__tests__/passage-style.test.tsx index 7cf68971..135ac745 100644 --- a/packages/ui/src/native/scripture/__tests__/passage-style.test.tsx +++ b/packages/ui/src/native/scripture/__tests__/passage-style.test.tsx @@ -1,11 +1,53 @@ +import type { AuthContextValue, Highlight } from '@youversion/platform-react-native-expo-core' import { renderHook } from '@testing-library/react-native' +import type { ComponentType, ReactNode } from 'react' import { INTER_FONT, UNTITLED_SERIF_FONT } from '../../../lib/reader-fonts' +import { YouVersionProvider } from '../../youversion-provider' +import { defaultHookOverrides, signedOutAuth } from '../../../test-utils/default-hook-overrides' import { youVersionProviderWrapper } from '../../../test-utils/youversion-provider-wrapper' import { usePassageStyle } from '../passage-style' +import { chapterRef, passageKey, type LoadedPassage } from '../use-passage' const wrapper = youVersionProviderWrapper() +const VERSION_ID = 3034 + +function samplePassage(chapter: string): LoadedPassage { + const ref = chapterRef('JHN', chapter) + return { + ...ref, + key: passageKey(VERSION_ID, ref), + versionId: VERSION_ID, + parsed: { blocks: [], verses: new Map(), rtl: false }, + reference: `John ${chapter}`, + } +} + +function authWrapper(initial: AuthContextValue) { + let current = initial + function Wrapper({ children }: { children: ReactNode }) { + return ( + + {children} + + ) + } + return { + Wrapper, + setAuth(next: AuthContextValue) { + current = next + }, + } +} + +const CHAPTER_THREE = samplePassage('3') +const JOHN_3_16 = [{ version_id: VERSION_ID, passage_id: 'JHN.3.16', color: 'fffe00' }] as const + describe('usePassageStyle host fontFamily', () => { it('styles host italics with fontStyle, not a suffixed family name', () => { const { result } = renderHook( @@ -117,3 +159,204 @@ describe('usePassageStyle host fontFamily', () => { expect(result.current.look.face(400, false).fontFamily).toBe('Untitled Serif') }) }) + +type RetentionProps = { + isCurrent: boolean + highlights: readonly Highlight[] + background?: string +} + +function renderRetention( + hookWrapper: ComponentType<{ children: ReactNode }> = wrapper, + initialProps: RetentionProps = { isCurrent: true, highlights: [...JOHN_3_16] }, +) { + return renderHook( + (props: RetentionProps) => + usePassageStyle({ + passage: CHAPTER_THREE, + highlights: props.highlights, + fontSize: 16, + lineMultiple: 1.5, + fontFamily: undefined, + background: props.background, + isCurrent: props.isCurrent, + }), + { wrapper: hookWrapper, initialProps }, + ) +} + +describe('usePassageStyle highlight retention', () => { + it('reuses retained server colors while the outgoing passage is dimmed', () => { + const { result, rerender } = renderRetention() + + expect(result.current.paint.get(16)?.background).toBe('#fffe00') + + rerender({ isCurrent: false, highlights: [] }) + + expect(result.current.paint.get(16)?.background).toBe('#fffe00') + }) + + it('clears paint immediately when highlights drop off the current passage', () => { + const { result, rerender } = renderRetention() + + expect(result.current.paint.size).toBe(1) + + rerender({ isCurrent: true, highlights: [] }) + + expect(result.current.paint.size).toBe(0) + }) + + it('keeps the outgoing chapter paint across multiple incoming highlight scopes while dimmed', () => { + const { result, rerender } = renderRetention() + + expect(result.current.paint.get(16)?.background).toBe('#fffe00') + + rerender({ + isCurrent: false, + highlights: [{ version_id: VERSION_ID, passage_id: 'JHN.4.1', color: '5dff79' }], + }) + rerender({ + isCurrent: false, + highlights: [{ version_id: VERSION_ID, passage_id: 'JHN.5.1', color: '00d6ff' }], + }) + + expect(result.current.paint.get(16)?.background).toBe('#fffe00') + }) + + it('re-derives highlight paint when the background changes on a dimmed passage in dark mode', () => { + const { result, rerender } = renderRetention(youVersionProviderWrapper('dark'), { + isCurrent: true, + background: '#111111', + highlights: [...JOHN_3_16], + }) + + const before = result.current.paint.get(16) + expect(before).toBeDefined() + + rerender({ isCurrent: false, highlights: [], background: '#333333' }) + const after = result.current.paint.get(16) + + expect(after).toBeDefined() + expect(after?.background).not.toBe(before?.background) + }) + + it('clears retained paint when the user signs out while a passage is dimmed', () => { + const auth = authWrapper( + signedOutAuth({ + isAuthenticated: true, + accessToken: 'token-1', + userInfo: { id: 'user-1' }, + }), + ) + + const { result, rerender } = renderRetention(auth.Wrapper) + + expect(result.current.paint.get(16)?.background).toBe('#fffe00') + + rerender({ isCurrent: false, highlights: [] }) + expect(result.current.paint.get(16)?.background).toBe('#fffe00') + + auth.setAuth(signedOutAuth()) + rerender({ isCurrent: false, highlights: [] }) + + expect(result.current.paint.size).toBe(0) + }) + + it('clears retained paint when the signed-in user switches while a passage is dimmed', () => { + const auth = authWrapper( + signedOutAuth({ + isAuthenticated: true, + accessToken: 'token-1', + userInfo: { id: 'user-1' }, + }), + ) + + const { result, rerender } = renderRetention(auth.Wrapper) + + rerender({ isCurrent: false, highlights: [] }) + expect(result.current.paint.get(16)?.background).toBe('#fffe00') + + auth.setAuth( + signedOutAuth({ + isAuthenticated: true, + accessToken: 'token-2', + userInfo: { id: 'user-2' }, + }), + ) + rerender({ isCurrent: false, highlights: [] }) + + expect(result.current.paint.size).toBe(0) + }) + + it('clears retained paint on sign-out even when userInfo.id is absent', () => { + const auth = authWrapper( + signedOutAuth({ + isAuthenticated: true, + accessToken: 'token-1', + userInfo: null, + }), + ) + + const { result, rerender } = renderRetention(auth.Wrapper) + + rerender({ isCurrent: false, highlights: [] }) + expect(result.current.paint.get(16)?.background).toBe('#fffe00') + + auth.setAuth(signedOutAuth()) + rerender({ isCurrent: false, highlights: [] }) + + expect(result.current.paint.size).toBe(0) + }) + + it('does not resurrect retained paint if the same user signs back in while dimmed', () => { + const signedIn = signedOutAuth({ + isAuthenticated: true, + accessToken: 'token-1', + userInfo: { id: 'user-1' }, + }) + const auth = authWrapper(signedIn) + + const { result, rerender } = renderRetention(auth.Wrapper) + + rerender({ isCurrent: false, highlights: [] }) + expect(result.current.paint.get(16)?.background).toBe('#fffe00') + + auth.setAuth(signedOutAuth()) + rerender({ isCurrent: false, highlights: [] }) + expect(result.current.paint.size).toBe(0) + + auth.setAuth(signedIn) + rerender({ isCurrent: false, highlights: [] }) + expect(result.current.paint.size).toBe(0) + }) + + it('clears dimmed cold-start cached paint on bootstrap teardown and keeps it when tokens settle', () => { + const coldStart = signedOutAuth({ + isAuthenticated: false, + isLoading: true, + userInfo: { id: 'user-1' }, + }) + + const teardownAuth = authWrapper(coldStart) + const teardown = renderRetention(teardownAuth.Wrapper) + teardown.rerender({ isCurrent: false, highlights: [] }) + expect(teardown.result.current.paint.get(16)?.background).toBe('#fffe00') + teardownAuth.setAuth(signedOutAuth()) + teardown.rerender({ isCurrent: false, highlights: [] }) + expect(teardown.result.current.paint.size).toBe(0) + + const settleAuth = authWrapper(coldStart) + const settle = renderRetention(settleAuth.Wrapper) + settle.rerender({ isCurrent: false, highlights: [] }) + settleAuth.setAuth( + signedOutAuth({ + isAuthenticated: true, + isLoading: false, + accessToken: 'token-1', + userInfo: { id: 'user-1' }, + }), + ) + settle.rerender({ isCurrent: false, highlights: [] }) + expect(settle.result.current.paint.get(16)?.background).toBe('#fffe00') + }) +}) diff --git a/packages/ui/src/native/scripture/passage-style.ts b/packages/ui/src/native/scripture/passage-style.ts index 050eb9d8..cc108048 100644 --- a/packages/ui/src/native/scripture/passage-style.ts +++ b/packages/ui/src/native/scripture/passage-style.ts @@ -1,5 +1,10 @@ -import { deriveServerColors, type Highlight } from '@youversion/platform-react-native-expo-core' -import { useMemo } from 'react' +import { + deriveServerColors, + useYVAuthOptional, + type Highlight, + type ServerColors, +} from '@youversion/platform-react-native-expo-core' +import { useMemo, useState } from 'react' import { useTheme } from '../../hooks/use-theme' import { useTokens } from '../../hooks/use-tokens' @@ -71,6 +76,36 @@ export type PassageStyleInput = { ink?: string /** `#rrggbb` under the text. Highlight covers paint it. Defaults to the scheme's background. */ background?: string + /** False while an outgoing passage stays on screen during navigation. Default true. */ + isCurrent?: boolean +} + +function sameColors(a: ServerColors, b: ServerColors): boolean { + if (a === b) { + return true + } + const aKeys = Object.keys(a) + if (aKeys.length !== Object.keys(b).length) { + return false + } + for (const key of aKeys) { + const verse = Number(key) + if (a[verse] !== b[verse]) { + return false + } + } + return true +} + +function authIdentityKey(auth: ReturnType): string { + if (auth === null) { + return '' + } + const userId = auth.userInfo?.id ?? null + if (userId !== null) { + return `user:${userId}` + } + return auth.isAuthenticated ? 'auth-anonymous' : 'signed-out' } export type PassageStyle = { @@ -89,6 +124,7 @@ export function usePassageStyle({ direction, ink: inkOverride, background: backgroundOverride, + isCurrent = true, }: PassageStyleInput): PassageStyle { const theme = useTheme() const tokens = useTokens() @@ -130,18 +166,51 @@ export function usePassageStyle({ [fontSize, lineMultiple, rtl, isSans, hostFamily, tokens, serifFaceFor, ink, background], ) - // Scoped to the rendered passage: the old one stays up while the next one loads. - const paint = useMemo(() => { - if (passage === null) { - return new Map() + const authKey = authIdentityKey(useYVAuthOptional()) + + const liveColors = useMemo((): ServerColors | null => { + if (passage === null || !isCurrent) { + return null } - const colors = deriveServerColors(Array.isArray(highlights) ? highlights : [], { + return deriveServerColors(Array.isArray(highlights) ? highlights : [], { versionId: passage.versionId, book: passage.book, chapter: passage.chapter, }) - const byColor = new Map() + }, [highlights, isCurrent, passage]) + + const [retained, setRetained] = useState<{ + key: string + authKey: string + colors: ServerColors + } | null>(null) + const retainedMatchesPassage = + passage !== null && + retained !== null && + retained.key === passage.key && + retained.authKey === authKey + const retainedMatchesLive = + retainedMatchesPassage && liveColors !== null && sameColors(retained.colors, liveColors) + if (passage !== null && liveColors !== null && !retainedMatchesLive) { + setRetained({ key: passage.key, authKey, colors: liveColors }) + } else if (retained !== null && retained.authKey !== authKey) { + setRetained(null) + } + + let colors: ServerColors | null = null + if (liveColors !== null) { + colors = retainedMatchesLive ? retained.colors : liveColors + } else if (retainedMatchesPassage) { + colors = retained.colors + } + + // Scoped to the rendered passage: the old one stays up while the next one loads. + const paint = useMemo(() => { const map = new Map() + if (colors === null) { + return map + } + const byColor = new Map() for (const [verse, color] of Object.entries(colors)) { const fill = byColor.get(color) ?? highlightPaint(color, theme, background, tokens.primaryForeground) @@ -149,7 +218,7 @@ export function usePassageStyle({ map.set(Number(verse), fill) } return map - }, [highlights, passage, theme, background, tokens.primaryForeground]) + }, [background, colors, theme, tokens.primaryForeground]) return { look, paint } }