Files
paseo/packages/react-native-enriched-markdown/lib/module/native/EnrichedMarkdownText.js
T
Mohamed Boudra 80c44321cc Move the Markdown engine into the repository and fix two Android list layouts (#10499)
* chore(app): vendor react-native-enriched-markdown with the Paseo patch applied

Copy react-native-enriched-markdown@1.2.0-nightly-20261014-766fc0e67 (upstream
software-mansion/enriched-markdown 766fc0e67) into
packages/react-native-enriched-markdown, with
patches/react-native-enriched-markdown+1.2.0-nightly-20261014-766fc0e67.patch
applied. Nothing else changes in this commit; the package is not a workspace yet.

Reproduce:

  npm pack react-native-enriched-markdown@1.2.0-nightly-20261014-766fc0e67
  tar xzf react-native-enriched-markdown-*.tgz
  mkdir -p t/node_modules && mv package t/node_modules/react-native-enriched-markdown
  (cd t && git init -q && git apply ../patches/react-native-enriched-markdown+*.patch)
  diff -r t/node_modules/react-native-enriched-markdown packages/react-native-enriched-markdown

The diff is empty.

* chore(app): consume react-native-enriched-markdown from its workspace

Make packages/react-native-enriched-markdown a private workspace and point the
app at it, then remove the patch-package patch it replaces.

- package.json: private, version follows the root like every workspace, only the
  postinstall script that downloads tree-sitter grammars. Upstream's
  devDependencies would install a second react-native, so they are gone.
- The package keeps its name, so autolinking, the Gradle project
  :react-native-enriched-markdown, the CocoaPods spec and imports are unchanged.
- Lockfile: drop the nested registry copy under packages/app/node_modules; npm
  links node_modules/react-native-enriched-markdown to the workspace.
- Formatting, lint and knip skip the vendored code. CI routes changes to it
  through the app and browser suites.
- The codegen test checks the vendored package's generated props.
- docs/markdown-renderer.md describes the fork and how to edit it.

* fix(app): keep numbered sub-list markers off their text on Android

From #9964, moved from the package patch into the vendored package.

On Android, a numbered list nested in a bulleted item drew "1." over
the first letters of each item. A nested item's text indent summed the
root list's narrow bullet column with a fixed marginLeft, while its
marker was right-aligned to its own wider "99." column, so the number
landed on the text. iOS already indents from the item's own column.

Backport the Android hunks of upstream enriched-markdown #1015 (size
the number column to the widest marker) and #1023 (nested items start
their text from their own marker column).

test:android now also runs the backported ListRenderingTest and
TaskListInteractionTest suites. docs/markdown-renderer.md lists the
fork's backports, this one and #924, which the removed postinstall
comment used to track.

The vendored tree equals the #9964 patch applied to the pristine
package.

* fix(app): keep Android assistant replies inside their turns

From #10380, moved from the package patch into the vendored package.

On Android, an assistant reply with blockquotes nested inside a list
could overlap its "Worked for ..." footer and the next user message:
the displayed text and the layout measurement applied spans in
different orders, and the list-wide line height inflated the blockquote
spacers when it ran after them.

Use the same span order for Android Markdown measurement and display.
Apply list line height before blockquote spacers so nested quotes keep
their configured padding and the reply fits above the turn footer.

test:android now also runs ListBlockquoteMeasurementTest.

Applied on top of #9964; the two changes share only ListRenderer.kt,
where #10380's import and line-height call sit beside #9964's marker
width code. Every other file equals the #10380 patch applied to the
pristine package.

* chore(app): match the vendored Markdown web block renderer source to its build

The package patch changed lib/module/web/renderers/BlockRenderers.js (the
renderers.codeBlock override and the zoom-in cursor on images) but not
src/web/renderers/BlockRenderers.tsx. The app runs lib, so behavior does
not change. Port both changes into src so src stays the source of lib.
2026-11-23 10:15:43 +07:00

357 lines
12 KiB
JavaScript

