diff --git a/src/hooks/__tests__/useMarkdown.spec.tsx b/src/hooks/__tests__/useMarkdown.spec.tsx new file mode 100644 index 00000000..e8f23948 --- /dev/null +++ b/src/hooks/__tests__/useMarkdown.spec.tsx @@ -0,0 +1,270 @@ +import { render, screen } from "@testing-library/react-native"; +import type { ReactNode } from "react"; +import React from "react"; +import { type ColorSchemeName, View } from "react-native"; +import type { MarkedStyles, UserTheme } from "../../theme/types"; +import useMarkdown, { areHookOptionsEqual } from "../useMarkdown"; + +const twoParagraphs = "First paragraph.\n\nSecond paragraph."; + +interface HarnessProps { + value: string; + collector: ReactNode[][]; + styles?: MarkedStyles; + theme?: UserTheme; + colorScheme?: ColorSchemeName; +} + +/** + * Renders via the hook and records the element array reference on every + * React render, so memos can be asserted on by identity (===). + */ +const MarkdownHarness = ({ + value, + collector, + styles, + theme, + colorScheme, +}: HarnessProps) => { + const elements = useMarkdown(value, { styles, theme, colorScheme }); + collector.push(elements); + return {elements}; +}; + +describe("useMarkdown", () => { + it("does not re-parse when the parent re-renders with constant value", async () => { + const collector: ReactNode[][] = []; + const { rerender } = await render( + , + ); + await rerender( + , + ); + + expect(collector.length).toBe(2); + expect(collector[0]).toBe(collector[1]); + }); + + it("keeps identities when options are inline object literals", async () => { + const collector: ReactNode[][] = []; + const inlineOptions = ( + props: { value: string } & { collector: ReactNode[][] }, + ) => ( + + ); + const { rerender } = await render( + inlineOptions({ value: twoParagraphs, collector }), + ); + await rerender(inlineOptions({ value: twoParagraphs, collector })); + + expect(collector.length).toBe(2); + expect(collector[0]).toBe(collector[1]); + }); + + it("re-parses when style content actually changes", async () => { + const collector: ReactNode[][] = []; + const { rerender } = await render( + , + ); + await rerender( + , + ); + + expect(collector.length).toBe(2); + expect(collector[0]).not.toBe(collector[1]); + }); + + it("reuses unchanged elements when value grows (streaming)", async () => { + const collector: ReactNode[][] = []; + const { rerender } = await render( + , + ); + await rerender( + , + ); + + expect(collector.length).toBe(2); + const initial = collector[0]; + const grown = collector[1]; + if (!initial || !grown) throw new Error("Both renders must be captured"); + + expect(grown.length).toBe(initial.length + 1); + for (let i = 0; i < initial.length; i++) { + expect(grown[i]).toBe(initial[i]); + } + }); + + it("reuses elements after adding a token before unchanged ones", async () => { + const collector: ReactNode[][] = []; + const { rerender } = await render( + , + ); + await rerender( + , + ); + + expect(collector.length).toBe(2); + const initial = collector[0]; + const grown = collector[1]; + if (!initial || !grown) throw new Error("Both renders must be captured"); + // The unchanged paragraphs keep their already rendered instances. + for (const element of initial) { + expect(grown).toContain(element); + } + }); + + it("re-parses when colorScheme changes", async () => { + const collector: ReactNode[][] = []; + const { rerender } = await render( + , + ); + await rerender( + , + ); + + expect(collector.length).toBe(2); + const initial = collector[0]; + const grown = collector[1]; + if (!initial || !grown) throw new Error("Both renders must be captured"); + + expect(grown).not.toBe(initial); + // Theme flip rebuilds styles + parser, so nothing is reused. + for (const element of initial) { + expect(grown).not.toContain(element); + } + }); + + it("renders identical top-level tokens with distinct keys", async () => { + const collector: ReactNode[][] = []; + await render( + , + ); + + const elements = collector[0] ?? []; + const keys = elements.map((element) => + React.isValidElement(element) ? element.key : undefined, + ); + expect(keys.length).toBe(2); + // Content-identical tokens must not deduplicate into one keyed element. + expect(new Set(keys).size).toBe(keys.length); + }); + + it("reuses the first instance when a duplicate token is added", async () => { + const collector: ReactNode[][] = []; + const { rerender } = await render( + , + ); + await rerender( + , + ); + + expect(collector.length).toBe(2); + const initial = collector[0]; + const grown = collector[1]; + if (!initial || !grown) throw new Error("Both renders must be captured"); + + // The original copy comes from cache; the duplicate is a fresh parse. + expect(grown[0]).toBe(initial[0]); + const keys = grown.map((element) => + React.isValidElement(element) ? element.key : undefined, + ); + expect(new Set(keys).size).toBe(keys.length); + }); + + it("renders all markdown content", async () => { + await render(); + expect(screen.queryByText("First paragraph.")).toBeTruthy(); + expect(screen.queryByText("Second paragraph.")).toBeTruthy(); + }); +}); + +describe("areHookOptionsEqual", () => { + it("treats inline theme/styles literals with equal content as equal", () => { + expect( + areHookOptionsEqual( + { + theme: { + colors: { + text: "#123456", + code: "#f6f8fa", + link: "#58a6ff", + border: "#d0d7de", + }, + }, + styles: { paragraph: { marginTop: 2 } }, + }, + { + theme: { + colors: { + text: "#123456", + code: "#f6f8fa", + link: "#58a6ff", + border: "#d0d7de", + }, + }, + styles: { paragraph: { marginTop: 2 } }, + }, + ), + ).toBe(true); + }); + + it("treats differently styled content as unequal", () => { + expect( + areHookOptionsEqual( + { styles: { paragraph: { marginTop: 2 } } }, + { styles: { paragraph: { marginTop: 4 } } }, + ), + ).toBe(false); + }); + + it("treats a colorScheme change as unequal", () => { + expect( + areHookOptionsEqual({ colorScheme: "light" }, { colorScheme: "dark" }), + ).toBe(false); + expect( + areHookOptionsEqual({ colorScheme: "dark" }, { colorScheme: "dark" }), + ).toBe(true); + }); + + it("requires the same renderer instance", () => { + const renderer = { paragraph: () => null } as never; + expect(areHookOptionsEqual({ renderer }, { renderer })).toBe(true); + expect(areHookOptionsEqual({ renderer }, { renderer: {} as never })).toBe( + false, + ); + }); +}); diff --git a/src/hooks/useMarkdown.ts b/src/hooks/useMarkdown.ts index 2b39c953..6f305eed 100644 --- a/src/hooks/useMarkdown.ts +++ b/src/hooks/useMarkdown.ts @@ -1,11 +1,14 @@ import { type Hooks, lexer, type Tokenizer } from "marked"; -import { type ReactNode, useMemo } from "react"; +import { type ReactNode, useMemo, useRef } from "react"; import type { ColorSchemeName } from "react-native"; import Parser from "../lib/Parser"; import Renderer from "../lib/Renderer"; import type { RendererInterface } from "../lib/types"; import getStyles from "./../theme/styles"; import type { MarkedStyles, UserTheme } from "./../theme/types"; +import isEqual from "./../utils/isEqual"; +import { assignStableKeys, getStableKeyOf } from "./../utils/stableKeys"; +import useStableValue from "./useStableValue"; export interface useMarkdownHookOptions { colorScheme?: ColorSchemeName; @@ -20,35 +23,125 @@ export interface useMarkdownHookOptions { selectable?: boolean; } +/** + * Equality check for hook options: class/hook instances (`renderer`, + * `tokenizer`, `hooks`) compare by reference, primitives (`baseUrl`, + * `colorScheme`, `selectable`) by value, style/theme objects structurally. + * Lets consumers pass inline `styles={{...}}`/`theme={{...}}` object literals + * without invalidating the parse on every render. + */ +export const areHookOptionsEqual = ( + previous?: useMarkdownHookOptions, + next?: useMarkdownHookOptions, +): boolean => { + if (previous === next) return true; + if (!previous || !next) return false; + return ( + previous.renderer === next.renderer && + previous.tokenizer === next.tokenizer && + previous.hooks === next.hooks && + previous.baseUrl === next.baseUrl && + previous.colorScheme === next.colorScheme && + previous.selectable === next.selectable && + isEqual(previous.theme, next.theme) && + isEqual(previous.styles, next.styles) + ); +}; + +/** + * Parsed-element cache for top-level tokens. + * + * Reuses previously parsed subtrees when their token content is unchanged, + * keeping element (and every wrapped component) identities stable during + * streaming updates so unchanged list items skip re-rendering. + */ +interface ElementsCache { + /** Cache only holds entries parsed by this exact parser instance. */ + epoch: Parser; + /** contentKey (occurrence-suffixed stable key + JSON) → parsed ReactNode[]. */ + entries: Map; +} + const useMarkdown = ( value: string, options?: useMarkdownHookOptions, ): ReactNode[] => { + const stableOptions = useStableValue(options, areHookOptionsEqual); + const { + styles: userStyles, + theme, + colorScheme, + baseUrl, + renderer, + selectable, + tokenizer, + hooks, + } = stableOptions ?? {}; + const styles = useMemo( - () => getStyles(options?.styles, options?.colorScheme, options?.theme), - [options?.styles, options?.theme, options?.colorScheme], + () => getStyles(userStyles, colorScheme, theme), + [userStyles, colorScheme, theme], ); const parser = useMemo( () => new Parser({ styles: styles, - baseUrl: options?.baseUrl, - renderer: - options?.renderer ?? - new Renderer({ selectable: options?.selectable }), + baseUrl: baseUrl, + renderer: renderer ?? new Renderer({ selectable: selectable }), }), - [options?.renderer, options?.baseUrl, styles, options?.selectable], + [renderer, baseUrl, styles, selectable], ); + const cacheRef = useRef(undefined); + const elements = useMemo(() => { const tokens = lexer(value, { gfm: true, - tokenizer: options?.tokenizer, - hooks: options?.hooks, + tokenizer: tokenizer, + hooks: hooks, }); - return parser.parse(tokens); - }, [value, parser, options?.tokenizer, options?.hooks]); + + /* + * Content-derived keys are assigned before parsing so that React keys + * stay identical across re-parses; unchanged tokens reconcile instead + * of remounting (no image refetches, no lost per-element state). + */ + assignStableKeys(tokens); + + /* Start a fresh cache for a new parser, keep hits from the previous. */ + const previousCache: ElementsCache | undefined = cacheRef.current; + const entries: Map = new Map(); + + const elements: ReactNode[] = []; + for (const token of tokens) { + /* + * The occurrence-suffixed stable key separates content-identical + * tokens; without it a plain JSON key would deduplicate them into a + * single cached element, duplicating sibling React keys. + */ + const stableKey = getStableKeyOf(token); + const contentKey = stableKey + ? `${stableKey}\u0000${JSON.stringify(token)}` + : JSON.stringify(token); + const cached = + previousCache?.epoch === parser + ? previousCache.entries.get(contentKey) + : undefined; + if (cached) { + entries.set(contentKey, cached); + elements.push(...cached); + continue; + } + /* One token at a time keeps releases localized, plus cache keys. */ + const parsed = parser.parse([token]); + entries.set(contentKey, parsed); + elements.push(...parsed); + } + + cacheRef.current = { epoch: parser, entries: entries }; + return elements; + }, [value, parser, tokenizer, hooks]); return elements; }; diff --git a/src/hooks/useMarkdownWithComponents.tsx b/src/hooks/useMarkdownWithComponents.tsx index 62c19cf7..9b65c6be 100644 --- a/src/hooks/useMarkdownWithComponents.tsx +++ b/src/hooks/useMarkdownWithComponents.tsx @@ -8,47 +8,46 @@ import { } from "../lib/ReactComponentTokenizer"; import Renderer from "../lib/Renderer"; import type { RendererInterface } from "../lib/types"; +import { getStableKeyOf } from "../utils/stableKeys"; import type { useMarkdownHookOptions } from "./useMarkdown"; -import useMarkdown from "./useMarkdown"; +import useMarkdown, { areHookOptionsEqual } from "./useMarkdown"; +import useStableValue from "./useStableValue"; export interface useMarkdownWithComponentsOptions extends Omit {} -interface ComponentData { - token: ReactComponentToken; - id: string; -} - export function useMarkdownWithComponents( value: string, options?: useMarkdownWithComponentsOptions, ): ReactNode[] { const registry = useReactComponentRegistry(); - const { tokenizer, componentMap } = useMemo(() => { - const map = new Map(); + /* Stable options snapshot: inline `renderer`/`styles` object literals must + * not invalidate the base renderer (and with it the whole parse). */ + const stableOptions = useStableValue(options, areHookOptionsEqual); + + const { tokenizer, tokenDataMap } = useMemo(() => { + const map = new Map(); const customTokenizer = new ReactComponentTokenizer(); const originalHtml = customTokenizer.html.bind(customTokenizer); - let componentCounter = 0; - customTokenizer.html = (src: string) => { const token = originalHtml(src); if (token && isReactComponentToken(token)) { - const id = `${token.componentName}-${componentCounter++}`; - map.set(token.raw, { token, id }); + map.set(token.raw, token); } return token; }; - return { tokenizer: customTokenizer, componentMap: map }; + return { tokenizer: customTokenizer, tokenDataMap: map }; }, []); - const baseRenderer = useMemo( + const baseRenderer = useMemo( () => - options?.renderer ?? new Renderer({ selectable: options?.selectable }), - [options?.renderer, options?.selectable], + (stableOptions?.renderer as Renderer) ?? + new Renderer({ selectable: stableOptions?.selectable }), + [stableOptions?.renderer, stableOptions?.selectable], ); const renderer = useMemo(() => { @@ -58,16 +57,24 @@ export function useMarkdownWithComponents( // consistent. If Renderer ever uses #private fields this pattern will need revisiting. const wrappedRenderer = Object.create(baseRenderer) as typeof baseRenderer; - wrappedRenderer.html = (text: string | ReactNode[], styles): ReactNode => { + wrappedRenderer.html = (text, styles, token): ReactNode => { if (typeof text === "string") { - const data = componentMap.get(text); + const data = tokenDataMap.get(text); if (data) { - if (registry?.hasComponent(data.token.componentName)) { - const Component = registry.getComponent(data.token.componentName); + if (registry?.hasComponent(data.componentName)) { + const Component = registry.getComponent(data.componentName); if (Component) { + /* + * Key from the assigned stable token key, so component + * instances keep their identity (and internal state) + * across re-parses and streaming updates. + */ return ( - - {data.token.componentChildren || undefined} + + {data.componentChildren || undefined} ); } @@ -76,14 +83,14 @@ export function useMarkdownWithComponents( } } - return baseRenderer.html(text, styles); + return baseRenderer.html(text, styles, token); }; return wrappedRenderer; - }, [baseRenderer, componentMap, registry]); + }, [baseRenderer, tokenDataMap, registry]); const elements = useMarkdown(value, { - ...options, + ...stableOptions, tokenizer, renderer, }); diff --git a/src/hooks/useStableValue.ts b/src/hooks/useStableValue.ts new file mode 100644 index 00000000..63c59a04 --- /dev/null +++ b/src/hooks/useStableValue.ts @@ -0,0 +1,35 @@ +import { useRef } from "react"; +import isEqual from "./../utils/isEqual"; + +/** + * Comparator over two values. Returning `true` keeps the previous reference. + */ +type EqualityCheck = (previous: T, next: T) => boolean; + +/** + * Returns a reference-stable version of `value`. + * + * While the comparator (structural equality by default) reports no change, + * the previously stored reference is returned so that `useMemo` dependency + * chains do not collapse when consumers pass inline object literals, e.g. + * `styles={{...}}` or `theme={{...}}` in JSX. + * + * Content grows are observed through the comparator; mutation-only updates + * are intentionally not (same semantics as current memo dependencies). + */ +export function useStableValue(value: T, comparator?: EqualityCheck): T { + const areEqual = comparator ?? isEqual; + const stored = useRef(value); + const hasStored = useRef(false); + + if (!hasStored.current) { + hasStored.current = true; + stored.current = value; + } else if (!areEqual(stored.current, value)) { + stored.current = value; + } + + return stored.current; +} + +export default useStableValue; diff --git a/src/lib/Markdown.tsx b/src/lib/Markdown.tsx index 9d895e3a..af41c183 100644 --- a/src/lib/Markdown.tsx +++ b/src/lib/Markdown.tsx @@ -1,8 +1,24 @@ -import React, { type ReactElement, type ReactNode, useCallback } from "react"; +import React, { + memo, + type ReactElement, + type ReactNode, + useCallback, +} from "react"; import { FlatList, useColorScheme } from "react-native"; import useMarkdown from "../hooks/useMarkdown"; import type { MarkdownProps } from "./types"; +/** + * FlatList cell renderer for a single top-level markdown element. + * + * Memoized: `useMarkdown` reuses element instances whose tokens are unchanged + * (see its element cache), so all unchanged items skip re-rendering on every + * streaming update instead of re-rendering the whole visible list. + */ +const MarkdownItem = memo(({ node }: { node: ReactNode }) => { + return node as ReactElement; +}); + const Markdown = ({ value, flatListProps, @@ -28,13 +44,18 @@ const Markdown = ({ }); const renderItem = useCallback(({ item }: { item: ReactNode }) => { - return item as ReactElement; + return ; }, []); - const keyExtractor = useCallback( - (_: ReactNode, index: number) => index.toString(), - [], - ); + const keyExtractor = useCallback((item: ReactNode, index: number) => { + /* Top-level elements carry stable, content-derived keys; prefer them + * so insertions above the viewport don't shift every cell. Nulls + * (e.g. separators) and foreign nodes fall back to the index. */ + if (React.isValidElement(item) && item.key !== null) { + return String(item.key); + } + return index.toString(); + }, []); return ( @@ -230,6 +265,7 @@ class Parser { this.styles.table, this.styles.tableRow, this.styles.tableCell, + token, ); } default: { @@ -276,6 +312,7 @@ class Parser { imageToken.text ?? imageToken.title ?? "", this.styles.image, imageToken.title, + t, ), ); } diff --git a/src/lib/ReactComponentRegistry.tsx b/src/lib/ReactComponentRegistry.tsx index 3a6d9c80..84ed3785 100644 --- a/src/lib/ReactComponentRegistry.tsx +++ b/src/lib/ReactComponentRegistry.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from "react"; import React, { createContext, useContext, useMemo } from "react"; +import { useStableValue } from "./../hooks/useStableValue"; import type { ReactComponentProps } from "./ReactComponentTokenizer"; export interface ReactComponentRendererProps { @@ -31,13 +32,17 @@ export function ReactComponentRegistryProvider({ components, children, }: ReactComponentRegistryProviderProps) { + /* Stable reference for inline `components={{...}}` object literals, so + * context consumers do not invalidate their parse on every render. */ + const stableComponents = useStableValue(components); + const contextValue = useMemo( () => ({ - components, - getComponent: (name: string) => components[name], - hasComponent: (name: string) => name in components, + components: stableComponents, + getComponent: (name: string) => stableComponents[name], + hasComponent: (name: string) => name in stableComponents, }), - [components], + [stableComponents], ); return ( diff --git a/src/lib/Renderer.tsx b/src/lib/Renderer.tsx index f89a1d1a..dd387432 100644 --- a/src/lib/Renderer.tsx +++ b/src/lib/Renderer.tsx @@ -1,4 +1,5 @@ import Slugger from "github-slugger"; +import type { Token } from "marked"; import React, { type ReactNode } from "react"; import { Dimensions, @@ -15,6 +16,8 @@ import MDList from "./../components/MDList"; import MDSvg from "./../components/MDSvg"; import MDTable from "./../components/MDTable"; import { onLinkPress } from "../utils/handlers"; +import hashString from "./../utils/hash"; +import { getStableKeyOf } from "./../utils/stableKeys"; import { getTableWidthArr } from "../utils/table"; import type { RendererInterface } from "./types"; @@ -26,6 +29,7 @@ export interface RendererOptions { } class Renderer implements RendererInterface { + /** Prefix for fallback keys of tokens without pre-assigned stable keys. */ private slugPrefix = "react-native-marked-ele"; private slugger: Slugger; private windowWidth: number; @@ -37,16 +41,29 @@ class Renderer implements RendererInterface { this.selectable = options?.selectable ?? true; } - paragraph(children: ReactNode[], styles?: ViewStyle): ReactNode { - return this.getViewNode(children, styles); + paragraph( + children: ReactNode[], + styles?: ViewStyle, + token?: Token, + ): ReactNode { + return this.getViewNode(children, styles, token); } - blockquote(children: ReactNode[], styles?: ViewStyle): ReactNode { - return this.getBlockquoteNode(children, styles); + blockquote( + children: ReactNode[], + styles?: ViewStyle, + token?: Token, + ): ReactNode { + return this.getBlockquoteNode(children, styles, token); } - heading(text: string | ReactNode[], styles?: TextStyle): ReactNode { - return this.getTextNode(text, styles); + heading( + text: string | ReactNode[], + styles?: TextStyle, + _depth?: number, + token?: Token, + ): ReactNode { + return this.getTextNode(text, styles, token); } code( @@ -54,11 +71,12 @@ class Renderer implements RendererInterface { _language?: string, containerStyle?: ViewStyle, textStyle?: TextStyle, + token?: Token, ): ReactNode { return ( {/* @@ -66,17 +84,21 @@ class Renderer implements RendererInterface { Error: Cannot add a child that doesn't have a YogaNode to a parent without a measure function! ref: https://github.com/facebook/react-native/issues/18773 */} - {this.getTextNode(text, textStyle)} + {this.getTextNode(text, textStyle, token)} ); } - hr(styles?: ViewStyle): ReactNode { - return this.getViewNode(null, styles); + hr(styles?: ViewStyle, token?: Token): ReactNode { + return this.getViewNode(null, styles, token); } - listItem(children: ReactNode[], styles?: ViewStyle): ReactNode { - return this.getViewNode(children, styles); + listItem( + children: ReactNode[], + styles?: ViewStyle, + token?: Token, + ): ReactNode { + return this.getViewNode(children, styles, token); } list( @@ -85,10 +107,11 @@ class Renderer implements RendererInterface { listStyle?: ViewStyle, textStyle?: TextStyle, startIndex?: number, + token?: Token, ): ReactNode { return ( @@ -128,40 +152,61 @@ class Renderer implements RendererInterface { alt?: string, style?: ImageStyle, title?: string, + token?: Token, ): ReactNode { - const key = this.getKey(); + const key = this.getKey(token); if (/\.svg$/i.test(uri.replace(/[?#].*/, ""))) { return ; } return ; } - strong(children: string | ReactNode[], styles?: TextStyle): ReactNode { - return this.getTextNode(children, styles); + strong( + children: string | ReactNode[], + styles?: TextStyle, + token?: Token, + ): ReactNode { + return this.getTextNode(children, styles, token); } - em(children: string | ReactNode[], styles?: TextStyle): ReactNode { - return this.getTextNode(children, styles); + em( + children: string | ReactNode[], + styles?: TextStyle, + token?: Token, + ): ReactNode { + return this.getTextNode(children, styles, token); } - codespan(text: string, styles?: TextStyle): ReactNode { - return this.getTextNode(text, styles); + codespan(text: string, styles?: TextStyle, token?: Token): ReactNode { + return this.getTextNode(text, styles, token); } - br(): ReactNode { - return this.getTextNode("\n", {}); + br(token?: Token): ReactNode { + return this.getTextNode("\n", {}, token); } - del(children: string | ReactNode[], styles?: TextStyle): ReactNode { - return this.getTextNode(children, styles); + del( + children: string | ReactNode[], + styles?: TextStyle, + token?: Token, + ): ReactNode { + return this.getTextNode(children, styles, token); } - text(text: string | ReactNode[], styles?: TextStyle): ReactNode { - return this.getTextNode(text, styles); + text( + text: string | ReactNode[], + styles?: TextStyle, + token?: Token, + ): ReactNode { + return this.getTextNode(text, styles, token); } - html(text: string | ReactNode[], styles?: TextStyle): ReactNode { - return this.getTextNode(text, styles); + html( + text: string | ReactNode[], + styles?: TextStyle, + token?: Token, + ): ReactNode { + return this.getTextNode(text, styles, token); } linkImage( @@ -169,15 +214,22 @@ class Renderer implements RendererInterface { imageUrl: string, alt?: string, style?: ImageStyle, - title?: string, + title?: string | null, + token?: Token, ): ReactNode { - const imageNode = this.image(imageUrl, alt, style, title); + const imageNode = this.image( + imageUrl, + alt, + style, + title ?? undefined, + token, + ); return ( {imageNode} @@ -190,12 +242,13 @@ class Renderer implements RendererInterface { tableStyle?: ViewStyle, rowStyle?: ViewStyle, cellStyle?: ViewStyle, + token?: Token, ): React.ReactNode { const widthArr = getTableWidthArr(header.length, this.windowWidth); const { borderWidth, borderColor } = tableStyle || {}; return ( 0 + ) { + childKeys = childKeys.concat(child.key, ","); + } + } + return childKeys ? hashString(childKeys).toString() : ""; + } + private getTextNode( children: string | ReactNode[], styles?: TextStyle, + token?: Token, ): ReactNode { return ( - + {children} ); @@ -225,9 +321,10 @@ class Renderer implements RendererInterface { private getViewNode( children: ReactNode[] | null, styles?: ViewStyle, + token?: Token, ): ReactNode { return ( - + {children} ); @@ -236,9 +333,10 @@ class Renderer implements RendererInterface { private getBlockquoteNode( children: ReactNode[], styles?: ViewStyle, + token?: Token, ): ReactNode { return ( - + {children} ); diff --git a/src/lib/types.ts b/src/lib/types.ts index 5c217b2c..c918c745 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -1,4 +1,4 @@ -import type { Hooks, Tokenizer } from "marked"; +import type { Hooks, Token, Tokenizer } from "marked"; import type { ReactNode } from "react"; import type { FlatListProps, @@ -33,55 +33,93 @@ export interface MarkdownProps extends Partial { export type TableColAlignment = "center" | "left" | "right" | null; +/** + * Optional trailing `token` parameter: when present (default flow), renderers + * can derive stable, content-based React keys from it via `Renderer.getKey(token)`. + */ export interface RendererInterface { - paragraph(children: ReactNode[], styles?: ViewStyle): ReactNode; - blockquote(children: ReactNode[], styles?: ViewStyle): ReactNode; + paragraph( + children: ReactNode[], + styles?: ViewStyle, + token?: Token, + ): ReactNode; + blockquote( + children: ReactNode[], + styles?: ViewStyle, + token?: Token, + ): ReactNode; heading( text: string | ReactNode[], styles?: TextStyle, depth?: number, + token?: Token, ): ReactNode; code( text: string, language?: string, containerStyle?: ViewStyle, textStyle?: TextStyle, + token?: Token, ): ReactNode; - hr(styles?: ViewStyle): ReactNode; - listItem(children: ReactNode[], styles?: ViewStyle): ReactNode; + hr(styles?: ViewStyle, token?: Token): ReactNode; + listItem(children: ReactNode[], styles?: ViewStyle, token?: Token): ReactNode; list( ordered: boolean, li: ReactNode[], listStyle?: ViewStyle, textStyle?: TextStyle, startIndex?: number, + token?: Token, ): ReactNode; - escape(text: string, styles?: TextStyle): ReactNode; + escape(text: string, styles?: TextStyle, token?: Token): ReactNode; link( children: string | ReactNode[], href: string, styles?: TextStyle, title?: string, + token?: Token, ): ReactNode; image( uri: string, alt?: string, style?: ImageStyle, title?: string, + token?: Token, + ): ReactNode; + strong( + children: string | ReactNode[], + styles?: TextStyle, + token?: Token, + ): ReactNode; + em( + children: string | ReactNode[], + styles?: TextStyle, + token?: Token, + ): ReactNode; + codespan(text: string, styles?: TextStyle, token?: Token): ReactNode; + br(token?: Token): ReactNode; + del( + children: string | ReactNode[], + styles?: TextStyle, + token?: Token, + ): ReactNode; + text( + text: string | ReactNode[], + styles?: TextStyle, + token?: Token, + ): ReactNode; + html( + text: string | ReactNode[], + styles?: TextStyle, + token?: Token, ): ReactNode; - strong(children: string | ReactNode[], styles?: TextStyle): ReactNode; - em(children: string | ReactNode[], styles?: TextStyle): ReactNode; - codespan(text: string, styles?: TextStyle): ReactNode; - br(): ReactNode; - del(children: string | ReactNode[], styles?: TextStyle): ReactNode; - text(text: string | ReactNode[], styles?: TextStyle): ReactNode; - html(text: string | ReactNode[], styles?: TextStyle): ReactNode; linkImage( href: string, imageUrl: string, alt?: string, style?: ImageStyle, title?: string | null, + token?: Token, ): ReactNode; table( header: ReactNode[][], @@ -89,5 +127,6 @@ export interface RendererInterface { tableStyle?: ViewStyle, rowStyle?: ViewStyle, cellStyle?: ViewStyle, + token?: Token, ): ReactNode; } diff --git a/src/utils/__tests__/isEqual.spec.ts b/src/utils/__tests__/isEqual.spec.ts new file mode 100644 index 00000000..a9c31aad --- /dev/null +++ b/src/utils/__tests__/isEqual.spec.ts @@ -0,0 +1,52 @@ +import isEqual from "../isEqual"; + +describe("isEqual", () => { + it("matches identical references and primitives", () => { + const obj = { a: 1 }; + expect(isEqual(obj, obj)).toBe(true); + expect(isEqual(1, 1)).toBe(true); + expect(isEqual("x", "x")).toBe(true); + expect(isEqual(null, null)).toBe(true); + }); + + it("rejects different primitives", () => { + expect(isEqual(1, 2)).toBe(false); + expect(isEqual("x", "y")).toBe(false); + expect(isEqual(1, "1")).toBe(false); + expect(isEqual(null, 1)).toBe(false); + }); + + it("compares arrays element-wise", () => { + expect(isEqual([1, { a: 2 }], [1, { a: 2 }])).toBe(true); + expect(isEqual([1, 2], [2, 1])).toBe(false); + expect(isEqual([1], [1, 2])).toBe(false); + expect(isEqual([1], "not-array")).toBe(false); + }); + + it("compares plain objects unordered by key list", () => { + expect(isEqual({ a: 1, b: 2 }, { b: 2, a: 1 })).toBe(true); + expect(isEqual({ a: 1 }, { a: 1, b: 2 })).toBe(false); + expect(isEqual({ a: 1 }, { b: 1 })).toBe(false); + }); + + it("compares nested structures", () => { + expect( + isEqual({ list: [1, { deep: "x" }] }, { list: [1, { deep: "x" }] }), + ).toBe(true); + }); + + it("falls back to reference equality for non-plain objects", () => { + const map = new Map(); + expect(isEqual(map, new Map())).toBe(false); + expect(isEqual(map, map)).toBe(true); + expect(isEqual(new Date(), new Date(0))).toBe(false); + }); + + it("treats functions by reference", () => { + const f = () => "x"; + const g = () => "x"; + expect(isEqual(f, f)).toBe(true); + expect(isEqual({ fn: f }, { fn: f })).toBe(true); + expect(isEqual({ fn: f }, { fn: g })).toBe(false); + }); +}); diff --git a/src/utils/__tests__/stableKeys.spec.ts b/src/utils/__tests__/stableKeys.spec.ts new file mode 100644 index 00000000..d07a1982 --- /dev/null +++ b/src/utils/__tests__/stableKeys.spec.ts @@ -0,0 +1,89 @@ +import type { Token, Tokens } from "marked"; +import { lexer } from "marked"; +import { assignStableKeys, getStableKeyOf } from "../stableKeys"; + +/** Collects the stable key of every token in a token tree. */ +const collectKeys = (tokens?: readonly unknown[]): string[] => { + if (!tokens || !Array.isArray(tokens)) return []; + const keys: string[] = []; + for (const entry of tokens) { + const token = entry as Token; + const key = getStableKeyOf(token); + if (key) keys.push(key); + keys.push(...collectKeys((token as Tokens.Generic).tokens as unknown[])); + keys.push(...collectKeys((token as Tokens.List).items as unknown[])); + keys.push(...collectKeys((token as Tokens.Table).header as unknown[])); + const rows = (token as Tokens.Table).rows; + if (rows) { + for (const row of rows) { + keys.push(...collectKeys(row as unknown[])); + } + } + } + return keys; +}; + +describe("stableKeys", () => { + it("assigns identical keys to unchanged content across lexes", () => { + const md = "# Heading\n\nSome paragraph text."; + + const first = lexer(md, { gfm: true }); + assignStableKeys(first); + const second = lexer(md, { gfm: true }); + assignStableKeys(second); + + expect(collectKeys(first)).toEqual(collectKeys(second)); + }); + + it("keeps keys stable when tokens are inserted before unchanged ones", () => { + const tail = lexer("B paragraph.", { gfm: true }); + const expanded = lexer("A paragraph.\n\nB paragraph.", { gfm: true }); + + assignStableKeys(tail); + assignStableKeys(expanded); + + const tailKeys = collectKeys(tail); + const expandedKeys = collectKeys(expanded); + + expect(expandedKeys.slice(expandedKeys.length - tailKeys.length)).toEqual( + tailKeys, + ); + }); + + it("assigns unique keys to identical duplicate block tokens", () => { + const tokens = lexer("Same.\n\nSame.", { gfm: true }); + assignStableKeys(tokens); + + const keys = collectKeys(tokens); + expect(new Set(keys).size).toBe(keys.length); + }); + + it("assigns unique keys to identical nested inline tokens", () => { + const tokens = lexer("a `code` b `code` c", { gfm: true }); + assignStableKeys(tokens); + + const keys = collectKeys(tokens); + expect(new Set(keys).size).toBe(keys.length); + }); + + it("guards non-array look-alike fields (table cells)", () => { + const tokens = lexer("| A | B |\n| --- | --- |\n| 1 | 2 |", { + gfm: true, + }); + + expect(() => assignStableKeys(tokens)).not.toThrow(); + expect(collectKeys(tokens).length).toBeGreaterThan(0); + }); + + it("handles empty input", () => { + expect(() => assignStableKeys(undefined)).not.toThrow(); + expect(() => assignStableKeys([])).not.toThrow(); + }); + + it("ignores tokens that were never assigned", () => { + expect(getStableKeyOf(undefined)).toBeUndefined(); + expect( + getStableKeyOf({ type: "custom", raw: "x" } as unknown as Token), + ).toBeUndefined(); + }); +}); diff --git a/src/utils/hash.ts b/src/utils/hash.ts new file mode 100644 index 00000000..8b175961 --- /dev/null +++ b/src/utils/hash.ts @@ -0,0 +1,18 @@ +/** + * Fast, deterministic 32-bit string hash (32-bit "hash * 31" variant). + * + * Used to derive stable React keys from token content so that identical + * tokens produce identical keys across parses. Collisions only cause a + * benign replacement render, never data loss. + */ +const hashString = (value: string): number => { + let hash = 0; + for (let i = 0; i < value.length; i++) { + hash = (hash << 5) - hash + value.charCodeAt(i); + // Multiply the hash by 31 and keep it a 32-bit integer. + hash &= 0xffffffff; + } + return hash >>> 0; +}; + +export default hashString; diff --git a/src/utils/isEqual.ts b/src/utils/isEqual.ts new file mode 100644 index 00000000..d9929047 --- /dev/null +++ b/src/utils/isEqual.ts @@ -0,0 +1,57 @@ +/** + * Structural equality for plain, JSON-able data: + * - primitives and functions: reference equality + * - arrays: element-wise deep equality + * - plain objects: unordered key-for-key deep equality + * - other object kinds (class instances, Map, Date, …): reference equality + * + * Conservative by design: it never reports equality for non-plain objects, + * so consumers only miss an optimization instead of reusing a wrong value. + */ +const isPlainObject = (value: object): boolean => { + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +}; + +const isEqual = (a: unknown, b: unknown): boolean => { + if (a === b) return true; + + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (!isEqual(a[i], b[i])) return false; + } + return true; + } + if (Array.isArray(b)) return false; + + if ( + typeof a !== "object" || + typeof b !== "object" || + a === null || + b === null + ) { + return false; + } + + if (!isPlainObject(a) || !isPlainObject(b)) return false; + + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + if (aKeys.length !== bKeys.length) return false; + + for (const key of aKeys) { + if ( + !(key in b) || + !isEqual( + (a as Record)[key], + (b as Record)[key], + ) + ) { + return false; + } + } + return true; +}; + +export default isEqual; diff --git a/src/utils/stableKeys.ts b/src/utils/stableKeys.ts new file mode 100644 index 00000000..e46fc493 --- /dev/null +++ b/src/utils/stableKeys.ts @@ -0,0 +1,61 @@ +import type { Token, Tokens } from "marked"; + +/** + * Maps every token instance reached by {@link assignStableKeys} to a stable, + * content-derived key. A WeakMap keeps lookups O(1) and lets token instances + * be garbage collected between parses. + */ +const stableKeys = new WeakMap(); + +/** + * Recursively walks a token tree and assigns each token a stable key: + * `type:raw` for the first occurrence, `type:raw@` for repeated content. + * The occurrence numbering is derived from the document content alone, so + * identical documents always produce identical keys — across parses, renders + * and streaming updates — which lets React reconcile instead of remount. + */ +const walk = ( + tokens: readonly unknown[] | undefined, + occurrences: Map, +): void => { + /* TypeScript-safe and collision-safe: `header` is an array on Tokens.Table + * but a boolean flag on Tokens.TableCell, so only real arrays are walked. */ + if (!tokens || !Array.isArray(tokens)) return; + for (const entry of tokens) { + const token = entry as Token; + const genericToken = token as Tokens.Generic; + const keyBase = `${genericToken.type ?? ""}:${genericToken.raw ?? ""}`; + const occurrence = occurrences.get(keyBase) ?? 0; + occurrences.set(keyBase, occurrence + 1); + stableKeys.set( + token, + occurrence === 0 ? keyBase : `${keyBase}@${occurrence}`, + ); + + /* Descend into the nested token arrays of every known token shape. */ + walk(genericToken.tokens, occurrences); + walk((token as Tokens.List).items, occurrences); + walk((token as Tokens.Table).header, occurrences); + walk((token as Tokens.Table).rows?.flat(), occurrences); + } +}; + +/** + * Assigns a deterministic, content-based key to every token in the tree. + * + * Call this right after lexing, before parsing. Keys survive re-parses of + * unchanged content (even when tokens are inserted or removed elsewhere in + * the document), preventing full-tree remounts during streaming updates. + */ +const assignStableKeys = (tokens?: Token[]): void => { + if (!tokens) return; + walk(tokens, new Map()); +}; + +/** Returns the stable key previously assigned to a token, if any. */ +const getStableKeyOf = (token?: Token): string | undefined => { + if (!token) return undefined; + return stableKeys.get(token); +}; + +export { assignStableKeys, getStableKeyOf };