import { useMemo, useCallback, useRef, useEffect } from 'react'; import EnrichedMarkdownTextNativeComponent from '../EnrichedMarkdownTextNativeComponent'; import type { MarkdownStyleInternal } from '../EnrichedMarkdownTextNativeComponent'; import EnrichedMarkdownNativeComponent from '../EnrichedMarkdownNativeComponent'; import { isLinkRecognitionEqual, toNativeLinkRecognition, type LinkRecognitionNative, } from '../utils/regexParser'; import { normalizeMarkdownStyle } from '../normalizeMarkdownStyle'; import { isLinkPillContentEqual, normalizeLinkPillContent, } from '../linkVariantUtils'; import { dispatchLinkContextMenuItem, isLinkContextMenuItemsEqual, normalizeLinkContextMenuItems, } from '../linkContextMenuUtils'; import { resolveAccessibilityLabels } from '../accessibilityLabelDefaults'; import { NOT_COLLECTED, useBlockSlots, useCollectedMarkdown, } from './useBlockSlots'; import { hasRenderers } from '../blockRenderers'; import { useImageSources } from './useImageSources'; import { useLinksChange } from '../linkOccurrences'; import { normalizeMenuItem, normalizeLegacyBooleanMenuItem, } from '../normalizeMenuItem'; import { processColor, type NativeSyntheticEvent } from 'react-native'; import { isDev } from '../utils/isDev'; import type { MarkdownStyle, Md4cFlags } from '../types/MarkdownStyle'; import type { EnrichedMarkdownTextProps, StreamingConfig, ContextMenuItem, SelectionMenuConfig, SelectionMenuPluralLabels, MarkdownBlockPlacement, MarkdownSlotBlock, MarkdownMediaBlock, MarkdownImageBlock, MarkdownVideoBlock, MarkdownLinkBlock, MarkdownCodeBlock, MarkdownBlock, MarkdownRenderers, MarkdownImagePlacement, MarkdownImageOccurrence, MarkdownImageSource, MarkdownLinkOccurrence, TextHighlight, } from '../types/MarkdownTextProps'; import type { LinkPressEvent, LinkLongPressEvent, ImagePressEvent, TextPressEvent, RenderedTextBlock, HighlightLayoutEvent, TaskListItemPressEvent, CopyPressEvent, LatexErrorEvent, CodeBlockPressEvent, OnContextMenuItemPressEvent, OnLinkContextMenuItemPressEvent, } from '../types/events'; export type { MarkdownStyle, Md4cFlags }; export type { EnrichedMarkdownTextProps, StreamingConfig, ContextMenuItem, SelectionMenuConfig, SelectionMenuPluralLabels, MarkdownBlockPlacement, MarkdownSlotBlock, MarkdownMediaBlock, MarkdownImageBlock, MarkdownVideoBlock, MarkdownLinkBlock, MarkdownCodeBlock, MarkdownBlock, MarkdownRenderers, MarkdownImagePlacement, MarkdownImageOccurrence, MarkdownImageSource, MarkdownLinkOccurrence, }; export type { LinkPressEvent, LinkLongPressEvent, ImagePressEvent, TaskListItemPressEvent, CopyPressEvent, LatexErrorEvent, CodeBlockPressEvent, }; // Default English labels for the built-in selection menu actions. Defaults are // resolved here (JS-side) so the native code always receives a concrete string. const DEFAULT_COPY_LABEL = 'Copy'; const DEFAULT_COPY_AS_MARKDOWN_LABEL = 'Copy as Markdown'; const DEFAULT_COPY_IMAGE_URL_LABEL = 'Copy Image URL'; const DEFAULT_COPY_IMAGE_URLS_LABEL = 'Copy {count} Image URLs'; /** * Resolves `pluralLabels` into a per-count template table (index = image count, * 0..100) the native side can index without any locale logic. `Intl.PluralRules` * selects the CLDR category for each count; missing categories fall back to the * required `other`. Index 1 uses the singular `label` (the single-image case). * Native uses `other` (copyImageUrlsLabel) for counts > 100, and falls back to * the singular/`{count}` templates entirely when this returns an empty array * (no plural labels set, or `Intl.PluralRules` unavailable). */ const buildPluralTemplates = ( pluralLabels: SelectionMenuPluralLabels | undefined, singularLabel: string ): string[] => { if (!pluralLabels) return []; const IntlRef = Intl as unknown as { PluralRules?: new (locales?: string | string[]) => { select(n: number): string; }; }; if (typeof IntlRef.PluralRules !== 'function') return []; let pluralRules: { select(n: number): string }; try { // TODO: expose `copyImageUrl.pluralLocale?: string` so i18n apps can force // a locale independent of the device. Today this resolves to the JS // runtime's default locale, so on an English device only `one` and `other` // ever fire even when richer plural labels are configured. pluralRules = new IntlRef.PluralRules(); } catch { return []; } const { other } = pluralLabels; const byCategory: Record = { zero: pluralLabels.zero ?? other, one: pluralLabels.one ?? other, two: pluralLabels.two ?? other, few: pluralLabels.few ?? other, many: pluralLabels.many ?? other, other, }; const templates: string[] = []; for (let n = 0; n <= 100; n++) { // The literal single-image case uses the (non-plural) singular label; every // other count uses its CLDR category form. templates.push( n === 1 ? singularLabel : (byCategory[pluralRules.select(n)] ?? other) ); } return templates; }; const NO_BLOCKS: ReadonlyArray = []; const NO_HIGHLIGHTS: ReadonlyArray = []; type NativeTextHighlight = { start: number; end: number; color: number; borderRadius: number; padding: number; }; // Colors go to native as signed 32-bit ARGB, the same on iOS and Android. const toNativeHighlights = ( highlights: ReadonlyArray | undefined ): ReadonlyArray => { if (!highlights || highlights.length === 0) return NO_HIGHLIGHTS; const result: NativeTextHighlight[] = []; for (const { start, end, color, borderRadius, padding } of highlights) { const processed = processColor(color); if (typeof processed !== 'number') { if (isDev) { console.warn( `[EnrichedMarkdownText] Ignoring highlight ${start}-${end}: its color is not a plain color.` ); } continue; } result.push({ start: Math.trunc(start), end: Math.trunc(end), color: processed > 0x7fffffff ? processed - 0x100000000 : processed, borderRadius: borderRadius ?? 0, padding: padding ?? 0, }); } return result; }; const toRenderedTextBlockKind = (kind: string): RenderedTextBlock['kind'] => kind === 'code' || kind === 'table' ? kind : 'text'; const defaultMd4cFlags: Md4cFlags = { underline: false, superscript: false, subscript: false, strikethrough: false, latexMath: true, highlight: false, hardSoftBreaks: false, preserveBlankLines: false, preserveWindowsPaths: false, admonitions: true, }; export const EnrichedMarkdownText = ({ markdown, markdownStyle = {}, containerStyle, onLinkPress, onLinkLongPress, onImagePress, onTextPress, highlights, onRenderedTextChange, onHighlightLayout, selectionClipboard, onTaskListItemPress, enableTaskListItemToggle = true, onCopyPress, onLatexError, onCodeBlockPress, enableCodeBlockWrapToggle = true, enableBlockContextMenu = true, enableLinkPreview, selectable = true, md4cFlags = defaultMd4cFlags, allowFontScaling = true, maxFontSizeMultiplier, allowTrailingMargin = false, flavor = 'commonmark', streamingAnimation = false, streamingConfig, spoilerOverlay = 'particles', contextMenuItems, linkContextMenuItems, imageRequestHeaders, renderers, resolveImageSource, onLinksChange, linkPillContent, linkRecognition, selectionMenuConfig, accessibilityLabels, selectionColor, selectionHandleColor, textBreakStrategy, lineBreakStrategyIOS, writingDirection = 'first-strong', numberOfLines, ellipsizeMode, ...rest }: EnrichedMarkdownTextProps) => { // An equal config keeps the previous object, so an inline literal does not // re-send the prop on every render. const linkRecognitionRef = useRef( undefined ); const nativeLinkRecognition = useMemo(() => { const next = toNativeLinkRecognition(linkRecognition); if (!isLinkRecognitionEqual(linkRecognitionRef.current, next)) { linkRecognitionRef.current = next; } return linkRecognitionRef.current!; }, [linkRecognition]); const normalizedStyleRef = useRef(null); const normalized = normalizeMarkdownStyle(markdownStyle); // normalizeMarkdownStyle returns cached objects for structurally equal inputs, // so this referential check is sufficient to preserve a stable prop reference. if (normalizedStyleRef.current !== normalized) { normalizedStyleRef.current = normalized; } const normalizedStyle = normalizedStyleRef.current!; // Keyed on the flag values, not the object, so an inline `md4cFlags` literal // neither re-sends the prop nor re-parses for `renderers` on every render. const underline = md4cFlags.underline ?? false; const superscript = md4cFlags.superscript ?? false; const subscript = md4cFlags.subscript ?? false; const latexMath = md4cFlags.latexMath ?? true; const highlight = md4cFlags.highlight ?? false; const hardSoftBreaks = md4cFlags.hardSoftBreaks ?? false; const preserveBlankLines = md4cFlags.preserveBlankLines ?? false; const preserveWindowsPaths = md4cFlags.preserveWindowsPaths ?? false; // Admonitions are a GitHub-flavor feature; force them off in commonmark so // `> [!NOTE]` renders as a plain blockquote. const admonitions = flavor === 'github' ? (md4cFlags.admonitions ?? true) : false; // GitHub flavor always parses strikethrough, so the flag cannot change the // result there; force it off so toggling it does not invalidate anything. const strikethrough = flavor === 'github' ? false : (md4cFlags.strikethrough ?? false); const normalizedMd4cFlags = useMemo( () => ({ underline, superscript, subscript, strikethrough, latexMath, highlight, hardSoftBreaks, preserveBlankLines, preserveWindowsPaths, admonitions, }), [ underline, superscript, subscript, strikethrough, latexMath, highlight, hardSoftBreaks, preserveBlankLines, preserveWindowsPaths, admonitions, ] ); const contextMenuCallbacksRef = useRef< Map >(new Map()); useEffect(() => { const callbacksMap = new Map(); if (contextMenuItems) { for (const item of contextMenuItems) { callbacksMap.set(item.text, item.onPress); } } contextMenuCallbacksRef.current = callbacksMap; }, [contextMenuItems]); const nativeContextMenuItems = useMemo( () => contextMenuItems ?.filter((item) => item.visible !== false) .map((item) => ({ text: item.text, icon: item.icon })), [contextMenuItems] ); const linkContextMenuItemsRef = useRef(linkContextMenuItems); linkContextMenuItemsRef.current = linkContextMenuItems; // Callbacks change on most renders; native only needs to hear about the menus // when what they show changes. const nativeLinkContextMenuItemsRef = useRef< ReturnType >([]); const nativeLinkContextMenuItems = useMemo(() => { const next = normalizeLinkContextMenuItems(linkContextMenuItems); if ( !isLinkContextMenuItemsEqual(nativeLinkContextMenuItemsRef.current, next) ) { nativeLinkContextMenuItemsRef.current = next; } return nativeLinkContextMenuItemsRef.current; }, [linkContextMenuItems]); const handleLinkContextMenuItemPress = useCallback( (event: NativeSyntheticEvent) => { const { url, pattern, itemText } = event.nativeEvent; dispatchLinkContextMenuItem( linkContextMenuItemsRef.current, pattern, itemText, url ); }, [] ); const nativeImageRequestHeaders = useMemo( () => imageRequestHeaders ? Object.entries(imageRequestHeaders) .map(([name, value]) => ({ name, value })) .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) : undefined, [imageRequestHeaders] ); // An equal map keeps the previous array, so passing the prop inline does not // re-send it to native on every render. const linkPillContentRef = useRef>(undefined); const nativeLinkPillContent = useMemo(() => { const next = normalizeLinkPillContent(linkPillContent); if (!isLinkPillContentEqual(linkPillContentRef.current, next)) { linkPillContentRef.current = next; } return linkPillContentRef.current; }, [linkPillContent]); const handleContextMenuItemPress = useCallback( (e: NativeSyntheticEvent) => { const { itemText, selectedText, selectionStart, selectionEnd } = e.nativeEvent; const callback = contextMenuCallbacksRef.current.get(itemText); callback?.({ text: selectedText, selection: { start: selectionStart, end: selectionEnd }, }); }, [] ); const handleLinkPress = useCallback( (e: NativeSyntheticEvent) => { const { url } = e.nativeEvent; onLinkPress?.({ url }); }, [onLinkPress] ); const handleLinkLongPress = useCallback( (e: NativeSyntheticEvent) => { const { url } = e.nativeEvent; onLinkLongPress?.({ url }); }, [onLinkLongPress] ); const handleImagePress = useCallback( (e: NativeSyntheticEvent) => { const { url, altText } = e.nativeEvent; onImagePress?.({ url, altText }); }, [onImagePress] ); const handleTextPress = useCallback( (e: NativeSyntheticEvent) => { const { index, text } = e.nativeEvent; onTextPress?.({ index, text }); }, [onTextPress] ); const nativeHighlights = useMemo( () => toNativeHighlights(highlights), [highlights] ); const handleRenderedTextChange = useCallback( ( e: NativeSyntheticEvent<{ text: string; blocks: ReadonlyArray<{ start: number; end: number; kind: string }>; }> ) => { const { text, blocks } = e.nativeEvent; onRenderedTextChange?.({ text, blocks: blocks.map(({ start, end, kind }) => ({ start, end, kind: toRenderedTextBlockKind(kind), })), }); }, [onRenderedTextChange] ); const handleHighlightLayout = useCallback( (e: NativeSyntheticEvent) => { onHighlightLayout?.({ highlights: e.nativeEvent.highlights.map( ({ index, x, y, width, height }) => ({ index, x, y, width, height }) ), }); }, [onHighlightLayout] ); const handleTaskListItemPress = useCallback( (e: NativeSyntheticEvent) => { const { index, checked, text } = e.nativeEvent; onTaskListItemPress?.({ index, checked, text }); }, [onTaskListItemPress] ); const handleCopyPress = useCallback( (e: NativeSyntheticEvent) => { const { code, language } = e.nativeEvent; onCopyPress?.({ code, language }); }, [onCopyPress] ); const handleLatexError = useCallback( (e: NativeSyntheticEvent) => { const { source, message, displayMode } = e.nativeEvent; onLatexError?.({ source, message: message || undefined, displayMode }); }, [onLatexError] ); const handleCodeBlockPress = useCallback( (e: NativeSyntheticEvent) => { const { code, language } = e.nativeEvent; onCodeBlockPress?.({ code, language }); }, [onCodeBlockPress] ); const tableMode = streamingConfig?.tableMode ?? 'progressive'; const codeBlockMode = streamingConfig?.codeBlockMode ?? 'progressive'; const mediaMode = streamingConfig?.mediaMode ?? 'progressive'; const normalizedStreamingConfig = useMemo( () => ({ tableMode, codeBlockMode, mediaMode }), [tableMode, codeBlockMode, mediaMode] ); const normalizedSelectionMenuConfig = useMemo(() => { // The boolean acceptance is confined to this wrapper boundary via a single // `as unknown` cast; the public type only exposes the object shape. const config = selectionMenuConfig as | { copy?: unknown; copyAsMarkdown?: unknown; copyImageUrl?: unknown; } | undefined; const copy = normalizeMenuItem(config?.copy, true, DEFAULT_COPY_LABEL); const copyAsMarkdown = normalizeLegacyBooleanMenuItem( config?.copyAsMarkdown, 'selectionMenuConfig', 'copyAsMarkdown', true, DEFAULT_COPY_AS_MARKDOWN_LABEL ); const copyImageUrl = normalizeLegacyBooleanMenuItem( config?.copyImageUrl, 'selectionMenuConfig', 'copyImageUrl', true, DEFAULT_COPY_IMAGE_URL_LABEL ); const pluralLabels = ( config?.copyImageUrl as | { pluralLabels?: SelectionMenuPluralLabels } | undefined )?.pluralLabels; return { copyAsMarkdown: copyAsMarkdown.enabled, copyImageUrl: copyImageUrl.enabled, copyLabel: copy.label, copyAsMarkdownLabel: copyAsMarkdown.label, copyImageUrlLabel: copyImageUrl.label, copyImageUrlsLabel: pluralLabels?.other ?? DEFAULT_COPY_IMAGE_URLS_LABEL, copyImageUrlPluralTemplates: buildPluralTemplates( pluralLabels, copyImageUrl.label ), }; }, [selectionMenuConfig]); const resolvedAccessibilityLabels = useMemo( () => resolveAccessibilityLabels(accessibilityLabels), [accessibilityLabels] ); const selectionClipboardConfig = useMemo( () => (selectionClipboard ? JSON.stringify(selectionClipboard) : ''), [selectionClipboard] ); // One parse on the JS thread serves both: the slot children land in the same // commit as the markdown they describe, the image sources before it is drawn. const isGFM = flavor === 'github'; const renderersEnabled = hasRenderers(renderers); const collectEnabled = renderersEnabled || resolveImageSource != null || onLinksChange != null; const collectStreaming = useMemo( () => ({ enabled: streamingAnimation, tableMode, codeBlockMode, mediaMode, }), [streamingAnimation, tableMode, codeBlockMode, mediaMode] ); const collected = useCollectedMarkdown( markdown, normalizedMd4cFlags, isGFM, collectEnabled, collectStreaming ); const slotChildren = useBlockSlots( renderersEnabled ? collected.blocks : NO_BLOCKS, renderers ); const imageSources = useImageSources( collected.images, resolveImageSource, resolveImageSource != null && isGFM ); useLinksChange(collected.links, onLinksChange, collected !== NOT_COLLECTED); const sharedProps = { selectionClipboardConfig, markdown, linkRecognition: nativeLinkRecognition, markdownStyle: normalizedStyle, onLinkPress: handleLinkPress, onLinkLongPress: handleLinkLongPress, onImagePress: handleImagePress, enableImagePress: onImagePress != null, onTextPress: handleTextPress, enableTextPress: onTextPress != null, highlights: nativeHighlights, onRenderedTextChange: handleRenderedTextChange, enableRenderedTextChange: onRenderedTextChange != null, onHighlightLayout: handleHighlightLayout, onTaskListItemPress: handleTaskListItemPress, enableTaskListItemToggle, onCopyPress: handleCopyPress, onLatexError: handleLatexError, onCodeBlockPress: handleCodeBlockPress, enableCodeBlockPress: onCodeBlockPress != null, enableBlockContextMenu, enableLinkPreview: onLinkLongPress == null && (enableLinkPreview ?? true), selectable, md4cFlags: normalizedMd4cFlags, isGFM, allowFontScaling, maxFontSizeMultiplier, allowTrailingMargin, streamingAnimation, streamingConfig: normalizedStreamingConfig, spoilerOverlay, style: containerStyle, contextMenuItems: nativeContextMenuItems, linkContextMenuItems: nativeLinkContextMenuItems, onLinkContextMenuItemPress: handleLinkContextMenuItemPress, imageRequestHeaders: nativeImageRequestHeaders, linkPillContent: nativeLinkPillContent, selectionMenuConfig: normalizedSelectionMenuConfig, accessibilityLabels: resolvedAccessibilityLabels, onContextMenuItemPress: handleContextMenuItemPress, selectionColor, selectionHandleColor, textBreakStrategy, lineBreakStrategyIOS, writingDirection, numberOfLines, ellipsizeMode, ...rest, }; if (isGFM) { return ( {slotChildren} ); } return ; }; export default EnrichedMarkdownText;