"use strict";
import { useMemo, useCallback, useRef, useEffect } from 'react';
import EnrichedMarkdownTextNativeComponent from '../EnrichedMarkdownTextNativeComponent';
import EnrichedMarkdownNativeComponent from '../EnrichedMarkdownNativeComponent';
import { isLinkRecognitionEqual, toNativeLinkRecognition } from "../utils/regexParser.js";
import { normalizeMarkdownStyle } from '../normalizeMarkdownStyle';
import { isLinkPillContentEqual, normalizeLinkPillContent } from "../linkVariantUtils.js";
import { dispatchLinkContextMenuItem, isLinkContextMenuItemsEqual, normalizeLinkContextMenuItems } from "../linkContextMenuUtils.js";
import { resolveAccessibilityLabels } from "../accessibilityLabelDefaults.js";
import { normalizeMenuItem, normalizeLegacyBooleanMenuItem } from "../normalizeMenuItem.js";
import { jsx as _jsx } from "react/jsx-runtime";
// 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, singularLabel) => {
if (!pluralLabels) return [];
const IntlRef = Intl;
if (typeof IntlRef.PluralRules !== 'function') return [];
let pluralRules;
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 = {
zero: pluralLabels.zero ?? other,
one: pluralLabels.one ?? other,
two: pluralLabels.two ?? other,
few: pluralLabels.few ?? other,
many: pluralLabels.many ?? other,
other
};
const templates = [];
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 defaultMd4cFlags = {
underline: false,
superscript: false,
subscript: false,
latexMath: true,
highlight: false,
hardSoftBreaks: false,
preserveBlankLines: false,
admonitions: true
};
export const EnrichedMarkdownText = ({
markdown,
markdownStyle = {},
containerStyle,
onLinkPress,
onLinkLongPress,
onImagePress,
onTaskListItemPress,
enableTaskListItemToggle = true,
onCopyPress,
onLatexError,
onCodeBlockPress,
enableBlockContextMenu = true,
enableLinkPreview,
selectable = true,
md4cFlags = defaultMd4cFlags,
allowFontScaling = true,
maxFontSizeMultiplier,
allowTrailingMargin = false,
flavor = 'commonmark',
streamingAnimation = false,
streamingConfig,
spoilerOverlay = 'particles',
contextMenuItems,
linkContextMenuItems,
imageRequestHeaders,
linkPillContent,
linkRecognition,
selectionMenuConfig,
accessibilityLabels,
selectionColor,
selectionHandleColor,
textBreakStrategy,
lineBreakStrategyIOS,
writingDirection = 'first-strong',
numberOfLines,
ellipsizeMode,
renderers: _renderers,
...rest
}) => {
// 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;
const normalizedMd4cFlags = useMemo(() => ({
underline: md4cFlags.underline ?? false,
superscript: md4cFlags.superscript ?? false,
subscript: md4cFlags.subscript ?? false,
latexMath: md4cFlags.latexMath ?? true,
highlight: md4cFlags.highlight ?? false,
hardSoftBreaks: md4cFlags.hardSoftBreaks ?? false,
preserveBlankLines: md4cFlags.preserveBlankLines ?? false,
// Admonitions are a GitHub-flavor feature; force them off in commonmark so
// `> [!NOTE]` renders as a plain blockquote.
admonitions: flavor === 'github' ? md4cFlags.admonitions ?? true : false
}), [md4cFlags, flavor]);
const contextMenuCallbacksRef = useRef(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([]);
const nativeLinkContextMenuItems = useMemo(() => {
const next = normalizeLinkContextMenuItems(linkContextMenuItems);
if (!isLinkContextMenuItemsEqual(nativeLinkContextMenuItemsRef.current, next)) {
nativeLinkContextMenuItemsRef.current = next;
}
return nativeLinkContextMenuItemsRef.current;
}, [linkContextMenuItems]);
const handleLinkContextMenuItemPress = useCallback(event => {
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 => {
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 => {
const {
url,
sourceType
} = e.nativeEvent;
onLinkPress?.({
url,
sourceType: sourceType
});
}, [onLinkPress]);
const handleLinkLongPress = useCallback(e => {
const {
url
} = e.nativeEvent;
onLinkLongPress?.({
url
});
}, [onLinkLongPress]);
const handleImagePress = useCallback(e => {
const {
url,
altText
} = e.nativeEvent;
onImagePress?.({
url,
altText
});
}, [onImagePress]);
const handleTaskListItemPress = useCallback(e => {
const {
index,
checked,
text
} = e.nativeEvent;
onTaskListItemPress?.({
index,
checked,
text
});
}, [onTaskListItemPress]);
const handleCopyPress = useCallback(e => {
const {
code,
language
} = e.nativeEvent;
onCopyPress?.({
code,
language
});
}, [onCopyPress]);
const handleLatexError = useCallback(e => {
const {
source,
message,
displayMode
} = e.nativeEvent;
onLatexError?.({
source,
message: message || undefined,
displayMode
});
}, [onLatexError]);
const handleCodeBlockPress = useCallback(e => {
const {
code,
language
} = e.nativeEvent;
onCodeBlockPress?.({
code,
language
});
}, [onCodeBlockPress]);
const tableMode = streamingConfig?.tableMode ?? 'progressive';
const codeBlockMode = streamingConfig?.codeBlockMode ?? 'progressive';
const normalizedStreamingConfig = useMemo(() => ({
tableMode,
codeBlockMode
}), [tableMode, codeBlockMode]);
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;
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?.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 sharedProps = {
markdown,
linkRecognition: nativeLinkRecognition,
markdownStyle: normalizedStyle,
onLinkPress: handleLinkPress,
onLinkLongPress: handleLinkLongPress,
onImagePress: handleImagePress,
enableImagePress: onImagePress != null,
onTaskListItemPress: handleTaskListItemPress,
enableTaskListItemToggle,
onCopyPress: handleCopyPress,
onLatexError: handleLatexError,
onCodeBlockPress: handleCodeBlockPress,
enableCodeBlockPress: onCodeBlockPress != null,
enableBlockContextMenu,
enableLinkPreview: onLinkLongPress == null && (enableLinkPreview ?? true),
selectable,
md4cFlags: normalizedMd4cFlags,
isGFM: flavor === 'github',
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 (flavor === 'github') {
return /*#__PURE__*/_jsx(EnrichedMarkdownNativeComponent, {
...sharedProps
});
}
return /*#__PURE__*/_jsx(EnrichedMarkdownTextNativeComponent, {
...sharedProps
});
};
export default EnrichedMarkdownText;
//# sourceMappingURL=EnrichedMarkdownText.js.map